Merge remote-tracking branch 'upstream/main' into export-log-phases-3713

# Conflicts:
#	crates/export/src/lib.rs
#	crates/export/src/webm.rs
#	crates/export/src/webm_av1.rs
This commit is contained in:
vangel76 committed 2026-11-18 12:54:29 +01:00
commit 3641cb38a8
201 files changed
+15652 -20055

No files matched your search

+7 -1
View File
@@ -155,4 +155,10 @@ under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and
| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) |
- Appearance theme previews, drawn procedurally from original shapes: `crates/ui-egui/src/panels/settings.rs` (original work, MIT OR Apache-2.0).
- Appearance theme previews, drawn procedurally from original shapes: `crates/ui-egui/src/panels/settings.rs` (original work, MIT OR Apache-2.0).
## Synthetic test audio
| Asset | Author | Source | Licence |
|---|---|---|---|
| `crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture` | Dylan M. Taylor | Original sine waves; reproducible recipe in `crates/media/tests/fixtures/README.md` | MIT OR Apache-2.0 |
Generated
+8945 -8303
View File
File diff suppressed because it is too large. Load diff
+241 -251
View File
@@ -1,251 +1,241 @@
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*"]
[workspace.package]
version = "0.24.1"
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 = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
craft-vectorcraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["egui"] }
# internal
effectcraft-time = { path = "crates/time" }
effectcraft-geom = { path = "crates/geom" }
effectcraft-color = { path = "crates/color" }
effectcraft-raster = { path = "crates/raster" }
effectcraft-path = { path = "crates/path" }
effectcraft-keyframe = { path = "crates/keyframe" }
effectcraft-project = { path = "crates/project" }
effectcraft-text = { path = "crates/text" }
effectcraft-effects = { path = "crates/effects" }
effectcraft-track = { path = "crates/track" }
effectcraft-segment = { path = "crates/segment" }
effectcraft-sam2 = { path = "crates/sam2" }
effectcraft-model = { path = "crates/model" }
effectcraft-render = { path = "crates/render" }
effectcraft-gpu = { path = "crates/gpu" }
effectcraft-media = { path = "crates/media" }
effectcraft-export = { path = "crates/export" }
effectcraft-expr = { path = "crates/expr" }
effectcraft-lottie = { path = "crates/lottie" }
effectcraft-interchange = { path = "crates/interchange" }
effectcraft-pdf = { path = "crates/pdf" }
effectcraft-psd = { path = "crates/psd" }
effectcraft-aep = { path = "crates/aep" }
effectcraft-svg = { path = "crates/svg" }
effectcraft-engine = { path = "crates/engine" }
effectcraft-host = { path = "crates/host" }
effectcraft-ui-egui = { path = "crates/ui-egui" }
effectcraft-automation = { path = "crates/automation" }
effectcraft-opusenc = { path = "crates/opusenc" }
effectcraft-script = { path = "crates/script" }
effectcraft-plugin = { path = "crates/plugin" }
effectcraft-helper-host = { path = "crates/helper-host" }
# foundation
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"
gif = "0.14"
proptest = "1"
# scripting (expressions)
boa_engine = { version = "0.22", default-features = false }
# WebAssembly effect plug-ins (sandboxed interpreter; MIT/Apache-2.0, pure Rust)
wasmi = { version = "2", default-features = false, features = ["std", "validate", "wat", "deterministic", "portable-dispatch"] }
# geometry / fonts
kurbo = { version = "0.13", features = ["serde"] }
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd"] }
skrifa = { version = "0.44", default-features = false, features = ["std"] }
harfrust = { version = "0.12", default-features = false, features = ["std"] }
exr = "1.74"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
same-file = "1.0"
tempfile = "3.27"
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# MPEG TS / PS headers read for AAC channel layouts (crates/media); craft-media has no MPEG TS reader
filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# decoders used as the round-trip oracles of craft-video's VP9, HEVC and AV1 encoders (crates/export
# dev-dependencies only); craft-video has no decoder for them
filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-hevc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-av1 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only)
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# gpu (the same wgpu eframe / egui-wgpu use)
wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] }
bytemuck = "1"
pollster = "1"
half = "2.7"
# ui
# Shared frontend components; keep this dependency above the engine boundary.
# Shared UI and the complete egui family select reviewed immutable commits below.
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", features = ["serde"] }
# `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
# and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
eframe = { version = "0.37", default-features = false }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
cpal = "0.16"
# The operating system's interface language (MIT/Apache-2.0, no dependencies on desktop).
sys-locale = "0.3"
# Local co-development against a FilmCraft checkout next to this repo: uncomment.
# [patch."https://github.com/storytold/filmcraft"]
# filmcraft-codecs = { path = "../filmcraft/crates/codecs" }
# filmcraft-media = { path = "../filmcraft/crates/media" }
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
# filmcraft-color = { path = "../filmcraft/crates/color" }
# filmcraft-time = { path = "../filmcraft/crates/time" }
# filmcraft-mpegts = { path = "../filmcraft/crates/mpegts" }
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
needless_range_loop = "allow"
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"
# Same settings as `dev`, but with full debug info for interactive debugger sessions: local
# variables, parameters and column breakpoints work. Use `--profile dev-full` when debugging;
# everything else stays on the fast default. See CONTRIBUTING.md, "Setup".
[profile.dev-full]
inherits = "dev"
debug = true
# Pixel hot loops: keep debug builds interactive.
[profile.dev.package.effectcraft-raster]
opt-level = 3
[profile.dev.package.effectcraft-render]
opt-level = 3
[profile.dev.package.effectcraft-gpu]
opt-level = 3
[profile.dev.package.effectcraft-effects]
opt-level = 3
[profile.dev.package.effectcraft-track]
opt-level = 3
[profile.dev.package.effectcraft-path]
opt-level = 3
[profile.dev.package.effectcraft-media]
opt-level = 3
[profile.dev.package.effectcraft-opusenc]
opt-level = 3
[profile.dev.package.effectcraft-export]
opt-level = 3
# craft-libs codec hot loops.
[profile.dev.package.craft-video]
opt-level = 3
[profile.dev.package.craft-audio]
opt-level = 3
[profile.dev.package.craft-media]
opt-level = 3
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
[profile.dev.package.filmcraft-h264]
opt-level = 3
[profile.dev.package.filmcraft-hevc]
opt-level = 3
[profile.dev.package.filmcraft-vp9]
opt-level = 3
[profile.dev.package.filmcraft-dnx]
opt-level = 3
[profile.dev.package.filmcraft-av1]
opt-level = 3
[profile.release]
lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.3.0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
# Patch a crate only together with the dependency that needs it: an unused patch makes the Nix
# build, which uses vendored sources, fail (`cargo xtask lock-patches`).
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*"]
[workspace.package]
version = "0.24.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd8bed815b8366869a800d2bf22588ca62dcb", default-features = false }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-vectorcraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["egui"] }
# internal
effectcraft-time = { path = "crates/time" }
effectcraft-geom = { path = "crates/geom" }
effectcraft-color = { path = "crates/color" }
effectcraft-raster = { path = "crates/raster" }
effectcraft-path = { path = "crates/path" }
effectcraft-keyframe = { path = "crates/keyframe" }
effectcraft-project = { path = "crates/project" }
effectcraft-text = { path = "crates/text" }
effectcraft-effects = { path = "crates/effects" }
effectcraft-track = { path = "crates/track" }
effectcraft-segment = { path = "crates/segment" }
effectcraft-sam2 = { path = "crates/sam2" }
effectcraft-model = { path = "crates/model" }
effectcraft-render = { path = "crates/render" }
effectcraft-gpu = { path = "crates/gpu" }
effectcraft-media = { path = "crates/media" }
effectcraft-export = { path = "crates/export" }
effectcraft-expr = { path = "crates/expr" }
effectcraft-lottie = { path = "crates/lottie" }
effectcraft-interchange = { path = "crates/interchange" }
effectcraft-pdf = { path = "crates/pdf" }
effectcraft-psd = { path = "crates/psd" }
effectcraft-aep = { path = "crates/aep" }
effectcraft-svg = { path = "crates/svg" }
effectcraft-engine = { path = "crates/engine" }
effectcraft-host = { path = "crates/host" }
effectcraft-ui-egui = { path = "crates/ui-egui" }
effectcraft-automation = { path = "crates/automation" }
effectcraft-script = { path = "crates/script" }
effectcraft-plugin = { path = "crates/plugin" }
effectcraft-helper-host = { path = "crates/helper-host" }
# foundation
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"
gif = "0.14"
proptest = "1"
# scripting (expressions)
boa_engine = { version = "0.22", default-features = false }
# WebAssembly effect plug-ins (sandboxed interpreter; MIT/Apache-2.0, pure Rust)
wasmi = { version = "2", default-features = false, features = ["std", "validate", "wat", "deterministic", "portable-dispatch"] }
# geometry / fonts
kurbo = { version = "0.13", features = ["serde"] }
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd"] }
skrifa = { version = "0.44", default-features = false, features = ["std"] }
harfrust = { version = "0.12", default-features = false, features = ["std"] }
exr = "1.74"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
same-file = "1.0"
tempfile = "3.27"
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode", "opus-encode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
# timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only)
filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" }
# gpu (the same wgpu eframe / egui-wgpu use)
wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] }
bytemuck = "1"
pollster = "1"
half = "2.7"
# ui
# Shared frontend components; keep this dependency above the engine boundary.
# Shared UI and the complete egui family select reviewed immutable commits below.
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["serde"] }
# `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
# and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
eframe = { version = "0.37", default-features = false }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
cpal = "0.16"
# The operating system's interface language (MIT/Apache-2.0, no dependencies on desktop).
sys-locale = "0.3"
# Local co-development against a FilmCraft checkout next to this repo: uncomment.
# [patch."https://github.com/storytold/filmcraft"]
# filmcraft-codecs = { path = "../filmcraft/crates/codecs" }
# filmcraft-media = { path = "../filmcraft/crates/media" }
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
# filmcraft-color = { path = "../filmcraft/crates/color" }
# filmcraft-time = { path = "../filmcraft/crates/time" }
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
needless_range_loop = "allow"
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"
# Same settings as `dev`, but with full debug info for interactive debugger sessions: local
# variables, parameters and column breakpoints work. Use `--profile dev-full` when debugging;
# everything else stays on the fast default. See CONTRIBUTING.md, "Setup".
[profile.dev-full]
inherits = "dev"
debug = true
# Pixel hot loops: keep debug builds interactive.
[profile.dev.package.effectcraft-raster]
opt-level = 3
[profile.dev.package.effectcraft-render]
opt-level = 3
[profile.dev.package.effectcraft-gpu]
opt-level = 3
[profile.dev.package.effectcraft-effects]
opt-level = 3
[profile.dev.package.effectcraft-track]
opt-level = 3
[profile.dev.package.effectcraft-path]
opt-level = 3
[profile.dev.package.effectcraft-media]
opt-level = 3
[profile.dev.package.effectcraft-export]
opt-level = 3
# craft-libs codec hot loops.
[profile.dev.package.craft-video]
opt-level = 3
[profile.dev.package.craft-audio]
opt-level = 3
[profile.dev.package.craft-media]
opt-level = 3
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
[profile.dev.package.filmcraft-h264]
opt-level = 3
[profile.dev.package.filmcraft-hevc]
opt-level = 3
[profile.dev.package.filmcraft-vp9]
opt-level = 3
[profile.dev.package.filmcraft-dnx]
opt-level = 3
[profile.dev.package.filmcraft-av1]
opt-level = 3
[profile.release]
lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.3.0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
# Patch a crate only together with the dependency that needs it: an unused patch makes the Nix
# build, which uses vendored sources, fail (`cargo xtask lock-patches`).
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+1
View File
@@ -2,6 +2,7 @@
**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (releases v0.22.0 through v0.24.1; .aep gained project export (#2594), drag-and-drop import (#3103), an audit of hostile inputs with every loss reported (#3299, #3300, #3319, #3365), placeholders for unmapped effects (#3087), Lumetri Color, Puppet, CC Color Neutralizer, EXtractoR/IDentifier, HDR Highlight Compression, Echo, Linear Wipe, Offset and Color Stabilizer mappings, text-animator and Source Text expressions (#3170) and twice the import speed (#3302); GPU rendering 2.6× faster with one upload per frame and single-copy readback (#3335), smooth preview lanes (#3345), bounded GPU memory (#3028), shared multi-layer EXR decode (#474), EXR output options (#2915, #2916) and a WebAssembly ABI 2 plug-in path (#3329); eighteen effect parameters now take After Effects' ranges (#3470–#3480, #3483–#3484, #3487–#3491), with Color Stabilizer sampling (#3125), masked Grid/Checkerboard/Circle (#3121), Cryptomatte selection and Matte Only (#2839, #3130), fast-conformed frame blending (#3180) and bounded Levels and time-stretch math; number-field arithmetic (#3195), expressionError (#3219), prop.get with footage (#3231), reversed-layer audio (#3239), keyframed audio waveforms (#1722), Effect Controls lock and rename selection (#3193, #3198), viewer snapping (#2681, #3229), Graph Editor theming (#3202), Convert To Bezier Path (#3237), stopwatch Add Expression (#3192), Shift-drag timeline snapping (#1828), anchored marquee (#2859), Go to Time (#3373), text layers whose names follow their text (#3233), mute-aware audio preview (#2104), ScriptUI panel bars (#2796), Closed-path and Effect Controls arrow fixes (#2817, #2869) and accessible Info, Flowchart, Script Console and 3D Camera Tracker blocks (#1341); a file-dialog crash fix (#3084), crash diagnostics and replayable repros (#3357, #1224), Flatpak updater and nightly release fixes (#3516, #3520), craft-libs format and update cutovers, and CI test stabilisation (#3650, #3689, #3704); readiness estimates unchanged) · **Target:** Adobe After Effects 2026 (26.5.0.89)
> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-11-05 · **Change:** minor (ProRes alpha final-run conformance; previously: features of 30 October in the progress log: text Line Join, Timeline drag-reorder and multi-select of effects, viewer edge pan, ScriptUI drag capture and dock size; previously: localization recount after #1774) · **Target:** Adobe After Effects 2026 (26.5.0.89)
EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written
+8 -1
View File
@@ -441,6 +441,8 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
#[cfg(target_os = "macos")]
menu: native_menu::NativeBar::new(&cc.egui_ctx),
#[cfg(target_os = "macos")]
menu_sync: Default::default(),
#[cfg(target_os = "macos")]
apple_events: apple_events.connect(&cc.egui_ctx),
app,
file_dialogs,
@@ -531,6 +533,8 @@ struct Desktop {
dialog_errors: std::sync::mpsc::Receiver<String>,
#[cfg(target_os = "macos")]
menu: native_menu::NativeBar,
#[cfg(target_os = "macos")]
menu_sync: effectcraft_ui_egui::native_menu::MenuSync,
/// Documents opened from Finder, the Dock or `open` (macOS).
#[cfg(target_os = "macos")]
apple_events: apple_events::Opened,
@@ -547,7 +551,7 @@ impl eframe::App for Desktop {
/// file dialogs asked for and, last, hand a close to the platform quit.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
self.menu.update(&mut self.app, ctx);
self.menu_sync.before(&mut self.app, |app| self.menu.update(app, ctx));
self.app.tick(ctx, frame);
self.app.finish_ime_logic(ctx);
while let Ok(e) = self.dialog_errors.try_recv() {
@@ -561,6 +565,9 @@ impl eframe::App for Desktop {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.app.ui(ui, frame);
// A file dialog this frame's commands opened (or one that closed) syncs the menu again.
#[cfg(target_os = "macos")]
self.menu_sync.after(&mut self.app, |app| self.menu.update(app, ui.ctx()));
if let Some(asked) = &self.file_dialogs {
file_dialogs::show_asked(asked, frame, ui.ctx());
}
+6
View File
@@ -118,6 +118,12 @@ impl NativeBar {
Role::Hide => PredefinedMenuItem::hide(Some(label)),
Role::HideOthers => PredefinedMenuItem::hide_others(Some(label)),
Role::ShowAll => PredefinedMenuItem::show_all(Some(label)),
Role::SelectAll => PredefinedMenuItem::select_all(Some(label)),
Role::Cut => PredefinedMenuItem::cut(Some(label)),
Role::Copy => PredefinedMenuItem::copy(Some(label)),
Role::Paste => PredefinedMenuItem::paste(Some(label)),
Role::Undo => PredefinedMenuItem::undo(Some(label)),
Role::Redo => PredefinedMenuItem::redo(Some(label)),
};
parent.append(&item)
}
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-mime = { workspace = true }
craft-aep = { workspace = true }
effectcraft-time = { workspace = true }
effectcraft-color = { workspace = true }
-10
View File
@@ -720,27 +720,17 @@ mod tests {
/// issue is fixed; the test fails on a row that is no longer needed.
#[rustfmt::skip]
const KNOWN_NARROWER: &[(&str, &str, u32)] = &[
("ec.blur.gaussian", "blurriness", 3460),
("ec.blur.fastbox", "radius", 3461),
("ec.blur.channel", "redBlurriness", 3462),
("ec.blur.channel", "greenBlurriness", 3462),
("ec.blur.channel", "blueBlurriness", 3462),
("ec.blur.channel", "alphaBlurriness", 3462),
("ec.obsolete.gaussianlegacy", "blurriness", 3463),
("ec.perspective.dropshadow", "softness", 3464),
("ec.blur.compound", "maximumBlur", 3465),
("ec.blur.sharpen", "amount", 3466),
("ec.blur.radial", "amount", 3467),
("ec.blur.ccradial", "amount", 3468),
("ec.distort.turbulentdisplace", "amount", 3469),
("ec.time.pixelmotionblur", "shutterAngle", 3481),
("ec.time.pixelmotionblur", "shutterSamples", 3482),
("ec.noise.fractal", "subSettings/subInfluence", 3485),
("ec.noise.fractal", "subSettings/subScaling", 3486),
("ec.distort.ccpowerpin", "expandTop", 3492),
("ec.distort.ccpowerpin", "expandLeft", 3492),
("ec.distort.ccpowerpin", "expandRight", 3492),
("ec.distort.ccpowerpin", "expandBottom", 3492),
];
/// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from.
+1 -13
View File
@@ -224,19 +224,7 @@ pub(crate) fn profile_json(icc: &[u8], name: &str) -> String {
/// Standard base64 with padding.
pub(crate) fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for c in data.chunks(3) {
let n = (u32::from(c[0]) << 16) | (u32::from(c.get(1).copied().unwrap_or(0)) << 8) | u32::from(c.get(2).copied().unwrap_or(0));
for (i, shift) in [18u32, 12, 6, 0].iter().enumerate() {
if i <= c.len() {
out.push(char::from(T[((n >> shift) & 63) as usize]));
} else {
out.push('=');
}
}
}
out
craft_mime::base64::STANDARD.encode(data)
}
#[cfg(test)]
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-mime = { workspace = true }
effectcraft-engine = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+13 -10
View File
@@ -1,16 +1,7 @@
//! Standard base64 (RFC 4648 §4, padded): MCP image content and the control channel's inline PNGs.
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn encode(data: &[u8]) -> String {
let mut s = String::with_capacity(data.len().div_ceil(3) * 4);
for c in data.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
s.push(if i <= c.len() { A[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
s
craft_mime::base64::STANDARD.encode(data)
}
/// Decode, ignoring ASCII whitespace; `None` on any other invalid input.
@@ -48,6 +39,18 @@ pub fn decode(s: &str) -> Option<Vec<u8>> {
#[cfg(test)]
mod tests {
#[test]
fn shared_encoder_round_trips_every_byte_and_remainder() {
let all: Vec<u8> = (0..=255).cycle().take(513).collect();
for length in 0..=all.len() {
let input = &all[..length];
let encoded = super::encode(input);
assert_eq!(encoded.len(), length.div_ceil(3) * 4);
assert_eq!(super::decode(&encoded).as_deref(), Some(input));
assert_eq!(encoded.bytes().rev().take_while(|b| *b == b'=').count(), (3 - length % 3) % 3);
}
}
#[test]
fn rfc4648_vectors() {
for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "58964adec11197594d9b6b79a94ae6232221211a" }
effectcraft-geom = { workspace = true }
effectcraft-color = { workspace = true }
effectcraft-keyframe = { workspace = true }
+1 -1
View File
@@ -147,7 +147,7 @@ pub fn effects_markdown() -> String {
- **Status**: {} implemented in full, {partial} partial (what is missing is listed).\n\n",
r.len() - partial
));
s.push_str("Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`).\n\n");
s.push_str("Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`). A parameter that was renamed keeps its old name working in expressions of older projects: `effect(\"CC Ball Action\")(\"Instability State\")` still reads Scatter Motion.\n\n");
for cat in CATEGORIES {
let list: Vec<_> = r.iter().filter(|e| e.category == *cat).collect();
if list.is_empty() {
+92 -5
View File
@@ -85,11 +85,24 @@ const TURBULENT_PINNING: [&str; 15] = [
"Pin Bottom Locked",
];
/// The largest Amount, in buffer pixels, Turbulent Displace displaces by: 2^24, exact in f32.
/// Only an expression gets past the -10000..10000 hard range. At this bound nearly every sample
/// already lands far outside any buffer, and the padding and the CPU and GPU samplers' integer
/// pixel positions (the gradient kinds move up to 2.5 × Amount) stay in range.
const TURBULENT_MAX_AMOUNT_PX: f64 = 16_777_216.0;
/// Turbulent Displace's Amount at `scale`, in buffer pixels, bounded to
/// ±[`TURBULENT_MAX_AMOUNT_PX`]; `None` when nothing moves (zero, or not a number). Shared with
/// the GPU path.
pub fn turbulent_amount_px(ctx: &EffectCtx, scale: f64) -> Option<f64> {
let amount = ctx.params.f("amount") * scale;
(amount.abs() >= 1e-9).then(|| amount.clamp(-TURBULENT_MAX_AMOUNT_PX, TURBULENT_MAX_AMOUNT_PX))
}
fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
let amount = ctx.params.f("amount") * b.scale;
if amount.abs() < 1e-9 {
let Some(amount) = turbulent_amount_px(ctx, b.scale) else {
return b;
}
};
// TURBULENT_KINDS order: the "Smoother" variants (3, 4, 5) use a gentler octave falloff.
let kind = ctx.params.e("displacement");
let size = (ctx.params.f("size") * b.scale).max(1.0);
@@ -110,6 +123,11 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
let falloff = if (3..=5).contains(&kind) { 0.3 } else { 0.5 };
let (lx, ly, lw, lh) = layer_rect(ctx, &b);
let edge = (lw.min(lh) * if locked { 0.25 } else { 0.1 }).max(1.0);
// Locked: samples stay between the outermost pixel centres, or at the centre of a layer under
// a pixel across (a reduced resolution). Its bounds may still differ by rounding, so the
// clamp is max/min, which `f64::clamp` would panic on.
let (ix, iy) = (0.5f64.min(lw * 0.5), 0.5f64.min(lh * 0.5));
let lock = (lx + ix, lx + lw - ix, ly + iy, ly + lh - iy);
let seed = (ctx.seed ^ 0x7d15).wrapping_add((ctx.params.f("evolutionOptions/randomSeed") as i64 as u32).wrapping_mul(0x9e37_79b9));
let n = |u: f64, v: f64, s: u32| {
let s = seed.wrapping_add(s);
@@ -156,7 +174,7 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf {
};
let (sx, sy) = (x + dx * k, y + dy * k);
if locked {
return Some((sx.clamp(lx + 0.5, lx + lw - 0.5), sy.clamp(ly + 0.5, ly + lh - 0.5)));
return Some((sx.max(lock.0).min(lock.1), sy.max(lock.2).min(lock.3)));
}
Some((sx, sy))
});
@@ -736,7 +754,7 @@ pub fn specs() -> Vec<EffectSpec> {
"Turbulent Displace",
vec![
p("displacement", "Displacement", Value::Enum(0), popup(&TURBULENT_KINDS)),
p("amount", "Amount", num(50.0), slider(-1000.0, 1000.0, -200.0, 200.0, 1)),
p("amount", "Amount", num(50.0), slider(-10000.0, 10000.0, -200.0, 200.0, 1)),
p("size", "Size", num(100.0), slider(2.0, 4000.0, 2.0, 400.0, 1)),
p("offset", "Offset (Turbulence)", pt(0.5, 0.5), ParamUi::Point),
p("complexity", "Complexity", num(1.0), slider(1.0, 10.0, 1.0, 10.0, 1)),
@@ -1010,6 +1028,75 @@ mod tests {
assert!(max_diff(&run("ec.distort.turbulentdisplace", &[], img.clone()).img, &img) > 1e-3);
}
/// #3469: Amount's hard range is After Effects' recorded valid range, -10000..10000; the
/// slider keeps its -200..200 scrub range.
#[test]
fn turbulent_displace_amount_takes_the_after_effects_range() {
let spec = crate::find("ec.distort.turbulentdisplace").unwrap();
let amount = spec.params.iter().find(|p| p.id == "amount").unwrap();
let ParamUi::Slider { min, max, slider_min, slider_max, .. } = amount.ui else { panic!("{:?}", amount.ui) };
assert_eq!((min, max, slider_min, slider_max), (-10000.0, 10000.0, -200.0, 200.0));
}
/// #3469: at either end of Amount's range, with every displacement kind, resized or not and
/// pinned or not, the output stays finite, in its alpha range and within the padding budget.
#[test]
fn turbulent_displace_extreme_amounts_stay_finite_and_bounded() {
let img = test_img(32, 24);
// Resize Layer grows the buffer to the padding budget (16 Mpx here), so it runs with two
// kinds; the rest stay layer-sized.
let cases = (0..9).flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 8, 0.0)]).chain([(0, 3, 1.0), (4, 14, 1.0)]);
for amount in [-10000.0, 10000.0] {
for (kind, pin, resize) in cases.clone() {
let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))];
let o = run("ec.distort.turbulentdisplace", &set, img.clone());
let what = format!("amount {amount} kind {kind} pinning {pin} resize {resize}");
assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite()) && (0.0..=1.0 + 1e-5).contains(&p[3])), "{what}");
let area = u64::from(o.img.width) * u64::from(o.img.height);
assert!(area <= 16_777_216, "{what}: {}x{}", o.img.width, o.img.height);
}
}
}
/// #3469: an Amount past the hard range, which only an expression produces, renders without
/// overflowing the padding or the sampler's pixel positions and stays finite (a plain, a
/// gradient and the cross kind; unpinned, pinned and locked); one that is not a number leaves
/// the layer as it is.
#[test]
fn turbulent_displace_unbounded_amounts_do_not_crash() {
let img = test_img(32, 24);
let cases = [0, 1, 8].into_iter().flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 11, 0.0)]).chain([(0, 1, 1.0)]);
for amount in [1e12, -1e300, f64::MAX, f64::INFINITY, f64::NEG_INFINITY] {
for (kind, pin, resize) in cases.clone() {
let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))];
let o = run("ec.distort.turbulentdisplace", &set, img.clone());
assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} kind {kind} pinning {pin} resize {resize}");
}
}
for resize in [0.0, 1.0] {
assert_eq!(run("ec.distort.turbulentdisplace", &[("amount", num(f64::NAN)), ("resizeLayer", num(resize))], img.clone()).img, img);
}
}
/// #3469: a locked pinning on a layer under a buffer pixel across (a 1-pixel layer at half or
/// third resolution, anywhere in the buffer) keeps samples inside it without its rounded
/// bounds crossing, at any Amount.
#[test]
fn turbulent_displace_locked_pinning_on_a_subpixel_layer_does_not_crash() {
let spec = crate::find("ec.distort.turbulentdisplace").unwrap();
for amount in [-10000.0, 50.0, 10000.0] {
let mut params = Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
params.values.insert("amount".into(), num(amount));
params.values.insert("pinning".into(), Value::Enum(8));
for (size, scale, offset) in [(1.0, 0.5, 0.0), (1.0, 1.0 / 3.0, -8.0), (1.0, 1.0 / 3.0, 7.0), (0.9, 1.0, -8.0), (f64::NAN, 1.0, 0.0)] {
let ctx = EffectCtx { params: &params, time: 0.5, layer_size: [size, size], seed: 3, adjustment: false, env: Default::default() };
let o = crate::apply(spec, &ctx, Buf { img: test_img(2, 2), offset: [offset, offset], scale });
// A layer size that is not a number only has to render without panicking.
assert!(size.is_nan() || o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} {size} {scale} {offset}");
}
}
}
#[test]
fn griddler_default_is_identity() {
let img = test_img(32, 24);
+6 -4
View File
@@ -955,10 +955,12 @@ pub fn specs() -> Vec<EffectSpec> {
p("bottomRight", "Bottom Right", pt(1.0, 1.0), ParamUi::Point),
p("perspective", "Perspective", num(100.0), pct()),
p("unstretch", "Unstretch", Value::Bool(false), ParamUi::Checkbox),
p("expandTop", "Top", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
p("expandLeft", "Left", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
p("expandRight", "Right", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
p("expandBottom", "Bottom", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)),
// Expansion: percent of the layer size each source edge moves out (After Effects'
// valid range is -200..200; the maximum stays at 1000 so existing values are kept).
p("expandTop", "Top", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
p("expandLeft", "Left", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
p("expandRight", "Right", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
p("expandBottom", "Bottom", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)),
],
cc_power_pin,
),
+51
View File
@@ -250,6 +250,57 @@ fn power_pin_unstretch_expands_pinned_region() {
assert!(maxd(&id.img, &im) < 1e-4);
}
/// #3492: an Expansion side moves that edge of the source rectangle by a percent of the layer
/// size. When two opposite sides add up to less than -100 % the edges cross and the rectangle
/// flips: Top -200 and Bottom -100 take rows 40 down to 0 of a 20-row layer, a mirrored copy
/// squeezed into the bottom half (the top half samples below the layer and is transparent).
/// -100 for both (the most the old minimum allowed) mirrors the whole layer.
#[test]
fn power_pin_crossed_expansion_flips_the_source() {
let im = img(20, 20);
let o = run("ec.distort.ccpowerpin", &[("expandTop", num(-200.0)), ("expandBottom", num(-100.0))], im.clone(), &[]);
assert_eq!((o.img.width, o.img.height), (20, 20));
// Output row 15: v = 15.5 / 20, source y = 40 - 40 v = 9 (between rows 8 and 9).
let px = o.img.get(10, 15);
assert!((px[1] - 8.5 / 20.0).abs() < 1e-3, "{px:?}");
assert_eq!(o.img.get(10, 5)[3], 0.0);
let both = run("ec.distort.ccpowerpin", &[("expandTop", num(-100.0)), ("expandBottom", num(-100.0))], im.clone(), &[]);
// Source y = 20 - 20 v = 4.5, row 4's centre.
let px = both.img.get(10, 15);
assert!((px[1] - 4.0 / 20.0).abs() < 1e-3, "{px:?}");
}
/// #3492: the buffer is sized by the pins alone, and Expansions at the ends of -200..1000 render
/// finite images: all sides at either end, flipped sources, a zero-size source (Top -50, Bottom
/// -50), and Unstretch, which divides by the source size (a zero size renders transparent).
#[test]
fn power_pin_is_finite_at_the_expansion_extremes() {
let im = img(24, 16);
let pins = [("topLeft", pt(3.0, -4.0)), ("topRight", pt(26.0, 2.0)), ("bottomRight", pt(20.0, 18.0)), ("bottomLeft", pt(-2.0, 14.0))];
let sides = ["expandTop", "expandLeft", "expandRight", "expandBottom"];
let cases: &[[f64; 4]] =
&[[-200.0; 4], [1000.0; 4], [-50.0, 0.0, 0.0, -50.0], [0.0, -200.0, -200.0, 0.0], [-200.0, 1000.0, -200.0, 1000.0], [-100.0, -150.0, 50.0, -200.0]];
for unstretch in [false, true] {
for perspective in [100.0, 40.0] {
let mut base: Vec<(&str, Value)> = pins.to_vec();
base.push(("unstretch", Value::Bool(unstretch)));
base.push(("perspective", num(perspective)));
let size = |o: &Buf| (o.img.width, o.img.height);
let neutral = size(&run("ec.distort.ccpowerpin", &base, im.clone(), &[]));
for ex in cases {
let mut set = base.clone();
set.extend(sides.iter().zip(ex).map(|(s, v)| (*s, num(*v))));
let o = run("ec.distort.ccpowerpin", &set, im.clone(), &[]);
let at = format!("{ex:?} unstretch {unstretch} perspective {perspective}");
assert_eq!(size(&o), neutral, "{at}");
for p in &o.img.data {
assert!(p.iter().all(|c| c.is_finite()) && (0.0..=1.0).contains(&p[3]), "{at}: {p:?}");
}
}
}
}
}
#[test]
fn split_opens_a_gap() {
let im = img(40, 30);
+4 -4
View File
@@ -84,7 +84,7 @@ pub use color_fx::{COLORAMA_PRESETS, ColoramaPalette};
pub use color2::{Curve, auto_correct_settings, color_link_mode, color_link_sample, equalize_tables, luma_clip_points, shadow_highlight_amounts};
pub use color3::OffsetCurve;
pub use distort::{transform_grow, transform_matrix_px, transform_shutter};
pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh};
pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh, turbulent_amount_px};
pub use distort3::{RESHAPE_POINTS, ReshapeSetup, SmearSetup, cc_smear_pad, reshape_setup, smear_setup, warp_inverse_map};
pub use distort4::liquify_mesh;
use effectcraft_keyframe::Value;
@@ -92,8 +92,8 @@ use effectcraft_project::build::Ids;
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
pub use effectcraft_raster::{AuxChannels, Image};
pub use misc::{
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, radial_wipe_sigma,
radial_wipe_wedge, venetian_cover, venetian_origin,
GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, drop_shadow_pad, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma,
radial_wipe_sigma, radial_wipe_wedge, venetian_cover, venetian_origin,
};
pub use sim::particle_state;
pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state};
@@ -112,7 +112,7 @@ pub use transition::{GridWipe, place_layer};
// effectcraft-gpu fx_noise.
pub use keying2::{InnerOuterPlan, inner_outer_plan};
pub use noise::remove_grain_level;
pub use noise3::{FractalGpu, NOISE_CELL, fractal_gpu};
pub use noise3::{FractalGpu, NOISE_CELL, OCTAVE_SCALE_MAX, fractal_gpu, sub_scaling_ratio};
pub use stylize3::{BumpLight, HexTile, bump_layer_id};
pub use textfx::{TextLayer, text_layer};
pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time, time_frames, timewarp_crop, timewarp_plan};
+44 -2
View File
@@ -44,6 +44,9 @@ pub const PARAM_ID_ALIASES: &[(&str, &str, &str)] = &[
("ec.key.innerouter", "additionalBackground", "additionalBackground/background1"),
// Generate: Radio Waves' growth speed was called Velocity; Velocity now moves the wave.
("ec.generate.radiowaves", "velocity", "waveMotion/expansion"),
// Simulation: CC Ball Action's Instability State is treated as the control After Effects
// 24.2 calls Scatter Motion (#3197; an assumption: 24.2 shows no Instability State).
("ec.sim.ccballaction", "instabilityState", "scatterMotion"),
];
/// Popup option labels renamed since they were first saved:
@@ -192,6 +195,14 @@ fn take_at(g: &mut PropGroup, id: &str) -> Option<Property> {
}
}
/// The position of the property at spec id `id` (`a/b/param`) among its siblings.
fn index_at(g: &PropGroup, id: &str) -> Option<usize> {
match id.split_once('/') {
None => g.children.iter().position(|c| matches!(c, Node::Prop(p) if p.match_id == id)),
Some((first, rest)) => index_at(g.sub(first)?, rest),
}
}
fn prop_at<'a>(g: &'a mut PropGroup, id: &str) -> Option<&'a mut Property> {
match id.split_once('/') {
None => g.get_mut(id),
@@ -279,6 +290,12 @@ pub fn upgrade_instance(spec: &EffectSpec, g: &mut PropGroup, ids: &mut Ids, lay
// before it moved into a twirl-down group.
let found = prop_at(g, ps.id).is_some();
if !found {
// A parameter renamed within its group keeps its place, so expressions that address
// it by index still read it.
let slot = PARAM_ID_ALIASES
.iter()
.filter(|(e, old, new)| *e == spec.id && *new == ps.id && old.rsplit_once('/').map(|(p, _)| p) == new.rsplit_once('/').map(|(p, _)| p))
.find_map(|(_, old, _)| index_at(g, old));
let moved = PARAM_ID_ALIASES.iter().filter(|(e, _, new)| *e == spec.id && *new == ps.id).find_map(|(_, old, _)| take_at(g, old)).or_else(|| {
let leaf = ps.id.rsplit('/').next().unwrap_or(ps.id);
// Not when the top-level leaf is an old id of another parameter (Radio
@@ -300,9 +317,13 @@ pub fn upgrade_instance(spec: &EffectSpec, g: &mut PropGroup, ids: &mut Ids, lay
pr
}
};
let at = |sub: &mut PropGroup| match slot {
Some(i) if i <= sub.children.len() => sub.children.insert(i, pr.into()),
_ => sub.children.push(pr.into()),
};
match path.and_then(|path| group_at(g, ids, path)) {
Some(sub) => sub.children.push(pr.into()),
None => g.children.push(pr.into()),
Some(sub) => at(sub),
None => at(g),
}
}
if let Some(pr) = prop_at(g, ps.id) {
@@ -584,6 +605,27 @@ mod tests {
assert_eq!((&pr.ui, &pr.value), (&ParamUi::Point, &Value::Vec2([20.0, -5.0])));
}
/// #3197 review: an old CC Ball Action saved Instability State as its 8th property; renamed to
/// Scatter Motion it keeps that place, so an expression that reads `effect(..)(8)` still gets
/// the same control (new controls are appended after it).
#[test]
fn upgrade_renames_a_param_in_place_and_keeps_its_index() {
let spec = find("ec.sim.ccballaction").unwrap();
let mut next = 1;
let mut g = instantiate(spec, &mut Ids(&mut next), "Ball Grid", [100.0, 50.0]);
// The layout an earlier version saved: eight parameters, Instability State last.
let old = ["scatter", "rotationAxis", "rotation", "twistProperty", "twistAngle", "gridSpacing", "ballSize", "scatterMotion"];
let mut kept: Vec<Property> = old.iter().map(|id| take_prop(&mut g, id).unwrap()).collect();
g.children.clear();
kept[7].match_id = "instabilityState".into();
kept[7].value = Value::Scalar(33.0);
g.children.extend(kept.into_iter().map(Node::from));
assert!(upgrade_instance(spec, &mut g, &mut Ids(&mut next), [100.0, 50.0]));
let ids: Vec<&str> = g.children.iter().take(8).map(|c| c.match_id()).collect();
assert_eq!(ids, ["scatter", "rotationAxis", "rotation", "twistProperty", "twistAngle", "gridSpacing", "ballSize", "scatterMotion"]);
assert_eq!(g.get("scatterMotion").unwrap().value, Value::Scalar(33.0));
}
#[test]
fn upgrade_moves_params_into_twirl_down_groups() {
let spec = find(crate::warp_stab::ID).unwrap();
+216 -16
View File
@@ -3,7 +3,7 @@
use effectcraft_color::luminance;
use effectcraft_keyframe::Value;
use effectcraft_project::ParamUi;
use effectcraft_raster::{Image, gaussian_blur, hash_noise};
use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded_at, hash_noise};
use rayon::prelude::*;
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
@@ -283,6 +283,12 @@ fn glow(ctx: &EffectCtx, mut b: Buf) -> Buf {
b
}
/// The margin Drop Shadow asks for around a layer: its Distance and its blur's reach (three
/// boxes of radius about σ = Softness / 2), both in buffer pixels. Shared with the GPU path.
pub fn drop_shadow_pad(dist: f64, soft: f64) -> u32 {
((dist + soft * 1.5).ceil() as u32).saturating_add(2)
}
fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf {
let color = ctx.params.color("color");
let opacity = ctx.params.f("opacity") as f32 / 100.0;
@@ -290,22 +296,41 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf {
let dist = ctx.params.f("distance") * b.scale;
let soft = ctx.params.f("softness") * b.scale;
let only = ctx.params.b("shadowOnly");
let pad = (dist + soft * 1.5).ceil() as u32 + 2;
let pad = drop_shadow_pad(dist, soft);
// Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a
// large Softness (After Effects' range reaches 30000, #3464); the shadow is then blurred
// before it is moved, as if the buffer went on with transparency, rather than dropping what
// the move or the blur takes past the buffer's edge, which would leave it far too faint or
// gone. An adjustment layer's buffer is the composition, as before.
let mut holds_blur = true;
if !ctx.adjustment {
let (w0, h0) = (b.img.width, b.img.height);
b.pad(pad);
let need = pad.saturating_mul(2);
holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need;
}
let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist);
let mut sh = Image::new(b.img.width, b.img.height);
let src = &b.img;
sh.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3];
*px = [color[0] * a, color[1] * a, color[2] * a, a];
}
});
if soft > 0.0 {
sh = gaussian_blur(&sh, soft / 2.0, soft / 2.0, false);
}
let shadow = |sh: &mut Image, (dx, dy): (f64, f64)| {
sh.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3];
*px = [color[0] * a, color[1] * a, color[2] * a, a];
}
});
};
let mut sh = if soft > 0.0 && !holds_blur {
// Only the fraction of the move is sampled (into one more column and row); the blur
// moves the rest.
let (ix, iy) = (dx.floor(), dy.floor());
let mut near = Image::new(src.width.saturating_add(1), src.height.saturating_add(1));
shadow(&mut near, (dx - ix, dy - iy));
gaussian_blur_unbounded_at(&near, soft / 2.0, soft / 2.0, [ix as i64, iy as i64], src.width, src.height)
} else {
let mut sh = Image::new(src.width, src.height);
shadow(&mut sh, (dx, dy));
if soft > 0.0 { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { sh }
};
if !only {
sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| {
let k = 1.0 - o[3];
@@ -756,7 +781,7 @@ pub fn specs() -> Vec<EffectSpec> {
"Gaussian Blur",
"Blur & Sharpen",
vec![
p("blurriness", "Blurriness", num(0.0), slider(0.0, 3000.0, 0.0, 50.0, 1)),
p("blurriness", "Blurriness", num(0.0), slider(0.0, 30000.0, 0.0, 50.0, 1)),
p("dimensions", "Blur Dimensions", Value::Enum(0), dims()),
p("repeatEdge", "Repeat Edge Pixels", Value::Bool(false), ParamUi::Checkbox),
],
@@ -786,7 +811,8 @@ pub fn specs() -> Vec<EffectSpec> {
"Radial Blur",
"Blur & Sharpen",
vec![
p("amount", "Amount", num(10.0), slider(0.0, 100.0, 0.0, 100.0, 1)),
// After Effects accepts 0..1000; its slider shows 0..100 (#3467).
p("amount", "Amount", num(10.0), slider(0.0, 1000.0, 0.0, 100.0, 1)),
p("center", "Center", Value::Vec2([0.5, 0.5]), ParamUi::Point),
p("type", "Type", Value::Enum(0), popup(&["Spin", "Zoom"])),
// Our blur is always fully anti-aliased; the choice is kept for compatibility.
@@ -794,7 +820,7 @@ pub fn specs() -> Vec<EffectSpec> {
],
radial,
),
spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 0))], sharpen),
spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 4000.0, 0.0, 100.0, 0))], sharpen),
spec(
"ec.blur.unsharp",
"Unsharp Mask",
@@ -871,7 +897,7 @@ pub fn specs() -> Vec<EffectSpec> {
p("opacity", "Opacity", num(50.0), slider(0.0, 100.0, 0.0, 100.0, 0)),
p("direction", "Direction", num(135.0), ParamUi::Angle),
p("distance", "Distance", num(5.0), slider(0.0, 32000.0, 0.0, 120.0, 1)),
p("softness", "Softness", num(0.0), slider(0.0, 1000.0, 0.0, 250.0, 1)),
p("softness", "Softness", num(0.0), slider(0.0, 30000.0, 0.0, 250.0, 1)),
p("shadowOnly", "Shadow Only", Value::Bool(false), ParamUi::Checkbox),
],
drop_shadow,
@@ -1036,6 +1062,134 @@ mod tests {
assert_ne!(row(2.0), row(2.4));
}
/// #3464: Softness takes After Effects' valid range, 0..30000; the slider still shows 0..250.
#[test]
fn drop_shadow_softness_takes_the_after_effects_range() {
let spec = crate::find("ec.perspective.dropshadow").unwrap();
let ui = &spec.params.iter().find(|p| p.id == "softness").unwrap().ui;
assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1));
}
/// #3464: a Softness far past the range (an expression can set one) used to overflow the
/// padding's `u32` (a panic in debug builds). It renders, finite.
#[test]
fn drop_shadow_takes_a_huge_softness() {
for softness in [1e12, f64::INFINITY] {
let layer = effectcraft_raster::Image::filled(8, 8, [1.0, 1.0, 1.0, 1.0]);
let out = run_fx("ec.perspective.dropshadow", &[("softness", num(softness))], layer, 0.0, EffectEnv::default());
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}");
}
}
/// #3464: with the margin cut, a Distance that takes the whole layer past the buffer's edge
/// still leaves the shadow's blur inside it. A 64 × 48 layer moved 3000 px right, Softness
/// 8000: at the layer's centre the shadow is the Gaussian's share there (it was 0 when the
/// layer was moved out of the buffer before the blur).
#[test]
fn drop_shadow_moved_past_a_cut_margin_keeps_its_blur() {
let (w, h, dist, softness) = (64u32, 48u32, 3000.0, 8000.0);
let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]);
let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(dist)), ("direction", num(90.0)), ("shadowOnly", Value::Bool(true))];
let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default());
assert!(out.offset[0] + f64::from(w) + dist > f64::from(out.img.width), "the move takes the layer past the buffer");
let sigma = softness / 2.0;
// The Gaussian's share of a `len`-pixel side, at `d` pixels from its centre.
let share = |len: u32, d: f64| {
let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0 + d) / sigma).powi(2) / 2.0).exp()).sum();
sum / (sigma * (2.0 * std::f64::consts::PI).sqrt())
};
let want = share(w, dist) * share(h, 0.0);
let at = |v: f64, half: u32| (v + f64::from(half)) as i64;
let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]);
assert!((0.85..1.1).contains(&(got / want)), "centre alpha {got}, Gaussian {want}");
}
/// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2)
/// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share
/// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the
/// boxes spread past the buffer left it at 0.11 of that at 8000.
#[test]
fn drop_shadow_keeps_its_blur_past_the_padding_budget() {
let (w, h) = (64u32, 48u32);
for softness in [500.0, 4000.0, 8000.0, 30000.0] {
let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]);
let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(0.0)), ("shadowOnly", Value::Bool(true))];
let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default());
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}");
let sigma = softness / 2.0;
let share = |len: u32| {
let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0) / sigma).powi(2) / 2.0).exp()).sum();
sum / (sigma * (2.0 * std::f64::consts::PI).sqrt())
};
let want = share(w) * share(h);
let at = |v: f64, half: u32| (v + f64::from(half)) as i64;
let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]);
assert!((0.85..1.02).contains(&(got / want)), "softness {softness}: centre alpha {got}, Gaussian {want}");
}
}
/// #3460: Blurriness goes up to After Effects' 30000. There the padding stays within the
/// effect pixel budget, every pixel stays finite, and Repeat Edge Pixels still repeats the
/// layer's edges: a layer white on the left and black on the right blurs to an even grey.
#[test]
fn gaussian_blur_at_the_highest_blurriness_is_bounded() {
for repeat in [false, true] {
let out = run_fx("ec.blur.gaussian", &[("blurriness", num(30000.0)), ("repeatEdge", Value::Bool(repeat))], edge(), 0.0, EffectEnv::default());
let (w, h) = (out.img.width, out.img.height);
assert!(f64::from(w) * f64::from(h) <= crate::pixel_budget(40.0, 8.0), "repeat {repeat}: {w} x {h}");
assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "repeat {repeat}");
if repeat {
assert_eq!((w, h), (40, 8));
for p in &out.img.data {
assert!(p[..3].iter().all(|v| (v - 0.5).abs() < 0.01) && (p[3] - 1.0).abs() < 1e-4, "{p:?}");
}
}
}
}
/// #3466: Sharpen Amount takes After Effects' valid range, 0..4000, and keeps its 0..100
/// slider. `prop.set` and the value editors clamp to the hard range.
#[test]
fn sharpen_amount_takes_the_after_effects_range() {
let spec = crate::find("ec.blur.sharpen").unwrap();
let ui = &spec.params.iter().find(|p| p.id == "amount").unwrap().ui;
assert!(
matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. }
if *min == 0.0 && *max == 4000.0 && *slider_min == 0.0 && *slider_max == 100.0),
"{ui:?}"
);
}
/// #3466: at the new top of the range the render stays linear in Amount and finite on 32 bpc
/// over-range input: colour moves away from the blur by Amount / 50 of the difference
/// (2000 → 4000 doubles it), never below 0, and alpha is untouched.
#[test]
fn sharpen_is_linear_and_finite_up_to_amount_4000() {
let mut img = edge();
for y in 0..8 {
for x in 0..20 {
img.set(x, y, [1000.0, 1000.0, 1000.0, 1.0]);
}
}
let sharpen = |a: f64| run_fx("ec.blur.sharpen", &[("amount", num(a))], img.clone(), 0.0, EffectEnv::default()).img;
let (half, top) = (sharpen(2000.0), sharpen(4000.0));
for y in 0..8 {
for x in 0..40 {
let (i, h, t) = (img.get(x, y), half.get(x, y), top.get(x, y));
assert_eq!(t[3], i[3], "alpha at {x}");
for c in 0..3 {
assert!(t[c].is_finite() && t[c] >= 0.0, "({x}, {y}): {t:?}");
if t[c] > 0.0 && h[c] > 0.0 {
let (dh, dt) = (h[c] - i[c], t[c] - i[c]);
assert!((dt - 2.0 * dh).abs() <= 1e-3 * dt.abs().max(1.0), "({x}, {y}): {dh} {dt}");
}
}
}
}
// The bright side of the edge moves 80 × its difference from the blur: far past 10 × the input.
assert!(top.get(19, 4)[0] > 1000.0 * 10.0, "{:?}", top.get(19, 4));
}
#[test]
fn fractional_box_blur_radius_is_continuous() {
let row = |v| blurred_row("ec.blur.fastbox", "radius", v);
@@ -1147,6 +1301,52 @@ mod tests {
}
}
/// Amount takes After Effects' valid range up to 1000 (#3467), Zoom 1000 a spread of 10.
/// Zoom samples along the ray from the centre through the pixel, never past the centre: on a
/// layer white left of the centre and black right of it, the right half stays black (scales
/// below 0 sampled the white half mirrored through the centre). Both Antialiasing settings (the
/// renderer does not read it yet; the test keeps both covered).
#[test]
fn radial_blur_zoom_at_the_largest_amount_stays_on_its_side_of_the_centre() {
let mut img = effectcraft_raster::Image::filled(64, 32, [0.0, 0.0, 0.0, 1.0]);
img.rows_mut().for_each(|(_, row)| row.iter_mut().take(32).for_each(|px| *px = [1.0, 1.0, 1.0, 1.0]));
for aa in 0..2 {
let vals = [("amount", num(1000.0)), ("type", Value::Enum(1)), ("center", Value::Vec2([32.5, 16.5])), ("antialiasing", Value::Enum(aa))];
let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default());
for y in 0..32 {
for x in 33..64 {
let p = o.img.get(x, y);
assert!(p[0].abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5, "aa {aa} ({x}, {y}): {p:?}");
}
}
}
}
/// Spin and Zoom at both ends of Amount (0..1000) and both Antialiasing settings give finite
/// colours over an opaque layer and keep it opaque (#3467). It guards the newly accepted
/// values; it passed before the Zoom fix too.
#[test]
fn radial_blur_is_finite_across_the_amount_range() {
let mut img = effectcraft_raster::Image::new(48, 40);
img.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
*px = [x as f32 / 47.0, y as f32 / 39.0, 0.5, 1.0];
}
});
for ty in 0..2 {
for aa in 0..2 {
for amount in [0.0, 100.0, 200.0, 1000.0] {
let vals = [("amount", num(amount)), ("type", Value::Enum(ty)), ("center", Value::Vec2([10.0, 30.0])), ("antialiasing", Value::Enum(aa))];
let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default());
assert_eq!((o.img.width, o.img.height), (48, 40));
for p in &o.img.data {
assert!(p.iter().all(|v| v.is_finite()) && (p[3] - 1.0).abs() < 1e-5, "type {ty} aa {aa} amount {amount}: {p:?}");
}
}
}
}
}
/// After Effects 2026, Venetian Blinds Completion 40, Direction 30, Width 50, Feather 5 on
/// an opaque 480 × 270 layer: alpha (0..255) along row y = 135. The transparent band starts
/// at the layer centre's phase, both edges are Gaussian (σ = Feather / 2).
+129 -26
View File
@@ -65,6 +65,33 @@ pub const NOISE_SOFT_LINEAR: u32 = 2;
/// correlation length), not 100 px.
pub const NOISE_CELL: f64 = 2.0 / 3.0;
/// Sub Scaling (percent, After Effects' valid 10..10000) as the size ratio of each octave to the
/// one before it. Above 1 each octave is larger than the last.
pub fn sub_scaling_ratio(percent: f64) -> f64 {
(percent / 100.0).clamp(0.1, 100.0)
}
/// Bound on an octave's frequency and on its Perspective Offset depth (and their inverses).
/// Unbounded, at Sub Scaling 10000 and Complexity 20 they would reach 100^±19, and Perspective
/// Offset multiplying the offset by the depth (and by Turbulence Factor's drift) overflowed to
/// infinity (NaN noise, #3486). Sub Scaling 10..100 never reaches the bound (10^19 at most). Both
/// stay each other's inverse inside it, so an octave's offset in lattice cells is unchanged; at a
/// frequency of 1e-20 an octave spans under 1e-12 cells of any layer, so it has no detail either way.
pub const OCTAVE_SCALE_MAX: f32 = 1e20;
/// Bound on an octave's scaled Offset Turbulence in pixels, so a huge offset times the depth stays
/// finite. Times a frequency of at least 1 / [`OCTAVE_SCALE_MAX`], over cells of at most about
/// 6700 px (Scale 10000 %), it is still over 10^12 lattice cells, past where the lattice index
/// saturates (2^31), so the output is the same.
const OCTAVE_OFFSET_MAX: f32 = 1e36;
/// The next octave's (frequency, depth) from this one's, for a Sub Scaling ratio `s`.
#[inline]
fn next_octave(f: f32, depth: f32, s: f32) -> (f32, f32) {
let lo = 1.0 / OCTAVE_SCALE_MAX;
((f / s).clamp(lo, OCTAVE_SCALE_MAX), (depth * s).clamp(lo, OCTAVE_SCALE_MAX))
}
fn spec(id: &'static str, name: &'static str, params: Vec<ParamSpec>, render: crate::RenderFn) -> EffectSpec {
EffectSpec { id, name, category: "Noise & Grain", params, render, gpu: false, float: true }
}
@@ -88,7 +115,7 @@ fn params(turbulent: bool) -> Vec<ParamSpec> {
p("transform/perspectiveOffset", "Perspective Offset", Value::Bool(false), ParamUi::Checkbox),
p("complexity", "Complexity", num(6.0), slider(1.0, 20.0, 1.0, 10.0, 1)),
p("subSettings/subInfluence", "Sub Influence (%)", num(70.0), slider(0.0, 100.0, 25.0, 100.0, 1)),
p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 100.0, 25.0, 100.0, 1)),
p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 10000.0, 25.0, 100.0, 1)),
];
if !turbulent {
v.extend([
@@ -158,7 +185,8 @@ pub fn typed_noise(x: f32, y: f32, z: f32, seed: u32, noise_type: u32) -> f32 {
let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32);
let l = |a: f32, b: f32, t: f32| a + (b - a) * t;
let slice = |dz: i32| -> f32 {
let c = |dx: i32, dy: i32| lattice(ix + dx, iy + dy, iz + dz, seed);
// Coordinates past the i32 range saturate; the neighbours wrap, as on the GPU (#3486).
let c = |dx: i32, dy: i32| lattice(ix.wrapping_add(dx), iy.wrapping_add(dy), iz.wrapping_add(dz), seed);
match noise_type {
0 => c(0, 0),
1 => l(l(c(0, 0), c(1, 0), tx), l(c(0, 1), c(1, 1), tx), ty),
@@ -195,7 +223,8 @@ pub(crate) struct Fractal {
pub perspective: bool,
pub octaves: f32,
pub influence: f32,
/// Sub Scaling as a fraction (each layer is this much smaller).
/// Sub Scaling as a size ratio ([`sub_scaling_ratio`]: each octave is this much the size of the
/// one before).
pub sub_scaling: f32,
pub sub_rotation: f32,
/// Sub Offset in pixels.
@@ -247,7 +276,7 @@ impl Fractal {
perspective: pr.b("transform/perspectiveOffset"),
octaves: pr.f("complexity").clamp(1.0, 20.0) as f32,
influence: (pr.f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0),
sub_scaling: (pr.f("subSettings/subScaling") as f32 / 100.0).clamp(0.1, 1.0),
sub_scaling: sub_scaling_ratio(pr.f("subSettings/subScaling")) as f32,
sub_rotation: (pr.f("subSettings/subRotation") as f32).to_radians(),
sub_offset: [(so[0] * b.scale) as f32, (so[1] * b.scale) as f32],
center_subscale: pr.b("subSettings/centerSubscale"),
@@ -274,6 +303,23 @@ impl Fractal {
}
}
/// Octave `of`'s origin in pixels, at Perspective Offset `depth`: Perspective Offset moves finer
/// (farther) layers less; turbulence makes them drift faster. The scaled offset stays within
/// ±[`OCTAVE_OFFSET_MAX`] (#3486).
#[inline]
fn octave_origin(&self, of: f32, depth: f32) -> [f32; 2] {
let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of);
let mut org = self.origin;
if k != 1.0 {
let d = |i: usize| ((self.origin[i] - self.center[i]) * k).clamp(-OCTAVE_OFFSET_MAX, OCTAVE_OFFSET_MAX);
org = [self.center[0] + d(0), self.center[1] + d(1)];
}
if !self.center_subscale {
org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of];
}
org
}
/// Raw fractal value (before contrast / overflow) at pixel centre (x, y).
pub(crate) fn raw(&self, x: f32, y: f32) -> f32 {
let n_oct = self.octaves.ceil() as usize;
@@ -284,16 +330,7 @@ impl Fractal {
for o in 0..n_oct {
let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 };
let of = o as f32;
// This layer's origin: Perspective Offset moves finer (farther) layers less;
// turbulence makes them drift faster.
let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of);
let mut org = self.origin;
if k != 1.0 {
org = [self.center[0] + (self.origin[0] - self.center[0]) * k, self.center[1] + (self.origin[1] - self.center[1]) * k];
}
if !self.center_subscale {
org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of];
}
let org = self.octave_origin(of, depth);
let (dx, dy) = (x - org[0], y - org[1]);
let (mut u, mut v) = ((dx * cr + dy * sr) / self.size[0], (-dx * sr + dy * cr) / self.size[1]);
if self.sub_rotation != 0.0 {
@@ -323,8 +360,7 @@ impl Fractal {
sum += n * amp * w;
norm += amp * w;
amp *= self.influence;
f /= self.sub_scaling;
depth *= self.sub_scaling;
(f, depth) = next_octave(f, depth, self.sub_scaling);
}
if self.kind == 7 { best } else { sum / norm.max(1e-6) }
}
@@ -376,22 +412,14 @@ pub fn fractal_gpu(ctx: &EffectCtx, offset: [f64; 2], scale: f64, turbulent: boo
for o in 0..n_oct {
let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 };
let of = o as f32;
let k = if fr.perspective { depth } else { 1.0 } * (1.0 + fr.turbulence * of);
let mut org = fr.origin;
if k != 1.0 {
org = [fr.center[0] + (fr.origin[0] - fr.center[0]) * k, fr.center[1] + (fr.origin[1] - fr.center[1]) * k];
}
if !fr.center_subscale {
org = [org[0] + fr.sub_offset[0] * of, org[1] + fr.sub_offset[1] * of];
}
let org = fr.octave_origin(of, depth);
let (s, c) = (fr.sub_rotation * of).sin_cos();
let evo = fr.evolution * (1.0 + fr.turbulence * of);
let dk = if fr.kind == 6 { 0.5 + of * 0.35 } else { 1.0 };
octaves.push([org[0], org[1], s, c, f, amp, w, evo, of * 7.31, dk]);
norm += amp * w;
amp *= fr.influence;
f /= fr.sub_scaling;
depth *= fr.sub_scaling;
(f, depth) = next_octave(f, depth, fr.sub_scaling);
}
let cycle = fr.cycle.map(|c| {
let t = fr.evolution.rem_euclid(c);
@@ -483,6 +511,37 @@ mod tests {
run_fx(id, vals, Image::filled(40, 24, [0.2, 0.4, 0.6, 1.0]), 0.0, EffectEnv::default()).img
}
/// #3486: lattice coordinates past the i32 range (an octave's frequency at Sub Scaling 10 % and
/// high Complexity) saturate, and their neighbours wrap instead of overflowing.
#[test]
fn noise_past_the_i32_range_is_finite() {
for noise_type in [0, 1, 2, 3] {
for (x, y) in [(1e30, -1e30), (f32::MAX, f32::MIN), (3e9, 2.5e9)] {
let n = typed_noise(x, y, 1e12, 7, noise_type);
assert!(n.is_finite(), "type {noise_type} at ({x}, {y}): {n}");
}
}
}
/// #3486: octave frequency and depth stay each other's inverse and finite at 20 octaves of
/// either end of Sub Scaling, and are unchanged inside the old 10..100 range.
#[test]
fn octave_scales_stay_finite_and_inverse() {
for s in [0.1f32, 0.56, 1.0, 2.0, 100.0] {
let (mut f, mut depth, (mut f0, mut d0)) = (1.0f32, 1.0f32, (1.0f32, 1.0f32));
for _ in 0..19 {
(f, depth) = next_octave(f, depth, s);
(f0, d0) = (f0 / s, d0 * s);
let lo = 1.0 / OCTAVE_SCALE_MAX;
assert!((lo..=OCTAVE_SCALE_MAX).contains(&f) && (lo..=OCTAVE_SCALE_MAX).contains(&depth), "{s}: {f} {depth}");
assert!((f * depth - 1.0).abs() < 1e-3, "{s}: {f} × {depth}");
if s <= 1.0 {
assert_eq!((f, depth), (f0, d0), "{s}");
}
}
}
}
/// Evolution moves the noise at a constant rate: no ease in or out within a revolution.
#[test]
fn evolution_is_linear() {
@@ -658,6 +717,50 @@ mod tests {
assert_ne!(t0, t1);
}
/// #3486: Sub Scaling takes After Effects' 10..10000 for both effects (the slider still shows
/// 25..100), and the renderer uses values above 100 instead of capping them there.
#[test]
fn sub_scaling_takes_the_after_effects_range() {
for id in ["ec.noise.fractal", "ec.noise.turbulent"] {
let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == "subSettings/subScaling").unwrap().ui;
assert!(
matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. }
if *min == 10.0 && *max == 10000.0 && *slider_min == 25.0 && *slider_max == 100.0),
"{id}: {ui:?}"
);
let at = |v: f64| run(id, &[("subSettings/subScaling", num(v))]);
assert_ne!(at(100.0), at(200.0), "{id}: 200 renders as 100");
assert_ne!(at(200.0), at(10000.0), "{id}: 10000 renders as 200");
}
}
/// #3486: above 100 %, each octave is larger than the last, so its scale grows as Sub
/// Scaling^octave (100^19 at Complexity 20). Perspective Offset and Turbulence Factor multiply
/// the offset by that, which overflowed to infinity and drew NaN, also for a huge offset. At
/// 10 % the lattice coordinates pass the i32 range, whose neighbour index overflowed.
#[test]
fn extreme_sub_scaling_stays_finite() {
for id in ["ec.noise.fractal", "ec.noise.turbulent"] {
for sub in [10.0, 100.0, 9999.0, 10000.0] {
for (perspective, offset) in [(false, [-3000.0, 2500.0]), (true, [-3000.0, 2500.0]), (true, [1e17, -1e17])] {
let mut vals = vec![
("subSettings/subScaling", num(sub)),
("complexity", num(20.0)),
("transform/perspectiveOffset", Value::Bool(perspective)),
("transform/offset", Value::Vec2(offset)),
("evolution", num(200.0)),
("blendingMode", Value::Enum(BLEND_NONE)),
];
if id == "ec.noise.turbulent" {
vals.push(("evolutionOptions/turbulenceFactor", num(10.0)));
}
let img = run(id, &vals);
assert!(img.data.iter().flatten().all(|c| c.is_finite()), "{id} sub {sub} perspective {perspective} offset {offset:?}: non-finite output");
}
}
}
}
/// Turbulent Basic Fractal Noise drawn alone at `w` × `h`.
fn turbulent_basic(w: u32, h: u32, vals: &[(&str, Value)]) -> Image {
let mut all = vec![("fractalType", Value::Enum(2)), ("blendingMode", Value::Enum(BLEND_NONE))];
+26 -79
View File
@@ -18,89 +18,31 @@ pub enum FileXform {
/// Parse a Sony Imageworks `.spimtx` matrix: three rows of four numbers, three matrix columns
/// and an offset in 16-bit code values (÷ 65535).
pub fn parse_spimtx(text: &str) -> Option<FileXform> {
let v: Vec<f64> = text.split_whitespace().map(|t| t.parse().ok()).collect::<Option<_>>()?;
if v.len() != 12 || v.iter().any(|x| !x.is_finite()) {
return None;
}
let mut m = [0.0; 16];
let mut offset = [0.0; 4];
for (r, row) in v.as_chunks::<4>().0.iter().enumerate() {
m[r * 4..r * 4 + 3].copy_from_slice(&row[..3]);
offset[r] = row[3] / 65535.0;
}
m[15] = 1.0;
Some(FileXform::Matrix { m, offset })
let value = craft_cms::sony_lut::parse_spimtx(text)?;
Some(FileXform::Matrix { m: value.matrix, offset: value.offset })
}
/// Parse a Sony Imageworks `.spi1d` 1D LUT: `From <min> <max>`, `Length <n>`, `Components
/// <1 | 3>`, then `{` the values `}`.
pub fn parse_spi1d(text: &str) -> Option<Lut> {
let (mut from, mut len, mut comps) = ([0.0f32, 1.0], 0usize, 1usize);
let mut values: Vec<f32> = vec![];
let mut body = false;
for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
if body {
if line.starts_with('}') {
break;
}
for t in line.split_whitespace() {
values.push(t.parse().ok()?);
}
continue;
}
let mut t = line.split_whitespace();
match t.next()? {
"{" => body = true,
"From" => from = [t.next()?.parse().ok()?, t.next()?.parse().ok()?],
"Length" => len = t.next()?.parse().ok()?,
"Components" => comps = t.next()?.parse().ok()?,
_ => {}
}
}
// A 1D table is interpolated by index, so cap it like the lattices (2²⁴ entries).
if !(2..=MAX_1D).contains(&len)
|| !matches!(comps, 1 | 3)
|| values.len() != len.checked_mul(comps)?
|| from[1] <= from[0]
|| from.iter().any(|v| !v.is_finite())
{
return None;
}
let d1 = values.chunks_exact(comps).map(|c| if comps == 3 { [c[0], c[1], c[2]] } else { [c[0]; 3] }).collect();
Some(Lut { n1: len, d1, n3: 0, d3: vec![], dmin: [from[0]; 3], dmax: [from[1]; 3] })
let table = craft_cms::spi1d::parse(text)?;
Some(Lut { n1: table.values.len(), d1: table.values, n3: 0, d3: vec![], dmin: [table.domain[0]; 3], dmax: [table.domain[1]; 3] })
}
/// Parse a Sony Imageworks `.spi3d` lattice: `SPILUT 1.0`, `3 3`, the sizes, then one
/// `r g b R G B` line per lattice point (indices, then the colour).
pub fn parse_spi3d(text: &str) -> Option<Lut> {
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
if !lines.next()?.starts_with("SPILUT") {
return None;
}
lines.next()?;
let size: Vec<usize> = lines.next()?.split_whitespace().map(|t| t.parse().ok()).collect::<Option<_>>()?;
let n = *size.first()?;
if size.len() != 3 || size.iter().any(|s| *s != n) || !(2..=MAX_LATTICE).contains(&n) {
return None;
}
let mut d3 = vec![[0.0f32; 3]; n * n * n];
let mut seen = 0usize;
for line in lines {
let v: Vec<&str> = line.split_whitespace().collect();
let [r, g, b, cr, cg, cb] = v.as_slice() else { return None };
let (r, g, b): (usize, usize, usize) = (r.parse().ok()?, g.parse().ok()?, b.parse().ok()?);
if r >= n || g >= n || b >= n {
return None;
}
// Our lattice is red fastest.
*d3.get_mut(r + g * n + b * n * n)? = [cr.parse().ok()?, cg.parse().ok()?, cb.parse().ok()?];
seen += 1;
}
(seen == n * n * n).then_some(Lut { n1: 0, d1: vec![], n3: n, d3, dmin: [0.0; 3], dmax: [1.0; 3] })
let value = craft_cms::sony_lut::parse_spi3d(text)?;
Some(Lut { n1: 0, d1: vec![], n3: value.size, d3: value.values, dmin: [0.0; 3], dmax: [1.0; 3] })
}
/// Parse an Autodesk `.3dl` lattice (integers, blue fastest; an optional input-mesh line).
pub fn parse_3dl(text: &str) -> Option<Lut> {
parse_3dl_limited(text, MAX_LATTICE)
}
/// [`parse_3dl`] with the largest accepted lattice side as a parameter, so tests can reach it.
pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option<Lut> {
let mut mesh: Option<Vec<f64>> = None;
let mut rows: Vec<[f64; 3]> = vec![];
let mut out_bits: Option<u32> = None;
@@ -111,34 +53,39 @@ pub fn parse_3dl(text: &str) -> Option<Lut> {
}
if l.starts_with(|c: char| c.is_ascii_alphabetic()) {
// "Mesh <in bits> <out bits>" (Lustre header); other keywords are ignored.
let t: Vec<&str> = l.split_whitespace().collect();
let t: Vec<&str> = l.split_whitespace().take(3).collect();
if t[0].eq_ignore_ascii_case("mesh") && t.len() >= 3 {
out_bits = t[2].parse().ok();
}
continue;
}
let v: Vec<f64> = l.split_whitespace().filter_map(|t| t.parse().ok()).collect();
let v: Vec<f64> = l.split_whitespace().filter_map(|t| t.parse().ok()).take(max_side.max(3).saturating_add(1)).collect();
if v.len() > 3 && mesh.is_none() && rows.is_empty() {
// The mesh length is the lattice side: refuse one no lattice reader accepts (#3830).
if v.len() > max_side {
return None;
}
mesh = Some(v);
} else if v.len() == 3 {
// One spare row while no mesh is known: a 3-entry mesh reads as a data row until the
// count tells them apart below.
if rows.len() >= max_side.saturating_pow(3).saturating_add(usize::from(mesh.is_none())) {
return None;
}
rows.push([v[0], v[1], v[2]]);
} else {
return None;
}
}
let is_cube = |k: usize| {
let n = (k as f64).cbrt().round() as usize;
n * n * n == k
};
// A 3-entry input mesh (3³ lattice) looks like a data row: tell them apart by the count.
if mesh.is_none() && !is_cube(rows.len()) && rows.len() == 28 {
// A 3-entry input mesh (3³ lattice) looks like a data row: 28 rows are a mesh and 27.
if mesh.is_none() && rows.len() == 28 {
mesh = Some(rows.remove(0).to_vec());
}
let n = match &mesh {
Some(m) => m.len(),
None => (rows.len() as f64).cbrt().round() as usize,
};
if n < 2 || rows.len() != n * n * n {
if !(2..=max_side).contains(&n) || n.checked_pow(3) != Some(rows.len()) {
return None;
}
let maxv = rows.iter().flat_map(|r| r.iter()).fold(0.0f64, |m, &v| m.max(v));
@@ -155,7 +102,7 @@ pub fn parse_3dl(text: &str) -> Option<Lut> {
Some(Lut { n1: 0, d1: vec![], n3: n, d3, dmin: [0.0; 3], dmax: [1.0; 3] })
}
/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`).
/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`, `.3dl`).
const MAX_LATTICE: usize = 129;
/// Most entries of a 1D table (interpolated by index, so capped like the lattices: 2²⁴).
const MAX_1D: usize = 1 << 24;
+56
View File
@@ -116,10 +116,24 @@ fn spi_files_parse() {
assert!((back[0] - 1.0).abs() < 1e-5 && (back[2] - 2.0).abs() < 1e-5, "{back:?}");
let three = parse_spi1d("Version 1\nFrom 0 1\nLength 2\nComponents 3\n{\n0 0 0\n1 0.5 2\n}\n").unwrap();
assert_eq!(three.d1, vec![[0.0; 3], [1.0, 0.5, 2.0]]);
let eof = parse_spi1d("Length 2\nFrom -1 2\n{\n0 1").unwrap();
assert_eq!(eof.n1, 2);
assert_eq!(eof.dmin, [-1.0; 3]);
assert_eq!(eof.dmax, [2.0; 3]);
assert_eq!(eof.n3, 0);
assert!(eof.d3.is_empty());
assert!(parse_spi1d("Length 2\n{\n0 1 2").is_none());
let mut spi3d = String::from("SPILUT 1.0\n3 3\n2 2 2\n");
for (r, g, b) in (0..8).map(|i| (i & 1, (i >> 1) & 1, i >> 2)) {
spi3d += &format!("{r} {g} {b} {} {} {}\n", r as f32 * 0.5, g, b);
}
let lattice = parse_spi3d(&spi3d).unwrap();
assert_eq!(lattice.n1, 0);
assert!(lattice.d1.is_empty());
assert_eq!(lattice.n3, 2);
assert_eq!(lattice.dmin, [0.0; 3]);
assert_eq!(lattice.dmax, [1.0; 3]);
assert!(parse_spimtx("1 0 0 0 0 1 0 0 0 0 1 0 extra").is_none());
let x = parse_file(&spi3d, "spi3d").unwrap();
let o = x.apply([1.0, 0.5, 0.25], 1, false, "");
assert!((o[0] - 0.5).abs() < 1e-6 && (o[1] - 0.5).abs() < 1e-6 && (o[2] - 0.25).abs() < 1e-6, "{o:?}");
@@ -533,3 +547,45 @@ fn an_ocio_transform_file_is_read_again_once_it_changes() {
assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap()));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_3dl_with_a_hostile_mesh_is_refused_without_overflow() {
// #3830: 2 642 246³ is past usize::MAX, so cubing the mesh length overflowed.
let huge = "0 ".repeat(2_642_246) + "\n0 0 0\n";
assert!(parse_file(&huge, "3dl").is_none());
// A mesh whose rows run out.
let short = (0..17).map(|i| (i * 64).to_string()).collect::<Vec<_>>().join(" ") + "\n0 0 0\n1 1 1\n";
assert!(parse_file(&short, "3dl").is_none());
// A normal small table still loads.
let mut ok = String::from("0 511 1023\n");
for k in 0..27 {
ok += &format!("{} {} {}\n", k * 30, k * 30, k * 30);
}
assert!(matches!(parse_file(&ok, "3dl"), Some(FileXform::Lut { lut, .. }) if lut.n3 == 3 && lut.d3.len() == 27));
}
/// A complete `.3dl` table of side `n`, with its input mesh line or without one.
fn table_3dl(n: usize, mesh: bool) -> String {
let mut text = if mesh { (0..n).map(|i| (i * 1023 / (n - 1)).to_string()).collect::<Vec<_>>().join(" ") + "\n" } else { String::new() };
for k in 0..n * n * n {
text += &format!("{} {} {}\n", k % 1024, k % 1024, k % 1024);
}
text
}
#[test]
fn a_3dl_lattice_is_capped_at_the_largest_side() {
// #3830: a complete table at the cap loads, and one a side larger is refused, with or without
// its mesh line (without one, row collection stops at the cap's volume).
for mesh in [true, false] {
let at = lut::parse_3dl_limited(&table_3dl(4, mesh), 4);
assert!(at.is_some_and(|l| l.n3 == 4 && l.d3.len() == 64), "mesh {mesh}");
assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 4).is_none(), "mesh {mesh}");
assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 5).is_some(), "mesh {mesh}");
}
// A 3-entry mesh reads as a 28th row until the count separates it, and a four-value row is
// still refused at the smallest limit.
assert!(lut::parse_3dl_limited(&table_3dl(3, true), 3).is_some_and(|l| l.n3 == 3));
let four = table_3dl(2, false).replacen("7 7 7", "7 7 7 7", 1);
assert!(lut::parse_3dl_limited(&four, 2).is_none());
}
+22
View File
@@ -93,6 +93,10 @@ pub enum Shape {
Disc,
/// Lit sphere (upper-left light, specular).
Sphere,
/// CC Ball Action's ball: [`Shape::Sphere`]'s light and shine scaled by `|shade|` (1 is the
/// sphere's look, 0 a flat disc; callers keep it finite, the GPU draws the same); a negative
/// `shade` mirrors the light's direction (lit from the lower right).
Ball { shade: f32 },
/// Disc fading linearly to its rim.
Faded,
/// Thin ring with a highlight.
@@ -277,6 +281,24 @@ fn sprite_shade(s: &Sprite, x: f32, y: f32) -> Option<Px> {
rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec];
cv
}
Shape::Ball { shade } => {
let d = (dx * dx + dy * dy).sqrt();
let cv = aa(r - d);
if cv <= 0.0 {
return None;
}
let (nx, ny) = (dx / r, dy / r);
let nz = (1.0 - nx * nx - ny * ny).max(0.0).sqrt();
let m = if shade < 0.0 { -1.0 } else { 1.0 };
let (lx, ly, lz) = (-0.48 * m, -0.58 * m, 0.66);
let diff = (nx * lx + ny * ly + nz * lz).max(0.0);
let rz = 2.0 * diff * nz - lz;
let st = shade.abs();
let spec = rz.max(0.0).powi(20) * 0.6 * st;
let k = (1.0 - st * 0.8 * (1.0 - diff)).max(0.0);
rgb = [rgb[0] * k + spec, rgb[1] * k + spec, rgb[2] * k + spec];
cv
}
Shape::Bubble => {
let d = (dx * dx + dy * dy).sqrt() / r;
if d > 1.0 + 1.0 / r {
+113 -5
View File
@@ -4,10 +4,91 @@ use super::{Acc, Buf, EffectCtx, IntoParallelIterator, ParallelIterator, Post, S
// ------------------------------------------------------------------ CC Ball Action
/// CC Ball Action's Coloring: how a ball takes its colour from the layer under its grid cell.
/// An approximation: After Effects' own meaning is not published beyond "how smooth the
/// balls look". Crisp takes the nearest pixel, Medium keeps EffectCraft's earlier smooth
/// sample at the cell centre (for compatibility), Smooth averages 16 samples over the cell.
pub(super) const BALL_COLORING: &[&str] = &["Crisp", "Medium", "Smooth"];
pub(super) const BALL_COLORING_MEDIUM: u32 = 1;
/// CC Ball Action's default Shading: the lit sphere (`Shape::Sphere`); 0 draws flat discs.
pub(super) const BALL_SHADING_DEFAULT: f64 = -75.0;
/// CC Ball Action's Displace Property: what pushes a ball towards (high values) or away from
/// (low values) the camera. The option names come from public descriptions; what Radius,
/// Diamond and Spherize compute here is an assumption pending a comparison with After Effects.
pub(super) const BALL_DISPLACE_PROPERTIES: &[&str] = &["Red", "Green", "Blue", "Brightness", "Saturation", "RGB", "Radius", "Diamond", "Spherize"];
pub(super) const BALL_DISPLACE_BRIGHTNESS: u32 = 3;
pub(super) fn ball_action(ctx: &EffectCtx, b: Buf) -> Buf {
ball_action_plan(ctx, &b).finish(b)
}
/// A parameter's number, or `default` when the instance does not carry it.
fn f_or(ctx: &EffectCtx, id: &str, default: f64) -> f64 {
ctx.params.values.get(id).map(|v| v.as_f64()).unwrap_or(default)
}
/// The layer's straight colour and alpha for the ball of the grid cell centred on (`sx`, `sy`)
/// (buffer pixels, cell `cell` buffer pixels wide), by Coloring `coloring`.
fn ball_color(src: &effectcraft_raster::Image, sx: f64, sy: f64, cell: f64, coloring: u32) -> ([f32; 3], f32) {
match coloring {
// Crisp: the pixel under the cell centre.
0 => unpremul(src.get(sx.floor() as i64, sy.floor() as i64)),
// Smooth: the cell's average (4 × 4 samples, premultiplied).
2 => {
const N: u32 = 4;
let mut acc = [0.0f32; 4];
for j in 0..N {
for i in 0..N {
let ox = (f64::from(i) + 0.5) / f64::from(N) - 0.5;
let oy = (f64::from(j) + 0.5) / f64::from(N) - 0.5;
let p = src.sample_bilinear(sx + ox * cell, sy + oy * cell);
for (a, v) in acc.iter_mut().zip(p) {
*a += v;
}
}
}
let n = (N * N) as f32;
unpremul([acc[0] / n, acc[1] / n, acc[2] / n, acc[3] / n])
}
// Medium: a smooth sample at the cell centre.
_ => unpremul(src.sample_bilinear(sx, sy)),
}
}
/// CC Ball Action's Displace Property `prop` (0..1) for a ball of straight colour `c` at
/// (`gx`, `gy`) on a `lw` × `lh` layer (`maxr`: half its diagonal). Assumed meanings (not
/// compared with After Effects yet): Radius, Diamond and Spherize are shapes that peak at the
/// layer centre.
fn ball_displace_value(prop: u32, c: [f32; 3], gx: f32, gy: f32, lw: f32, lh: f32, maxr: f32) -> f32 {
let (cx, cy) = (lw * 0.5, lh * 0.5);
let v = match prop {
0 => c[0],
1 => c[1],
2 => c[2],
// Brightness: the brightest channel (HSB brightness).
3 => c[0].max(c[1]).max(c[2]),
// Saturation: HSB saturation.
4 => {
let mx = c[0].max(c[1]).max(c[2]);
let mn = c[0].min(c[1]).min(c[2]);
if mx > 0.0 { (mx - mn) / mx } else { 0.0 }
}
// RGB: the channels' mean.
5 => (c[0] + c[1] + c[2]) / 3.0,
// Radius: high at the centre, low at the corners.
6 => 1.0 - (gx - cx).hypot(gy - cy) / maxr.max(1.0),
// Diamond: high at the centre, falling linearly to the edge midpoints' diamond.
7 => 1.0 - ((gx - cx).abs() / cx.max(0.5) + (gy - cy).abs() / cy.max(0.5)) * 0.5,
// Spherize: a hemisphere over the largest centred circle.
_ => {
let rr = cx.min(cy).max(0.5);
let d = (gx - cx).hypot(gy - cy) / rr;
(1.0 - d * d).max(0.0).sqrt()
}
};
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
}
/// CC Ball Action's balls (far to near), coloured by the layer's pixels.
fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let pr = ctx.params;
@@ -18,7 +99,29 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let twist = pr.f("twistAngle").to_radians();
let spacing = pr.f("gridSpacing").max(1.0) as f32;
let size = pr.f("ballSize") as f32 / 100.0;
let instab = pr.f("instabilityState").to_radians() as f32;
// Scatter Motion, treated as the renamed Instability State (an assumption: After Effects
// 24.2 shows Scatter Motion and no Instability State): turns each ball's scatter direction.
let instab = pr.f("scatterMotion").to_radians() as f32;
let coloring = pr.values.get("coloring").map(|v| v.as_enum()).unwrap_or(BALL_COLORING_MEDIUM);
let shading = f_or(ctx, "shading", BALL_SHADING_DEFAULT);
// Shading: -75 is the lit sphere as it always was, 0 flat discs; the magnitude scales the
// light and shine (strength 1 at 75) and the sign mirrors the light's direction (positive
// lights the balls from the lower right). How this compares with After Effects' sign
// (described as concave versus convex) is unverified, as is the -100..100 range.
let shape = if shading == BALL_SHADING_DEFAULT || !shading.is_finite() {
Shape::Sphere
} else if shading == 0.0 {
Shape::Disc
} else {
// Clamped: a huge value would reach the GPU as an infinite strength (and NaN colours).
Shape::Ball { shade: (-shading.clamp(-100.0, 100.0) / 75.0) as f32 }
};
// Displace: pushes each ball along z by its Displace Property (high values towards the
// camera, pivoting at the property's middle value); 100 moves the extremes by half the
// layer's diagonal. Scale, direction, pivot and range are EffectCraft's own choice,
// pending a comparison with After Effects. Clamped so huge values stay finite.
let displace = pr.f("displace").clamp(-1000.0, 1000.0) as f32;
let displace_prop = pr.values.get("displaceProperty").map(|v| v.as_enum()).unwrap_or(BALL_DISPLACE_BRIGHTNESS);
let seed = ctx.seed.wrapping_mul(0x2545f491);
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
let s = b.scale as f32;
@@ -43,7 +146,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let gx = (i % nx) as f32 * spacing + spacing * 0.5;
let gy = (i / nx) as f32 * spacing + spacing * 0.5;
let (sx, sy) = b.to_px([gx as f64, gy as f64]);
let (c, a) = unpremul(src.sample_bilinear(sx, sy));
let (c, a) = ball_color(src, sx, sy, f64::from(spacing * s), coloring);
if a <= 0.0 || size <= 0.0 {
return None;
}
@@ -54,11 +157,16 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
_ => crate::util::rgb3([c[0], c[1], c[2], 0.0]).iter().sum::<f32>() / 3.0,
} as f64;
let ang = rot + twist * tp;
// Scatter: random 3D offsets whose direction drifts with the instability state.
// Scatter: random 3D offsets whose direction drifts with Scatter Motion.
let ph = h(i, 1, seed) * std::f32::consts::TAU + instab;
let sc = scatter * h(i, 2, seed);
let off = [(sc * ph.cos()) as f64, (sc * ph.sin()) as f64, (scatter * hs(i, 3, seed)) as f64];
let p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]];
let mut p0 = [gx as f64 - cx + off[0], gy as f64 - cy + off[1], off[2]];
// Only when set, so Displace 0 leaves every depth (and the far-to-near order) as is.
if displace != 0.0 && displace.is_finite() {
let v = ball_displace_value(displace_prop, c, gx, gy, lw, lh, maxr);
p0[2] -= f64::from(displace / 100.0 * (v - 0.5) * 2.0 * maxr);
}
let m = rot_axis(ax, ang);
let q: [f64; 3] = std::array::from_fn(|k| m[k][0] * p0[0] + m[k][1] * p0[1] + m[k][2] * p0[2]);
if d + q[2] <= d * 0.05 {
@@ -67,7 +175,7 @@ fn ball_action_plan(ctx: &EffectCtx, b: &Buf) -> SpritePlan {
let persp = d / (d + q[2]);
let (bx, by) = b.to_px([cx + q[0] * persp, cy + q[1] * persp]);
let r = spacing * 0.5 * size * persp as f32 * s;
Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], Shape::Sphere)))
Some((q[2], Sprite::new(bx as f32, by as f32, r, [c[0], c[1], c[2], a], shape)))
})
.collect();
balls.sort_by(|a, b| b.0.total_cmp(&a.0));
+15 -6
View File
@@ -1,5 +1,7 @@
use super::foam::{FOAM_TEXTURES, foam};
use super::pixels::{ball_action, pixel_polly, scatterize};
use super::pixels::{
BALL_COLORING, BALL_COLORING_MEDIUM, BALL_DISPLACE_BRIGHTNESS, BALL_DISPLACE_PROPERTIES, BALL_SHADING_DEFAULT, ball_action, pixel_polly, scatterize,
};
use super::shatter::{CD_PROPS, CD_SOURCES, SHATTER_PATTERNS, SHATTER_TEXTURE_MODES, card_dance, shatter};
use super::surfaces::{caustics, wave_world};
use super::{EffectSpec, ParamUi, Value, col, num, p, pct, popup, pt, slider, spec};
@@ -80,15 +82,22 @@ pub fn specs() -> Vec<EffectSpec> {
spec(
"ec.sim.ccballaction",
"Ball Grid",
// After Effects' order and defaults since 24.2 (#3197). Scatter Motion is treated as
// the renamed Instability State (an assumption, `migrate::PARAM_ID_ALIASES`). The
// Shading range is not published; -100..100 is an assumption.
vec![
p("gridSpacing", "Grid Spacing", num(5.0), slider(1.0, 200.0, 1.0, 50.0, 0)),
p("ballSize", "Ball Size", num(100.0), slider(0.0, 400.0, 0.0, 200.0, 1)),
p("coloring", "Coloring", Value::Enum(BALL_COLORING_MEDIUM), popup(BALL_COLORING)),
p("shading", "Shading", num(BALL_SHADING_DEFAULT), slider(-100.0, 100.0, -100.0, 100.0, 1)),
p("scatter", "Scatter", num(0.0), slider(0.0, 2000.0, 0.0, 300.0, 1)),
p("scatterMotion", "Scatter Motion", num(0.0), ParamUi::Angle),
p("displace", "Displace", num(0.0), slider(-1000.0, 1000.0, 0.0, 100.0, 1)),
p("displaceProperty", "Displace Property", Value::Enum(BALL_DISPLACE_BRIGHTNESS), popup(BALL_DISPLACE_PROPERTIES)),
p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle),
p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])),
p("rotationAxis", "Rotation Axis", Value::Enum(0), popup(&["X Axis", "Y Axis", "Z Axis", "XY Axis", "XZ Axis", "YZ Axis", "XYZ Axis"])),
p("rotation", "Rotation", num(0.0), ParamUi::Angle),
p("twistProperty", "Twist Property", Value::Enum(0), popup(&["X Axis", "Y Axis", "Radius", "Brightness"])),
p("twistAngle", "Twist Angle", num(0.0), ParamUi::Angle),
p("gridSpacing", "Grid Spacing", num(4.0), slider(1.0, 200.0, 1.0, 50.0, 0)),
p("ballSize", "Ball Size", num(40.0), slider(0.0, 400.0, 0.0, 200.0, 1)),
p("instabilityState", "Instability State", num(0.0), ParamUi::Angle),
],
ball_action,
),
+132
View File
@@ -46,6 +46,138 @@ fn ball_action_draws_balls() {
assert!(sum_diff(&a, &sc) > 1.0);
}
/// #3197: CC Ball Action has After Effects' controls (since 24.2), in its order, with its
/// defaults: Coloring, Shading, Scatter Motion (formerly Instability State), Displace and
/// Displace Property were missing.
#[test]
fn ball_action_has_after_effects_controls() {
let spec = crate::find("ec.sim.ccballaction").unwrap();
let names: Vec<&str> = spec.params.iter().map(|p| p.name).collect();
assert_eq!(
names,
[
"Grid Spacing",
"Ball Size",
"Coloring",
"Shading",
"Scatter",
"Scatter Motion",
"Displace",
"Displace Property",
"Twist Angle",
"Twist Property",
"Rotation Axis",
"Rotation"
]
);
let sp = |id: &str| spec.params.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("no {id}"));
assert_eq!(sp("gridSpacing").default, num(5.0));
assert_eq!(sp("ballSize").default, num(100.0));
assert_eq!(sp("coloring").default, Value::Enum(1));
assert_eq!(sp("coloring").ui, ParamUi::Popup { options: vec!["Crisp".into(), "Medium".into(), "Smooth".into()] });
assert_eq!(sp("shading").default, num(-75.0));
assert!(matches!(sp("shading").ui, ParamUi::Slider { min, max, .. } if min <= -100.0 && max >= 100.0));
assert_eq!(sp("scatterMotion").default, num(0.0));
assert_eq!(sp("scatterMotion").ui, ParamUi::Angle);
assert_eq!(sp("displace").default, num(0.0));
let ParamUi::Popup { options } = &sp("displaceProperty").ui else { panic!("Displace Property is a popup") };
let Value::Enum(d) = sp("displaceProperty").default else { panic!("Displace Property defaults to an option") };
assert_eq!(options.get(d as usize).map(String::as_str), Some("Brightness"));
// Old projects' Instability State becomes Scatter Motion through `PARAM_ID_ALIASES`; the
// engine test `opening_an_old_project_upgrades_effect_instances` covers every alias.
}
/// #3197: the new controls at After Effects' defaults draw exactly what CC Ball Action drew
/// before (the lit sphere, a smooth colour sample, no displacement).
#[test]
fn ball_action_new_controls_at_defaults_keep_the_render() {
let base = [("ballSize", num(80.0)), ("scatter", num(6.0)), ("rotationAxis", Value::Enum(1)), ("rotation", num(25.0))];
let a = run("ec.sim.ccballaction", &base, ramp(32, 32), 0.0);
let mut explicit = base.to_vec();
explicit.extend([
("coloring", Value::Enum(1)),
("shading", num(-75.0)),
("scatterMotion", num(0.0)),
("displace", num(0.0)),
("displaceProperty", Value::Enum(3)),
]);
assert_eq!(a, run("ec.sim.ccballaction", &explicit, ramp(32, 32), 0.0));
}
/// #3197: Shading 0 removes the built-in light: every ball is the layer's flat colour. The
/// default (-75) shades it; a smaller magnitude shades less, a positive value lights the balls
/// from the other side.
#[test]
fn ball_action_shading_zero_is_flat() {
let c = [0.6, 0.3, 0.2, 1.0];
let shade = |v: f64| run("ec.sim.ccballaction", &[("ballSize", num(100.0)), ("gridSpacing", num(8.0)), ("shading", num(v))], Image::filled(32, 32, c), 0.0);
let flat = shade(0.0);
let covered: Vec<&[f32; 4]> = flat.data.iter().filter(|p| p[3] > 0.999).collect();
assert!(!covered.is_empty(), "balls drawn");
for p in &covered {
for k in 0..3 {
assert!((p[k] / p[3] - c[k]).abs() < 1e-4, "flat colour: {p:?}");
}
}
let lit = shade(-75.0);
assert!(lit.data.iter().any(|p| p[3] > 0.999 && (0..3).any(|k| (p[k] / p[3] - c[k]).abs() > 0.05)), "the default shading lights and darkens the balls");
let soft = shade(-30.0);
assert!(sum_diff(&flat, &soft) > 0.1 && sum_diff(&flat, &soft) < sum_diff(&flat, &lit), "less shading, closer to flat");
assert!(sum_diff(&shade(75.0), &lit) > 1.0, "the sign moves the light");
}
/// #3197: Coloring Crisp takes the pixel under each ball's cell centre; Medium samples
/// smoothly between pixels. Grid Spacing 4 puts the cell centres on pixel corners (with the
/// default 5 they fall on pixel centres, where Medium's sample equals Crisp's).
#[test]
fn ball_action_coloring_crisp_takes_the_pixel() {
let mut src = Image::new(32, 32);
for y in 0..32u32 {
for x in 0..32u32 {
src.set(x, y, [x as f32 / 32.0, y as f32 / 32.0, ((x * 7 + y * 3) % 5) as f32 / 4.0, 1.0]);
}
}
let col = |m: u32| {
let v = [("gridSpacing", num(4.0)), ("ballSize", num(100.0)), ("shading", num(0.0)), ("coloring", Value::Enum(m))];
run("ec.sim.ccballaction", &v, src.clone(), 0.0)
};
let crisp = col(0);
// Flat, opaque balls of radius 2 centred on (4i + 2, 4j + 2): the pixel to the lower right
// of each centre is fully covered by its ball alone.
for j in 0..8i64 {
for i in 0..8i64 {
let (x, y) = (4 * i + 2, 4 * j + 2);
let (got, want) = (crisp.get(x, y), src.get(x, y));
assert!((0..4).all(|k| (got[k] - want[k]).abs() < 1e-5), "ball ({i}, {j}): {got:?} vs the pixel {want:?}");
}
}
assert!(sum_diff(&crisp, &col(1)) > 1.0, "medium blends the pixels");
}
/// #3197: a huge Shading (typed or from an expression) is clamped, so the balls stay finite.
#[test]
fn ball_action_huge_shading_stays_finite() {
for v in [1e45, -1e45, f64::MAX] {
let o = run("ec.sim.ccballaction", &[("gridSpacing", num(8.0)), ("shading", num(v))], ramp(32, 32), 0.0);
assert!(o.data.iter().all(|p| p.iter().all(|c| c.is_finite())), "shading {v}");
assert!(o.data.iter().any(|p| p[3] > 0.0), "shading {v}: balls drawn");
}
}
/// #3197: Displace pushes the balls along z by the chosen property (Radius: the centre comes
/// towards the camera and grows); 0 leaves them in the layer's plane.
#[test]
fn ball_action_displace_moves_balls_in_depth() {
let flat = run("ec.sim.ccballaction", &[("ballSize", num(80.0))], ramp(32, 32), 0.0);
let d = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0);
assert_eq!(d, run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(60.0)), ("displaceProperty", Value::Enum(6))], ramp(32, 32), 0.0));
assert!(sum_diff(&flat, &d) > 1.0);
for prop in 0..9 {
let o = run("ec.sim.ccballaction", &[("ballSize", num(80.0)), ("displace", num(400.0)), ("displaceProperty", Value::Enum(prop))], ramp(32, 32), 0.0);
assert!(o.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "property {prop}");
}
}
#[test]
fn pixel_polly_breaks_after_start() {
let v = [("forceCenter", pt(16.0, 16.0)), ("gridSpacing", num(4.0))];
+49 -4
View File
@@ -216,8 +216,16 @@ pub struct Lut {
pub dmax: [f32; 3],
}
// Cube LUT Specification 1.0 §§6–7 permits at most 65,536 1D rows and a 256³
// lattice. Allow their sum for combined shaper + 3D files, regardless of header order.
const MAX_CUBE_ROWS: usize = 65_536 + 256 * 256 * 256;
/// Parse `.cube` text (TITLE, LUT_1D_SIZE, LUT_3D_SIZE, DOMAIN_MIN/MAX, data red-fastest).
pub fn parse_cube(text: &str) -> Option<Lut> {
parse_cube_limited(text, MAX_CUBE_ROWS)
}
fn parse_cube_limited(text: &str, max_rows: usize) -> Option<Lut> {
let mut lut = Lut { n1: 0, d1: vec![], n3: 0, d3: vec![], dmin: [0.0; 3], dmax: [1.0; 3] };
let mut rows: Vec<[f32; 3]> = Vec::new();
let three = |it: &mut std::str::SplitWhitespace| -> Option<[f32; 3]> {
@@ -259,16 +267,27 @@ pub fn parse_cube(text: &str) -> Option<Lut> {
lut.dmax = [hi; 3];
}
k if k.starts_with(|c: char| c.is_ascii_alphabetic()) => continue,
_ => rows.push(three(&mut it)?),
_ => {
if rows.len() == max_rows {
return None;
}
let row = three(&mut it)?;
// Make buffer growth fallible before push can allocate.
rows.try_reserve(1).ok()?;
rows.push(row);
}
}
}
if lut.n3 > 256 {
return None;
}
let need1 = lut.n1;
let need3 = lut.n3 * lut.n3 * lut.n3;
if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 {
if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) {
return None;
}
lut.d1 = rows[..need1].to_vec();
lut.d3 = rows[need1..].to_vec();
lut.d1 = rows.get(..need1)?.to_vec();
lut.d3 = rows.get(need1..)?.to_vec();
Some(lut)
}
@@ -571,6 +590,10 @@ mod tests {
fn bad_cube_is_passthrough() {
assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none());
assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none());
// A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`.
assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none());
assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none());
assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n{}", usize::MAX, "0 0 0\n".repeat(7))).is_none());
let img = test_img();
let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone());
assert_eq!(out.img, img);
@@ -686,6 +709,28 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn cube_accepts_maximum_1d_shaper_with_3d_table() {
let text = format!("LUT_1D_SIZE 65536\nLUT_3D_SIZE 2\n{}", "0 0 0\n".repeat(65_536 + 8));
let lut = parse_cube(&text).unwrap();
assert_eq!(lut.d1.len(), 65_536);
assert_eq!(lut.d3.len(), 8);
// Keep the parser's existing tolerance for headers following data.
let text = format!("{}LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n", "0 0 0\n".repeat(10));
let lut = parse_cube(&text).unwrap();
assert_eq!(lut.d1, vec![[0.0; 3]; 2]);
assert_eq!(lut.d3, vec![[0.0; 3]; 8]);
}
#[test]
fn cube_row_collection_is_bounded() {
assert_eq!(MAX_CUBE_ROWS, 65_536 + 256 * 256 * 256);
let text = "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n";
let lut = parse_cube_limited(text, 2).unwrap();
assert_eq!(lut.d1, vec![[0.0; 3], [1.0; 3]]);
assert!(parse_cube_limited("LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n", 2).is_none());
}
#[test]
fn one_d_lut_with_domain() {
let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap();
+21 -21
View File
@@ -192,7 +192,7 @@ fn cases() -> Vec<(&'static str, Vec<Set>)> {
vec![
vec![],
vec![("scatter", n(20.0)), ("rotationAxis", e(6)), ("rotation", n(40.0)), ("twistProperty", e(3)), ("twistAngle", n(90.0))],
vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))],
vec![("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2)), ("twistAngle", n(30.0))],
],
),
(
@@ -538,26 +538,26 @@ const GOLDEN: &[(&str, u64)] = &[
("ec.sim.particleplayground/8/32bpc/t1.5", 0xb5b7f0281f26baad),
("ec.sim.particleplayground/8/32bpc/t0.8", 0x8b6934363ef4dcfd),
("ec.sim.particleplayground/8/32bpc/t2.2", 0x0a31c17e8e34b9f5),
("ec.sim.ccballaction/0/8bpc/t0.5", 0x12698ec8353be38c),
("ec.sim.ccballaction/0/8bpc/t1.5", 0x12698ec8353be38c),
("ec.sim.ccballaction/0/8bpc/t0.8", 0x12698ec8353be38c),
("ec.sim.ccballaction/0/8bpc/t2.2", 0x12698ec8353be38c),
("ec.sim.ccballaction/0/32bpc/t0.5", 0x3fb733487e120261),
("ec.sim.ccballaction/0/32bpc/t1.5", 0x3fb733487e120261),
("ec.sim.ccballaction/0/32bpc/t0.8", 0x3fb733487e120261),
("ec.sim.ccballaction/0/32bpc/t2.2", 0x3fb733487e120261),
("ec.sim.ccballaction/0/8bpc/half/t0.5", 0x4946070917cc0945),
("ec.sim.ccballaction/0/8bpc/half/t1.5", 0x4946070917cc0945),
("ec.sim.ccballaction/0/8bpc/half/t0.8", 0x4946070917cc0945),
("ec.sim.ccballaction/0/8bpc/half/t2.2", 0x4946070917cc0945),
("ec.sim.ccballaction/1/8bpc/t0.5", 0xf34b3be38a4dd468),
("ec.sim.ccballaction/1/8bpc/t1.5", 0xf34b3be38a4dd468),
("ec.sim.ccballaction/1/8bpc/t0.8", 0xf34b3be38a4dd468),
("ec.sim.ccballaction/1/8bpc/t2.2", 0xf34b3be38a4dd468),
("ec.sim.ccballaction/1/32bpc/t0.5", 0x503b7238edf2912c),
("ec.sim.ccballaction/1/32bpc/t1.5", 0x503b7238edf2912c),
("ec.sim.ccballaction/1/32bpc/t0.8", 0x503b7238edf2912c),
("ec.sim.ccballaction/1/32bpc/t2.2", 0x503b7238edf2912c),
("ec.sim.ccballaction/0/8bpc/t0.5", 0x5f7401d3d1e5a513),
("ec.sim.ccballaction/0/8bpc/t1.5", 0x5f7401d3d1e5a513),
("ec.sim.ccballaction/0/8bpc/t0.8", 0x5f7401d3d1e5a513),
("ec.sim.ccballaction/0/8bpc/t2.2", 0x5f7401d3d1e5a513),
("ec.sim.ccballaction/0/32bpc/t0.5", 0x9cf15a7756ab88ed),
("ec.sim.ccballaction/0/32bpc/t1.5", 0x9cf15a7756ab88ed),
("ec.sim.ccballaction/0/32bpc/t0.8", 0x9cf15a7756ab88ed),
("ec.sim.ccballaction/0/32bpc/t2.2", 0x9cf15a7756ab88ed),
("ec.sim.ccballaction/0/8bpc/half/t0.5", 0xe2e3a624434f8e88),
("ec.sim.ccballaction/0/8bpc/half/t1.5", 0xe2e3a624434f8e88),
("ec.sim.ccballaction/0/8bpc/half/t0.8", 0xe2e3a624434f8e88),
("ec.sim.ccballaction/0/8bpc/half/t2.2", 0xe2e3a624434f8e88),
("ec.sim.ccballaction/1/8bpc/t0.5", 0x07382912d068a625),
("ec.sim.ccballaction/1/8bpc/t1.5", 0x07382912d068a625),
("ec.sim.ccballaction/1/8bpc/t0.8", 0x07382912d068a625),
("ec.sim.ccballaction/1/8bpc/t2.2", 0x07382912d068a625),
("ec.sim.ccballaction/1/32bpc/t0.5", 0xa1e843936e72815f),
("ec.sim.ccballaction/1/32bpc/t1.5", 0xa1e843936e72815f),
("ec.sim.ccballaction/1/32bpc/t0.8", 0xa1e843936e72815f),
("ec.sim.ccballaction/1/32bpc/t2.2", 0xa1e843936e72815f),
("ec.sim.ccballaction/2/8bpc/t0.5", 0x0b6bf26753ee4582),
("ec.sim.ccballaction/2/8bpc/t1.5", 0x0b6bf26753ee4582),
("ec.sim.ccballaction/2/8bpc/t0.8", 0x0b6bf26753ee4582),
@@ -2,7 +2,7 @@
//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys
//! those releases saved: if a type change alters this text, write that part out here.
use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid};
use effectcraft_project::{Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, ParamUi, Project, PropGroup, Uid};
use super::fnv;
@@ -41,12 +41,40 @@ pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String {
if g.uid == uid {
break;
}
s.push_str(&format!("{g:?}"));
s.push_str(&effect_text(g));
}
}
format!("{:016x}", fnv(&s))
}
/// Slider ranges as 0.22–0.24 gave them, for parameters whose range has changed since, as
/// (effect, parameter path, [min, max, slider min, slider max], decimals). Those releases hashed
/// each effect's UI hints into the Roto Brush Input Key, and opening a project replaces an
/// instance's hints with the current ones, so [`effect_text`] puts these back. A range change
/// above a Roto Brush would otherwise drop the analysis such a key kept: add a row with it.
/// Not every range changed since 0.24.1 has its row yet (#3815).
#[rustfmt::skip]
const SLIDERS_0_24: &[(&str, &str, [f64; 4], u8)] = &[
("ec.blur.gaussian", "blurriness", [0.0, 3000.0, 0.0, 50.0], 1),
];
/// An effect instance as 0.22–0.24 wrote it into a Roto Brush Input Key: its derived `Debug`,
/// with the [`SLIDERS_0_24`] ranges in place of today's.
pub(crate) fn effect_text(g: &PropGroup) -> String {
let GroupKind::Effect { effect } = &g.kind else { return format!("{g:?}") };
let mut rows = SLIDERS_0_24.iter().filter(|r| r.0 == effect).peekable();
if rows.peek().is_none() {
return format!("{g:?}");
}
let mut g = g.clone();
for &(_, path, [min, max, slider_min, slider_max], decimals) in rows {
if let Some(p) = g.prop_mut(path).filter(|p| matches!(p.ui, ParamUi::Slider { .. })) {
p.ui = ParamUi::Slider { min, max, slider_min, slider_max, decimals };
}
}
format!("{g:?}")
}
/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23),
/// with `missing` in place of the item's.
pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String {
+1 -1
View File
@@ -17,7 +17,7 @@ fn export_lottie(s: &mut Session, p: &Value) -> Result<Value> {
let dot = path.to_ascii_lowercase().ends_with(".lottie");
let bytes = if dot {
let stem = std::path::Path::new(&path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
effectcraft_lottie::to_dotlottie(&res, &stem)
effectcraft_lottie::try_to_dotlottie(&res, &stem).map_err(|e| EngineError::Other(e.to_string()))?
} else {
res.to_string_compact().into_bytes()
};
+8
View File
@@ -167,6 +167,13 @@ pub struct Session {
pub journal: Vec<(String, Value)>,
/// Processed-layer pixels reused across frames and edits (content-keyed, never stale).
pub layer_cache: Arc<LayerCache>,
/// Set when this project closes ([`Session::replace_project`]), then replaced by a fresh flag
/// for the next one: work started for the project off the UI thread (Project panel
/// thumbnails) stops reading its footage and lets go of what it read, so it can't fill the
/// shared caches with a closed project's frames. Public only so that other crates can build a
/// `Session { .. }`.
#[doc(hidden)]
pub project_closed: Arc<std::sync::atomic::AtomicBool>,
/// The last Cryptomatte pick probe (see [`Session::crypto_probe_job`]). Public only so that
/// other crates can build a `Session { .. }`; its type is crate-private.
#[doc(hidden)]
@@ -351,6 +358,7 @@ impl Default for Session {
events: vec![],
journal: vec![],
layer_cache: Arc::new(LayerCache::default()),
project_closed: Default::default(),
crypto_probe: Default::default(),
disk_cache: None,
pending_disk_drops: Default::default(),
+12 -6
View File
@@ -196,6 +196,9 @@ impl Session {
/// Replace the whole project (open/new), resetting history and state.
pub fn replace_project(&mut self, mut p: Project, path: Option<String>) {
// Work still running for the closed project stops reading it (see `project_closed`).
self.project_closed.store(true, std::sync::atomic::Ordering::SeqCst);
self.project_closed = Arc::default();
if self.stop_render()
&& let Some(mut job) = self.render_job.take()
{
@@ -221,13 +224,13 @@ impl Session {
self.script_ui.project_epoch = self.script_ui.project_epoch.wrapping_add(1);
p.fix_next_id();
upgrade_effects(&mut p);
// The media layer keys decoded frames by path: files of the new project may have changed
// since an earlier project decoded them (#1070).
for it in p.items.values() {
if let effectcraft_project::ItemKind::Footage(f) = &it.kind {
self.forget_decoded(f);
}
// Let go of what the closed project's footage and proxies decoded (frames, decoders,
// models), and of what the new project's files decoded under an earlier project: the
// media layer keys them by path, and the files may have changed since (#1070).
for f in super::render::project_footage(&self.project).chain(super::render::project_footage(&p)) {
super::render::forget_files(self.footage.as_ref(), f);
}
self.drop_crypto_probe();
self.layer_cache.clear();
self.project = Arc::new(p);
// The set of footage effects read the channels of is sent again, even when it is empty.
@@ -237,6 +240,9 @@ impl Session {
self.path = path;
self.bump();
self.mark_saved();
// The viewers' RAM preview shows the closed project's frames, whose comp ids can collide
// with the new project's.
self.events.push(Event::PurgeCaches);
let first = self.project.comps().next().map(|(id, _)| *id);
if let Some(c) = first {
self.open_comp(c);
+48 -8
View File
@@ -1,3 +1,7 @@
use std::sync::atomic::Ordering;
use effectcraft_render::{CancellableFootage, FootageSource};
use super::{EngineError, Image, ItemId, RenderOpts, Renderer, Result, Session, ThumbnailJob, Tick, Value, commands};
impl Session {
@@ -77,9 +81,12 @@ impl Session {
/// A Project panel thumbnail of an item (a comp at `t`, footage at its first frame), longest
/// side at most `max_side`, as a job that owns everything it reads: frontends run it off the
/// UI thread (a big comp takes far longer than a frame). `None` for items without pixels.
/// Once the project closes ([`Session::replace_project`]) the job reads no more and answers
/// `None`, after letting go of what it read meanwhile: a thread that started late or decoded
/// through Close can't fill the shared caches with the closed project's frames.
pub fn thumbnail_job(&self, item: ItemId, t: Tick, max_side: u32) -> Option<ThumbnailJob> {
let it = self.project.item(item)?;
let footage = self.footage.clone();
let (footage, closed) = (self.footage.clone(), self.project_closed.clone());
match &it.kind {
effectcraft_project::ItemKind::Comp(c) => {
let (project, expr, cache) = (self.project.clone(), self.expr.clone(), self.layer_cache.clone());
@@ -93,21 +100,38 @@ impl Session {
};
let bg = c.background;
Some(Box::new(move || {
let mut r = Renderer::new(&project, footage.as_ref(), opts);
if closed.load(Ordering::SeqCst) {
return None;
}
let src = CancellableFootage { inner: footage.as_ref(), cancel: closed.clone() };
let mut r = Renderer::new(&project, &src, opts);
r.expr = expr.as_deref();
r.cache = Some(&cache);
let img = r.comp_frame(item, t);
if closed.load(Ordering::SeqCst) {
project_footage(&project).for_each(|f| forget_files(footage.as_ref(), f));
cache.clear();
return None;
}
Some((img.width, img.height, img.to_rgba8_over(bg)))
}))
}
effectcraft_project::ItemKind::Footage(f) if f.has_video => {
let f = f.clone();
Some(Box::new(move || {
if closed.load(Ordering::SeqCst) {
return None;
}
// Vector footage is drawn at the thumbnail's size: its declared size can be a
// 16384² canvas, gigabytes of pixels to point-sample down to a few dozen.
let scale = (max_side.max(1) as f64 / f.width.max(f.height).max(1) as f64).min(1.0);
let src = footage.vector_frame(item, &f, scale).or_else(|| footage.frame(item, &f, Tick(0)))?;
let img = effectcraft_render::cineon_frame(src, &f);
let read = CancellableFootage { inner: footage.as_ref(), cancel: closed.clone() };
let src = read.vector_frame(item, &f, scale).or_else(|| read.frame(item, &f, Tick(0)));
if closed.load(Ordering::SeqCst) {
forget_files(footage.as_ref(), &f);
return None;
}
let img = effectcraft_render::cineon_frame(src?, &f);
// Point-sample down to at most `max_side` on the long side (a drawn size one
// pixel over it, from rounding, is shrunk by that pixel, not halved).
let (long, max) = (u64::from(img.width.max(img.height)), u64::from(max_side.max(1)));
@@ -119,7 +143,7 @@ impl Session {
for x in 0..w {
let (sx, sy) = (u64::from(x) * u64::from(img.width) / u64::from(w), u64::from(y) * u64::from(img.height) / u64::from(h));
let i = ((sy * u64::from(img.width) + sx) * 4) as usize;
px.extend_from_slice(&full[i..i + 4]);
px.extend_from_slice(full.get(i..i + 4)?);
}
}
Some((w, h, px))
@@ -145,9 +169,7 @@ impl Session {
/// Make the media layer and the layer cache let go of what they decoded from `footage`'s
/// files (it keys frames by path, so an overwritten file would keep showing its old pixels).
pub(crate) fn forget_decoded(&self, footage: &effectcraft_project::Footage) {
for p in std::iter::once(&footage.path).chain(&footage.sequence) {
self.footage.forget(p);
}
forget_files(self.footage.as_ref(), footage);
self.layer_cache.clear();
self.drop_crypto_probe();
}
@@ -191,3 +213,21 @@ pub(crate) fn aux_footage(project: &effectcraft_project::Project) -> Vec<String>
paths.dedup();
paths
}
/// Make `src` let go of what it decoded from `footage`'s files (its file, or a sequence's).
pub(crate) fn forget_files(src: &dyn FootageSource, footage: &effectcraft_project::Footage) {
for p in std::iter::once(&footage.path).chain(&footage.sequence) {
src.forget(p);
}
}
/// Every footage `project` shows: its footage items and the proxies of its items.
pub(crate) fn project_footage(project: &effectcraft_project::Project) -> impl Iterator<Item = &effectcraft_project::Footage> {
project.items.values().flat_map(|it| {
let own = match &it.kind {
effectcraft_project::ItemKind::Footage(f) => Some(f),
_ => None,
};
own.into_iter().chain(it.proxy.as_deref().map(|px| &px.footage))
})
}
+240 -15
View File
@@ -255,6 +255,80 @@ fn release_problem(r: &Release) -> Option<String> {
None
}
/// An owner or repository name on GitHub: letters, digits, `.`, `-`, `_`, and not `.` or `..`.
fn valid_repo_part(p: &str) -> bool {
!p.is_empty() && p != "." && p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
/// The rest of `s` after `prefix`, ignoring ASCII case.
fn strip_prefix_ignore_case<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
let head = s.get(..prefix.len())?;
head.eq_ignore_ascii_case(prefix).then(|| s.get(prefix.len()..)).flatten()
}
/// A `.` or `..` path segment, also percent-encoded.
fn dot_segment(p: &str) -> bool {
let p = p.to_ascii_lowercase().replace("%2e", ".");
p == "." || p == ".."
}
/// A character a release or repository URL may not contain: `?`, `#`, `\`, Unicode white space,
/// or U+FEFF (the catalog schema's `\s` matches it too).
fn bad_url_char(c: char) -> bool {
matches!(c, '?' | '#' | '\\' | '\u{feff}') || c.is_whitespace()
}
/// `(owner, name)` in lower case of a `https://github.com/<owner>/<name>` repository URL (an
/// optional trailing `/` or `.git`) or of a folder in one, `https://github.com/<owner>/<name>/tree/<ref>/<path>`;
/// `None` for anything else.
fn github_repo(repo: &str) -> Option<(String, String)> {
let rest = strip_prefix_ignore_case(repo.trim(), "https://github.com/")?;
if rest.contains(bad_url_char) {
return None;
}
let rest = rest.strip_suffix('/').unwrap_or(rest);
let parts: Vec<&str> = rest.split('/').collect();
let (owner, name) = match parts.as_slice() {
[owner, name] => (*owner, name.strip_suffix(".git").unwrap_or(name)),
[owner, name, "tree", folder @ ..] if !folder.is_empty() && folder.iter().all(|p| !p.is_empty() && !dot_segment(p)) => (*owner, *name),
_ => return None,
};
(valid_repo_part(owner) && valid_repo_part(name)).then(|| (owner.to_ascii_lowercase(), name.to_ascii_lowercase()))
}
/// Why an `https://` release URL can't be used, if it can't: it must be a release asset,
/// `https://github.com/<owner>/<name>/releases/download/<tag>/<file>`, and when the package
/// names a `repo`, that must be a GitHub repository URL (see [`github_repo`]) of `<owner>/<name>`.
fn release_url_problem(repo: &str, url: &str) -> Option<String> {
let not_asset = || Some(format!("`{url}` isn't a release asset (https://github.com/<owner>/<repo>/releases/download/<tag>/<file>)"));
let Some(rest) = strip_prefix_ignore_case(url, "https://github.com/") else { return not_asset() };
if rest.contains(bad_url_char) {
return not_asset();
}
let parts: Vec<&str> = rest.split('/').collect();
// At least six segments, not exactly six: a tag may contain `/` (`release/v1`), and its assets are
// then at `releases/download/release/v1/<file>`. `.` and `..` (also percent-encoded) would move
// the download to another path.
if parts.len() < 6 || parts.iter().any(|p| p.is_empty() || dot_segment(p)) {
return not_asset();
}
let (Some(owner), Some(name), Some(releases), Some(download)) = (parts.first(), parts.get(1), parts.get(2), parts.get(3)) else { return not_asset() };
if !valid_repo_part(owner) || !valid_repo_part(name) || *releases != "releases" || *download != "download" {
return not_asset();
}
let repo = repo.trim();
if repo.is_empty() {
return None;
}
match github_repo(repo) {
Some((o, n)) if o == owner.to_ascii_lowercase() && n == name.to_ascii_lowercase() => None,
Some(_) => Some(format!("`{url}` isn't a release asset of the package's repository {repo}")),
None => Some(format!(
"the package's `repo` {repo} isn't a GitHub repository URL (https://github.com/<owner>/<repo>), so `{url}` can't be checked against it"
)),
}
}
/// Read a catalog: packages and releases that are malformed are left out (and reported), so one
/// bad entry doesn't hide the others.
pub fn parse_catalog(bytes: &[u8]) -> std::result::Result<(Catalog, Vec<String>), String> {
@@ -325,27 +399,44 @@ enum Source {
File(PathBuf),
}
/// `file:///C:/x` or `file:///home/x` as a path (percent-decoded; no remote hosts).
fn file_url_path(url: &str) -> Option<PathBuf> {
let rest = url.strip_prefix("file://")?;
/// `file:///C:/x` or `file:///home/x` as a path (percent-decoded; no remote hosts). A path that
/// starts with two separators or holds a `\` (raw or percent-encoded), or a percent-encoded `/`,
/// is refused: on Windows such a path can name a network share, and reading it contacts that host.
fn file_url_path(url: &str) -> std::result::Result<PathBuf, String> {
let bad = |why: &str| format!("bad file URL `{url}`: {why}");
let rest = url.strip_prefix("file://").ok_or_else(|| bad("it doesn't start with file://"))?;
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
if !rest.starts_with('/') {
return None;
return Err(bad("only local files can be read (file:///path)"));
}
let b = rest.as_bytes();
// `/C:/…` on Windows.
let rest = if b.len() > 2 && b.get(2) == Some(&b':') { rest.get(1..)? } else { rest };
let rest =
if b.get(1).is_some_and(u8::is_ascii_alphabetic) && b.get(2) == Some(&b':') { rest.get(1..).ok_or_else(|| bad("bad drive letter"))? } else { rest };
let mut out = Vec::with_capacity(rest.len());
let mut bytes = rest.bytes();
while let Some(c) = bytes.next() {
if c == b'%' {
let hex = [bytes.next()?, bytes.next()?];
out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
let hex = [bytes.next(), bytes.next()];
let [Some(hi), Some(lo)] = hex else { return Err(bad("a % isn't followed by two hex digits")) };
let byte =
std::str::from_utf8(&[hi, lo]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()).ok_or_else(|| bad("a % isn't followed by two hex digits"))?;
if matches!(byte, b'/' | b'\\') {
return Err(bad("a percent-encoded / or \\ isn't allowed"));
}
out.push(byte);
} else {
out.push(c);
}
}
String::from_utf8(out).ok().map(PathBuf::from)
let path = String::from_utf8(out).map_err(|_| bad("the path isn't UTF-8"))?;
if path.contains('\\') {
return Err(bad("use / between folders, not \\"));
}
if path.starts_with("//") {
return Err(bad("network paths can't be read, only local files"));
}
Ok(PathBuf::from(path))
}
/// Check `url` against the rules: `https://` on GitHub's hosts; `file://` when the catalog
@@ -360,7 +451,7 @@ fn source(url: &str, catalog: Option<&str>) -> std::result::Result<Source, Strin
}
let local_catalog = catalog.is_none_or(|c| c.starts_with("file://"));
if url.starts_with("file://") && local_catalog {
return file_url_path(url).map(Source::File).ok_or_else(|| format!("bad file URL `{url}`"));
return file_url_path(url).map(Source::File);
}
Err(format!("`{url}` isn't an https:// URL"))
}
@@ -801,7 +892,11 @@ fn pick(s: &Session, c: &str, p: &Value) -> Result<(String, Package, Release)> {
),
));
}
source(&rel.url, Some(&url)).map_err(|e| bad(c, e))?;
if let Source::Https(u) = source(&rel.url, Some(&url)).map_err(|e| bad(c, e))?
&& let Some(why) = release_url_problem(&pkg.repo, &u)
{
return Err(bad(c, format!("{}: {why}", pkg.name)));
}
Ok((url, pkg, rel))
}
@@ -1033,7 +1128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Refresh Plug-in Catalog",
[],
None,
"{catalog?: https:// or file:// URL of an index.json (default: the community catalog), wait?}",
"{catalog?: https:// or file:// URL of an index.json (default: the community catalog; file:// takes a local path, not a network path such as //server/share), wait?}",
always,
refresh
),
@@ -1051,7 +1146,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{id, version?, wait?} — downloads the release, checks its SHA-256 against the catalog, loads it",
"{id, version?, wait?} — downloads the release (a GitHub release asset, in the package's repo when it names one), checks its SHA-256 against the catalog, loads it",
always,
install
),
@@ -1135,6 +1230,99 @@ mod tests {
assert!(latest_compatible(&Package::default()).is_none());
}
#[test]
fn release_urls_are_assets_of_the_declared_repository() {
let asset = "https://github.com/Me/Glow/releases/download/v1.0.0/glow.wasm";
for repo in ["https://github.com/me/glow", "https://github.com/Me/Glow/", "https://GitHub.com/me/glow.git", ""] {
assert_eq!(release_url_problem(repo, asset), None, "{repo}");
}
assert_eq!(release_url_problem("", "https://github.com/a/b/releases/download/tags/v1/x.wasm"), None, "a tag with a slash");
assert!(
release_url_problem("https://github.com/me/glow", "https://github.com/me/other/releases/download/v1/x.wasm")
.unwrap()
.contains("package's repository")
);
assert!(release_url_problem("https://github.com/me/glow", "https://github.com/you/glow/releases/download/v1/x.wasm").is_some());
for no in [
"https://raw.githubusercontent.com/me/glow/main/x.wasm",
"https://objects.githubusercontent.com/x.wasm",
"https://github.com/me/glow/blob/main/x.wasm",
"https://github.com/me/glow/releases/download/v1",
"https://github.com/me/glow/releases/download//x.wasm",
"https://github.com/me/glow/releases/download/v1/x.wasm?x=1",
"https://github.com/me/glow/releases/download/v1/x.wasm#x",
"https://github.com/me/glow/releases/download/../../../you/evil/releases/download/v1/x.wasm",
"https://github.com/me/glow/releases/download/%2e%2e/%2E./x/y/x.wasm",
"https://github.com/me/glow/releases/download/./v1/x.wasm",
"https://github.com/me/glow/releases/download/v1\\x.wasm",
"https://github.com/m e/glow/releases/download/v1/x.wasm",
"https://github.com/me/glow/releases/download/v 1/x.wasm",
"https://github.com/me/glow/releases/download/v1/x\t.wasm",
"https://github.com/me/glow/releases/download/v1/x.wasm\n",
"https://github.com/me/glow/releases/download/v1\u{a0}/x.wasm",
"https://github.com/me/glow/releases/download/v1/\u{85}x.wasm",
"https://github.com/me/glow/releases/download/v1/x\u{feff}.wasm",
"https://github.com/../glow/releases/download/v1/x.wasm",
"https://github.com.evil.com/me/glow/releases/download/v1/x.wasm",
] {
assert!(release_url_problem("https://github.com/me/glow", no).is_some(), "{no}");
assert!(release_url_problem("", no).is_some(), "{no}");
}
assert_eq!(github_repo("https://github.com/Me/Glow.git"), Some(("me".into(), "glow".into())));
assert_eq!(github_repo("https://github.com/Me/Glow/tree/main/plugins/glow"), Some(("me".into(), "glow".into())));
for no in ["https://github.com/me", "https://github.com/me/glow/tree", "http://github.com/me/glow", "me/glow"] {
assert_eq!(github_repo(no), None, "{no}");
}
}
#[test]
fn a_repo_that_isnt_a_github_repository_url_refuses_every_release() {
let asset = "https://github.com/me/glow/releases/download/v1/glow.wasm";
for repo in [
"https://github.com/me/glow",
"https://github.com/me/glow/",
"https://github.com/me/glow.git",
"https://github.com/me/glow.git/",
" https://github.com/ME/glow ",
"https://github.com/me/glow/tree/main",
"https://github.com/me/glow/tree/main/plugins/glow/",
"",
" ",
] {
assert_eq!(release_url_problem(repo, asset), None, "{repo:?}");
}
let elsewhere = release_url_problem("https://github.com/me/glow/tree/main", "https://github.com/you/evil/releases/download/v1/glow.wasm");
assert!(elsewhere.as_deref().is_some_and(|w| w.contains("package's repository")), "{elsewhere:?}");
for repo in [
"https://github.com/me/glow/tree",
"https://github.com/me/glow/tree/",
"https://github.com/me/glow/tree//x",
"https://github.com/me/glow/tree/main/../../you/evil",
"https://github.com/me/glow/tree/main/%2e%2e",
"https://github.com/me/glow/blob/main/README.md",
"https://github.com/me/glow.git/x",
"https://github.com/me/glow/releases",
"https://github.com/me/glow//",
"https://github.com/me",
"https://github.com/me/",
"http://github.com/me/glow",
"github.com/me/glow",
"me/glow",
"https://www.github.com/me/glow",
"https://gitlab.com/me/glow",
"https://github.com/me/glow?tab=readme",
"https://github.com/me/glow#readme",
"https://github.com/me/gl ow",
"https://github.com/me/glow/tree/main/my plug-in",
"https://github.com/me/glow/tree/ma\tin",
"https://github.com/me/glow/tree/main/x\u{feff}",
"https://github.com/me/..",
] {
let why = release_url_problem(repo, asset);
assert!(why.as_deref().is_some_and(|w| w.contains("isn't a GitHub repository URL")), "{repo:?}: {why:?}");
}
}
#[test]
fn catalogs_leave_out_bad_entries() {
let good = "a".repeat(64);
@@ -1180,10 +1368,47 @@ mod tests {
assert_eq!(source("file:///C:/p/x.wasm", None), Ok(Source::File(PathBuf::from("C:/p/x.wasm"))));
assert!(source("file://", None).is_err());
// Percent-decoded; no remote hosts.
assert_eq!(file_url_path("file:///C:/My%20Plug-ins/Jos%C3%A9%23.wasm"), Some(PathBuf::from("C:/My Plug-ins/José#.wasm")));
assert_eq!(file_url_path("file://localhost/home/x.wasm"), Some(PathBuf::from("/home/x.wasm")));
assert_eq!(file_url_path("file:///C:/My%20Plug-ins/Jos%C3%A9%23.wasm"), Ok(PathBuf::from("C:/My Plug-ins/José#.wasm")));
assert_eq!(file_url_path("file://localhost/home/x.wasm"), Ok(PathBuf::from("/home/x.wasm")));
for no in ["file://server/share/x.wasm", "file:///bad%2", "file:///bad%zz"] {
assert_eq!(file_url_path(no), None, "{no}");
assert!(file_url_path(no).is_err(), "{no}");
}
}
#[test]
fn file_urls_cannot_name_a_network_path() {
for ok in [
("file:///C:/p/x.wasm", "C:/p/x.wasm"),
("file:///c:/p/x.wasm", "c:/p/x.wasm"),
("file:///home/me/x.wasm", "/home/me/x.wasm"),
("file://localhost/C:/p/x.wasm", "C:/p/x.wasm"),
("file:///home/me/a%20b/x.wasm", "/home/me/a b/x.wasm"),
("file:///C:/p//x.wasm", "C:/p//x.wasm"),
] {
assert_eq!(file_url_path(ok.0), Ok(PathBuf::from(ok.1)), "{}", ok.0);
}
for no in [
// Two separators at the start: `//server/share/…`.
"file:////server/share/x.wasm",
"file://localhost//server/share/x.wasm",
"file://///server/share/x.wasm",
"file:////:x.wasm",
// Backslashes, raw or percent-encoded.
"file:///\\\\server\\share\\x.wasm",
"file:///\\server/share/x.wasm",
"file:///C:\\p\\x.wasm",
"file:///%5C%5Cserver/share/x.wasm",
"file:///%5c%5cserver/share/x.wasm",
"file:///C:/p%5Cx.wasm",
// Percent-encoded slashes.
"file:///%2F%2Fserver/share/x.wasm",
"file:///%2fserver/share/x.wasm",
"file:///C:/p%2Fx.wasm",
] {
let e = file_url_path(no).expect_err(no);
assert!(e.starts_with("bad file URL"), "{no}: {e}");
assert!(source(no, None).is_err(), "{no}");
assert!(source(no, Some("file:///tmp/index.json")).is_err(), "{no}");
}
}
+1
View File
@@ -46,6 +46,7 @@ mod motion_blur_depth;
mod paint;
mod panels;
mod project_items;
mod project_release;
mod proxy;
mod quick_offset;
mod render_overwrite;
+14 -1
View File
@@ -5,7 +5,7 @@ use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
use effectcraft_effects::roto::{FROZEN, INPUT_KEY};
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
use effectcraft_keyframe::Value;
use effectcraft_project::{ItemId, LayerId, Project};
use effectcraft_project::{GroupKind, ItemId, LayerId, ParamUi, Project};
use serde_json::json;
use crate::Session;
@@ -93,6 +93,19 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() {
assert_eq!(saved(&s), before);
}
/// 0.24 hashed each effect's UI hints into the Roto Brush's key, and opening a project takes the
/// current ones: the legacy text puts back Gaussian Blur's 0.24 Blurriness range (#3460).
#[test]
fn legacy_roto_keys_hash_the_0_24_blurriness_range() {
let s = open(ANALYSED_0_24);
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let is_blur = |kind: &GroupKind| matches!(kind, GroupKind::Effect { effect } if effect == "ec.blur.gaussian");
let blur = layer.effects().and_then(|fx| fx.groups().find(|g| is_blur(&g.kind))).expect("the fixture has a Gaussian Blur above the Roto Brush");
let mut as_0_24 = blur.clone();
as_0_24.get_mut("blurriness").unwrap().ui = ParamUi::Slider { min: 0.0, max: 3000.0, slider_min: 0.0, slider_max: 50.0, decimals: 1 };
assert_eq!(crate::analysis::frames_key::legacy::effect_text(blur), format!("{as_0_24:?}"));
}
/// The text keys are made from today, written field by field (#3536). It changes only when this
/// test is changed with it: a new field of a type it writes doesn't compile until it is decided
/// in `analysis::frames_key`, and renaming a field or variant doesn't change it.
+28
View File
@@ -60,6 +60,17 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[
(3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0),
(3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0),
(3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0),
(3464, "ec.perspective.dropshadow", "softness", 0.0, 30000.0),
(3467, "ec.blur.radial", "amount", 0.0, 1000.0),
(3460, "ec.blur.gaussian", "blurriness", 0.0, 30000.0),
(3469, "ec.distort.turbulentdisplace", "amount", -10000.0, 10000.0),
(3492, "ec.distort.ccpowerpin", "expandTop", -200.0, 1000.0),
(3492, "ec.distort.ccpowerpin", "expandLeft", -200.0, 1000.0),
(3492, "ec.distort.ccpowerpin", "expandRight", -200.0, 1000.0),
(3492, "ec.distort.ccpowerpin", "expandBottom", -200.0, 1000.0),
(3486, "ec.noise.fractal", "subSettings/subScaling", 10.0, 10000.0),
(3486, "ec.noise.turbulent", "subSettings/subScaling", 10.0, 10000.0),
(3466, "ec.blur.sharpen", "amount", 0.0, 4000.0),
];
fn path(effect: &str, param: &str) -> String {
@@ -161,6 +172,23 @@ fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() {
}
}
/// #3466: Sharpen Amount clamps just outside After Effects' 0..4000, and an undo after a
/// clamped set restores the value from before it.
#[test]
fn sharpen_amount_clamps_outside_the_after_effects_range() {
let (mut s, l, _) = session();
let (e, p) = ("ec.blur.sharpen", "amount");
for (v, want) in [(4001.0, 4000.0), (-1.0, 0.0)] {
set(&mut s, l, e, p, 1000.0);
assert_eq!(set(&mut s, l, e, p, v), json!(want), "{v}: prop.set reply");
assert_eq!(read(&mut s, l, e, p), want, "{v}");
assert!(s.undo());
assert_eq!(read(&mut s, l, e, p), 1000.0, "{v}: undo");
assert!(s.redo());
assert_eq!(read(&mut s, l, e, p), want, "{v}: redo");
}
}
/// The property at `path` (`group/param`) in an effect instance.
fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> {
match path.split_once('/') {
+1 -1
View File
@@ -192,7 +192,7 @@ fn an_overridden_lut_file_renders_again() {
#[test]
fn ocio_files_render_again_from_warm_caches() {
let dir = tempfile::tempdir().unwrap();
let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube"));
let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts").join("grade.cube"));
std::fs::create_dir_all(dir.path().join("luts")).unwrap();
write(&lut, BLACK, 1_000);
write(&grade, BLACK, 1_000);
+161
View File
@@ -0,0 +1,161 @@
//! Close, New and Open Project let go of what the closed project decoded (#2042).
use std::sync::{Arc, Mutex};
use effectcraft_project::{Footage, ItemId, ItemKind, Project};
use effectcraft_time::Tick;
use serde_json::json;
use crate::render::{FootageSource, Image};
use crate::{Event, Session};
/// A footage source that records the paths it is told to forget.
#[derive(Default)]
struct Recording(Mutex<Vec<String>>);
impl FootageSource for Recording {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
None
}
fn forget(&self, path: &str) {
self.0.lock().unwrap().push(path.to_string());
}
}
fn with_footage(base: &Project, name: &str, path: &str) -> Project {
let mut p = base.clone();
p.add_item(name, Default::default(), None, ItemKind::Footage(Footage { path: path.into(), ..Default::default() }));
p
}
#[test]
fn replacing_project_releases_old_footage() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Main", "width": 640, "height": 360, "frameRate": 30, "duration": 10})).unwrap();
let src = Arc::new(Recording::default());
s.footage = src.clone();
let recorded = || src.0.lock().unwrap().clone();
let open_old = |s: &mut Session| {
let old = with_footage(&s.project, "old", "/old.mp4");
s.replace_project(old, None);
s.drain_events();
src.0.lock().unwrap().clear();
};
// Close Project lets go of the closed project's footage and clears the RAM preview.
open_old(&mut s);
s.execute("file.closeProject", json!({})).unwrap();
assert!(recorded().contains(&"/old.mp4".to_string()), "{:?}", recorded());
assert!(s.drain_events().contains(&Event::PurgeCaches));
// Opening a project forgets the old project's files and the new project's.
open_old(&mut s);
s.replace_project(with_footage(&Project::default(), "new", "/new.mp4"), None);
let paths = recorded();
assert!(paths.contains(&"/old.mp4".to_string()) && paths.contains(&"/new.mp4".to_string()), "{paths:?}");
assert!(s.drain_events().contains(&Event::PurgeCaches));
// New Project does the same.
open_old(&mut s);
s.execute("file.newProject", json!({})).unwrap();
assert!(recorded().contains(&"/old.mp4".to_string()), "{:?}", recorded());
assert!(s.drain_events().contains(&Event::PurgeCaches));
}
#[test]
fn closing_a_project_releases_its_proxies() {
let mut s = Session::default();
let src = Arc::new(Recording::default());
s.footage = src.clone();
let mut p = with_footage(&Project::default(), "old", "/old.mp4");
let item = p.items.values_mut().next().unwrap();
let footage = Footage { path: "/old-proxy.mov".into(), ..Default::default() };
item.proxy = Some(Box::new(effectcraft_project::Proxy { footage, enabled: true }));
s.replace_project(p, None);
src.0.lock().unwrap().clear();
s.execute("file.closeProject", json!({})).unwrap();
assert!(src.0.lock().unwrap().contains(&"/old-proxy.mov".to_string()), "{:?}", src.0.lock().unwrap());
}
/// A footage source with a memory cache, like the media pool: a frame read keeps its file's
/// entry until the file is forgotten. With a gate, the first read waits for the test.
#[derive(Default)]
struct Caching {
cached: Mutex<std::collections::HashSet<String>>,
gate: Mutex<Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>>,
}
impl FootageSource for Caching {
fn frame(&self, _: ItemId, footage: &Footage, _: Tick) -> Option<Arc<Image>> {
let gate = self.gate.lock().unwrap().take();
if let Some((entered, go)) = gate {
entered.send(()).unwrap();
go.recv().unwrap();
}
self.cached.lock().unwrap().insert(footage.path.clone());
Some(Arc::new(Image::new(footage.width, footage.height)))
}
fn forget(&self, path: &str) {
self.cached.lock().unwrap().remove(path);
}
}
/// A session showing `/old.png` (a footage item, and a comp with a layer of it) through a
/// [`Caching`] source: (session, source, footage item, comp).
fn old_project() -> (Session, Arc<Caching>, ItemId, ItemId) {
let mut s = Session::default();
let src = Arc::new(Caching::default());
s.footage = src.clone();
let still = Footage { path: "/old.png".into(), has_video: true, width: 8, height: 8, ..Default::default() };
let mut p = Project::default();
let item = p.add_item("old", Default::default(), None, ItemKind::Footage(still));
s.replace_project(p, None);
s.execute("comp.new", json!({"name": "Main", "width": 8, "height": 8, "frameRate": 30, "duration": 1})).unwrap();
s.execute("layer.addItem", json!({"item": item.0})).unwrap();
let comp = s.active_comp_id().unwrap();
(s, src, item, comp)
}
#[test]
fn held_thumbnail_jobs_cannot_refill_the_closed_projects_caches() {
for close in ["file.closeProject", "file.newProject"] {
let (mut s, src, item, comp) = old_project();
// Project panel thumbnails, made while the project is open and run after it closed (a
// thread that started late).
let jobs = [s.thumbnail_job(item, Tick(0), 16).unwrap(), s.thumbnail_job(comp, Tick(0), 16).unwrap()];
s.execute(close, json!({})).unwrap();
let shown: Vec<_> = jobs.into_iter().map(|job| job()).collect();
assert!(src.cached.lock().unwrap().is_empty(), "{close}: the closed project's frames came back");
assert_eq!(s.layer_cache.stats().entries, 0, "{close}: the closed project's layers came back");
assert!(shown.iter().all(Option::is_none), "{close}: a closed project's thumbnail isn't shown");
}
}
#[test]
fn thumbnails_reading_through_close_let_go_of_what_they_read() {
for which in ["footage", "comp"] {
let (mut s, src, item, comp) = old_project();
let (entered, entered_rx) = std::sync::mpsc::channel();
let (go, go_rx) = std::sync::mpsc::channel();
*src.gate.lock().unwrap() = Some((entered, go_rx));
let job = s.thumbnail_job(if which == "comp" { comp } else { item }, Tick(0), 16).unwrap();
let running = std::thread::spawn(job);
// The job is decoding the closed project's still when the project closes.
entered_rx.recv_timeout(std::time::Duration::from_secs(30)).unwrap();
s.execute("file.closeProject", json!({})).unwrap();
go.send(()).unwrap();
let shown = running.join().unwrap();
assert!(src.cached.lock().unwrap().is_empty(), "{which}: the frame decoded through Close was kept");
assert_eq!(s.layer_cache.stats().entries, 0, "{which}: the closed project's layers were kept");
assert!(shown.is_none(), "{which}: a closed project's thumbnail isn't shown");
}
}
#[test]
fn an_open_projects_thumbnails_still_render() {
let (s, src, item, comp) = old_project();
let (w, h, px) = s.thumbnail_job(item, Tick(0), 16).unwrap()().unwrap();
assert_eq!((w, h, px.len()), (8, 8, 8 * 8 * 4));
assert!(s.thumbnail_job(comp, Tick(0), 16).unwrap()().is_some());
assert!(src.cached.lock().unwrap().contains("/old.png"));
}
+5 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "effectcraft-export"
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC), ProRes and uncompressed MOV (+PCM) , HEVC / AV1 MP4 (+AAC) and WebM (VP9 or AV1) via craft-libs codecs, Opus via effectcraft-opusenc, PNG/JPEG/TIFF/EXR/Targa sequences, animated GIF, WAV/AIFF"
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC), ProRes and uncompressed MOV (+PCM) , HEVC / AV1 MP4 (+AAC) and WebM (VP9 or AV1) via craft-libs codecs, Opus via craft-audio, PNG/JPEG/TIFF/EXR/Targa sequences, animated GIF, WAV/AIFF"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -17,21 +17,20 @@ effectcraft-render = { workspace = true }
craft-video = { workspace = true }
craft-audio = { workspace = true }
craft-media = { workspace = true }
effectcraft-opusenc = { workspace = true }
craft-gif = { workspace = true }
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] }
exr = { workspace = true }
gif = { workspace = true }
rayon = { workspace = true }
web-time = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[dev-dependencies]
gif = { workspace = true }
tempfile = { workspace = true }
effectcraft-media = { workspace = true }
effectcraft-effects = { workspace = true }
effectcraft-color = { workspace = true }
filmcraft-hevc = { workspace = true }
filmcraft-av1 = { workspace = true }
filmcraft-vp9 = { workspace = true }
# The decoders that check the VP9, HEVC and AV1 encoders round-trip (av1 is already on).
craft-video = { workspace = true, features = ["vp9-decode", "hevc-decode"] }
effectcraft-keyframe = { workspace = true }
+37 -18
View File
@@ -9,7 +9,7 @@
//! | OpenEXR sequence | one file per frame, scan lines | 32-bit float (default) or half float, linear light, premultiplied; compression None, RLE, ZIPS, ZIP (default), PIZ, PXR24, B44, B44A, DWAA, DWAB | yes | — |
//! | Targa sequence | one file per frame | uncompressed 8-bit: 24-bit RGB, 32-bit RGB + Alpha (8 alpha bits), 8-bit grey for Alpha; top-left origin | yes (straight or premultiplied) | — |
//! | Animated GIF | GIF89a | 256-colour palette per frame (NeuQuant) | 1-bit | — |
//! | WebM | WebM (Matroska) | VP9 profile 0 (`craft_video::vp9`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0; or AV1 (`craft_video::av1`) | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`: SILK / hybrid / CELT by bitrate and application), 48 kHz |
//! | WebM | WebM (Matroska) | VP9 profile 0 (`craft_video::vp9`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0; or AV1 (`craft_video::av1`) | VP9 alpha (BlockAdditional) | Opus (`craft_audio::opus::Encoder`: SILK / hybrid / CELT by bitrate and application), 48 kHz |
//! | HEVC | MP4 (`hvc1`) | `craft_video::hevc` Main / Main 10 4:2:0, I + P slices, bitrate or constant quality, level, key-frame interval | no | AAC-LC (`craft_audio::aac`) |
//! | AV1 | MP4 (`av01`) | `craft_video::av1` Main 8/10-bit 4:2:0, key + inter frames | no | AAC-LC (`craft_audio::aac`) |
//! | WAV / AIFF | RIFF WAVE / AIFF (AIFF-C for float) | — | — | PCM 16/24-bit or 32-bit float, mono/stereo (audio only) |
@@ -451,13 +451,22 @@ fn write_still<W: std::io::Write + std::io::Seek>(cx: &Cx, file: &mut W, img: &I
}
async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
if w > u16::MAX as u32 || h > u16::MAX as u32 {
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
}
use craft_gif::write::{AnimationWriter, Disposal, Options, PreparedFrame};
validate_gif_dimensions(w, h)?;
let path = job.place(job.path, 1);
let mut file = job.create(&path)?;
let mut enc = gif::Encoder::new(&mut file, w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;
enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?;
let mut enc = AnimationWriter::new(
&mut file,
w,
h,
Options {
loop_forever: job.output.gif_loop,
disposal: if job.output.channels == Channels::Rgba { Disposal::Background } else { Disposal::Keep },
speed: 10,
},
)
.map_err(|e| ExportError::Encode(e.to_string()))?;
let rate = job.settings.rate(comp);
// GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing.
let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64;
@@ -467,22 +476,16 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_
let mut i = 0;
while i < st.total {
let end = (i + batch).min(st.total);
let frames: Vec<gif::Frame<'static>> = job
.frames(comp, (i..end).collect(), |_, img| {
let mut px = job.pixels_with(&img, comp, job.output.channels, w, h, false);
gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10)
})
let frames: Vec<std::result::Result<PreparedFrame, craft_gif::write::Error>> = job
.frames(comp, (i..end).collect(), |_, img| craft_gif::write::prepare_frame(w, h, job.pixels_with(&img, comp, job.output.channels, w, h, false), 10))
.await;
let t = Instant::now();
for mut f in frames {
for frame in frames {
clock += cs_per_frame;
let d = (clock.round() as u64).saturating_sub(emitted).max(1);
emitted += d;
f.delay = d.min(u16::MAX as u64) as u16;
if job.output.channels == Channels::Rgba {
f.dispose = gif::DisposalMethod::Background;
}
enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?;
let frame = frame.map_err(|e| ExportError::Encode(e.to_string()))?;
enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string()))?;
}
// The GIF writer compresses as it writes: the two are not measured apart.
job.add_time(pipeline::Stage::EncodeWrite, t);
@@ -490,12 +493,19 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_
i = end;
}
let t = Instant::now();
drop(enc);
let _ = enc.finish().map_err(|e| ExportError::Encode(e.to_string()))?;
let bytes = file.finish()?;
job.add_time(pipeline::Stage::EncodeWrite, t);
Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![], timing: Default::default() })
}
fn validate_gif_dimensions(w: u32, h: u32) -> Result<()> {
if w > u16::MAX as u32 || h > u16::MAX as u32 {
return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -513,4 +523,13 @@ mod tests {
assert_eq!(OutputFormat::H264.coded_size(1, 101), (2, 100));
assert_eq!(OutputFormat::Gif.coded_size(1, 101), (1, 101));
}
#[test]
fn gif_dimension_limit_keeps_the_existing_unsupported_error() {
assert!(validate_gif_dimensions(u16::MAX as u32, u16::MAX as u32).is_ok());
assert!(matches!(
validate_gif_dimensions(u16::MAX as u32 + 1, 1),
Err(ExportError::Unsupported(message)) if message == "GIF frames are limited to 65535 px"
));
}
}
+20 -13
View File
@@ -8,12 +8,13 @@
//! with `AlphaMode` 1 on the track, as WebM defines. VP9 comes from `craft_video::vp9` (key
//! frames every two seconds, inter frames between them: SimpleBlocks carry the key flag, inter
//! BlockGroups a ReferenceBlock; the alpha stream's key frames line up with the colour stream's),
//! Opus from `effectcraft-opusenc` (CELT, 48 kHz stereo, 20 ms packets,
//! Opus from `craft_audio::opus::Encoder` (SILK / hybrid / CELT, 48 kHz, 20 ms packets,
//! `CodecDelay` = pre-skip). WAV (RIFF, PCM or IEEE float) and AIFF (big-endian PCM, 80-bit
//! extended sample rate; AIFF-C `fl32` for float) follow their published file layouts.
use std::io::{Seek, SeekFrom, Write};
use craft_audio::opus::encoder as opus;
use effectcraft_project::Comp;
use effectcraft_project::render_queue::{AudioFormat, Channels};
use effectcraft_time::{TICKS_PER_SECOND, Tick};
@@ -21,7 +22,7 @@ use web_time::Instant;
use crate::encode::{mix, pcm_bytes};
use crate::pipeline::Stage;
use crate::{Cx, Report, Result, State, batch_size, io, wants_audio};
use crate::{Cx, ExportError, Report, Result, State, batch_size, io, wants_audio};
pub(crate) const OPUS_RATE: u32 = 48_000;
@@ -126,13 +127,18 @@ fn cluster(frames: &mut [Frame]) -> Vec<u8> {
}
/// The Opus encoder of a WebM output: the module's channel count, bitrate and application.
pub(crate) fn opus_encoder(job: &Cx) -> effectcraft_opusenc::OpusEncoder {
pub(crate) fn opus_encoder(job: &Cx) -> Result<opus::Encoder> {
let channels = if job.output.audio_channels == 1 { 1 } else { 2 };
let app = match job.output.opus_application {
effectcraft_project::render_queue::OpusApplication::Audio => effectcraft_opusenc::Application::Audio,
effectcraft_project::render_queue::OpusApplication::Voip => effectcraft_opusenc::Application::Voip,
effectcraft_project::render_queue::OpusApplication::Audio => opus::Application::Audio,
effectcraft_project::render_queue::OpusApplication::Voip => opus::Application::Voip,
};
effectcraft_opusenc::OpusEncoder::with_application(channels, job.output.opus_bitrate_kbps.clamp(6, 510) * 1000, app)
opus::Encoder::with_application(channels, job.output.opus_bitrate_kbps.clamp(6, 510) * 1000, app).map_err(opus_error)
}
/// An Opus encoder error as an export error.
pub(crate) fn opus_error(e: opus::Error) -> ExportError {
ExportError::Encode(format!("Opus: {e}"))
}
pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result<Report> {
@@ -158,7 +164,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
let mut alpha_enc = alpha.then(|| craft_video::vp9::Vp9Encoder::new(cfg.clone()));
let with_audio = wants_audio(job);
let opus_channels = if job.output.audio_channels == 1 { 1usize } else { 2 };
let mut opus = with_audio.then(|| opus_encoder(job));
let mut opus = with_audio.then(|| opus_encoder(job)).transpose()?;
let total = st.total;
let frame_ms = |k: u64| -> i64 { ((k as i128 * 1000 * rate.den as i128 + rate.num as i128 / 2) / rate.num as i128) as i64 };
let duration_ms = frame_ms(total) as f64;
@@ -231,8 +237,8 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
let mut cursor = span_start.to_units_floor(OPUS_RATE as i64);
let mut pcm_left: Vec<f32> = vec![];
let mut packets = 0u64;
let mut audio_until = |until: Tick, frames: &mut Vec<Frame>, finish: bool| {
let Some(enc) = opus.as_mut() else { return };
let mut audio_until = |until: Tick, frames: &mut Vec<Frame>, finish: bool| -> Result<()> {
let Some(enc) = opus.as_mut() else { return Ok(()) };
let end = until.to_units_floor(OPUS_RATE as i64);
if end > cursor {
let n = (end - cursor) as usize;
@@ -240,7 +246,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
pcm_left.extend(mix(job, start, n, OPUS_RATE));
cursor = end;
}
let fs = effectcraft_opusenc::OpusEncoder::FRAME_SIZE * opus_channels;
let fs = craft_audio::opus::Encoder::FRAME_SIZE * opus_channels;
if finish && !pcm_left.is_empty() {
// Pad the last packet (pre-skip + padding cover the encoder delay).
let pad = (fs - pcm_left.len() % fs) % fs + fs;
@@ -249,11 +255,12 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
// Packets are read in place and the encoded samples dropped once: draining each packet
// from the front would shift the rest of the batch's audio every 20 ms.
for packet in pcm_left.chunks_exact(fs) {
let pkt = enc.encode_float(packet);
let pkt = enc.encode_float(packet).map_err(crate::webm::opus_error)?;
frames.push(Frame { ms: packets as i64 * 20, track: 2, key: true, prev_ms: None, data: pkt, alpha: None });
packets += 1;
}
pcm_left.drain(..pcm_left.len() / fs * fs);
Ok(())
};
let batch = batch_size();
@@ -285,7 +292,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
drop(pixels);
job.add_time(Stage::Encode, t);
let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) };
job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut frames, end >= total));
job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut frames, end >= total))?;
let t = Instant::now();
let c = cluster(&mut frames);
file.write_all(&c).map_err(io)?;
@@ -296,7 +303,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
}
if total == 0 {
let mut frames = vec![];
audio_until(span_end, &mut frames, true);
audio_until(span_end, &mut frames, true)?;
if !frames.is_empty() {
let c = cluster(&mut frames);
file.write_all(&c).map_err(io)?;
+8 -7
View File
@@ -47,7 +47,7 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
let mut venc = crate::hevc_av1::Av1::new(w, h, rate, job.output, codes)?;
let with_audio = wants_audio(job);
let opus_channels = if job.output.audio_channels == 1 { 1usize } else { 2 };
let mut opus = with_audio.then(|| opus_encoder(job));
let mut opus = with_audio.then(|| opus_encoder(job)).transpose()?;
let total = st.total;
let frame_ms = |k: u64| -> i64 { ((k as i128 * 1000 * rate.den as i128 + rate.num as i128 / 2) / rate.num as i128) as i64 };
let duration_ms = frame_ms(total) as f64;
@@ -112,8 +112,8 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
let mut cursor = span_start.to_units_floor(OPUS_RATE as i64);
let mut pcm_left: Vec<f32> = vec![];
let mut packets = 0u64;
let mut audio_until = |until: Tick, blocks: &mut Vec<Block>, finish: bool| {
let Some(enc) = opus.as_mut() else { return };
let mut audio_until = |until: Tick, blocks: &mut Vec<Block>, finish: bool| -> Result<()> {
let Some(enc) = opus.as_mut() else { return Ok(()) };
let end = until.to_units_floor(OPUS_RATE as i64);
if end > cursor {
let n = (end - cursor) as usize;
@@ -121,7 +121,7 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
pcm_left.extend(mix(job, start, n, OPUS_RATE));
cursor = end;
}
let fs = effectcraft_opusenc::OpusEncoder::FRAME_SIZE * opus_channels;
let fs = craft_audio::opus::Encoder::FRAME_SIZE * opus_channels;
if finish && !pcm_left.is_empty() {
let pad = (fs - pcm_left.len() % fs) % fs + fs;
pcm_left.extend(std::iter::repeat_n(0.0, pad));
@@ -129,11 +129,12 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
// Packets are read in place and the encoded samples dropped once: draining each packet
// from the front would shift the rest of the batch's audio every 20 ms.
for packet in pcm_left.chunks_exact(fs) {
let pkt = enc.encode_float(packet);
let pkt = enc.encode_float(packet).map_err(crate::webm::opus_error)?;
blocks.push(Block { ms: packets as i64 * 20, track: 2, key: true, data: pkt });
packets += 1;
}
pcm_left.drain(..pcm_left.len() / fs * fs);
Ok(())
};
let batch = batch_size();
@@ -160,13 +161,13 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut
}
}
let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) };
job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut blocks, end >= total));
job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut blocks, end >= total))?;
job.timed(Stage::Write, || flush_blocks(&mut blocks, &mut file, &mut seg_len))?;
st.advance(end - i)?;
i = end;
}
if total == 0 {
audio_until(span_end, &mut blocks, true);
audio_until(span_end, &mut blocks, true)?;
flush_blocks(&mut blocks, &mut file, &mut seg_len)?;
}
let mut size = [0u8; 8];
+2 -2
View File
@@ -86,13 +86,13 @@ pub struct Run {
pub lf_levels: Vec<u32>,
}
/// Encodes `pics`, checks every packet decodes (filmcraft-av1) to exactly the encoder's
/// Encodes `pics`, checks every packet decodes (craft-video's AV1 decoder) to exactly the encoder's
/// reconstruction and returns packets, reconstructions and luma PSNRs.
pub fn encode_and_check(cfg: EncoderConfig, pics: &[Pic]) -> Run {
let bd = cfg.bit_depth as u32;
let mut enc = Encoder::new(cfg).expect("config");
// single-threaded: each packet's picture comes out of its own decode call
let mut dec = filmcraft_av1::Decoder::with_threads(1);
let mut dec = craft_video::av1::decode::Decoder::with_threads(1);
let mut run = Run { packets: Vec::new(), recons: Vec::new(), psnr_y: Vec::new(), lf_levels: Vec::new() };
for (i, p) in pics.iter().enumerate() {
let pkt = enc.encode(&p.frame()).expect("encode");
+1 -1
View File
@@ -1,4 +1,4 @@
//! craft-video's AV1 encoder against the filmcraft-av1 decoder and ffmpeg's libdav1d.
//! craft-video's AV1 encoder against craft-video's AV1 decoder and ffmpeg's libdav1d.
mod bench;
mod common;
+1 -27
View File
@@ -8,6 +8,7 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::support::write_tone;
use effectcraft_color::Label;
use effectcraft_export::render_queue::{
AudioOutput, CodecProfile, OpusApplication, OutputFormat, OutputModule, RateControlMode, RenderSettings, TimeSpan, WebmVideoCodec,
@@ -299,30 +300,3 @@ fn rms(v: impl Iterator<Item = f32>) -> f32 {
let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1));
(s / n.max(1) as f64).sqrt() as f32
}
/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right).
fn write_tone(path: &Path, secs: f64) {
let sr = 48_000u32;
let n = (secs * sr as f64) as usize;
let mut data = Vec::with_capacity(n * 4);
for i in 0..n {
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
data.extend_from_slice(&s.to_le_bytes());
data.extend_from_slice(&0i16.to_le_bytes());
}
let mut w = Vec::new();
w.extend_from_slice(b"RIFF");
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
w.extend_from_slice(b"WAVEfmt ");
w.extend_from_slice(&16u32.to_le_bytes());
w.extend_from_slice(&1u16.to_le_bytes());
w.extend_from_slice(&2u16.to_le_bytes());
w.extend_from_slice(&sr.to_le_bytes());
w.extend_from_slice(&(sr * 4).to_le_bytes());
w.extend_from_slice(&4u16.to_le_bytes());
w.extend_from_slice(&16u16.to_le_bytes());
w.extend_from_slice(b"data");
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(&data);
std::fs::write(path, w).expect("write wav");
}
+13 -13
View File
@@ -1,4 +1,4 @@
//! Round trips through the filmcraft-hevc decoder and (when installed) ffmpeg: decoded pictures must
//! Round trips through the craft-video HEVC decoder and (when installed) ffmpeg: decoded pictures must
//! equal the encoder's own reconstruction bit-exactly.
use craft_video::hevc::{Encoder, EncoderConfig, Frame, Profile, RateControl};
@@ -84,9 +84,9 @@ fn encode(cfg: EncoderConfig, pics: &[Pic]) -> Run {
run
}
/// Decode with filmcraft-hevc and compare with the reconstructions.
fn check_filmcraft(run: &Run, w: usize, h: usize) {
let mut dec = filmcraft_hevc::Decoder::from_hvcc(&run.hvcc).unwrap();
/// Decode with craft-video's HEVC decoder and compare with the reconstructions.
fn check_decoder(run: &Run, w: usize, h: usize) {
let mut dec = craft_video::hevc::decode::Decoder::from_hvcc(&run.hvcc).unwrap();
let mut pics = Vec::new();
for (i, p) in run.packets.iter().enumerate() {
pics.extend(dec.decode(p, i as i64).unwrap());
@@ -211,7 +211,7 @@ fn intra_8bit_quality_and_decoders() {
let run = encode(cfg(w as u32, h as u32, 22, 1, Profile::Main), &pics);
eprintln!("intra QP22: {} bytes, PSNR-Y {:.2}", run.packets[0].len(), run.psnr_y[0]);
assert!(run.psnr_y[0] > 35.0, "PSNR {}", run.psnr_y[0]);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 8, "intra8");
}
@@ -267,7 +267,7 @@ fn inter_8bit_moving_pattern() {
let p_avg = sizes[1..].iter().sum::<usize>() as f64 / 5.0;
assert!(p_avg < sizes[0] as f64 * 0.6, "P frames {p_avg} vs I {}", sizes[0]);
assert!(run.psnr_y.iter().all(|&p| p > 33.0));
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 8, "inter8");
}
@@ -276,7 +276,7 @@ fn odd_multiple_sizes_and_cropping() {
for (w, h) in [(34usize, 18usize), (66, 38), (8, 8), (130, 72), (2, 2), (2, 70), (264, 6)] {
let pics: Vec<Pic> = (0..3).map(|i| synth(w, h, 8, i, 2 * i)).collect();
let run = encode(cfg(w as u32, h as u32, 30, 2, Profile::Main), &pics);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 8, &format!("size{w}x{h}"));
}
}
@@ -305,7 +305,7 @@ fn noise_low_qp() {
.collect();
let run = encode(cfg(w as u32, h as u32, 0, 2, profile), &pics);
assert!(run.psnr_y.iter().all(|&p| p > 45.0), "{:?}", run.psnr_y);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, bd, &format!("noise{bd}"));
}
}
@@ -317,7 +317,7 @@ fn high_qp_deblocking() {
for (qp, profile, bd) in [(38u8, Profile::Main, 8u32), (44, Profile::Main, 8), (37, Profile::Main10, 10)] {
let pics: Vec<Pic> = (0..5).map(|i| synth(w, h, bd, 2 * i, i)).collect();
let run = encode(cfg(w as u32, h as u32, qp, 4, profile), &pics);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, bd, &format!("hq{qp}"));
}
}
@@ -329,7 +329,7 @@ fn long_gop_poc_wrap() {
let pics: Vec<Pic> = (0..300).map(|i| synth(w, h, 8, i % 7, i % 5)).collect();
let run = encode(cfg(w as u32, h as u32, 30, 0, Profile::Main), &pics);
assert_eq!(run.keys.iter().filter(|&&k| k).count(), 1);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 8, "pocwrap");
let run = encode(cfg(w as u32, h as u32, 30, 260, Profile::Main), &pics);
assert_eq!(run.keys.iter().filter(|&&k| k).count(), 2);
@@ -348,7 +348,7 @@ fn main10_round_trip() {
let run = encode(cfg(w as u32, h as u32, 24, 3, Profile::Main10), &pics);
eprintln!("main10 psnr {:?}", run.psnr_y);
assert!(run.psnr_y[0] > 35.0);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 10, "main10");
}
@@ -358,7 +358,7 @@ fn qp_extremes() {
for qp in [0u8, 51] {
let pics: Vec<Pic> = (0..2).map(|i| synth(w, h, 8, i, i)).collect();
let run = encode(cfg(w as u32, h as u32, qp, 30, Profile::Main), &pics);
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
check_ffmpeg(&run, w, h, 8, &format!("qp{qp}"));
}
}
@@ -375,7 +375,7 @@ fn bitrate_mode_hits_target() {
let kbps = bits as f64 / (pics.len() as f64 / 30.0) / 1000.0;
eprintln!("bitrate mode: {kbps:.1} kbit/s for a 400 kbit/s target");
assert!(kbps > 400.0 / 2.0 && kbps < 400.0 * 2.0, "{kbps}");
check_filmcraft(&run, w, h);
check_decoder(&run, w, h);
}
#[test]
+1
View File
@@ -19,6 +19,7 @@ mod opus_roundtrip;
mod prores_color;
mod render_settings;
mod roundtrip;
mod support;
mod targa_sequence;
mod uncompressed_mov;
mod vp9_roundtrip;
+5 -5
View File
@@ -1,9 +1,9 @@
//! Round trip of `effectcraft-opusenc` through FilmCraft's spec-derived Opus decoder, plus an
//! Round trip of WebM export's Opus encoder (`craft_audio::opus::Encoder`) through FilmCraft's spec-derived Opus decoder, plus an
//! ffmpeg oracle (skipped when ffmpeg is not installed) reading an Ogg Opus file written here.
use std::process::Command;
use effectcraft_opusenc::OpusEncoder;
use craft_audio::opus::Encoder as OpusEncoder;
const SR: f32 = 48_000.0;
const FRAME: usize = OpusEncoder::FRAME_SIZE;
@@ -11,12 +11,12 @@ const FRAME: usize = OpusEncoder::FRAME_SIZE;
/// Encodes interleaved `pcm`, padding the tail so the encoder's look-ahead is flushed.
fn encode(pcm: &[f32], channels: u8, bitrate: u32) -> (OpusEncoder, Vec<Vec<u8>>) {
let c = channels as usize;
let mut enc = OpusEncoder::new(channels, bitrate);
let mut enc = OpusEncoder::new(channels, bitrate).expect("1 or 2 channels");
let total = pcm.len() / c + enc.pre_skip() as usize;
let frames = total.div_ceil(FRAME);
let mut padded = pcm.to_vec();
padded.resize(frames * FRAME * c, 0.0);
let packets = padded.chunks(FRAME * c).map(|f| enc.encode_float(f)).collect();
let packets = padded.chunks(FRAME * c).map(|f| enc.encode_float(f).expect("one whole frame")).collect();
(enc, packets)
}
@@ -303,7 +303,7 @@ fn ogg_page(out: &mut Vec<u8>, packet: &[u8], header_type: u8, granule: u64, seq
fn ogg_opus(enc: &OpusEncoder, packets: &[Vec<u8>], len: usize) -> Vec<u8> {
let mut out = Vec::new();
ogg_page(&mut out, &enc.opus_head(), 0x02, 0, 0);
let vendor = b"effectcraft-opusenc";
let vendor = b"craft-audio";
let mut tags = b"OpusTags".to_vec();
tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
tags.extend_from_slice(vendor);
+58 -34
View File
@@ -9,6 +9,7 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::support::write_tone;
use effectcraft_color::Label;
use effectcraft_export::render_queue::{AlphaMode, AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderSettings, TimeSpan, sequence_path};
use effectcraft_export::{Job, Progress, export};
@@ -543,21 +544,47 @@ fn exr_sequence_values_at_or_below_one_are_unchanged() {
assert!((c[0] - 1.0).abs() < 1e-4 && (c[1] - lin(0.4)).abs() < 1e-4 && c[2].abs() < 1e-6, "{channels:?}: {c:?}");
}
}
#[test]
fn gif_roundtrip() {
/// Render the test project as a GIF with `om` into `out_dir(name)`, and open it for RGBA decoding.
fn render_gif(name: &str, om: &OutputModule) -> (PathBuf, gif::Decoder<std::fs::File>) {
let (p, cid) = project(None);
let d = out_dir("gif");
let om = OutputModule::for_format(OutputFormat::Gif);
let path = d.join("anim.gif");
run(&p, cid, &NoFootage, &om, &path);
let path = out_dir(name).join("anim.gif");
run(&p, cid, &NoFootage, om, &path);
let mut opts = gif::DecodeOptions::new();
opts.set_color_output(gif::ColorOutput::RGBA);
let mut dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header");
let dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header");
(path, dec)
}
/// The test project's frames, rendered as PNGs, re-encoded through the former app-local gif 0.13
/// path (`Frame::from_rgba_speed` at speed 10, 1/10 s per frame, looping).
fn reference_gif() -> Vec<u8> {
let (p, cid) = project(None);
let png_pattern = out_dir("gif-byte-parity").join("frame_[#####].png");
run(&p, cid, &NoFootage, &OutputModule::for_format(OutputFormat::PngSequence), &png_pattern);
let png_pattern = png_pattern.to_string_lossy();
let mut expected = Vec::new();
let mut encoder = gif::Encoder::new(&mut expected, W as u16, H as u16, &[]).expect("reference GIF encoder");
encoder.set_repeat(gif::Repeat::Infinite).expect("reference GIF repeat");
for frame_number in 0..FRAMES {
let mut rgba = image::open(sequence_path(&png_pattern, frame_number as i64)).expect("reference PNG").to_rgba8().into_raw();
let mut frame = gif::Frame::from_rgba_speed(W as u16, H as u16, &mut rgba, 10);
frame.delay = 10;
encoder.write_frame(&frame).expect("reference GIF frame");
}
drop(encoder);
expected
}
#[test]
fn gif_roundtrip() {
let (path, mut dec) = render_gif("gif", &OutputModule::for_format(OutputFormat::Gif));
assert_eq!((dec.width() as u32, dec.height() as u32), (W, H));
assert_eq!(dec.repeat(), gif::Repeat::Infinite);
let mut k = 0;
let mut total_delay = 0u32;
while let Some(f) = dec.read_next_frame().expect("frame") {
assert_eq!((f.width as u32, f.height as u32), (W, H));
assert_eq!(f.dispose, gif::DisposalMethod::Keep);
total_delay += f.delay as u32;
let img = Image::from_rgba8(W, H, &f.buffer);
check_frame(&img, k, 0.06);
@@ -570,6 +597,30 @@ fn gif_roundtrip() {
}
}
#[test]
fn gif_matches_the_former_encoder_byte_for_byte() {
// The shared writer must keep the complete output, quantization and LZW data included.
let (path, _) = render_gif("gif-parity", &OutputModule::for_format(OutputFormat::Gif));
let actual = std::fs::read(&path).expect("GIF bytes");
let expected = reference_gif();
let difference = actual.iter().zip(&expected).position(|(a, b)| a != b);
assert!(
actual.len() == expected.len() && difference.is_none(),
"GIF bytes differ: {} vs {} bytes, first difference at {difference:?}",
actual.len(),
expected.len()
);
}
#[test]
fn gif_rgba_keeps_background_disposal_and_non_looping() {
let om = OutputModule { channels: Channels::Rgba, gif_loop: false, ..OutputModule::for_format(OutputFormat::Gif) };
let (_, mut dec) = render_gif("gif-rgba", &om);
assert_eq!(dec.repeat(), gif::Repeat::Finite(0));
let first = dec.read_next_frame().expect("frame").expect("first frame");
assert_eq!(first.dispose, gif::DisposalMethod::Background);
}
#[test]
fn cancel_stops_early() {
let (p, cid) = project(None);
@@ -596,33 +647,6 @@ fn cancel_stops_early() {
assert_eq!(written, 0, "cancelled before the first batch");
}
/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right).
fn write_tone(path: &Path, secs: f64) {
let sr = 48_000u32;
let n = (secs * sr as f64) as usize;
let mut data = Vec::with_capacity(n * 4);
for i in 0..n {
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
data.extend_from_slice(&s.to_le_bytes());
data.extend_from_slice(&0i16.to_le_bytes());
}
let mut w = Vec::new();
w.extend_from_slice(b"RIFF");
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
w.extend_from_slice(b"WAVEfmt ");
w.extend_from_slice(&16u32.to_le_bytes());
w.extend_from_slice(&1u16.to_le_bytes());
w.extend_from_slice(&2u16.to_le_bytes());
w.extend_from_slice(&sr.to_le_bytes());
w.extend_from_slice(&(sr * 4).to_le_bytes());
w.extend_from_slice(&4u16.to_le_bytes());
w.extend_from_slice(&16u16.to_le_bytes());
w.extend_from_slice(b"data");
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(&data);
std::fs::write(path, w).expect("write wav");
}
fn rms(v: impl Iterator<Item = f32>) -> f32 {
let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1));
(s / n.max(1) as f64).sqrt() as f32
+30
View File
@@ -0,0 +1,30 @@
//! Helpers shared by the integration test modules.
use std::path::Path;
/// 16-bit stereo 48 kHz WAV: a 440 Hz sine at 0.5 on the left, silence on the right.
pub(crate) fn write_tone(path: &Path, secs: f64) {
let sr = 48_000u32;
let n = (secs * sr as f64) as usize;
let mut data = Vec::with_capacity(n * 4);
for i in 0..n {
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
data.extend_from_slice(&s.to_le_bytes());
data.extend_from_slice(&0i16.to_le_bytes());
}
let mut w = Vec::new();
w.extend_from_slice(b"RIFF");
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
w.extend_from_slice(b"WAVEfmt ");
w.extend_from_slice(&16u32.to_le_bytes());
w.extend_from_slice(&1u16.to_le_bytes());
w.extend_from_slice(&2u16.to_le_bytes());
w.extend_from_slice(&sr.to_le_bytes());
w.extend_from_slice(&(sr * 4).to_le_bytes());
w.extend_from_slice(&4u16.to_le_bytes());
w.extend_from_slice(&16u16.to_le_bytes());
w.extend_from_slice(b"data");
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(&data);
std::fs::write(path, w).expect("write wav");
}
+1 -27
View File
@@ -8,6 +8,7 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::support::write_tone;
use craft_media::isobmff::TrackKind;
use effectcraft_color::Label;
use effectcraft_export::render_queue::{AudioFormat, AudioOutput, Channels, OutputFormat, OutputModule, RenderSettings, TimeSpan, sequence_path};
@@ -28,33 +29,6 @@ fn out_dir(name: &str) -> PathBuf {
d
}
/// 16-bit stereo 48 kHz WAV: a 440 Hz sine at 0.5 on the left, silence on the right.
fn write_tone(path: &Path, secs: f64) {
let sr = 48_000u32;
let n = (secs * sr as f64) as usize;
let mut data = Vec::with_capacity(n * 4);
for i in 0..n {
let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16;
data.extend_from_slice(&s.to_le_bytes());
data.extend_from_slice(&0i16.to_le_bytes());
}
let mut w = Vec::new();
w.extend_from_slice(b"RIFF");
w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
w.extend_from_slice(b"WAVEfmt ");
w.extend_from_slice(&16u32.to_le_bytes());
w.extend_from_slice(&1u16.to_le_bytes());
w.extend_from_slice(&2u16.to_le_bytes());
w.extend_from_slice(&sr.to_le_bytes());
w.extend_from_slice(&(sr * 4).to_le_bytes());
w.extend_from_slice(&4u16.to_le_bytes());
w.extend_from_slice(&16u16.to_le_bytes());
w.extend_from_slice(b"data");
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(&data);
std::fs::write(path, w).expect("write wav");
}
fn project(audio: Option<&Path>) -> (Project, ItemId) {
let mut p = Project::default();
let mut comp = Comp::new(W, H, FrameRate::new(10, 1), Tick::from_seconds_f64(FRAMES as f64 / 10.0));
+4 -4
View File
@@ -1,8 +1,8 @@
//! The VP9 intra encoder (`craft_video::vp9`) round-trips through FilmCraft's VP9 decoder (and
//! The VP9 intra encoder (`craft_video::vp9`) round-trips through craft-video's VP9 decoder (and
//! ffmpeg as an external oracle when installed): sizes, lossless exactness, PSNR.
use craft_video::vp9::decode::{Decoder, Picture, Plane};
use craft_video::vp9::{EncoderConfig, Vp9Encoder};
use filmcraft_vp9::{Decoder, Plane};
fn plane_u8(p: &Plane) -> Vec<u8> {
match p {
@@ -40,7 +40,7 @@ fn source(w: usize, h: usize, kind: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
(y, u, v)
}
fn decode(frame: &[u8]) -> filmcraft_vp9::Picture {
fn decode(frame: &[u8]) -> Picture {
let mut d = Decoder::with_threads(1);
let mut pics = d.decode(frame, 0).expect("decode");
assert_eq!(pics.len(), 1);
@@ -179,7 +179,7 @@ fn moving(w: usize, h: usize, t: usize, kind: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>
(y, u, v)
}
fn planes_of(p: &filmcraft_vp9::Picture, w: usize, h: usize) -> [Vec<u8>; 3] {
fn planes_of(p: &Picture, w: usize, h: usize) -> [Vec<u8>; 3] {
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
[crop(&plane_u8(&p.y), p.y_stride, w, h), crop(&plane_u8(&p.u), p.uv_stride, cw, ch), crop(&plane_u8(&p.v), p.uv_stride, cw, ch)]
}
+1 -1
View File
@@ -11,6 +11,7 @@ workspace = true
[dependencies]
effectcraft-time = { workspace = true }
effectcraft-effects = { workspace = true }
effectcraft-geom = { workspace = true }
effectcraft-keyframe = { workspace = true }
serde_json = { workspace = true }
@@ -25,5 +26,4 @@ boa_engine = { workspace = true, features = ["js"] }
[dev-dependencies]
effectcraft-color = { workspace = true }
effectcraft-effects = { workspace = true }
effectcraft-text = { workspace = true }
+15
View File
@@ -7,6 +7,7 @@
//! the answers and runs the script again. Expressions are pure functions of these answers, so
//! re-running is exact, and the runtime stays free of borrowed state.
use effectcraft_effects::migrate::PARAM_ID_ALIASES;
use effectcraft_geom::{Mat3, Mat4};
use effectcraft_keyframe::Value;
use effectcraft_project::ae_order::{self, AeChild};
@@ -300,10 +301,24 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
// An effect by its After Effects match name, an imported placeholder's effect id
// (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`).
.or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name)))
// Last, so a legacy name never shadows a current one.
.or_else(|| legacy_effect_child(g, &c))
}
}
}
/// A parameter of an effect instance addressed by a name it had when the project was saved
/// ([`PARAM_ID_ALIASES`]): `effect("CC Ball Action")("Instability State")` keeps reading the
/// parameter that is now Scatter Motion. `c` is the compacted (lowercase, no spaces) name. Only
/// renames inside the instance's own top-level group count; moves into twirl-downs do not.
fn legacy_effect_child<'g>(g: &'g PropGroup, c: &str) -> Option<&'g Node> {
let GroupKind::Effect { effect } = &g.kind else { return None };
PARAM_ID_ALIASES
.iter()
.filter(|(e, old, new)| e == effect && !old.contains('/') && !new.contains('/') && compact(old) == c)
.find_map(|(_, _, new)| g.children.iter().find(|n| n.match_id() == *new))
}
impl<'a> Resolver<'a> {
fn comp(&self, c: u64) -> Option<&'a Comp> {
if c == self.ctx.comp_id.0 { Some(self.ctx.comp) } else { self.ctx.project.comp(ItemId(c)) }
+7 -3
View File
@@ -870,14 +870,18 @@ Prop.prototype = {
propertyGroup: function (n) { return __ancestor(this.__c, this.__l, this.__p, n); },
__wrap: function (v) {
var kind = this.__info[2];
if (kind === 'layer') return v === null ? null : __layer(this.__c, v);
// A layer parameter set to None is the layer it sits on, as in After Effects.
if (kind === 'layer') return __layer(this.__c, v === null ? this.__l : v);
if (kind === 'path' && v !== null) return new __Path(v[0], v[1], v[2], v[3]);
return v;
},
get value() { return this.__self ? value : this.valueAtTime(time); },
get value() { return this.__self ? this.__selfValue() : this.valueAtTime(time); },
// The evaluated property's own value: a layer parameter reads as its layer here too.
// (After posterizeTime, `value` may already be the layer.)
__selfValue: function () { return this.__info[2] === 'layer' && !value?.__isLayer ? this.__wrap(value) : value; },
valueAtTime: function (t) {
t = __v(t);
if (this.__self && t === time) return value;
if (this.__self && t === time) return this.__selfValue();
return this.__wrap(__h(__VALUE, this.__c, this.__l, this.__p, t, this.__self));
},
velocityAtTime: function (t) {
+129
View File
@@ -1928,6 +1928,52 @@ fn layer_control_property_stands_for_its_layer() {
assert_close!(f.num("effect('Map')(1).value.name == 'B' ? 1 : 0", 0.0), 1.0);
}
#[test]
fn an_empty_layer_control_stands_for_its_own_layer() {
// In After Effects a Layer Control set to None gives the layer the effect is on: truthy, named
// and callable as that layer. Rigs test it with `L ? … : …` and then read `L.sourceRectAtTime`.
let mut f = fx();
let spec = effectcraft_effects::find("ec.control.layer").unwrap();
let mut map = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Map", [20.0, 20.0]));
map.prop_mut("layer").unwrap().value = Value::Layer(None);
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(map.into());
assert_close!(f.num("effect('Map')(1) ? 1 : 0", 0.0), 1.0);
assert_close!(f.num("effect('Map')(1).name == thisLayer.name ? 1 : 0", 0.0), 1.0);
assert_close!(f.num("effect('Map')(1).index", 0.0), 1.0);
assert_close!(f.num("var L = effect('Map')(1); L ? L.transform.position[0] : -1", 0.0), 50.0);
assert_close!(f.num("effect('Map')(1).sourceRectAtTime(time).width == thisLayer.sourceRectAtTime(time).width ? 1 : 0", 0.0), 1.0);
}
#[test]
fn a_layer_parameters_own_expression_reads_its_layer() {
// An expression on the layer parameter itself: `thisProperty.value` and
// `thisProperty.valueAtTime(time)` give the layer, as reads from other properties do.
let mut f = fx();
let spec = effectcraft_effects::find("ec.control.layer").unwrap();
let mut empty = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Empty", [20.0, 20.0]));
empty.prop_mut("layer").unwrap().value = Value::Layer(None);
let mut set = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Set", [20.0, 20.0]));
set.prop_mut("layer").unwrap().value = Value::Layer(Some(f.b.0));
let fx_group = f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap();
fx_group.children.push(empty.into());
fx_group.children.push(set.into());
let n = f.p.comp(f.cid).unwrap().layers[0].props.sub("effects").unwrap().children.len();
let (empty_path, set_path) = (format!("effects/#{}/layer", n - 1), format!("effects/#{n}/layer"));
// Each expression throws unless it reads the right layer's name.
for (path, read, want) in [
(&empty_path, "thisProperty.value", "A"),
(&empty_path, "thisProperty.valueAtTime(time)", "A"),
(&set_path, "thisProperty.value", "B"),
(&set_path, "thisProperty.valueAtTime(time)", "B"),
] {
let e = format!("if ({read}.name !== '{want}') throw new Error('read ' + {read}); value");
f.ev(f.a, path, &e, 0.0).unwrap_or_else(|err| panic!("{path} {read}: {err}"));
// After posterizeTime moves the sample time, `value` already holds the layer.
let e = format!("posterizeTime(1); if ({read}.name !== '{want}') throw new Error('read ' + {read}); value");
f.ev(f.a, path, &e, 0.5).unwrap_or_else(|err| panic!("posterized {path} {read}: {err}"));
}
}
#[test]
fn time_to_frames_rounds_durations_away_from_zero() {
let f = fx();
@@ -2145,6 +2191,89 @@ fn bench_evaluation() {
}
}
/// Layer A with an old-format CC Ball Action: Scatter Motion saved as `instabilityState`
/// ("Instability State"), opened through the migration (#3197). Scatter Motion is 37 and keyed
/// 10 at 0 s, 50 at 2 s.
fn old_ball_action() -> Fx {
let mut f = fx();
let spec = effectcraft_effects::find("ec.sim.ccballaction").unwrap();
let mut g = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "CC Ball Action", [20.0, 20.0]));
let sm = g.prop_mut("scatterMotion").unwrap();
sm.value = Value::Scalar(37.0);
sm.keys = vec![Keyframe::new(Tick::ZERO, Value::Scalar(10.0)), Keyframe::new(secs(2.0), Value::Scalar(50.0))];
sm.match_id = "instabilityState".into();
sm.name = "Instability State".into();
let mut next = f.p.next_id;
assert!(effectcraft_effects::migrate::upgrade_instance(spec, &mut g, &mut Ids(&mut next), [20.0, 20.0]));
f.p.next_id = next;
assert!(g.prop("scatterMotion").is_some(), "the migration renamed the parameter");
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(g.into());
f
}
#[test]
fn old_parameter_names_still_resolve_in_expressions() {
let f = old_ball_action();
for name in ["Instability State", "instabilityState", "instability state", "InstabilityState"] {
// Keyframes still apply: the keyed value at 0 s, not the stored 37.
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 0.0), 10.0);
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 2.0), 50.0);
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}').valueAtTime(2)"), 0.0), 50.0);
}
// Current names read the same property, unchanged.
for name in ["Scatter Motion", "scatterMotion"] {
assert_close!(f.num(&format!("effect('CC Ball Action')('{name}')"), 0.0), 10.0);
}
}
#[test]
fn old_parameter_name_follows_the_parameter_expression() {
let mut f = old_ball_action();
let p = f.p.comp_mut(f.cid).unwrap().layers[0].props.prop_mut("effects/#2/scatterMotion");
let p = match p {
Some(p) => p,
None => panic!("scatterMotion at effects/#2"),
};
p.expr = Some(Expression { text: "123".into(), enabled: true });
assert_close!(f.num("effect('CC Ball Action')('Instability State')", 0.0), 123.0);
}
#[test]
fn unknown_parameter_names_still_fail() {
let f = old_ball_action();
assert!(f.ev(f.a, ROT, "effect('CC Ball Action')('No Such Thing')", 0.0).is_err());
// Old names only exist on the effect they were renamed on.
assert!(f.ev(f.a, ROT, "effect('Slider Control')('Instability State')", 0.0).is_err());
}
/// Every in-group rename in the alias table keeps resolving by its old id and display name.
#[test]
fn every_in_group_alias_resolves_by_its_old_name() {
let mut n = 0;
for (effect, old, new) in effectcraft_effects::migrate::PARAM_ID_ALIASES {
if old.contains('/') || new.contains('/') {
continue;
}
let Some(spec) = effectcraft_effects::find(effect) else { continue };
let mut f = fx();
let g = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Probe", [20.0, 20.0]));
f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(g.into());
let (new_name, kind) = {
let l = &f.p.comp(f.cid).unwrap().layers[0];
let p = l.props.prop(&format!("effects/#2/{new}")).unwrap();
(p.name.clone(), p.value.clone())
};
if !matches!(kind, Value::Scalar(_)) {
continue;
}
let a = f.ev(f.a, ROT, &format!("effect('Probe')('{old}')"), 0.0).unwrap();
let b = f.ev(f.a, ROT, &format!("effect('Probe')('{new_name}')"), 0.0).unwrap();
assert_eq!(a, b, "{effect}: {old}");
n += 1;
}
assert!(n >= 1);
}
/// Viewport clipping must never affect layer-space expression reads (#1388).
#[test]
fn sample_image_reads_3d_shape_behind_camera_before_and_after_effects() {
+31 -13
View File
@@ -1207,17 +1207,25 @@ impl GpuContext {
if !ticket.active() {
return;
}
let mapping = Arc::new(crate::readback::Mapping::new());
let b = buffer.clone();
let callback_mapping = Arc::clone(&mapping);
buffer.map_async(wgpu::MapMode::Read, .., move |r| {
if !ticket.active() {
b.unmap();
if let Err(e) = r {
callback_mapping.failed();
ticket.complete(Err(format!("GPU buffer mapping: {e}")));
return;
}
let result = r.map_err(|e| format!("GPU buffer mapping: {e}")).and_then(|_| {
let view = b.get_mapped_range(..).map_err(|e| format!("GPU mapped range: {e}"))?;
crate::readback::packed(&view, row, stride, height)
});
b.unmap();
if !callback_mapping.mapped() {
return;
}
if !ticket.active() {
callback_mapping.unmap(|| b.unmap());
return;
}
let result =
b.get_mapped_range(..).map_err(|e| format!("GPU mapped range: {e}")).and_then(|view| crate::readback::packed(&view, row, stride, height));
callback_mapping.unmap(|| b.unmap());
ticket.complete(result);
});
}
@@ -1264,20 +1272,30 @@ impl GpuContext {
if !ticket.active() {
return Err("GPU readback cancelled".into());
}
let mapping = Arc::new(crate::readback::Mapping::new());
let b = buffer.clone();
let callback_mapping = Arc::clone(&mapping);
buffer.map_async(wgpu::MapMode::Read, .., move |r| {
if let Err(e) = r {
callback_mapping.failed();
ticket.complete(Err(format!("GPU buffer mapping: {e}")));
return;
}
if !callback_mapping.mapped() {
return;
}
// Timed out or cancelled: nobody reads the mapping.
if !ticket.active() {
b.unmap();
callback_mapping.unmap(|| b.unmap());
return;
}
// Mapped: the waiting thread reads the rows and unmaps (an empty vector = mapped).
ticket.complete(r.map(|_| Vec::new()).map_err(|e| format!("GPU buffer mapping: {e}")));
ticket.complete(Ok(Vec::new()));
});
// On any failure, unmap (harmless when not mapped; cancels a pending map) so a mapped
// buffer can never be handed out again.
// A timeout can cancel a pending map while its callback is being dispatched. The shared
// guard makes sure the callback and waiter cannot both unmap the same buffer.
let fail = |e: String| {
buffer.unmap();
mapping.unmap(|| buffer.unmap());
e
};
self.wait_mapped(&rx, submission).map_err(fail)?.map_err(fail)?;
@@ -1285,7 +1303,7 @@ impl GpuContext {
let view = buffer.get_mapped_range(..).map_err(|e| format!("GPU mapped range: {e}"));
view.and_then(|view| read(&view))
};
buffer.unmap();
mapping.unmap(|| buffer.unmap());
result
}
+7 -3
View File
@@ -411,8 +411,12 @@ fn drop_shadow(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option<GBuf> {
let dist = ctx.params.f("distance") * b.scale;
let soft = ctx.params.f("softness") * b.scale;
let only = ctx.params.b("shadowOnly");
let pad = (dist + soft * 1.5).ceil() as u32 + 2;
let pad = effectcraft_effects::drop_shadow_pad(dist, soft);
if !ctx.adjustment {
// A margin cut to the pixel budget: the CPU blurs on past the buffer's edge (#3464).
if soft > 0.0 && effectcraft_effects::pad_within_budget(b.img.width, b.img.height, pad) < pad {
return None;
}
b.pad(e, pad)?;
}
let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist);
@@ -592,7 +596,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
let (ox, oy) = b.to_px(pr.v2("transform/offset"));
let s = f("transform/scale");
let (sw, sh) = if pr.b("transform/uniformScaling") { (s, s) } else { (f("transform/scaleWidth"), f("transform/scaleHeight")) };
let sub = (f("subSettings/subScaling") / 100.0).clamp(0.1, 1.0);
let sub = effectcraft_effects::sub_scaling_ratio(f("subSettings/subScaling"));
p.u[0] = [10, kind, octaves.ceil() as u32, f("evolutionOptions/seed") as u32 ^ 0x51ed];
p.u[1] = [pr.b("invert") as u32, pr.e("overflow"), mode, 0];
p.f[0] = [
@@ -608,7 +612,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
(f("opacity") as f32 / 100.0).clamp(0.0, 1.0),
(sh * effectcraft_effects::NOISE_CELL * b.scale).max(1.0) as f32,
];
p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, 0.0, 0.0];
p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, effectcraft_effects::OCTAVE_SCALE_MAX, 0.0];
}
_ => return None,
}
+2 -3
View File
@@ -172,10 +172,9 @@ fn cc_lens(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
}
fn turbulent(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option<GBuf> {
let amount = ctx.params.f("amount") * b.scale;
if amount.abs() < 1e-9 {
let Some(amount) = effectcraft_effects::turbulent_amount_px(ctx, b.scale) else {
return Some(b);
}
};
let kind = ctx.params.e("displacement");
let size = (ctx.params.f("size") * b.scale).max(1.0);
if ctx.params.b("resizeLayer") && !ctx.adjustment {
+4 -4
View File
@@ -100,14 +100,14 @@ fn radial_blur(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
if amount.abs() < 1e-6 {
return Some(b);
}
let n = 32usize;
// The CPU's samples (`raster::radial_blur`).
let n = effectcraft_raster::RADIAL_BLUR_SAMPLES;
let mut data = Vec::with_capacity(2 * n);
for i in 0..n {
let t = i as f64 / (n - 1) as f64 - 0.5;
if zoom {
data.push((1.0 + t * amount) as f32);
data.push(effectcraft_raster::radial_blur_zoom_scale(i, amount) as f32);
} else {
let (s, c) = (t * amount).to_radians().sin_cos();
let (s, c) = effectcraft_raster::radial_blur_spin_degrees(i, amount).to_radians().sin_cos();
data.extend([s as f32, c as f32]);
}
}
+2
View File
@@ -228,6 +228,8 @@ pub(crate) fn sprite_layer(e: &mut Enc, src: &GpuImage, plan: &SpritePlan) -> Op
Shape::Square => (6.0, 0.0, 0.0),
Shape::Tri => (7.0, 0.0, 0.0),
Shape::Line { dx, dy } => (8.0, dx, dy),
// The strength rides in the (otherwise unused) first segment slot.
Shape::Ball { shade } => (9.0, shade, 0.0),
};
let mut rec = [kind, s.x, s.y, s.r, s.c[0], s.c[1], s.c[2], s.c[3], s.rot, dx, dy, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
match plan.tints.get(i).copied().unwrap_or(Tint::Fixed) {
+120
View File
@@ -4,6 +4,7 @@
use std::collections::BTreeMap;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Condvar;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
@@ -92,6 +93,48 @@ pub(crate) struct Ticket {
id: u64,
}
/// Tracks one GPU buffer mapping shared by the callback and its waiter. A timeout can race a
/// late callback, so the buffer must be unmapped exactly once. A failed map is never unmapped.
pub(crate) struct Mapping(AtomicU8);
impl Mapping {
const PENDING: u8 = 0;
const MAPPED: u8 = 1;
const FAILED: u8 = 2;
const FINISHED: u8 = 3;
pub(crate) fn new() -> Self {
Self(AtomicU8::new(Self::PENDING))
}
/// Claim a successful map callback. False means a timeout already cancelled the map.
pub(crate) fn mapped(&self) -> bool {
self.0.compare_exchange(Self::PENDING, Self::MAPPED, Ordering::AcqRel, Ordering::Acquire).is_ok()
}
/// Record a failed map so the waiter will not unmap a buffer that was never mapped.
pub(crate) fn failed(&self) {
let _ = self.0.compare_exchange(Self::PENDING, Self::FAILED, Ordering::AcqRel, Ordering::Acquire);
}
/// Unmap once if mapping is pending (cancel it) or mapped (release it).
pub(crate) fn unmap(&self, unmap: impl FnOnce()) {
let mut unmap = Some(unmap);
loop {
let state = self.0.load(Ordering::Acquire);
if state != Self::PENDING && state != Self::MAPPED {
return;
}
if self.0.compare_exchange(state, Self::FINISHED, Ordering::AcqRel, Ordering::Acquire).is_ok() {
if let Some(unmap) = unmap.take() {
unmap();
}
return;
}
}
}
}
/// User callbacks run outside locks and are isolated one at a time. On panic=abort
/// (including the usual wasm build), Rust panics cannot be caught: the host must
/// avoid panicking callbacks. This branch does not claim abort-mode recovery.
@@ -402,6 +445,83 @@ mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn timeout_racing_late_map_callback_unmaps_once() {
let mapping = Arc::new(Mapping::new());
let unmap_calls = Arc::new(AtomicUsize::new(0));
let barrier = Arc::new(std::sync::Barrier::new(3));
let timeout_mapping = Arc::clone(&mapping);
let timeout_calls = Arc::clone(&unmap_calls);
let timeout_barrier = Arc::clone(&barrier);
let timeout = std::thread::spawn(move || {
timeout_barrier.wait();
timeout_mapping.unmap(|| {
timeout_calls.fetch_add(1, Ordering::SeqCst);
});
});
let callback_mapping = Arc::clone(&mapping);
let callback_calls = Arc::clone(&unmap_calls);
let callback_barrier = Arc::clone(&barrier);
let callback = std::thread::spawn(move || {
callback_barrier.wait();
if callback_mapping.mapped() {
callback_mapping.unmap(|| {
callback_calls.fetch_add(1, Ordering::SeqCst);
});
}
});
barrier.wait();
timeout.join().unwrap();
callback.join().unwrap();
assert_eq!(unmap_calls.load(Ordering::SeqCst), 1);
}
#[test]
fn timeout_before_map_callback_cancels_late_map() {
let mapping = Mapping::new();
let unmap_calls = AtomicUsize::new(0);
mapping.unmap(|| {
unmap_calls.fetch_add(1, Ordering::SeqCst);
});
assert!(!mapping.mapped());
mapping.unmap(|| {
unmap_calls.fetch_add(1, Ordering::SeqCst);
});
assert_eq!(unmap_calls.load(Ordering::SeqCst), 1);
}
#[test]
fn mapped_callback_and_timeout_release_once() {
let mapping = Mapping::new();
let unmap_calls = AtomicUsize::new(0);
assert!(mapping.mapped());
mapping.unmap(|| {
unmap_calls.fetch_add(1, Ordering::SeqCst);
});
mapping.unmap(|| {
unmap_calls.fetch_add(1, Ordering::SeqCst);
});
assert_eq!(unmap_calls.load(Ordering::SeqCst), 1);
}
#[test]
fn failed_map_is_not_unmapped() {
let mapping = Mapping::new();
let unmap_calls = AtomicUsize::new(0);
mapping.failed();
mapping.unmap(|| {
unmap_calls.fetch_add(1, Ordering::SeqCst);
});
assert_eq!(unmap_calls.load(Ordering::SeqCst), 0);
}
#[test]
fn early_rejection_reports_no_pixels_exactly_once() {
let calls = Arc::new(AtomicUsize::new(0));
+8 -7
View File
@@ -75,8 +75,9 @@ fn fxc_colorama_phase(c: vec3<f32>, a: f32, mode: u32) -> f32 {
// Selective Color range weights (color2::sc_weights).
fn fxc_sc_weights(c0: vec3<f32>) -> array<f32, 9> {
let c = clamp(c0, vec3<f32>(0.0), vec3<f32>(1.0));
// Stable descending sort of the channel indices.
var idx = vec3<u32>(0u, 1u, 2u);
// Stable descending sort of the channel indices. Use an array because llvmpipe does not
// preserve dynamically indexed writes to vector components here.
var idx = array<u32, 3>(0u, 1u, 2u);
for (var i = 1u; i < 3u; i++) {
var j = i;
while (j > 0u && c[idx[j]] > c[idx[j - 1u]]) {
@@ -86,14 +87,14 @@ fn fxc_sc_weights(c0: vec3<f32>) -> array<f32, 9> {
j--;
}
}
let mx = c[idx.x];
let md = c[idx.y];
let mn = c[idx.z];
let mx = c[idx[0]];
let md = c[idx[1]];
let mn = c[idx[2]];
var w = array<f32, 9>(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
var prim = array<u32, 3>(0u, 2u, 4u);
var sec = array<u32, 3>(3u, 5u, 1u);
w[prim[idx.x]] = mx - md;
w[sec[idx.z]] = md - mn;
w[prim[idx[0]]] = mx - md;
w[sec[idx[2]]] = md - mn;
w[6] = max((mn - 0.5) * 2.0, 0.0);
w[8] = max((0.5 - mx) * 2.0, 0.0);
w[7] = clamp(1.0 - (abs(mx - 0.5) + abs(mn - 0.5)), 0.0, 1.0);
+38 -26
View File
@@ -130,12 +130,15 @@ fn fxl_shape(at: u32, n: u32, x: f32, flip: bool) -> f32 {
// partition_point(|p| p.x < x).
var lo = 0u;
var hi = n;
while (lo < hi) {
let mid = (lo + hi) / 2u;
if (data[at + mid * 2u + kx] < x) {
lo = mid + 1u;
} else {
hi = mid;
// Bound the partition search as for inverse 1D LUTs below.
for (var step = 0u; step < 32u; step++) {
if (lo < hi) {
let mid = lo + (hi - lo) / 2u;
if (data[at + mid * 2u + kx] < x) {
lo = mid + 1u;
} else {
hi = mid;
}
}
}
let i = clamp(lo, 1u, n - 1u);
@@ -156,13 +159,22 @@ fn fxl_shaper_at(s: u32, k: u32) -> vec2<u32> {
return vec2<u32>(at, u32(data[s + k]));
}
// Evaluate independent shaper channels without dynamically writing vector lanes.
fn fxl_shaper_apply(sh: u32, c: vec3<f32>, flip: bool) -> vec3<f32> {
let r = fxl_shaper_at(sh, 0u);
let g = fxl_shaper_at(sh, 1u);
let b = fxl_shaper_at(sh, 2u);
return vec3<f32>(
fxl_shape(r.x, r.y, c.x, flip),
fxl_shape(g.x, g.y, c.y, flip),
fxl_shape(b.x, b.y, c.z, flip)
);
}
fn fxl_file_fwd(o: u32, sh: i32, c0: vec3<f32>, interp: u32) -> vec3<f32> {
var c = c0;
if (sh >= 0) {
for (var k = 0u; k < 3u; k++) {
let a = fxl_shaper_at(u32(sh), k);
c[k] = fxl_shape(a.x, a.y, c[k], false);
}
c = fxl_shaper_apply(u32(sh), c, false);
}
return fxl_lut_apply(o, c, interp);
}
@@ -176,12 +188,16 @@ fn fxl_inv_1d(o: u32, i: u32, y: f32) -> f32 {
// partition_point over the table's values.
var lo = 0u;
var hi = n;
while (lo < hi) {
let mid = (lo + hi) / 2u;
if (data[b1 + mid * 3u + i] < y) {
lo = mid + 1u;
} else {
hi = mid;
// A u32 interval needs at most 32 halvings. A fixed trip count avoids
// a divergent data-dependent loop on software Vulkan without changing lookup.
for (var step = 0u; step < 32u; step++) {
if (lo < hi) {
let mid = lo + (hi - lo) / 2u;
if (data[b1 + mid * 3u + i] < y) {
lo = mid + 1u;
} else {
hi = mid;
}
}
}
let k = clamp(lo, 1u, n - 1u);
@@ -205,10 +221,7 @@ fn fxl_file(o: u32, sh: i32, c: vec3<f32>, interp: u32, inverse: bool) -> vec3<f
x = vec3<f32>(fxl_inv_1d(o, 0u, c.x), fxl_inv_1d(o, 1u, c.y), fxl_inv_1d(o, 2u, c.z));
}
if (sh >= 0) {
for (var k = 0u; k < 3u; k++) {
let a = fxl_shaper_at(u32(sh), k);
x[k] = fxl_shape(a.x, a.y, x[k], true);
}
x = fxl_shaper_apply(u32(sh), x, true);
}
return x;
}
@@ -444,12 +457,11 @@ fn fxl_run(c0: vec3<f32>) -> vec3<f32> {
case 1u, 2u: {
let tf = u32(data[pc + 1u]);
let g = data[pc + 2u];
for (var i = 0u; i < 3u; i++) {
if (op == 1u) {
c[i] = fxl_decode(tf, g, c[i]);
} else {
c[i] = fxl_encode(tf, g, c[i]);
}
// Explicit components avoid llvmpipe's dynamically indexed vector writes.
if (op == 1u) {
c = vec3<f32>(fxl_decode(tf, g, c.x), fxl_decode(tf, g, c.y), fxl_decode(tf, g, c.z));
} else {
c = vec3<f32>(fxl_encode(tf, g, c.x), fxl_encode(tf, g, c.y), fxl_encode(tf, g, c.z));
}
pc += 3u;
}
+21
View File
@@ -145,6 +145,27 @@ fn fxm_sprite(at: u32, x: f32, y: f32) -> FxmShade {
}
cov = fxm_aa(m);
}
// sim::Shape::Ball (CC Ball Action's Shading): the sphere's light and shine scaled by
// |shade| (data[at + 9]), lit from the lower right when shade < 0.
case 9u: {
let d = sqrt(dx * dx + dy * dy);
let cv = fxm_aa(r - d);
if (cv <= 0.0) {
return fxm_none();
}
let shade = data[at + 9u];
let nx = dx / r;
let ny = dy / r;
let nz = sqrt(max(1.0 - nx * nx - ny * ny, 0.0));
let m = select(1.0, -1.0, shade < 0.0);
let diff = max(nx * (-0.48 * m) + ny * (-0.58 * m) + nz * 0.66, 0.0);
let rz = 2.0 * diff * nz - 0.66;
let st = abs(shade);
let spec = powz(max(rz, 0.0), 20.0) * 0.6 * st;
let k = max(1.0 - st * 0.8 * (1.0 - diff), 0.0);
rgb = rgb * k + spec;
cov = cv;
}
default: {
let lx = data[at + 9u];
let ly = data[at + 10u];
+22 -3
View File
@@ -289,9 +289,25 @@ fn box_pass(gid: vec3<u32>, horizontal: bool) {
}
let norm = 1.0 / f32(2 * r + 1);
var acc = vec4<f32>(0.0);
for (var i = b0 - r; i <= b0 + r; i++) {
// The starting window, as the CPU sums it: the pixels inside the line once each, and the
// repeated edge pixels counted rather than visited (a radius far past the line, such as
// Gaussian Blur's at Blurriness 30000, would otherwise loop over it once per pixel).
let lo = b0 - r;
let hi = b0 + r;
for (var i = max(lo, 0); i <= min(hi, n - 1); i++) {
acc += line_get(horizontal, line, i, n, repeat);
}
if (repeat) {
let before = f32(max(-lo, 0));
let after = f32(max(hi - (n - 1), 0));
// A zero count adds nothing (0 * NaN would be NaN).
if (before > 0.0) {
acc += line_get(horizontal, line, 0, n, repeat) * before;
}
if (after > 0.0) {
acc += line_get(horizontal, line, n - 1, n, repeat) * after;
}
}
let b1 = min(b0 + block, n);
for (var i = b0; i < b1; i++) {
if (horizontal) {
@@ -618,7 +634,8 @@ fn straight(px: vec4<f32>) -> vec3<f32> {
// 9 Gradient Ramp f[0] = (sx, sy, ex, ey); f[1] = start colour; f[2] = end colour;
// f[3] = (len2, scatter, blend); u[0] = (_, radial, seed)
// 10 Fractal Noise f[0] = (contrast, brightness, scale x, frac); f[1] = (ox, oy, sr, cr);
// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling);
// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling,
// OCTAVE_SCALE_MAX);
// u[0] = (_, kind, n_oct, seed); u[1] = (invert, overflow, normal blend)
@compute @workgroup_size(16, 16)
fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
@@ -856,6 +873,7 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
let scale_y = P.f[2].w;
let infl = P.f[3].x;
let fmul = P.f[3].y;
let fmax = P.f[3].z;
let frac = P.f[0].w;
let ox = P.f[1].x;
let oy = P.f[1].y;
@@ -888,7 +906,8 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3<u32>) {
sum += n * amp * w;
norm += amp * w;
amp *= infl;
f *= fmul;
// noise3::next_octave: the frequency stays within OCTAVE_SCALE_MAX (#3486).
f = clamp(f * fmul, 1.0 / fmax, fmax);
}
var val = sum / max(norm, 1e-6);
val = (val - 0.5) * contrast + 0.5 + brightness;
+62
View File
@@ -760,6 +760,68 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() {
}
}
/// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU
/// runs it and matches the CPU (1000, the old maximum, on a 70 × 44 layer). Once the pixel
/// budget cuts the padding only the CPU blurs past the buffer's edge, so the GPU declines the
/// effect; the render then takes it on the CPU at 8 and 32 bpc, with and without Shadow Only.
#[test]
fn drop_shadow_large_softness_matches_cpu() {
effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]);
let Some(g) = gpu() else { return };
for only in [false, true] {
let vals = [("distance", n(6.0)), ("softness", n(30000.0)), ("opacity", n(100.0)), ("shadowOnly", Value::Bool(only))];
let spec = effectcraft_effects::find("ec.perspective.dropshadow").unwrap();
let mut params = effectcraft_effects::Params {
values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, [70.0, 44.0]))).collect(),
};
for (k, v) in &vals {
params.values.insert(k.to_string(), v.clone());
}
let ctx = effectcraft_effects::EffectCtx { params: &params, time: 0.0, layer_size: [70.0, 44.0], seed: 11, adjustment: false, env: Default::default() };
let buf = effectcraft_effects::Buf { img: pattern(7, 70, 44), offset: [0.0, 0.0], scale: 1.0 };
let step = effectcraft_render::FxStep { spec, ctx };
assert!(effectcraft_render::Accelerator::effects(g, &[step], &buf, None).is_none(), "the GPU hands a cut margin to the CPU");
for depth in [BitDepth::Bpc8, BitDepth::Bpc32] {
let mut s = Scene::new(depth);
let bg = s.solid([0.15, 0.1, 0.2], 97, 61);
s.push(bg);
let mut l = s.footage(70, 44);
s.effect(&mut l, "ec.perspective.dropshadow", &vals);
s.push(l);
check(&format!("drop shadow 30000 only {only} {depth:?}"), compare_at(&s, opts(), Tick::ZERO), 0.0);
}
}
}
/// #3460: a box radius far past the image (Gaussian Blur's at Blurriness 30000 is about 15000 px)
/// starts each running sum as the CPU does, the pixels inside once and the repeated edges
/// counted, so the GPU matches it along rows and columns, with and without repeated edges.
#[test]
fn box_passes_with_a_radius_far_past_the_image_match_cpu() {
let Some(g) = gpu() else { return };
let img = pattern(5, 96, 40);
let up = g.ctx.upload_image(&img).expect("upload");
let tol = tolerance(BitDepth::Bpc32);
for repeat in [true, false] {
let mut e = crate::context::Enc::new(&g.ctx);
let r = [15_000usize; 3];
let out = crate::effects::box_passes(&mut e, &up, &r, &r, repeat);
let got = e.download(&out).expect("download");
let want = effectcraft_raster::box_blur(&img, 15_000, 15_000, 3, repeat);
assert_eq!((got.width, got.height), (want.width, want.height));
let d = diff(&want, &got, tol);
assert_eq!(d.over, 0, "repeat {repeat}: max {} at {:?} on {}", d.max, d.worst, g.ctx.name);
}
}
/// #3460: Gaussian Blur's highest Blurriness, 30000, renders the same on the GPU as on the CPU,
/// with the padding cut to the effect pixel budget and with Repeat Edge Pixels.
#[test]
fn gaussian_blur_at_the_highest_blurriness_matches_cpu() {
effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0))]);
effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0)), ("repeatEdge", Value::Bool(true))]);
}
#[test]
fn gpu_effects_match_cpu() {
// Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939).
+8
View File
@@ -57,6 +57,14 @@ fn turbulent_displace_and_cc_lens() {
],
);
effect_case("ec.distort.turbulentdisplace", &[("displacement", e(8)), ("size", n(15.0)), ("pinning", e(6))]);
// #3469: both ends of After Effects' Amount range, resized and pinned, and an expression's
// Amount past it.
effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(10000.0))]);
effect_case(
"ec.distort.turbulentdisplace",
&[("displacement", e(1)), ("size", n(25.0)), ("amount", n(-10000.0)), ("pinning", e(1)), ("resizeLayer", on())],
);
effect_case("ec.distort.turbulentdisplace", &[("displacement", e(7)), ("amount", n(f64::INFINITY)), ("pinning", e(2))]);
// #943: Evolution moves the pattern at a constant rate on both paths, including steps of a
// few degrees and angles past a whole revolution, where an eased evolution axis diverges.
for evolution in [10.0, 37.0, 400.0, 725.5] {
+3
View File
@@ -24,6 +24,9 @@ fn radial_blur() {
effect_case("ec.blur.radial", &[("amount", n(12.0))]);
effect_case("ec.blur.radial", &[("amount", n(30.0)), ("type", e(1)), ("center", pt(20.3, 14.7))]);
effect_case("ec.blur.radial", &[("amount", n(-45.0)), ("center", pt(50.0, 30.0))]);
// Amount's largest value, 1000 (#3467): Spin over ±500°, Zoom from the centre outwards.
effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("center", pt(20.3, 14.7))]);
effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("type", e(1)), ("center", pt(20.3, 14.7)), ("antialiasing", e(1))]);
}
#[test]
+29
View File
@@ -97,6 +97,35 @@ fn apply_color_lut() {
effect_case("ec.utility.applylut", &[("lut", s("/nonexistent/grade.cube"))]);
}
// Keep this separate so Nextest runs the inverse lookup in a fresh process/device,
// without the preceding 3D LUT submissions in `ocio_file_transform`. The combined
// test stays intact to cover ordering and shared-device state as well.
#[test]
fn inverse_1d_lut_on_a_fresh_device_matches_cpu() {
effect_direct("ec.color.ociofile", &[("file", s(&cube_1d())), ("direction", e(1))], false);
}
// Isolate the first profile conversion that failed in hosted llvmpipe coverage.
// This retains the same oracle and tolerance as the broader profile test.
#[test]
fn profile_conversion_on_a_fresh_device_matches_cpu() {
effect_direct("ec.utility.colorprofileconverter", &[("inputProfile", e(1)), ("outputProfile", e(3)), ("intent", e(0))], false);
}
// Unequal CSP channel point counts exercise shaper offsets on a fresh device.
#[test]
fn csp_shaper_on_a_fresh_device_matches_cpu() {
effect_direct("ec.color.ociofile", &[("file", s(&csp())), ("interpolation", e(1))], false);
effect_direct("ec.color.ociofile", &[("file", s(&csp())), ("direction", e(1))], false);
}
// A 1D CSP takes the direct inverse-shaper path (flip=true), unlike a 3D CSP.
#[test]
fn inverse_1d_csp_shaper_on_a_fresh_device_matches_cpu() {
let lut = "CSPLUTV100\n1D\n3\n0 0.5 1\n0 0.3 1\n2\n0 1\n0 1\n4\n0 0.2 0.6 1\n0 0.4 0.7 1\n2\n0 0 0\n1 1 1\n";
effect_direct("ec.color.ociofile", &[("file", s(lut)), ("direction", e(1))], false);
}
#[test]
fn ocio_file_transform() {
for interp in 1..4 {
+20
View File
@@ -75,6 +75,8 @@ fn edge_preserving_blurs() {
fn sharpen_and_unsharp_mask() {
effect_case("ec.blur.sharpen", &[("amount", n(60.0))]);
effect_case("ec.blur.sharpen", &[("amount", n(250.0))]);
// #3466: the top of After Effects' range (80 × the difference from the blur).
effect_case("ec.blur.sharpen", &[("amount", n(4000.0))]);
effect_case("ec.blur.unsharp", &[("amount", n(120.0)), ("radius", n(4.0))]);
effect_case("ec.blur.unsharp", &[("amount", n(80.0)), ("radius", n(2.5)), ("threshold", n(12.0))]);
}
@@ -136,6 +138,24 @@ fn turbulent_noise() {
effect_case("ec.noise.turbulent", &[("fractalType", e(7)), ("noiseType", e(0)), ("transform/perspectiveOffset", on()), ("opacity", n(70.0))]);
}
/// #3486: Sub Scaling above 100 % on both GPU paths (the `pointwise` kernel for the plain
/// settings, `fxn_fractal` for Perspective Offset and Turbulent Noise), up to After Effects'
/// 10000 at the highest Complexity.
#[test]
fn fractal_noise_sub_scaling_above_100() {
for sub in [200.0, 10000.0] {
effect_case("ec.noise.fractal", &[("subSettings/subScaling", n(sub)), ("complexity", n(20.0))]);
effect_case(
"ec.noise.fractal",
&[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("transform/perspectiveOffset", on()), ("evolution", n(90.0))],
);
effect_case(
"ec.noise.turbulent",
&[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("evolution", n(120.0)), ("evolutionOptions/turbulenceFactor", n(10.0))],
);
}
}
#[test]
fn fractal_noise_other_modes() {
effect_case("ec.noise.fractal", &[("noiseType", e(3)), ("fractalType", e(4)), ("blendingMode", e(3))]);
+16 -1
View File
@@ -141,7 +141,22 @@ fn ball_action_pixel_polly_scatterize() {
0.0,
0.0,
);
case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("instabilityState", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0);
case("ec.sim.ccballaction", &[("gridSpacing", n(2.0)), ("ballSize", n(80.0)), ("scatterMotion", n(45.0)), ("twistProperty", e(2))], 0.0, 0.0);
// #3197: Shading (flat, weaker, stronger, lit from the other side), Coloring, Displace.
for shading in [0.0, -30.0, -100.0, 60.0, 1e45] {
case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("shading", n(shading))], 0.0, 0.0);
}
for coloring in [0, 2] {
case("ec.sim.ccballaction", &[("ballSize", n(80.0)), ("coloring", e(coloring))], 0.0, 0.0);
}
for prop in [3, 6, 8] {
case(
"ec.sim.ccballaction",
&[("ballSize", n(80.0)), ("rotationAxis", e(1)), ("rotation", n(30.0)), ("displace", n(40.0)), ("displaceProperty", e(prop))],
0.0,
0.0,
);
}
for object in 0..4 {
case("ec.sim.ccpixelpolly", &[("object", e(object)), ("gridSpacing", n(6.0))], 0.6, 0.0);
}
+7
View File
@@ -218,6 +218,13 @@ fn twirl_legacy_ripple_pulse_power_pin() {
// Perspective below 100 %: blended toward the bilinear inverse.
effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(0.0))]);
effect_case("ec.distort.ccpowerpin", &[("topLeft", pt(12.0, 6.0)), ("bottomRight", pt(75.0, 30.0)), ("perspective", n(40.0)), ("expandTop", n(15.0))]);
// #3492: Expansion down to -200; opposite sides adding up to less than -100 % flip the source,
// and Top -50 / Bottom -50 leave it zero high.
effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("expandTop", n(-200.0)), ("expandBottom", n(-100.0)), ("expandLeft", n(-150.0))]);
effect_case(
"ec.distort.ccpowerpin",
&[("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(40.0)), ("expandTop", n(-50.0)), ("expandBottom", n(-50.0)), ("expandRight", n(-200.0))],
);
}
#[test]
+38
View File
@@ -156,6 +156,44 @@ fn a_wrong_checksum_or_a_bad_module_installs_nothing() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn downloads_are_release_assets_of_the_package_repository() {
let dir = tmp("assets");
let sum = "0".repeat(64);
let pkg =
|id: &str, repo: &str, url: &str| json!({"id": id, "name": id, "repo": repo, "versions": [{"version": "1", "api": 1, "url": url, "sha256": sum}]});
let catalog = write_catalog(
&dir,
json!([
pkg("org.test.other", "https://github.com/me/glow", "https://github.com/someone/else/releases/download/v1/glow.wasm"),
pkg("org.test.raw", "https://github.com/me/glow", "https://raw.githubusercontent.com/me/glow/main/glow.wasm"),
pkg("org.test.page", "", "https://github.com/me/glow/blob/main/glow.wasm"),
pkg("org.test.dots", "https://github.com/me/glow", "https://github.com/me/glow/releases/download/%2e%2e/%2E%2E/x/y/glow.wasm"),
pkg("org.test.tree", "https://github.com/me/glow/tree/main", "https://github.com/someone/else/releases/download/v1/glow.wasm"),
pkg("org.test.http", "http://github.com/me/glow", "https://github.com/me/glow/releases/download/v1/glow.wasm"),
pkg("org.test.blob", "https://github.com/me/glow/blob/main/README.md", "https://github.com/me/glow/releases/download/v1/glow.wasm"),
]),
);
let mut s = session(&dir);
s.execute("library.refresh", json!({"catalog": catalog, "wait": true})).unwrap();
for (id, why) in [
("org.test.other", "isn't a release asset of the package's repository https://github.com/me/glow"),
("org.test.raw", "isn't a release asset"),
("org.test.page", "isn't a release asset"),
("org.test.dots", "isn't a release asset"),
("org.test.tree", "isn't a release asset of the package's repository https://github.com/me/glow/tree/main"),
("org.test.http", "org.test.http: the package's `repo` http://github.com/me/glow isn't a GitHub repository URL"),
("org.test.blob", "org.test.blob: the package's `repo` https://github.com/me/glow/blob/main/README.md isn't a GitHub repository URL"),
] {
for c in ["library.install", "library.preview"] {
let e = s.execute(c, json!({"id": id, "wait": true})).unwrap_err().to_string();
assert!(e.contains(why), "{c} {id}: {e}");
}
}
assert!(!dir.join("Plug-ins").join("Library").join("installed.json").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn installed_packages_load_at_start_and_changed_files_are_refused() {
let dir = tmp("startup");
+2 -1
View File
@@ -54,6 +54,7 @@ fn still(p: &mut fp::Project, path: &str) -> fp::ItemId {
codec: "png".into(),
pixel_format: String::new(),
color: Default::default(),
color_assumed: None,
has_alpha: false,
bitrate: None,
hdr: None,
@@ -75,7 +76,7 @@ fn still(p: &mut fp::Project, path: &str) -> fp::ItemId {
identity: None,
};
let name = path.rsplit('/').next().unwrap().to_string();
p.add_item(&name, fp::Label::Iris, fp::ItemKind::Media(clip), None)
p.add_item(&name, fp::Label::Iris, fp::ItemKind::Media(Box::new(clip)), None)
}
/// V1: red for 2 s; V2: blue at 50 % opacity and 50 % scale; a cross dissolve from red to green
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-timeline = { workspace = true }
effectcraft-time = { workspace = true }
effectcraft-color = { workspace = true }
effectcraft-keyframe = { workspace = true }
+16 -3
View File
@@ -365,7 +365,7 @@ impl Exporter<'_> {
let mut clip = media_clip(fp::MediaRef::File { path: path.clone() }, info);
clip.offline = f.missing;
let bin = self.bin(it.and_then(|i| i.parent));
let id = self.fp.add_item(&name, fp::Label::Iris, fp::ItemKind::Media(clip), bin);
let id = self.fp.add_item(&name, fp::Label::Iris, fp::ItemKind::Media(Box::new(clip)), bin);
self.media.insert(path, id);
id
}
@@ -384,7 +384,7 @@ impl Exporter<'_> {
Some(b)
}
};
let id = self.fp.add_item(name, fp::Label::Violet, fp::ItemKind::Media(clip), bin);
let id = self.fp.add_item(name, fp::Label::Violet, fp::ItemKind::Media(Box::new(clip)), bin);
self.media.insert(r.path.clone(), id);
id
}
@@ -405,7 +405,7 @@ impl Exporter<'_> {
);
let clip = media_clip(fp::MediaRef::Generator(Generator::ColorMatte { color: [color[0], color[1], color[2], 1.0] }), info);
let bin = self.bin(it.and_then(|i| i.parent));
let id = self.fp.add_item(&name, fp::Label::Rose, fp::ItemKind::Media(clip), bin);
let id = self.fp.add_item(&name, fp::Label::Rose, fp::ItemKind::Media(Box::new(clip)), bin);
self.media.insert(key, id);
id
}
@@ -540,6 +540,9 @@ impl Exporter<'_> {
comment: if m.chapter.is_empty() { String::new() } else { m.comment.clone() },
kind: if m.chapter.is_empty() { fp::MarkerKind::Comment } else { fp::MarkerKind::Chapter },
color: fp::Label::Green,
custom_color: None,
author: String::new(),
url: m.url.clone(),
})
.collect();
if let Some(seq) = self.fp.sequence_mut(sid) {
@@ -733,6 +736,7 @@ fn media_info(name: &str, kind: MediaKind, duration: Tick, video: Option<VideoSp
codec,
pixel_format: String::new(),
color: Default::default(),
color_assumed: None,
has_alpha,
bitrate: None,
hdr: None,
@@ -755,6 +759,15 @@ fn media_clip(media: fp::MediaRef, info: MediaInfo) -> fp::MediaClip {
mod tests {
use super::*;
#[test]
fn synthesized_video_metadata_does_not_claim_an_inferred_color_profile() {
let info = media_info("clip", MediaKind::Movie, Tick::ZERO, Some((1920, 1080, FrameRate::new(24, 1), 1.0, "raw".into(), true)), false);
let video = info.video.unwrap();
assert_eq!((video.width, video.height), (1920, 1080));
assert!(video.color_assumed.is_none());
assert!(video.has_alpha);
}
/// A folder's bin is the same one each time it is asked for (a cached folder once answered
/// `None`, so a folder's second item went to the project root); a non-item has no bin.
#[test]
+6 -75
View File
@@ -49,78 +49,7 @@ pub struct ImportResult {
/// a few levels per nested sequence; parsing several thousand levels overflowed the stack.
pub const MAX_DEPTH: usize = 256;
/// The deepest element nesting of an XML document (a quick scan that skips comments, CDATA,
/// processing instructions, declarations and quoted attribute values).
pub(crate) fn xml_depth(b: &[u8]) -> usize {
let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize);
let skip_to = |from: usize, end: &[u8]| b.get(from..).and_then(|r| r.windows(end.len()).position(|w| w == end)).map_or(b.len(), |p| from + p + end.len());
while let Some(&c) = b.get(i) {
if c != b'<' {
i += 1;
continue;
}
let rest = b.get(i..).unwrap_or_default();
if rest.starts_with(b"<!--") {
i = skip_to(i + 4, b"-->");
} else if rest.starts_with(b"<![CDATA[") {
i = skip_to(i + 9, b"]]>");
} else if rest.starts_with(b"<?") {
i = skip_to(i + 2, b"?>");
} else if rest.starts_with(b"<!") {
i = skip_to(i + 2, b">");
} else if rest.starts_with(b"</") {
depth = depth.saturating_sub(1);
i = skip_to(i + 2, b">");
} else {
// A start tag: find its end outside quotes; `/>` closes it at once.
let mut j = i + 1;
let mut quote = None;
while let Some(&c) = b.get(j) {
match quote {
Some(q) if c == q => quote = None,
Some(_) => {}
None if c == b'"' || c == b'\'' => quote = Some(c),
None if c == b'>' => break,
None => {}
}
j += 1;
}
if b.get(j.wrapping_sub(1)) != Some(&b'/') {
depth += 1;
max = max.max(depth);
}
i = j + 1;
}
}
max
}
/// The deepest array / object nesting of a JSON document (strings skipped).
pub(crate) fn json_depth(b: &[u8]) -> usize {
let (mut depth, mut max, mut in_str, mut esc) = (0usize, 0usize, false, false);
for &c in b {
if in_str {
if esc {
esc = false;
} else if c == b'\\' {
esc = true;
} else if c == b'"' {
in_str = false;
}
continue;
}
match c {
b'"' => in_str = true,
b'[' | b'{' => {
depth += 1;
max = max.max(depth);
}
b']' | b'}' => depth = depth.saturating_sub(1),
_ => {}
}
}
max
}
pub(crate) use craft_timeline::preflight::{json_depth, xml_depth};
pub fn import(
project: &mut Project,
@@ -201,8 +130,8 @@ const EDL_MEDIA_TIME_NOTE: &str = "EDL source timecodes were imported as media t
/// The largest start timecode, in frames, a file may have: a day at 1000 fps.
const MAX_FILE_TIMECODE: i64 = 24 * 3600 * 1000;
/// The paths an EDL reader guessed (media it flags offline: a line without `SOURCE FILE` names
/// only its clip) that are not inside the list's folder: a clip name of `../x.mov` or an absolute
/// The paths an EDL reader guessed (identified by its `Tape Name` metadata: a line without
/// `SOURCE FILE` names only its clip) that are not inside the list's folder: a clip name of `../x.mov` or an absolute
/// one would link a file elsewhere on the disk. They stay placeholders. A `SOURCE FILE` path is
/// the list's own choice and is kept, also when another clip guesses the same path.
fn guessed_outside(project: &fp::Project, base_dir: Option<&str>) -> HashSet<String> {
@@ -219,7 +148,9 @@ fn guessed_outside(project: &fp::Project, base_dir: Option<&str>) -> HashSet<Str
if let fp::ItemKind::Media(m) = &it.kind
&& let fp::MediaRef::File { path } = &m.media
{
if m.offline && !inside(path) {
// Film reserves `offline` for an explicit user action now. Its EDL reader sets
// Tape Name only on reel/clip-name guesses, never on SOURCE FILE references.
if it.metadata.contains_key("Tape Name") && !inside(path) {
guessed.insert(path.clone());
} else {
named.insert(path.clone());
+16 -1
View File
@@ -34,6 +34,7 @@ fn info(kind: filmcraft_media::MediaKind, video: bool, audio: bool) -> filmcraft
codec: "png".into(),
pixel_format: String::new(),
color: Default::default(),
color_assumed: None,
has_alpha: false,
bitrate: None,
hdr: None,
@@ -60,7 +61,7 @@ fn media(p: &mut fp::Project, name: &str, path: &str, kind: filmcraft_media::Med
proxy: None,
identity: None,
};
p.add_item(name, fp::Label::Iris, fp::ItemKind::Media(clip), bin)
p.add_item(name, fp::Label::Iris, fp::ItemKind::Media(Box::new(clip)), bin)
}
fn rate() -> filmcraft_time::FrameRate {
@@ -882,3 +883,17 @@ fn import_finds_each_clips_transitions_without_scanning_the_track() {
let mid = m.layers.iter().find(|l| near(l.in_point, t(100.0 - 0.08))).expect("clip 250 extended into its incoming transition");
assert!(near(mid.out_point, t(100.4 + 0.08)), "{}", mid.out_point.seconds());
}
#[test]
fn edl_explicit_source_file_allows_the_same_path_as_an_outside_guess() {
let edl = b"TITLE: CUT\nFCM: NON-DROP FRAME\n\n001 A001 V C 00:00:00:00 00:00:01:00 00:00:00:00 00:00:01:00\n* FROM CLIP NAME: ../shared.mov\n\n002 A002 V C 00:00:00:00 00:00:01:00 00:00:01:00 00:00:02:00\n* FROM CLIP NAME: named.mov\n* SOURCE FILE: /shared.mov\n";
let mut asked = Vec::new();
let mut probe_all = |path: &str| {
asked.push(path.to_string());
probe(path)
};
let mut p = Project::default();
let opts = ImportOptions { name: "hand.edl".into(), edl_frame_rate: Some(25.0), base_dir: Some("/work".into()) };
import(&mut p, edl, None, &opts, &mut probe_all).unwrap();
assert_eq!(asked, ["/shared.mov"], "explicit SOURCE FILE permits the shared path, probed once");
}
+9 -3
View File
@@ -505,11 +505,17 @@ pub fn export_comp(project: &Project, comp: ItemId, opts: &ExportOptions, read:
/// Package an export as a dotLottie archive (`manifest.json` + `animations/<id>.json`).
pub fn to_dotlottie(res: &ExportResult, id: &str) -> Vec<u8> {
try_to_dotlottie(res, id).unwrap_or_default()
}
/// Package an export, reporting serialization or ZIP failures before any output is written.
pub fn try_to_dotlottie(res: &ExportResult, id: &str) -> Result<Vec<u8>, LottieError> {
let id: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
let id = if id.is_empty() { "animation".to_string() } else { id };
let manifest = json!({"version": "1", "generator": "EffectCraft", "author": "", "animations": [{"id": id, "speed": 1, "loop": true}]});
crate::zip::store(&[
("manifest.json".into(), serde_json::to_vec(&manifest).unwrap_or_default()),
(format!("animations/{id}.json"), serde_json::to_vec(&res.json).unwrap_or_default()),
crate::zip::try_store(&[
("manifest.json".into(), serde_json::to_vec(&manifest).map_err(|e| LottieError::Invalid(e.to_string()))?),
(format!("animations/{id}.json"), serde_json::to_vec(&res.json).map_err(|e| LottieError::Invalid(e.to_string()))?),
])
.map_err(|e| LottieError::Invalid(format!("dotLottie ZIP: {e}")))
}
+4 -4
View File
@@ -41,7 +41,7 @@ pub struct ImportResult {
pub warnings: Vec<String>,
}
/// The Lottie document inside raw bytes (plain JSON, or a stored dotLottie archive), read into
/// The Lottie document inside raw bytes (plain JSON, or a dotLottie archive), read into
/// `craft-lottie`'s model within its default limits.
fn document(bytes: &[u8]) -> Result<Animation, LottieError> {
let read = |b: &[u8]| {
@@ -51,12 +51,12 @@ fn document(bytes: &[u8]) -> Result<Animation, LottieError> {
})
};
if bytes.starts_with(b"PK") {
let entries = crate::zip::read_stored(bytes);
let entries = crate::zip::read_entries(bytes).map_err(|e| LottieError::Parse(format!("dotLottie ZIP: {e}")))?;
let anim = entries
.iter()
.find(|(n, _)| n.starts_with("animations/") && n.ends_with(".json"))
.or_else(|| entries.iter().find(|(n, _)| n.ends_with(".json") && n != "manifest.json"))
.ok_or_else(|| LottieError::Parse("dotLottie archive without an uncompressed animation".into()))?;
.ok_or_else(|| LottieError::Parse("dotLottie archive without a JSON animation".into()))?;
return read(&anim.1);
}
read(bytes)
@@ -102,7 +102,7 @@ fn external_image(stored: &str, base_dir: &str) -> Result<String, String> {
}
}
/// Import a Lottie document (JSON or a stored `.lottie` archive) into `project` as a new
/// Import a Lottie document (JSON or a `.lottie` archive) into `project` as a new
/// composition. `store` saves embedded images and returns the file path to use;
/// `base_dir` resolves external image references.
pub fn import(
+1 -1
View File
@@ -30,7 +30,7 @@ pub mod zip;
use effectcraft_color::BlendMode;
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
pub use export::{ExportOptions, ExportResult, export_comp, to_dotlottie};
pub use export::{ExportOptions, ExportResult, export_comp, to_dotlottie, try_to_dotlottie};
pub use import::{ImportResult, ImportedImage, import};
#[derive(Debug, thiserror::Error)]
+36 -1
View File
@@ -12,7 +12,7 @@ use effectcraft_render::render_frame;
use effectcraft_time::{FrameRate, Tick};
use serde_json::{Value as Json, json};
use crate::{ExportOptions, export_comp, import};
use crate::{ExportOptions, LottieError, export_comp, import};
fn s(x: f64) -> Tick {
Tick::from_seconds_f64(x)
@@ -799,6 +799,32 @@ fn dotlottie_archive_roundtrip() {
assert_eq!(q.comp(imp.comp).unwrap().layers.len(), 1);
}
#[test]
fn dotlottie_archive_without_animation_is_rejected() {
let zip = craft_lottie::zip::try_store(&[("manifest.json".into(), b"{}".to_vec())]).unwrap();
let mut project = Project::default();
let err = import(&mut project, &zip, "empty archive", "", &mut |_| None).unwrap_err();
assert!(matches!(err, LottieError::Parse(message) if message.contains("without a JSON animation")));
}
#[test]
fn deflated_dotlottie_archive_imports() {
let (mut p, cid) = setup();
let l = solid_layer(&mut p, cid, [0.0, 1.0, 0.0], 40, 40);
push(&mut p, cid, l);
let res = export_comp(&p, cid, &ExportOptions::default(), &no_read).unwrap();
let manifest = serde_json::to_vec(&serde_json::json!({"version":"1","animations":[{"id":"main"}]})).unwrap();
let animation = serde_json::to_vec(&res.json).unwrap();
let zip = craft_lottie::zip::try_store_with_compression(
&[("manifest.json".into(), manifest), ("animations/main.json".into(), animation)],
craft_lottie::zip::Compression::Deflated,
)
.unwrap();
let mut q = Project::default();
let imp = import(&mut q, &zip, "compressed", "", &mut |_| None).unwrap();
assert_eq!(q.comp(imp.comp).unwrap().layers.len(), 1);
}
// ---------------------------------------------------------------- hand-written fixtures
fn fixture(name: &str) -> (Project, ItemId, Vec<String>) {
@@ -1062,3 +1088,12 @@ fn only_image_bytes_are_embedded() {
assert!(res.json["assets"].as_array().is_none_or(|a| a.is_empty()), "{}", res.json["assets"]);
assert!(res.warnings.iter().any(|w| w.contains("not a PNG")), "{:?}", res.warnings);
}
#[test]
fn dotlottie_export_rejects_an_unrepresentable_entry_name() {
let (p, cid) = setup();
let res = export_comp(&p, cid, &ExportOptions::default(), &no_read).unwrap();
let err = crate::try_to_dotlottie(&res, &"a".repeat(usize::from(u16::MAX))).unwrap_err();
assert!(matches!(err, LottieError::Invalid(message) if message.contains("dotLottie ZIP")));
assert_eq!(crate::try_to_dotlottie(&res, "Main").unwrap(), crate::to_dotlottie(&res, "Main"));
}
+2 -120
View File
@@ -1,121 +1,3 @@
//! A minimal ZIP writer (stored entries, PKWARE APPNOTE 6.3 local headers + central directory)
//! for `.lottie` (dotLottie) archives.
//! Shared stored-entry ZIP functions used by dotLottie imports and exports.
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for &b in data {
crc ^= b as u32;
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
!crc
}
/// Build a ZIP archive with the given (name, bytes) entries, uncompressed.
pub fn store(entries: &[(String, Vec<u8>)]) -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
let put16 = |v: &mut Vec<u8>, x: u16| v.extend_from_slice(&x.to_le_bytes());
let put32 = |v: &mut Vec<u8>, x: u32| v.extend_from_slice(&x.to_le_bytes());
for (name, data) in entries {
let offset = out.len() as u32;
let crc = crc32(data);
let n = name.as_bytes();
// Local file header.
put32(&mut out, 0x0403_4b50);
put16(&mut out, 20); // version needed
put16(&mut out, 0x0800); // flags: UTF-8 names
put16(&mut out, 0); // stored
put16(&mut out, 0); // time
put16(&mut out, 0x21); // date (1980-01-01)
put32(&mut out, crc);
put32(&mut out, data.len() as u32);
put32(&mut out, data.len() as u32);
put16(&mut out, n.len() as u16);
put16(&mut out, 0);
out.extend_from_slice(n);
out.extend_from_slice(data);
// Central directory record.
put32(&mut central, 0x0201_4b50);
put16(&mut central, 20); // made by
put16(&mut central, 20);
put16(&mut central, 0x0800);
put16(&mut central, 0);
put16(&mut central, 0);
put16(&mut central, 0x21);
put32(&mut central, crc);
put32(&mut central, data.len() as u32);
put32(&mut central, data.len() as u32);
put16(&mut central, n.len() as u16);
put16(&mut central, 0); // extra
put16(&mut central, 0); // comment
put16(&mut central, 0); // disk
put16(&mut central, 0); // internal attrs
put32(&mut central, 0); // external attrs
put32(&mut central, offset);
central.extend_from_slice(n);
}
let cd_offset = out.len() as u32;
let cd_len = central.len() as u32;
out.extend_from_slice(&central);
put32(&mut out, 0x0605_4b50);
put16(&mut out, 0);
put16(&mut out, 0);
put16(&mut out, entries.len() as u16);
put16(&mut out, entries.len() as u16);
put32(&mut out, cd_len);
put32(&mut out, cd_offset);
put16(&mut out, 0);
out
}
/// Whether an entry name is a relative path inside the archive: not absolute (`/…`, `\…`), no
/// drive (`C:…`) and no `..` component.
fn is_relative_name(name: &str) -> bool {
let drive = name.as_bytes().get(1) == Some(&b':');
!name.starts_with(['/', '\\']) && !drive && !name.split(['/', '\\']).any(|c| c == "..")
}
/// Read the stored (uncompressed) entries of a ZIP archive written by [`store`] or any other
/// writer that did not compress. Compressed entries and entries whose names are not relative
/// paths inside the archive are skipped.
pub fn read_stored(data: &[u8]) -> Vec<(String, Vec<u8>)> {
let mut out = vec![];
let mut i = 0usize;
let u16_at = |p: usize| data.get(p..p + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize);
let u32_at = |p: usize| data.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize);
while u32_at(i) == Some(0x0403_4b50) {
let (Some(method), Some(size), Some(nlen), Some(xlen)) = (u16_at(i + 8), u32_at(i + 18), u16_at(i + 26), u16_at(i + 28)) else { break };
let name_start = i + 30;
let body = name_start + nlen + xlen;
let (Some(name), Some(bytes)) = (data.get(name_start..name_start + nlen), data.get(body..body + size)) else { break };
let name = String::from_utf8_lossy(name).to_string();
if method == 0 && is_relative_name(&name) {
out.push((name, bytes.to_vec()));
}
i = body + size;
}
out
}
#[cfg(test)]
mod tests {
#[test]
fn crc_and_roundtrip() {
assert_eq!(super::crc32(b"123456789"), 0xCBF4_3926);
let z = super::store(&[("a.json".into(), b"{}".to_vec()), ("b/c.txt".into(), b"hello".to_vec())]);
let back = super::read_stored(&z);
assert_eq!(back.len(), 2);
assert_eq!(back[1].0, "b/c.txt");
assert_eq!(back[1].1, b"hello");
}
#[test]
fn entries_outside_the_archive_root_are_skipped() {
let names = ["../up.txt", "a/../../up.txt", "/abs/x", "\\abs\\x", "C:\\x", "c:x", "a\\..\\x", "ok/x.txt", "ok/..x"];
let z = super::store(&names.iter().map(|n| (n.to_string(), b"x".to_vec())).collect::<Vec<_>>());
let back: Vec<String> = super::read_stored(&z).into_iter().map(|(n, _)| n).collect();
assert_eq!(back, ["ok/x.txt", "ok/..x"]);
}
}
pub use craft_lottie::zip::{Limits, read_entries, read_entries_with_limits, read_stored, store, try_store, try_store_with_compression};
+6 -7
View File
@@ -23,16 +23,14 @@ effectcraft-model = { workspace = true }
filmcraft-codecs = { workspace = true }
filmcraft-media = { workspace = true }
craft-dpx = { workspace = true }
craft-exr = { workspace = true }
craft-gif = { workspace = true }
craft-webp = { workspace = true }
craft-audio = { workspace = true }
craft-media = { workspace = true }
filmcraft-mpegts = { workspace = true }
craft-exr = { workspace = true, features = ["decode"] }
craft-gif = { workspace = true, features = ["frames"] }
craft-webp = { workspace = true, features = ["frames"] }
craft-audio = { workspace = true, features = ["aac-decode"] }
craft-media = { workspace = true, features = ["mpegts"] }
filmcraft-frame = { workspace = true }
filmcraft-color = { workspace = true }
filmcraft-time = { workspace = true }
exr = { workspace = true }
image = { workspace = true, features = ["gif", "webp", "tiff", "bmp", "exr", "tga", "hdr"] }
rayon = { workspace = true }
serde_json = { workspace = true }
@@ -40,6 +38,7 @@ thiserror = { workspace = true }
log = { workspace = true }
[dev-dependencies]
exr = { workspace = true }
# Writes the animated GIFs of the tests.
gif = { workspace = true }
tempfile = { workspace = true }
+5 -14
View File
@@ -62,15 +62,15 @@ fn matroska(file: &dyn ByteReader) -> Option<Vec<u8>> {
/// first unit it can read. Only AAC is asked about, so the streams before that one were refused
/// whatever their codec, and an ADTS stream played has no configuration outside its frames.
fn latm(file: &dyn ByteReader) -> Option<Vec<u8>> {
use filmcraft_mpegts::Codec;
use craft_media::mpegts::{self, Codec};
let head = Head(file, file.len().min(MPEG_HEAD));
let mpeg = filmcraft_mpegts::open(&head).ok()?;
let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == filmcraft_mpegts::Kind::Audio && !s.units.is_empty());
let mpeg = mpegts::open(&head).ok()?;
let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty());
let played = audio.take(filmcraft_media::MAX_AUDIO_STREAMS).find_map(|(i, s)| {
let first = mpeg.read_unit(&head, i, 0).ok()?;
match s.codec {
Codec::AacAdts => filmcraft_mpegts::frame_info(&s.codec, &first).map(|_| None),
Codec::AacLatm => filmcraft_codecs::audio::latm_config(&first).map(|c| Some(c.asc)),
Codec::AacAdts => mpegts::frame_info(&s.codec, &first).map(|_| None),
Codec::AacLatm => craft_audio::aac::latm_config(&first).map(|c| Some(c.asc)),
_ => None,
}
});
@@ -97,12 +97,3 @@ impl craft_media::ByteSource for Head<'_> {
self.read(offset, buf)
}
}
impl filmcraft_mpegts::ByteSource for Head<'_> {
fn len(&self) -> u64 {
self.1
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
self.read(offset, buf)
}
}
+176 -224
View File
@@ -1,5 +1,5 @@
//! Auxiliary channels from multi-layer OpenEXR files (depth, object / material IDs, normals,
//! Cryptomatte, …) for the 3D Channel effects, read with the pure-Rust `exr` crate.
//! Cryptomatte, …) for the 3D Channel effects, read through the shared `craft-exr` decoder.
//!
//! Every channel of every layer becomes a plane named `layer.channel` (or just `channel` for
//! the unnamed layer), placed in the display window (pixels outside a layer's data window are
@@ -18,12 +18,6 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, split_channel};
use effectcraft_raster::{AuxChannels, Image};
use effectcraft_render::reads::{ReadFile, ReadFiles};
use exr::block::UncompressedBlock;
use exr::block::chunk::TileCoordinates;
use exr::image::read::image::ReadImage;
use exr::image::read::layers::{ChannelsReader, ReadAllLayers, ReadChannels};
use exr::meta::attribute::SampleType;
use exr::meta::header::Header;
use crate::convert::{AlphaOp, float_to_image};
@@ -35,179 +29,20 @@ const MAX_DISPLAY_PIXELS: usize = 1 << 28;
use craft_exr::channels::{is_depth, part_channel_name as channel_name};
pub use craft_exr::cryptomatte::parse_manifest;
/// The part name channels are prefixed with (`None`: unnamed).
fn part_name(header: &Header) -> Option<String> {
header.own_attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty())
}
/// Why an OpenEXR file's pixels can't be decoded when its headers name a compression this build
/// can't decompress (HTJ2K, OpenEXR 3.4's High-Throughput JPEG 2000): the decoders only said
/// "no non-deep rgb channels" or showed a transparent frame (#482). `None` for other files.
pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> {
use exr::compression::Compression;
let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).ok()?;
meta.headers
let mut limits = craft_exr::decode::Limits::default();
limits.max_pixels = u64::MAX;
limits.max_bytes = u64::MAX;
craft_exr::decode::parts(bytes, &limits)
.ok()?
.iter()
.any(|h| matches!(h.compression, Compression::HTJ2K32 | Compression::HTJ2K256))
.any(|part| matches!(part.compression.as_str(), "HTJ2K32" | "HTJ2K256"))
.then_some("OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression")
}
/// Which channels a decode keeps, by plane name, and the display window they are placed in
/// (the first part's, as the `exr` crate reports the image's).
struct Planes<'k> {
keep: &'k dyn Fn(&str) -> bool,
display: exr::meta::attribute::IntegerBounds,
}
/// One part's kept channels while it is decoded: each line of samples goes straight into its
/// channel's display-window plane (no copy of the part's samples in their own type first).
struct PlanesReader {
/// Per channel of the part: its plane name, sample type and plane (`None`: not kept).
planes: Vec<Option<(String, SampleType, Vec<f32>)>>,
/// The data window's position in the display window, and the data window's and display
/// window's sizes.
offset: (i64, i64),
layer: (usize, usize),
display: (usize, usize),
f16s: Vec<exr::prelude::f16>,
u32s: Vec<u32>,
f32s: Vec<f32>,
/// The part's channel indices of exact `R`, `G`, `B` and `A`, when it has R, G and B.
rgb: Option<([usize; 3], Option<usize>)>,
/// The part's display window differs from the first part's.
own_display: bool,
}
/// A decoded part: its kept planes (in channel order) and what [`PlanesReader`] found.
struct PartPlanes {
planes: Vec<(String, Vec<f32>)>,
/// Positions in `planes` of the part's R, G, B (and A) channels, when it has them and keeps
/// them all.
rgb: Option<([usize; 3], Option<usize>)>,
has_rgb: bool,
exact: bool,
}
impl<'s> ReadChannels<'s> for Planes<'_> {
type Reader = PlanesReader;
fn create_channels_reader(&'s self, header: &Header) -> exr::error::Result<PlanesReader> {
if header.deep {
return Err(exr::error::Error::NotSupported("deep data".into()));
}
let dw = self.display;
let display = (dw.size.0, dw.size.1);
// Each channel is a display-window plane: a 60000² window over a 1×1 data window was a
// multi-gigabyte allocation per channel (#2141).
let n = display.0.checked_mul(display.1).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(exr::error::Error::Invalid("display window".into()))?;
let prefix = part_name(header);
let pos = header.own_attributes.layer_position;
let offset = (i64::from(pos.0) - i64::from(dw.position.0), i64::from(pos.1) - i64::from(dw.position.1));
let planes = header
.channels
.list
.iter()
.map(|ch| {
let name = channel_name(prefix.as_deref(), &ch.name.to_string());
let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 };
(self.keep)(&name).then(|| (name, ch.sample_type, vec![fill; n]))
})
.collect();
let find = |c: &str| header.channels.find_index_of_channel(&exr::meta::attribute::Text::from(c));
let rgb = match (find("R"), find("G"), find("B")) {
(Some(r), Some(g), Some(b)) => Some(([r, g, b], find("A"))),
_ => None,
};
Ok(PlanesReader {
planes,
offset,
layer: (header.layer_size.0, header.layer_size.1),
display,
f16s: vec![],
u32s: vec![],
f32s: vec![],
rgb,
own_display: header.shared_attributes.display_window != dw,
})
}
}
impl ChannelsReader for PlanesReader {
type Channels = PartPlanes;
fn filter_block(&self, tile: TileCoordinates) -> bool {
tile.is_largest_resolution_level() && self.planes.iter().any(Option::is_some)
}
fn read_block(&mut self, header: &Header, block: UncompressedBlock) -> exr::error::UnitResult {
let ((lw, lh), (w, h)) = (self.layer, self.display);
for line in block.lines(&header.channels) {
let Some(Some((_, kind, plane))) = self.planes.get_mut(line.location.channel) else { continue };
let (x0, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count);
// The samples of data-window row `y`, columns `x0..x0 + count`, at display row `ty`
// from display column `tx0`; clipped to the display window.
if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) {
continue;
}
let Some(ty) = usize::try_from(y as i64 + self.offset.1).ok().filter(|ty| *ty < h) else { continue };
let tx0 = x0 as i64 + self.offset.0;
let skip = usize::try_from(-tx0).unwrap_or(0).min(count);
let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX);
let take = (count - skip).min(w.saturating_sub(tx));
let start = ty.checked_mul(w).and_then(|row| row.checked_add(tx));
let Some(dst) = start.filter(|_| take > 0).and_then(|s| plane.get_mut(s..s.checked_add(take)?)) else { continue };
match kind {
SampleType::F16 => {
self.f16s.resize(count, exr::prelude::f16::ZERO);
line.read_samples_into_slice(&mut self.f16s)?;
for (d, s) in dst.iter_mut().zip(self.f16s.iter().skip(skip)) {
*d = s.to_f32();
}
}
SampleType::F32 => {
self.f32s.resize(count, 0.0);
line.read_samples_into_slice(&mut self.f32s)?;
for (d, s) in dst.iter_mut().zip(self.f32s.iter().skip(skip)) {
*d = *s;
}
}
SampleType::U32 => {
self.u32s.resize(count, 0);
line.read_samples_into_slice(&mut self.u32s)?;
for (d, s) in dst.iter_mut().zip(self.u32s.iter().skip(skip)) {
*d = *s as f32;
}
}
}
}
Ok(())
}
fn into_channels(self) -> PartPlanes {
// Positions of the kept channels among the kept planes.
let mut at = vec![None; self.planes.len()];
let mut planes = Vec::with_capacity(self.planes.len());
for (i, p) in self.planes.into_iter().enumerate() {
if let Some((name, _, data)) = p {
if let Some(slot) = at.get_mut(i) {
*slot = Some(planes.len());
}
planes.push((name, data));
}
}
let kept = |i: usize| at.get(i).copied().flatten();
let has_rgb = self.rgb.is_some();
let rgb = self.rgb.and_then(|([r, g, b], a)| {
let a = match a {
Some(a) => Some(kept(a)?),
None => None,
};
Some(([kept(r)?, kept(g)?, kept(b)?], a))
});
PartPlanes { planes, rgb, has_rgb, exact: !self.own_display }
}
}
/// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G`
/// and `B` channels (alpha `A` when it has one, else opaque), placed in the display window with
/// 0 outside the data window.
@@ -253,73 +88,117 @@ enum Refused {
TooLarge(String),
}
/// Bytes the planes of the channels `keep` names would take (`None`: not a readable header).
fn planes_bytes(meta: &exr::meta::MetaData, keep: &dyn Fn(&str) -> bool) -> Option<usize> {
let dw = meta.headers.first()?.shared_attributes.display_window;
let n = dw.size.0.checked_mul(dw.size.1)?;
let mut kept = 0usize;
for header in meta.headers.iter() {
let prefix = part_name(header);
kept = kept.saturating_add(header.channels.list.iter().filter(|ch| keep(&channel_name(prefix.as_deref(), &ch.name.to_string()))).count());
}
Some(n.saturating_mul(kept).saturating_mul(std::mem::size_of::<f32>()))
/// Bytes the selected channels occupy in each part's own display window. The channel cache
/// reserves this before decoding so concurrent imports cannot exceed its soft budget.
fn planes_bytes(infos: &[craft_exr::decode::PartInfo], keep: &dyn Fn(&str) -> bool) -> Option<usize> {
infos.first()?;
let total = infos.iter().try_fold(0u64, |total, part| {
let count = part.channels.iter().filter(|channel| keep(&channel_name(part.name.as_deref(), &channel.name))).count() as u64;
if count == 0 {
return Some(total);
}
let pixels = u64::from(part.display_window.width).checked_mul(u64::from(part.display_window.height))?;
total.checked_add(pixels.checked_mul(count)?.checked_mul(4)?)
})?;
usize::try_from(total).ok()
}
/// Decode the channels of an EXR file's bytes that `keep` names (by plane name).
/// Decode selected EXR channels through craft-exr, which places each selected block directly
/// into its bounded display-window plane.
fn decode(bytes: &[u8], keep: &dyn Fn(&str) -> bool) -> Result<Decoded, Refused> {
let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?;
let display = meta.headers.first().ok_or(Refused::Unreadable)?.shared_attributes.display_window;
let need = planes_bytes(&meta, keep).ok_or(Refused::Unreadable)?;
if need > MAX_DECODE_BYTES {
let gb = |b: usize| b as f64 / f64::from(1u32 << 30);
use craft_exr::decode::{self, Error as ExrError, Limits};
let mut limits = Limits::default();
limits.max_pixels = MAX_DISPLAY_PIXELS as u64;
limits.max_bytes = MAX_DECODE_BYTES as u64;
// Header-only checks must not charge channels this caller does not decode. The shared display
// decoder independently checks the exact selected display planes before allocating them. It
// also bounds a selected part's data window across all of its channels (decoded blocks carry
// every channel before the unused ones are dropped), so a part whose full channel set exceeds
// `max_bytes` is refused even when the kept planes alone would fit.
let mut header_limits = limits;
header_limits.max_width = u32::MAX;
header_limits.max_height = u32::MAX;
header_limits.max_pixels = u64::MAX;
header_limits.max_bytes = u64::MAX;
let infos = decode::parts(bytes, &header_limits).map_err(|e| match e {
ExrError::LimitExceeded(message) => Refused::TooLarge(message),
_ => Refused::Unreadable,
})?;
let display = infos.first().ok_or(Refused::Unreadable)?.display_window;
let needed = planes_bytes(&infos, keep).filter(|bytes| *bytes > 0).ok_or(Refused::Unreadable)?;
if needed > MAX_DECODE_BYTES {
let gb = |b: u64| b as f64 / f64::from(1u32 << 30);
return Err(Refused::TooLarge(format!(
"its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use",
display.size.0,
display.size.1,
gb(need),
gb(MAX_DECODE_BYTES)
display.width,
display.height,
gb(needed as u64),
gb(MAX_DECODE_BYTES as u64),
)));
}
let read = ReadImage::new(ReadAllLayers { read_channels: Planes { keep, display } }, |_| {});
let img = read.from_buffered(std::io::Cursor::new(bytes)).map_err(|_| Refused::Unreadable)?;
let dw = img.attributes.display_window;
let mut aux = AuxChannels::new(dw.size.0 as u32, dw.size.1 as u32, 1.0);
let mut aux = AuxChannels::new(display.width, display.height, 1.0);
let mut crypto: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
let mut collect_meta = |other: &HashMap<exr::meta::attribute::Text, exr::meta::attribute::AttributeValue>| {
for (k, v) in other {
let key = k.to_string();
let mut rgb = Rgb::None;
for info in infos {
for (key, value) in &info.text_attributes {
let Some(rest) = key.strip_prefix("cryptomatte/") else { continue };
let Some((id, field)) = rest.split_once('/') else { continue };
let exr::meta::attribute::AttributeValue::Text(t) = v else { continue };
let e = crypto.entry(id.to_string()).or_default();
let entry = crypto.entry(id.to_string()).or_default();
match field {
"name" => e.0 = Some(t.to_string()),
"manifest" => e.1 = Some(t.to_string()),
"name" => entry.0 = Some(value.clone()),
"manifest" => entry.1 = Some(value.clone()),
_ => {}
}
}
};
collect_meta(&img.attributes.other);
let mut rgb = Rgb::None;
for layer in img.layer_data {
collect_meta(&layer.attributes.other);
let part = layer.channel_data;
if rgb == Rgb::None && part.has_rgb {
let prefix = info.name.as_deref();
let exact = info.display_window == display;
let rgb_indices = ["R", "G", "B"].map(|wanted| info.channels.iter().position(|channel| channel.name == wanted));
let has_rgb = rgb_indices.iter().all(Option::is_some);
let alpha_index = info.channels.iter().position(|channel| channel.name == "A");
// Metadata above still belongs to the file, but an ignored part must not allocate or
// impose its pixel/deep-data limits on the selected picture channels.
if !info.channels.iter().any(|channel| keep(&channel_name(prefix, &channel.name))) {
if rgb == Rgb::None && has_rgb {
rgb = Rgb::Unsupported;
}
continue;
}
let mut part = decode::decode_display_part(
bytes,
info.index,
keep,
&|name| {
if is_depth(name) { BACKGROUND_DEPTH } else { 0.0 }
},
&limits,
)
.map_err(|error| match error {
ExrError::LimitExceeded(message) => Refused::TooLarge(message),
_ => Refused::Unreadable,
})?;
if rgb == Rgb::None && has_rgb {
let base = aux.channels.len();
rgb = match part.rgb {
Some(([r, g, b], a)) if part.exact => {
let picked = [Some(r), Some(g), Some(b), a];
let depth = picked.iter().flatten().any(|i| part.planes.get(*i).is_some_and(|(n, _)| is_depth(n)));
if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|a| base + a)) }
let locate = |raw: usize| {
let name = channel_name(prefix, &info.channels.get(raw)?.name);
part.channels.iter().position(|channel| channel.name == name)
};
rgb = match (rgb_indices[0].and_then(locate), rgb_indices[1].and_then(locate), rgb_indices[2].and_then(locate)) {
(Some(r), Some(g), Some(b)) if exact => {
let a = alpha_index.and_then(locate);
let depth =
[Some(r), Some(g), Some(b), a].into_iter().flatten().any(|i| part.channels.get(i).is_some_and(|channel| is_depth(&channel.name)));
if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|i| base + i)) }
}
_ => Rgb::Unsupported,
};
}
aux.channels.extend(part.planes);
aux.channels.extend(part.channels.drain(..).map(|channel| (channel.name, channel.samples)));
}
for (_, (name, manifest)) in crypto {
if let (Some(n), Some(m)) = (name, manifest) {
aux.manifests.push((n, parse_manifest(&m)));
if let (Some(name), Some(manifest)) = (name, manifest) {
aux.manifests.push((name, parse_manifest(&manifest)));
}
}
aux.manifests.sort();
@@ -389,11 +268,16 @@ fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option<String>)> {
/// headers, then only those channels decoded; in a multi-part file the other parts' pixels are
/// not even decompressed), with the names of its planes.
fn picture_only(bytes: &[u8]) -> Result<(Decoded, [String; 3], Option<String>), Refused> {
let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?;
let mut limits = craft_exr::decode::Limits::default();
limits.max_width = u32::MAX;
limits.max_height = u32::MAX;
limits.max_pixels = u64::MAX;
limits.max_bytes = u64::MAX;
let meta = craft_exr::decode::parts(bytes, &limits).map_err(|_| Refused::Unreadable)?;
let mut names = AuxChannels::new(0, 0, 1.0);
for header in meta.headers.iter() {
let prefix = part_name(header);
names.channels.extend(header.channels.list.iter().map(|ch| (channel_name(prefix.as_deref(), &ch.name.to_string()), vec![])));
for part in meta {
let prefix = part.name.as_deref();
names.channels.extend(part.channels.iter().map(|ch| (channel_name(prefix, &ch.name), vec![])));
}
let (rgb, a) = picture_names(&names).ok_or(Refused::Unreadable)?;
// Planes are looked up by name ignoring case, so every channel that could answer is kept.
@@ -679,8 +563,13 @@ impl ChannelCache {
/// Decode the file at `path` whose bytes are `bytes` for `slot` (see [`ChannelCache::get`]).
fn decode_file(&self, path: &str, slot: &Slot, bytes: &[u8]) -> Option<Arc<Decoded>> {
// The planes it will allocate count against the budget while it decodes.
if let Ok(meta) = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false)
&& let Some(need) = planes_bytes(&meta, &|_| true)
let mut limits = craft_exr::decode::Limits::default();
limits.max_width = u32::MAX;
limits.max_height = u32::MAX;
limits.max_pixels = u64::MAX;
limits.max_bytes = u64::MAX;
if let Ok(infos) = craft_exr::decode::parts(bytes, &limits)
&& let Some(need) = planes_bytes(&infos, &|_| true)
{
self.account(slot, need.min(MAX_DECODE_BYTES));
}
@@ -1264,6 +1153,69 @@ mod tests {
assert!(aux.get("ViewLayer.Combined.R").is_some());
}
#[test]
fn multipart_fallback_filters_channels_and_reserves_display_planes() {
use exr::prelude::*;
let part = |name: &str, pos: (i32, i32), size: (usize, usize), channels: Vec<AnyChannel<FlatSamples>>| {
let attrs = LayerAttributes { layer_name: Some(Text::from(name)), layer_position: Vec2(pos.0, pos.1), ..Default::default() };
Layer::new(size, attrs, Encoding::FAST_LOSSLESS, AnyChannels::sort(channels.into()))
};
let (w, h) = (2usize, 1usize);
let bytes = file(
vec![
part("Depth", (0, 0), (1, 1), vec![AnyChannel::new("Z", FlatSamples::F32(vec![7.0]))]),
part(
"Beauty",
(1, 1),
(w, h),
vec![
AnyChannel::new("R", FlatSamples::F32(vec![0.1; w * h])),
AnyChannel::new("G", FlatSamples::F32(vec![0.2; w * h])),
AnyChannel::new("B", FlatSamples::F32(vec![0.3; w * h])),
],
),
],
IntegerBounds::from_dimensions((3, 2)),
);
let mut limits = craft_exr::decode::Limits::default();
limits.max_width = u32::MAX;
limits.max_height = u32::MAX;
limits.max_pixels = u64::MAX;
limits.max_bytes = u64::MAX;
let parts = craft_exr::decode::parts(&bytes, &limits).unwrap();
assert_eq!(planes_bytes(&parts, &|name| name == "Beauty.R"), Some(3 * 2 * 4));
assert_eq!(planes_bytes(&parts, &|_| false), Some(0));
// Different display windows must not reserve every part at the first part's size.
let mut varied = parts.clone();
varied[0].display_window.width = 1;
varied[0].display_window.height = 1;
varied[1].display_window.width = 10;
varied[1].display_window.height = 20;
assert_eq!(planes_bytes(&varied, &|_| true), Some(4 + 10 * 20 * 3 * 4));
assert_eq!(planes_bytes(&varied, &|name| name == "Beauty.R"), Some(10 * 20 * 4));
varied[1].display_window.width = u32::MAX;
varied[1].display_window.height = u32::MAX;
assert_eq!(planes_bytes(&varied, &|_| true), None);
assert_eq!(planes_bytes(&varied, &|name| name == "Depth.Z"), Some(4));
// Skipping the RGB part preserves the first-RGB fallback state and depth samples.
let depth = decode(&bytes, &|name| name == "Depth.Z").unwrap();
assert_eq!(depth.rgb, Rgb::Unsupported);
assert_eq!(depth.aux.channels.len(), 1);
assert_eq!(depth.aux.get("Depth.Z").unwrap()[0], 7.0);
let selected = decode(&bytes, &|name| name == "Beauty.R").unwrap();
assert_eq!(selected.aux.channels.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["Beauty.R"]);
assert_eq!(selected.aux.get("Beauty.R").unwrap(), [0.0, 0.0, 0.0, 0.0, 0.1, 0.1]);
// The old app decoder selected the named beauty part when the first part was depth-only,
// and placed its data into the shared display window; retain that layered-picture result.
let image = layered_image(&bytes).unwrap().to_rgba32f();
assert_eq!(image.get_pixel(1, 1).0, [0.1, 0.2, 0.3, 1.0]);
assert_eq!(image.get_pixel(0, 0).0, [0.0, 0.0, 0.0, 1.0]);
}
/// Straight RGBA of [`layered_image`] at pixel 0 for a file of single-value channels.
fn picture<S: AsRef<str>>(channels: &[(S, f32)]) -> Vec<f32> {
use exr::prelude::*;
+155 -34
View File
@@ -5,11 +5,9 @@
//! delays), so uneven timing is kept exactly; [`Anim::frame_at`] looks the frame up by time.
//! Animated WebP ([`crate::webp_anim`]) shares [`Anim`] and this decode path.
use std::io::Cursor;
use effectcraft_project::{AlphaMode, Footage, FootageKind};
use effectcraft_time::{FrameRate, Tick};
use image::{AnimationDecoder, DynamicImage, codecs::gif::GifDecoder};
use image::DynamicImage;
use crate::{MediaError, Result};
@@ -26,6 +24,10 @@ pub(crate) const MAX_BYTES: usize = 256 << 20;
/// Frames read from a GIF's or animated WebP's headers when probing.
pub(crate) const MAX_FRAMES: usize = 100_000;
/// Frames kept when decoding a GIF or animated WebP: all of them. Only [`MAX_BYTES`] and the
/// canvas budget bound decoding, as before the shared frame readers; [`MAX_FRAMES`] bounds probing.
pub(crate) const DECODE_FRAMES: usize = usize::MAX;
/// Whether `f` is an animated GIF or WebP imported by [`probe`] or [`crate::webp_anim::probe`]:
/// its frames come from an [`Anim`].
pub(crate) fn is_animated(f: &Footage) -> bool {
@@ -86,43 +88,57 @@ impl Anim {
if crate::webp_anim::is_webp(bytes) {
return crate::webp_anim::load(bytes);
}
let mut dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?;
// A frame may be far larger than the canvas, and the decoder allocates its buffer before
// decoding it: no single buffer may pass what all the frames may hold.
let mut limits = image::Limits::no_limits();
limits.max_alloc = Some(MAX_BYTES as u64);
image::ImageDecoder::set_limits(&mut dec, limits).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?;
// The decoder allocates the full logical canvas for the first frame, however small the
// frames themselves are: check it before decoding any.
let (w, h) = image::ImageDecoder::dimensions(&dec);
if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 {
return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory")));
}
let (mut frames, mut starts) = (Vec::new(), Vec::new());
let (mut at, mut size) = (0i64, 0usize);
for frame in dec.into_frames() {
let frame = match frame {
Ok(f) => f,
Err(e) if frames.is_empty() => return Err(MediaError::Decode(format!("GIF: {e}"))),
Err(e) => {
log::warn!("media: GIF stops after {} frames: {e}", frames.len());
break;
}
};
let (numer, denom) = frame.delay().numer_denom_ms();
let cs = delay_cs(numer.checked_div(denom).unwrap_or(0) / 10);
let buf = frame.into_buffer();
size = size.saturating_add(buf.as_raw().len());
if size > MAX_BYTES {
return Err(MediaError::Unsupported("GIF is too large to hold in memory".into()));
// The frame reader scans every image descriptor before it checks the canvas: refuse a
// logical screen too large to hold first, as the former decoder did.
if let Some(&[w0, w1, h0, h1]) = bytes.get(6..10).filter(|_| bytes.starts_with(b"GIF8")) {
let (w, h) = (u16::from_le_bytes([w0, w1]), u16::from_le_bytes([h0, h1]));
if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 {
return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory")));
}
}
let mut limits = craft_gif::frames::FrameLimits::default();
limits.max_frames = DECODE_FRAMES;
limits.max_bytes = MAX_BYTES as u64;
limits.max_canvas_bytes = MAX_BYTES as u64;
limits.max_decode_bytes = Some(MAX_BYTES as u64);
let decoded = craft_gif::frames::read_frames(bytes, &limits).map_err(|e| match e {
craft_gif::frames::FrameError::Malformed(m) => MediaError::Decode(format!("GIF: {m}")),
craft_gif::frames::FrameError::LimitExceeded(m)
if m.contains("cannot hold") || m.contains("decode-allocation limit") || m.to_ascii_lowercase().contains("memory limit") =>
{
MediaError::Unsupported("GIF is too large to hold in memory".into())
}
craft_gif::frames::FrameError::LimitExceeded(m) if m.contains("canvas is over") => {
MediaError::Unsupported("GIF canvas is too large to hold in memory".into())
}
craft_gif::frames::FrameError::LimitExceeded(m) => MediaError::Unsupported(format!("GIF: {m}")),
})?;
if matches!(&decoded.stop, craft_gif::frames::Stop::ByteLimit | craft_gif::frames::Stop::FrameLimit) {
return Err(MediaError::Unsupported("GIF is too large to hold in memory".into()));
}
if let craft_gif::frames::Stop::Damaged(ref e) = decoded.stop {
log::warn!("media: GIF stops after {} frames: {e}", decoded.frames.len());
}
let mut frames = Vec::with_capacity(decoded.frames.len());
let mut starts = Vec::with_capacity(decoded.frames.len());
let mut at = 0i64;
for frame in decoded.frames {
let cs = delay_cs(frame.delay_ms / 10);
let image = image::RgbaImage::from_raw(decoded.width, decoded.height, frame.rgba)
.ok_or_else(|| MediaError::Decode("GIF: invalid decoded frame dimensions".into()))?;
starts.push(Tick::from_units(at, 100));
at = at.saturating_add(i64::from(cs));
frames.push(DynamicImage::ImageRgba8(buf));
frames.push(DynamicImage::ImageRgba8(image));
}
Anim::new(frames, starts).ok_or_else(|| MediaError::Decode("GIF: no frames".into()))
}
/// How many frames were decoded.
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.frames.len()
}
/// The frame shown at source time `t` (the first one before the start, the last one past the
/// end).
pub(crate) fn frame_at(&self, t: Tick) -> Option<&DynamicImage> {
@@ -133,9 +149,13 @@ impl Anim {
#[cfg(test)]
mod tests {
use std::io::Cursor;
use effectcraft_project::{Footage, FootageKind};
use effectcraft_time::{FrameRate, Tick};
use image::AnimationDecoder;
use super::MAX_FRAMES;
use crate::{MediaPool, probe_bytes};
/// A 2×2 GIF with one solid-colour frame per `(rgb, delay)`.
@@ -152,6 +172,15 @@ mod tests {
out
}
/// Preserve the old consumer path as a test oracle while the frame API is shared.
fn legacy_gif_frames(bytes: &[u8]) -> Vec<image::RgbaImage> {
image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).unwrap().into_frames().map(|frame| frame.unwrap().into_buffer()).collect()
}
fn legacy_gif_frames_until_error(bytes: &[u8]) -> Vec<image::RgbaImage> {
image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).unwrap().into_frames().map_while(|frame| frame.ok()).map(|frame| frame.into_buffer()).collect()
}
const RED: [u8; 3] = [255, 0, 0];
const GREEN: [u8; 3] = [0, 255, 0];
const BLUE: [u8; 3] = [0, 0, 255];
@@ -201,6 +230,62 @@ mod tests {
assert_eq!(f.duration, Tick::from_units(20, 100));
}
#[test]
fn shared_gif_frames_match_legacy_compositing_and_disposal() {
let mut bytes = Vec::new();
{
let palette = [255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0];
let mut enc = gif::Encoder::new(&mut bytes, 3, 2, &palette).unwrap();
let first = gif::Frame {
width: 3,
height: 2,
buffer: vec![0; 6].into(), // red background
delay: 5,
dispose: gif::DisposalMethod::Keep,
..gif::Frame::default()
};
enc.write_frame(&first).unwrap();
let second = gif::Frame {
left: 1,
width: 1,
height: 1,
buffer: vec![1].into(), // green patch
delay: 7,
dispose: gif::DisposalMethod::Background,
..gif::Frame::default()
};
enc.write_frame(&second).unwrap();
let third = gif::Frame {
left: 2,
width: 1,
height: 1,
buffer: vec![2].into(), // blue patch after disposal
delay: 9,
dispose: gif::DisposalMethod::Previous,
..gif::Frame::default()
};
enc.write_frame(&third).unwrap();
let fourth = gif::Frame {
width: 1,
height: 1,
buffer: vec![3].into(), // black patch after restoring the previous canvas
delay: 11,
..gif::Frame::default()
};
enc.write_frame(&fourth).unwrap();
}
let expected = legacy_gif_frames(&bytes);
let actual = super::Anim::load(&bytes).unwrap();
assert_eq!(actual.frames.len(), expected.len());
for (frame, old) in actual.frames.iter().zip(expected) {
assert_eq!(frame.to_rgba8(), old);
}
assert_eq!(actual.starts, vec![Tick::from_units(0, 100), Tick::from_units(5, 100), Tick::from_units(12, 100), Tick::from_units(21, 100)]);
}
#[test]
fn a_single_frame_gif_stays_a_still() {
let f = probe_bytes("a.gif", gif(&[(RED, 10)]).into()).unwrap();
@@ -228,6 +313,20 @@ mod tests {
let _ = probe_bytes("a.gif", bytes.into());
}
#[test]
fn a_damaged_gif_tail_keeps_frames_already_decoded() {
let mut bytes = gif(&[(RED, 5), (GREEN, 5), (BLUE, 5)]);
let info = craft_gif::scan(&bytes, MAX_FRAMES).unwrap();
assert_eq!(info.frames.len(), 3);
bytes.truncate(info.frames[1].offset);
let legacy = legacy_gif_frames_until_error(&bytes);
assert_eq!(legacy.len(), 1);
let actual = super::Anim::load(&bytes).unwrap();
assert_eq!(actual.frames.len(), legacy.len());
assert_eq!(actual.frames[0].to_rgba8(), legacy[0]);
}
#[test]
fn a_huge_canvas_is_refused_before_decoding() {
// A 65535×65535 logical screen (16 GiB of RGBA) holding one 1×1 frame.
@@ -239,6 +338,28 @@ mod tests {
}
}
let e = super::Anim::load(&out).err().unwrap();
assert!(e.to_string().contains("too large"), "{e}");
assert!(e.to_string().contains("GIF canvas of 65535×65535 is too large"), "{e}");
}
/// A 1×1 GIF of `n` frames.
fn tiny_gif(n: usize) -> Vec<u8> {
let mut out = Vec::new();
{
let mut enc = gif::Encoder::new(&mut out, 1, 1, &[]).unwrap();
let frame = gif::Frame::from_rgb(1, 1, &RED);
for _ in 0..n {
enc.write_frame(&frame).unwrap();
}
}
out
}
#[test]
fn decoding_keeps_every_frame_past_the_probe_frame_count() {
// 1×1 frames fit the byte budget however many there are: the frame count refuses none.
for n in [MAX_FRAMES, MAX_FRAMES + 1] {
let anim = super::Anim::load(&tiny_gif(n)).unwrap();
assert_eq!(anim.len(), n);
}
}
}
+54 -8
View File
@@ -208,6 +208,10 @@ struct CacheState {
last: HashMap<Arc<str>, i64>,
/// Movies whose frames can't be kept as 8-bit levels (more bits, or shown turned).
wide: HashSet<Arc<str>>,
/// Counts [`MediaPool::forget`]s and frame clears: a decode keeps its frame only when none
/// came while it ran, so one in flight when a file is forgotten (a closed project's, or one
/// changed on disk) can't bring the frame back.
forgets: u64,
}
/// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait
@@ -406,6 +410,7 @@ impl MediaPool {
let mut c = lock(&self.inner.cache);
c.lru = Lru::default();
c.last.clear();
c.forgets = c.forgets.wrapping_add(1);
drop(c);
// Decoded GIFs sit outside the frame budget; Purge frees them too.
lock(&self.inner.gifs).clear();
@@ -418,7 +423,9 @@ impl MediaPool {
lock(&self.inner.problems).clear();
}
/// Forget a file (after it changed on disk, or to retry a file that failed to open).
/// Forget a file (after it changed on disk or its project closed, or to retry a file that
/// failed to open). A decode of any file in flight meanwhile keeps nothing (see
/// [`CacheState::forgets`]).
pub fn forget(&self, path: &str) {
lock(&self.inner.sources).remove(path);
lock(&self.inner.models).remove(path);
@@ -431,6 +438,7 @@ impl MediaPool {
}
c.last.remove(path);
c.wide.remove(path);
c.forgets = c.forgets.wrapping_add(1);
drop(c);
crate::exr_channels::forget(path);
}
@@ -455,7 +463,7 @@ impl MediaPool {
if lock(&self.inner.cache).wide.contains(footage.path.as_str()) {
return None;
}
match Inner::frame_px(&self.inner, footage, t, true, None, float, true) {
match Inner::frame_px(&self.inner, footage, t, true, None, float, true, None) {
Ok(Pixels::Q8(f)) => Some(f),
_ => None,
}
@@ -850,7 +858,7 @@ impl Inner {
/// The frame of `footage` at `t`, resampled to `size` (see [`FootageSource::frame_at_size`]):
/// a movie's made at that size directly, a still's resampled once and kept at that size.
fn frame_at(self: &Arc<Self>, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve) -> Result<Arc<Image>> {
match Self::frame_px(self, footage, t, playback, size, float, false)? {
match Self::frame_px(self, footage, t, playback, size, float, false, None)? {
Pixels::F32(img) => Ok(img),
// (a float request's key never holds 8-bit levels)
Pixels::Q8(_) => Err(MediaError::Decode(format!("{}: 8-bit frame for a float request", footage.path))),
@@ -859,8 +867,20 @@ impl Inner {
/// [`Self::frame_at`], kept as 8-bit levels when `q8` is set and the frame has 8 bits (a
/// float frame under the float key otherwise, and the movie is remembered as `wide`).
/// `since`: the [`CacheState::forgets`] count the read was asked at (a read-ahead's, when it
/// was queued); a read that missed is not decoded once a forget came after it, and a frame
/// decoded while one came is not kept.
#[allow(clippy::too_many_arguments)]
fn frame_px(self: &Arc<Self>, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) -> Result<Pixels> {
fn frame_px(
self: &Arc<Self>,
footage: &Footage,
t: Tick,
playback: bool,
size: Option<(u32, u32)>,
float: FloatCurve,
q8: bool,
since: Option<u64>,
) -> Result<Pixels> {
if !footage.has_video {
return Err(MediaError::Unsupported(format!("{}: no video", footage.path)));
}
@@ -909,6 +929,10 @@ impl Inner {
}
c = self.done.wait(c).unwrap_or_else(std::sync::PoisonError::into_inner);
}
let since = since.unwrap_or(c.forgets);
if c.forgets != since {
return Err(MediaError::Cancelled);
}
self.misses.fetch_add(1, Ordering::Relaxed);
c.inflight.insert(loc.key.clone());
drop(c);
@@ -917,6 +941,9 @@ impl Inner {
reads::note_all(&files);
let img = img?;
let mut c = lock(&self.cache);
if c.forgets != since {
return Ok(img);
}
if q8 && let Pixels::F32(_) = img {
// not 8-bit: kept as the float frame it is, which the renderer asks for next
c.wide.insert(loc.key.path.clone());
@@ -935,23 +962,23 @@ impl Inner {
next.key.size = loc.key.size;
next.key.q8 = loc.key.q8;
if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) {
self.prefetch(footage, next_t, size, float, loc.key.q8);
self.prefetch(footage, next_t, size, float, loc.key.q8, c.forgets);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn prefetch(self: &Arc<Self>, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) {
fn prefetch(self: &Arc<Self>, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool, since: u64) {
let (me, f) = (self.clone(), footage.clone());
self.prefetched.fetch_add(1, Ordering::Relaxed);
// A plain thread, not a rayon job: the decode below parallelises with rayon itself.
std::thread::spawn(move || {
let _ = me.frame_px(&f, t, false, size, float, q8);
let _ = me.frame_px(&f, t, false, size, float, q8, Some(since));
});
}
#[cfg(target_arch = "wasm32")]
fn prefetch(self: &Arc<Self>, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool) {}
fn prefetch(self: &Arc<Self>, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool, _since: u64) {}
/// A still (image file or sequence frame) at `loc.key.size` when one is set: resampled as the
/// renderer would ([`FootageSource::frame_at_size`]), so the pool keeps the reduced frame and a
@@ -1215,6 +1242,25 @@ fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mod tests {
use super::*;
/// #2042: a read queued before its file was forgotten (as a read-ahead of a closed project's
/// movie is, by the read of the frame before) decodes nothing and keeps nothing; a read asked
/// after the forget decodes and keeps its frame. (A still stands in for the movie.)
#[test]
fn reads_queued_before_a_forget_keep_nothing() {
let mut png = std::io::Cursor::new(Vec::new());
image::RgbaImage::new(2, 2).write_to(&mut png, image::ImageFormat::Png).unwrap();
let pool = MediaPool::new();
pool.add_bytes("/a.png", png.into_inner().into());
let f = Footage { path: "/a.png".into(), kind: FootageKind::Still, width: 2, height: 2, has_video: true, ..Default::default() };
let queued = lock(&pool.inner.cache).forgets;
pool.forget("/a.png");
let read = Inner::frame_px(&pool.inner, &f, Tick::ZERO, false, None, FloatCurve::Srgb, false, Some(queued));
assert!(matches!(read, Err(MediaError::Cancelled)), "{:?}", read.err());
assert_eq!(pool.stats().frames, 0, "the forgotten file's frame came back");
pool.frame_at(&f, Tick::ZERO).unwrap();
assert_eq!(pool.stats().frames, 1);
}
/// Conforming a long file's audio reads every chunk at its own time: the sample index times
/// ticks per second overflowed `i64` past 12:36 at 48 kHz, and later chunks came out silent
/// (#172).
+125 -26
View File
@@ -9,13 +9,11 @@
//! every delay is a whole number of frames at (1000 / the greatest common divisor of the delays),
//! so it is kept exactly. A still WebP (no animation flag, or a single frame) stays a still.
use std::io::Cursor;
use effectcraft_project::{AlphaMode, Footage, FootageKind};
use effectcraft_time::{FrameRate, Tick};
use image::{AnimationDecoder, DynamicImage, codecs::webp::WebPDecoder};
use image::DynamicImage;
use crate::gif_anim::{Anim, MAX_BYTES, MAX_FRAMES, gcd};
use crate::gif_anim::{Anim, DECODE_FRAMES, MAX_BYTES, MAX_FRAMES, gcd};
use crate::{MediaError, Result};
/// The `Footage::codec` of an animated WebP.
@@ -121,29 +119,29 @@ pub(crate) fn load(bytes: &[u8]) -> Result<Anim> {
if frame_bytes.saturating_mul(h.delays.len()) > MAX_BYTES {
return Err(MediaError::Unsupported(format!("animated WebP of {} frames of {}×{} is too large to hold in memory", h.delays.len(), h.width, h.height)));
}
let dec = WebPDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("WebP: {e}")))?;
// The budget above used the canvas this file's header scan found; the decoder must agree, or
// a second VP8X header could make it allocate a far larger canvas.
if image::ImageDecoder::dimensions(&dec) != (h.width, h.height) {
let mut limits = craft_webp::frames::FrameLimits::default();
limits.max_frames = DECODE_FRAMES;
limits.max_bytes = MAX_BYTES as u64;
limits.max_canvas_bytes = MAX_BYTES as u64;
let decoded = craft_webp::frames::read_frames(bytes, &limits).map_err(|e| match e {
craft_webp::frames::FrameError::Malformed(m) => MediaError::Decode(format!("WebP: {m}")),
craft_webp::frames::FrameError::LimitExceeded(m) => MediaError::Unsupported(format!("WebP: {m}")),
})?;
if matches!(&decoded.stop, craft_webp::frames::Stop::ByteLimit | craft_webp::frames::Stop::FrameLimit) {
return Err(MediaError::Unsupported("animated WebP is too large to hold in memory".into()));
}
if let craft_webp::frames::Stop::Damaged(ref e) = decoded.stop {
log::warn!("media: WebP stops after {} frames: {e}", decoded.frames.len());
}
if (decoded.width, decoded.height) != (h.width, h.height) {
return Err(MediaError::Decode("WebP: conflicting canvas sizes".into()));
}
let (mut frames, mut delays, mut size) = (Vec::new(), Vec::new(), 0usize);
for frame in dec.into_frames() {
let frame = match frame {
Ok(f) => f,
Err(e) if frames.is_empty() => return Err(MediaError::Decode(format!("WebP: {e}"))),
Err(e) => {
log::warn!("media: WebP stops after {} frames: {e}", frames.len());
break;
}
};
let (numer, denom) = frame.delay().numer_denom_ms();
delays.push(numer.checked_div(denom).unwrap_or(0));
let buf = frame.into_buffer();
size = size.saturating_add(buf.as_raw().len());
if size > MAX_BYTES {
return Err(MediaError::Unsupported("animated WebP is too large to hold in memory".into()));
}
let mut frames = Vec::with_capacity(decoded.frames.len());
let mut delays = Vec::with_capacity(decoded.frames.len());
for frame in decoded.frames {
delays.push(frame.delay_ms);
let buf = image::RgbaImage::from_raw(decoded.width, decoded.height, frame.rgba)
.ok_or_else(|| MediaError::Decode("WebP: invalid decoded frame dimensions".into()))?;
frames.push(DynamicImage::ImageRgba8(buf));
}
let starts = timing(&delays).starts;
@@ -152,9 +150,11 @@ pub(crate) fn load(bytes: &[u8]) -> Result<Anim> {
#[cfg(test)]
mod tests {
use std::io::Cursor;
use effectcraft_project::{AlphaMode, Footage, FootageKind};
use effectcraft_time::{FrameRate, Tick};
use image::{ExtendedColorType, ImageEncoder, codecs::webp::WebPEncoder};
use image::{AnimationDecoder, ExtendedColorType, ImageEncoder, codecs::webp::WebPDecoder, codecs::webp::WebPEncoder};
use super::timing;
use crate::{MediaPool, probe_bytes};
@@ -204,6 +204,43 @@ mod tests {
chunk(b"RIFF", &body)
}
/// Build an animation whose frames may cover only part of the canvas. `x` and `y` are even,
/// as required by ANMF; bit 1 of `flags` selects no-blend and bit 0 selects disposal.
fn webp_subframes(canvas: (u32, u32), frames: &[(u32, u32, u32, u32, [u8; 4], u32, u8)]) -> Vec<u8> {
let (w, h) = canvas;
let mut vp8x = vec![0x12, 0, 0, 0];
vp8x.extend_from_slice(&u24(w - 1));
vp8x.extend_from_slice(&u24(h - 1));
let mut body = b"WEBP".to_vec();
body.extend(chunk(b"VP8X", &vp8x));
body.extend(chunk(b"ANIM", &[0; 6]));
for &(x, y, fw, fh, rgba, delay, flags) in frames {
let mut anmf = Vec::new();
anmf.extend_from_slice(&u24(x / 2));
anmf.extend_from_slice(&u24(y / 2));
anmf.extend_from_slice(&u24(fw - 1));
anmf.extend_from_slice(&u24(fh - 1));
anmf.extend_from_slice(&u24(delay));
anmf.push(flags);
anmf.extend(vp8l(fw, fh, rgba));
body.extend(chunk(b"ANMF", &anmf));
}
chunk(b"RIFF", &body)
}
fn anmf_offsets(bytes: &[u8]) -> Vec<usize> {
let mut offsets = Vec::new();
let mut at = 12usize;
while at + 8 <= bytes.len() {
let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize;
if &bytes[at..at + 4] == b"ANMF" {
offsets.push(at);
}
at = at.saturating_add(8).saturating_add(size).saturating_add(size & 1);
}
offsets
}
const RED: [u8; 4] = [255, 0, 0, 255];
const GREEN: [u8; 4] = [0, 255, 0, 255];
const BLUE: [u8; 4] = [0, 0, 255, 128];
@@ -238,6 +275,38 @@ mod tests {
assert_eq!(pixel_at(&pool, &f, 5.0), last);
}
#[test]
fn shared_webp_frames_match_legacy_subrect_blending_and_disposal() {
// Includes a blended alpha patch, then a no-blend patch disposed to the background.
let bytes =
webp_subframes((4, 2), &[(0, 0, 4, 2, RED, 50, 0b10), (2, 0, 2, 2, BLUE, 60, 0b00), (0, 0, 2, 2, GREEN, 70, 0b11), (2, 0, 2, 2, RED, 80, 0b10)]);
let expected = WebPDecoder::new(Cursor::new(&bytes)).unwrap().into_frames().map(|frame| frame.unwrap().into_buffer()).collect::<Vec<_>>();
let actual = super::load(&bytes).unwrap();
assert_eq!(expected.len(), 4);
for (index, (start_ms, old)) in [(0, &expected[0]), (50, &expected[1]), (110, &expected[2]), (180, &expected[3])].into_iter().enumerate() {
let tick = Tick::from_units(start_ms, 1000);
let frame = actual.frame_at(tick).unwrap().to_rgba8();
assert_eq!(frame, *old, "frame {index} at {start_ms} ms");
}
}
#[test]
fn a_damaged_webp_tail_keeps_frames_already_decoded() {
let mut bytes = webp(4, 2, &[(RED, 50), (GREEN, 60), (BLUE, 70)]);
let offsets = anmf_offsets(&bytes);
assert_eq!(offsets.len(), 3);
bytes.truncate(offsets[2]);
let legacy =
WebPDecoder::new(Cursor::new(&bytes)).unwrap().into_frames().map_while(|frame| frame.ok()).map(|frame| frame.into_buffer()).collect::<Vec<_>>();
assert_eq!(legacy.len(), 2);
let actual = super::load(&bytes).unwrap();
for (index, old) in legacy.iter().enumerate() {
let tick = Tick::from_units(if index == 0 { 0 } else { 50 }, 1000);
assert_eq!(actual.frame_at(tick).unwrap().to_rgba8(), *old);
}
}
#[test]
fn delays_rounded_to_milliseconds_read_as_the_standard_rate() {
// 24 frames a second rounded to whole milliseconds, as ffmpeg writes them.
@@ -312,4 +381,34 @@ mod tests {
bytes[4..8].copy_from_slice(&riff.to_le_bytes());
assert!(super::load(&bytes).is_err());
}
/// A 1×1 animated WebP of `n` identical frames.
fn tiny_webp(n: usize) -> Vec<u8> {
let mut anmf = vec![0; 6];
anmf.extend_from_slice(&u24(0));
anmf.extend_from_slice(&u24(0));
anmf.extend_from_slice(&u24(50));
anmf.push(0b10);
anmf.extend(vp8l(1, 1, RED));
let frame = chunk(b"ANMF", &anmf);
let mut vp8x = vec![0x12, 0, 0, 0];
vp8x.extend_from_slice(&u24(0));
vp8x.extend_from_slice(&u24(0));
let mut body = b"WEBP".to_vec();
body.extend(chunk(b"VP8X", &vp8x));
body.extend(chunk(b"ANIM", &[0; 6]));
for _ in 0..n {
body.extend_from_slice(&frame);
}
chunk(b"RIFF", &body)
}
#[test]
fn decoding_keeps_every_frame_past_the_probe_frame_count() {
// 1×1 frames fit the byte budget however many there are: the frame count refuses none.
for n in [crate::gif_anim::MAX_FRAMES, crate::gif_anim::MAX_FRAMES + 1] {
let anim = super::load(&tiny_webp(n)).unwrap();
assert_eq!(anim.len(), n);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
# Synthetic AAC layout fixture
`pce61-ffmpeg.aac-fixture` contains only original mathematical sine tones generated for these tests by Dylan M. Taylor. No recorded audio or third-party source/assets were copied; the generated fixture is covered by this repository's license. FFmpeg is a generation tool, not a runtime test dependency.
Generator: FFmpeg 7.1.5 (Debian 7.1.5-0+deb13u1, AAC encoder Lavc61.19.101).
SHA-256: `07c460636dce4aa4163df8ef35f3b76f1214c38bf217aacd23243e608d87071e`.
The seven PCM inputs are FL500Hz, FR700Hz, FC300Hz, LFE60Hz, BC900Hz, SL1100Hz, SR1300Hz, each amplitude0.25 at48kHz for2seconds. The real encoder emits its own PCE and matching element tags; unlike the previous synthetic configuration rewrite, no LFE element is mislabeled as an unlisted SCE.
Reproduce using FFmpeg/ffprobe and Python3:
```sh
ffmpeg -hide_banner -loglevel error -f lavfi -i 'aevalsrc=0.25*sin(2*PI*500*t)|0.25*sin(2*PI*700*t)|0.25*sin(2*PI*300*t)|0.25*sin(2*PI*60*t)|0.25*sin(2*PI*900*t)|0.25*sin(2*PI*1100*t)|0.25*sin(2*PI*1300*t):s=48000:d=2:c=6.1' -c:a aac -b:a 672k pce61.m4a
ffprobe -v error -show_streams -show_packets -show_data -of json pce61.m4a > pce61.json
python3 - <<'PY'
import json, struct
x = json.load(open('pce61.json'))
def raw(text):
return bytes.fromhex(''.join(line.split(': ', 1)[1].split(' ', 1)[0].replace(' ', '')
for line in text.strip().splitlines()))
asc = raw(x['streams'][0]['extradata'])
units = [raw(p['data']) for p in x['packets']]
assert len(units) == 95
output = bytearray(b'PCE1')
for record in [asc, *units]:
output += struct.pack('>I', len(record)) + record
open('pce61-ffmpeg.aac-fixture', 'wb').write(output)
PY
```
Envelope: ASCII `PCE1`, then a big-endian32-bit length and ASC bytes, then95 length-prefixed raw AAC access units. Container priming trim is deliberately not retained, matching the existing tests' encoder units; measurements start0.5seconds into decoded audio. Other encoder versions can yield different bytes; preserve actual PCE/AU consistency and all existing tone-gain assertions.
Binary file not shown.
@@ -0,0 +1,7 @@
asset: pce61-ffmpeg.aac-fixture
title: Synthetic seven-channel AAC PCE tone fixture
author: Dylan M. Taylor
source: crates/media/tests/fixtures/README.md (reproducible generation recipe)
license: MIT OR Apache-2.0
added: 2026-11-16
notes: Original sine-wave signals, no recorded audio or copied assets. Encoded using FFmpeg 7.1.5. SHA-256 07c460636dce4aa4163df8ef35f3b76f1214c38bf217aacd23243e608d87071e.
+37 -26
View File
@@ -1,7 +1,8 @@
//! Multichannel AAC reaches stereo by where each channel plays, whatever order its channel
//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder (no
//! ffmpeg needed, so nothing is skipped), with the configuration rewritten where the coded
//! elements fit another: configurations 11 and 12 code the same elements as the encoder's 7- and
//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder,
//! plus a checked-in genuine FFmpeg-generated 6.1-channel fixture (no external tool at test time, nothing skipped).
//! The configuration is rewritten only where the coded elements fit another: configurations 11
//! and 12 code the same elements as the encoder's 7- and
//! 8-channel output, and a program config element can name any of them.
use std::f64::consts::PI;
@@ -9,7 +10,7 @@ use std::io::Cursor;
use std::path::PathBuf;
use std::sync::Arc;
use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig, ProgramConfig};
use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig};
use effectcraft_media::{MediaPool, probe, probe_bytes};
use effectcraft_time::Tick;
@@ -59,13 +60,6 @@ fn lc(config: u8) -> Option<AudioSpecificConfig> {
Some(AudioSpecificConfig::lc(3, config))
}
fn pce(front: Vec<(bool, u8)>, side: Vec<(bool, u8)>, back: Vec<(bool, u8)>, lfe: Vec<u8>, comment: &[u8]) -> Option<AudioSpecificConfig> {
let pce = ProgramConfig { object_type: 1, sf_index: 3, front, side, back, lfe, comment: comment.to_vec(), ..Default::default() };
let mut asc = AudioSpecificConfig::lc(3, 0);
asc.pce = Some(pce);
Some(asc)
}
use Ch::*;
fn cases() -> Vec<Case> {
@@ -80,15 +74,9 @@ fn cases() -> Vec<Case> {
Case { name: "config12", content: &[C, L, R, Ls, Rs, Ls, Rs, Lfe], asc: lc(12) },
// the encoder's own 6.1: a PCE listing the centre first
Case { name: "pce61-centre-first", content: &[C, L, R, Ls, Rs, Cs, Lfe], asc: None },
// ffmpeg's 6.1 PCE: front pair and centre, a side SCE, a back pair and SCE, no LFE
// element, its channels in ffmpeg's order L R C LFE Cs Ls Rs. The decoder places the
// encoder's SCE 0 in the front SCE, pair 0 front, pair 1 back, SCE 1 in the back SCE (tag
// 1) and the LFE in the side SCE left over (tag 5).
Case {
name: "pce61-ffmpeg",
content: &[C, L, R, Cs, Ls, Rs, Lfe],
asc: pce(vec![(true, 0), (false, 0)], vec![(false, 5)], vec![(true, 1), (false, 1)], vec![], b"Lavc62.28.102"),
},
// A genuine FFmpeg-generated 6.1-channel PCE and matching coded elements; rewriting only the ASC of
// our encoder's LFE0 stream to claim a side SCE5 would make an invalid access unit.
Case { name: "pce61-ffmpeg", content: &[C, L, R, Cs, Ls, Rs, Lfe], asc: None },
]
}
@@ -110,6 +98,32 @@ fn encode(content: &[Ch], adts: bool) -> (Vec<u8>, Vec<Vec<u8>>) {
(enc.audio_specific_config(), units)
}
/// Preserve the fixture's real element types/tags instead of changing only its ASC.
/// The envelope and reproducible tone-generation recipe are in `tests/fixtures/README.md`.
fn encode_case(case: &Case) -> (Vec<u8>, Vec<Vec<u8>>) {
if case.name == "pce61-ffmpeg" {
let bytes = include_bytes!("../fixtures/pce61-ffmpeg.aac-fixture");
assert_eq!(&bytes[..4], b"PCE1");
let mut rest = &bytes[4..];
let mut record = || {
let len = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize;
let (data, tail) = rest[4..].split_at(len);
rest = tail;
data.to_vec()
};
let asc = record();
let mut units = Vec::new();
// The generated fixture contains 95 access units (including encoder priming).
for _ in 0..95 {
units.push(record());
}
assert!(rest.is_empty(), "fixture has no unparsed records");
return (asc, units);
}
let (asc, units) = encode(case.content, false);
(case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")), units)
}
fn mp4(asc: Vec<u8>, channels: u32, units: &[Vec<u8>]) -> Vec<u8> {
mp4_after(None, asc, channels, units)
}
@@ -211,8 +225,7 @@ fn lfe_is_coded(case: &Case, bytes: Vec<u8>) {
#[test]
fn every_aac_layout_mixes_by_speaker_in_mp4() {
for case in cases() {
let (asc, units) = encode(case.content, false);
let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC"));
let (asc, units) = encode_case(&case);
let bytes = mp4(asc, case.content.len() as u32, &units);
lfe_is_coded(&case, bytes.clone());
let p = write(&format!("{}.mp4", case.name), &bytes);
@@ -228,8 +241,7 @@ fn every_aac_layout_mixes_by_speaker_in_mp4() {
#[test]
fn matroska_aac_layouts_mix_by_speaker() {
for case in cases().into_iter().filter(|c| matches!(c.name, "config12" | "pce61-centre-first" | "pce61-ffmpeg")) {
let (asc, units) = encode(case.content, false);
let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC"));
let (asc, units) = encode_case(&case);
let p = write(&format!("{}.mkv", case.name), &mkv(asc, case.content.len() as u32, &units));
check(case.name, case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe")));
}
@@ -254,8 +266,7 @@ fn an_empty_audio_track_lends_its_configuration_to_no_other() {
let case = cases().into_iter().find(|c| c.name == name).expect("case");
let n = case.content.len() as u32;
let empty = Some((AudioSpecificConfig::lc(3, empty).to_bytes().expect("ASC"), n));
let (asc, units) = encode(case.content, false);
let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC"));
let (asc, units) = encode_case(&case);
let p = write(&format!("{name}-after-empty.mp4"), &mp4_after(empty.clone(), asc.clone(), n, &units));
check(&format!("{name} MP4"), case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe")));
let p = write(&format!("{name}-after-empty.mkv"), &mkv_after(empty, asc, n, &units));
-15
View File
@@ -1,15 +0,0 @@
[package]
name = "effectcraft-opusenc"
description = "Clean-room pure-Rust Opus encoder (RFC 6716 SILK NB/MB/WB, hybrid SWB/FB and CELT FB modes, 48 kHz, 20 ms; RFC 7845 OpusHead) for WebM export audio"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
[dev-dependencies]
craft-audio = { workspace = true }
-136
View File
@@ -1,136 +0,0 @@
# effectcraft-opusenc
Clean-room, pure-Rust Opus encoder for EffectCraft's WebM export audio (layer L0, `std` only,
no `unsafe`, builds for `wasm32-unknown-unknown`).
All three Opus modes, 20 ms packets (one frame per packet), 48 kHz float input, mono or stereo:
- **CELT** (fullband): MDCT transform coding, constant packet size.
- **SILK** (narrowband 8 kHz, mediumband 12 kHz, wideband 16 kHz internal rate): linear
prediction with long-term (pitch) prediction; packet size varies around the target bitrate.
- **Hybrid** (super-wideband, fullband): SILK wideband codes 0–8 kHz and CELT codes bands 17 and
up (8 kHz and above) in the same range-coded frame; constant packet size.
```rust
use effectcraft_opusenc::{Application, OpusEncoder};
let mut enc = OpusEncoder::with_application(2, 48_000, Application::Voip);
let packet = enc.encode_float(&vec![0.0; OpusEncoder::FRAME_SIZE * 2]);
// enc.mode(), enc.bandwidth(), enc.pre_skip(), enc.opus_head() ...
```
`OpusEncoder::new(channels, bitrate)` is `with_application(.., Application::Audio)`.
`OpusEncoder::with_mode(channels, bitrate, mode, bandwidth)` forces a mode/bandwidth pair
(SILK: NB/MB/WB; hybrid: SWB/FB; CELT: FB).
## Mode table
Chosen once per stream (constant-bitrate export, no in-stream switching) from the bitrate per
channel (bitrate / channels; the total is clamped to 6 kb/s per channel … 510 kb/s):
| per-channel bitrate | `Application::Voip` | `Application::Audio` (default) |
|---------------------|-------------------------|--------------------------------|
| < 10 kb/s | SILK narrowband (8 kHz) | SILK wideband |
| 10–12 kb/s | SILK mediumband (12 kHz)| SILK wideband |
| 12–16 kb/s | SILK wideband (16 kHz) | SILK wideband |
| 16–18 kb/s | SILK wideband | hybrid fullband |
| 18–28 kb/s | hybrid super-wideband | hybrid fullband |
| 28–36 kb/s | hybrid fullband | hybrid fullband |
| 36–40 kb/s | hybrid fullband | CELT fullband |
| ≥ 40 kb/s | CELT fullband | CELT fullband |
TOC configurations (RFC 6716 §3.1, Table 2): SILK NB/MB/WB 20 ms = 1/5/9, hybrid SWB/FB 20 ms
= 13/15, CELT FB 20 ms = 31; the stereo bit is set for two channels; frame-count code 0.
`pre_skip()` is 120 samples in every mode: the CELT MDCT overlap, and for SILK/hybrid the
decimator delay (83 samples at 48 kHz, 88 for narrowband) plus the decoder's SILK delay (one
internal-rate sample and the resampler delay of RFC 6716 Table 54). The SILK and CELT halves of a
hybrid frame are therefore aligned without extra buffering.
## What is implemented
**SILK** (RFC 6716 §4.2, encoder direction; own analysis and search design):
- 48 kHz → 8/12/16 kHz decimation with a linear-phase Kaiser-windowed-sinc FIR.
- Per frame: energy VAD (inactive / unvoiced / voiced), open-loop pitch search (normalised
correlation with octave checks, joint lag + contour codebook choice, §4.2.7.6.1), windowed
autocorrelation LPC (Levinson, lag window, bandwidth expansion), LPC → NLSF by root search,
NLSF quantisation (stage-1 preselection by weighted distance, backwards-predictive stage-2
scalar quantiser reproducing the decoder's dequantisation exactly, rate-distortion choice),
LTP codebook search over the three periodicity codebooks, independent + delta gain coding.
- Analysis-by-synthesis excitation: every sample is chosen by running the decoder's exact
fixed-point reconstruction (LTP from the decoder's own past output, LPC synthesis with the Q12
coefficients of the *dequantised* NLSFs, gain rescaling between subframes, quantisation
offsets, the LCG sign sequence), so encoder and decoder never drift. A noise-feedback loop
shapes the coding noise by `1/A(z/γ)` (γ 0.75–0.9, coarser quantisation → more shaping), and a
small rate penalty biases pulses towards zero.
- Excitation coding: rate level, per-block pulse counts with LSB escapes, shell coding, LSBs and
signs (§4.2.7.8).
- Rate control: per-frame search over a gain offset (integer bracket, then bisection) to the
frame budget; SILK-only streams carry a bit reservoir across frames (packet sizes vary).
- Stereo: mid/side with the decoder's stereo prediction (§4.2.7.1, §4.2.8; ridge-regularised
least-squares weights, quantised to the decoder grid, interpolation mirrored), mid-only frames
when the predicted side is negligible, side gains floored at the mid gains.
- Not implemented: LBRR (in-band FEC), NLSF interpolation, 10/40/60 ms frames, DTX.
**Hybrid** (§4.3 with start band 17): the SILK frame is written first, then the redundancy flag
(always 0) when there is room, then a CELT frame coding bands 17–18 (SWB) or 17–20 (FB) in the
same range coder with the remaining packet bytes (no silence flag or post-filter in hybrid
frames, decoder band-energy reset for uncoded bands mirrored). SILK gets 72 % (SWB) / 62 % (FB)
of the per-channel bitrate, at most the bitrate minus 6 kb/s, and never more than leaves CELT a
fifth of the packet (at least 80 bits).
**CELT** (unchanged): forward MDCT with the low-overlap window, band energies with inter/intra
coarse prediction, fine and final energy bits, the decoder's exact bit allocation, spreading,
recursive band splitting, greedy PVQ search. Not implemented: transient frames, TF changes,
pitch post-filter, intensity stereo, dynamic allocation, VBR. All-zero CELT frames become 3-byte
silence packets.
## Measured (tests in `tests/`, craft-audio's Opus decoder)
Synthetic speech (glottal pulses 100–200 Hz through three moving formants, syllable envelopes,
pauses) and music (three-note harmonic chords); waveform SNR against the input band-limited to
the mode's bandwidth (full band for hybrid/CELT), residual delay 0 (±1 for narrowband) after the
pre-skip:
| mode / bandwidth | bitrate target → actual | speech SNR | music SNR |
|--------------------|-------------------------|------------|-----------|
| SILK NB | 8 → 7.5 kb/s | 15.9 dB | 6.9 dB (9 kb/s) |
| SILK MB | 11 → 10.1 kb/s | 21.8 dB | 7.9 dB |
| SILK WB | 12 → 10.9 kb/s | 21.5 dB | 8.1 dB |
| SILK WB | 16 → 14.3 kb/s | 28.1 dB | 12.1 dB |
| SILK WB | 24 → 21.1 kb/s | 37.0 dB | 19.7 dB |
| hybrid SWB | 24 kb/s (CBR) | 28.7 dB | 13.0 dB |
| hybrid FB | 32 kb/s (CBR) | 32.1 dB | 15.6 dB |
| CELT FB | 12 kb/s (CBR) | 13.0 dB | — |
At 12 kb/s mono, SILK wideband beats the CELT path on speech by ~8 dB (21.0 vs 13.0 dB
full-band SNR). SILK bitrates land within −13 % … 0 % of the target (speech spends little in
pauses), hybrid is exact. Stereo SILK WB at 32 kb/s: 41 dB dual-mono, 40/37 dB panned, 22/19 dB
for two independent speech signals.
ffmpeg (external oracle, Ogg Opus written by the test) decodes every mode with both its native
`opus` decoder and `libopus` without errors, honouring pre-skip and end trimming, with the same
SNRs (libopus residual delay 0, ffmpeg's native decoder 0–4 samples). The only message tolerated
is ffmpeg's raw-PCM muxer timestamp complaint that its native decoder also prints for
narrowband files encoded by libopus itself.
## Specifications
- RFC 6716, *Definition of the Opus Audio Codec* (September 2012), with the RFC 8251 updates
(October 2017) as implemented by the decoder we round-trip against.
- RFC 7845, *Ogg Encapsulation for the Opus Audio Codec* (April 2016), §5.1 `OpusHead` and
§4.2 pre-skip.
## Provenance
Implemented from the RFC text. Constant tables (CELT band edges, `eMeans`, the coarse-energy
Laplace model, the allocation table, ICDFs; all SILK probability tables and codebooks: NLSF
stage-1/2 codebooks and prediction weights, gain, pitch, contour, LTP and pulse ICDFs, stereo
weights) and the decoder-side normative arithmetic the encoder must reproduce bit-exactly (CELT
allocation; SILK NLSF dequantisation and stabilisation, NLSF → LPC conversion, `log2lin`, the
fixed-point division/inverse helpers and the LPC analysis filter) are mirrored from FilmCraft's
first-party, spec-derived `filmcraft-opus` decoder (MIT OR Apache-2.0). That decoder, now
`craft_audio::opus` in craft-libs, is also the round-trip oracle in `tests/` and `crates/export/tests/it/opus_roundtrip.rs` (ffmpeg is a second,
external oracle when installed). All encoder-side analysis and search (pitch, LPC, NLSF and
LTP search, noise feedback, rate control, stereo prediction, the decimator) is our own design.
No third-party encoder or decoder source (libopus or otherwise) was consulted.
-720
View File
@@ -1,720 +0,0 @@
//! Band shape coding: PVQ search and codeword indexing, spreading, recursive band splitting
//! (RFC 6716 §4.3.4, encoder direction).
//!
//! The encoder codes 20 ms long-block frames only (no transients, no TF changes), and stereo
//! as dual (independent L/R) stereo, so a band is always coded by `quant_partition` with a single
//! block. Every bit-budget computation mirrors the decoder so both sides take the same
//! split/pulse decisions.
use crate::range::{BITRES, RangeEncoder, ilog};
use crate::rate::{Mode, QTHETA_OFFSET, get_pulses};
use crate::tables::EBANDS;
use crate::{CeltFrame, rate::Allocation};
pub const SPREAD_NORMAL: usize = 2;
#[inline]
fn frac_mul16(a: i32, b: i32) -> i32 {
(16384 + (a as i16 as i32) * (b as i16 as i32)) >> 15
}
fn bitexact_cos(x: i32) -> i32 {
let tmp = (4096 + x * x) >> 13;
let x2 = tmp;
let x2 = (32767 - x2) + frac_mul16(x2, -7651 + frac_mul16(x2, 8277 + frac_mul16(-626, x2)));
1 + x2
}
fn bitexact_log2tan(isin: i32, icos: i32) -> i32 {
let lc = ilog(icos as u32);
let ls = ilog(isin as u32);
let icos = icos << (15 - lc);
let isin = isin << (15 - ls);
(ls - lc) * (1 << 11) + frac_mul16(isin, frac_mul16(isin, -2597) + 7932) - frac_mul16(icos, frac_mul16(icos, -2597) + 7932)
}
fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 {
const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048];
let mut n2 = 2 * n - 1;
if stereo && n == 2 {
n2 -= 1;
}
let mut qb = (b + n2 * offset) / n2;
qb = qb.min(b - pulse_cap - (4 << BITRES));
qb = qb.min(8 << BITRES);
if qb < (1 << BITRES >> 1) {
1
} else {
let qn = EXP2_TABLE8[(qb & 0x7) as usize] >> (14 - (qb >> BITRES));
(qn + 1) >> 1 << 1
}
}
/// One elementary pass of the spreading rotation, inverted (the decoder applies the forward
/// pass; the encoder undoes it before the pulse search).
fn exp_rotation1_inv(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) {
if len <= stride {
return;
}
if len > 2 * stride {
for i in 0..=len - 2 * stride - 1 {
let x1 = x[i];
let x2 = x[i + stride];
x[i + stride] = c * x2 - s * x1;
x[i] = c * x1 + s * x2;
}
}
for i in (0..len - stride).rev() {
let x1 = x[i];
let x2 = x[i + stride];
x[i + stride] = c * x2 - s * x1;
x[i] = c * x1 + s * x2;
}
}
/// Inverse of the decoder's spreading rotation (§4.3.4.3) for one block of `len` samples.
pub fn exp_rotation_inv(x: &mut [f32], len: usize, k: usize, spread: usize) {
const SPREAD_FACTOR: [usize; 3] = [15, 10, 5];
if 2 * k >= len || spread == 0 {
return;
}
let factor = SPREAD_FACTOR[spread - 1];
let gain = len as f32 / (len + factor * k) as f32;
let theta = 0.5 * gain * gain;
let c = (0.5 * std::f32::consts::PI * theta).cos();
let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos();
let mut stride2 = 0;
if len >= 8 {
stride2 = 1;
while stride2 * stride2 + stride2 < len {
stride2 += 1;
}
}
// The decoder applies (stride2: s, c) then (1: c, s); undo in reverse order.
exp_rotation1_inv(x, len, 1, c, s);
if stride2 != 0 {
exp_rotation1_inv(x, len, stride2, s, c);
}
}
/// Relative slack for the pulse-candidate filter in [`pvq_search`]: far above the f32 rounding of
/// the filter score (a few 1e-7), far below the spread of real scores.
const PVQ_SCORE_SLACK: f32 = 1e-5;
/// Greedy PVQ search: the integer vector `y` with `sum |y| = k` closest in direction to `x`.
pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) {
let n = x.len();
y[..n].fill(0);
// `abs`, `dy` (2 y + 1, infinite in the padding) and the per-pass scores `score`, each padded to
// whole 8-lane chunks.
let np = n.next_multiple_of(8);
let mut buf = vec![0f32; 3 * np];
let (abs, rest) = buf.split_at_mut(np);
let (dy, score) = rest.split_at_mut(np);
for (a, v) in abs.iter_mut().zip(x) {
*a = v.abs();
}
let sum: f32 = abs[..n].iter().sum();
if !sum.is_finite() || sum <= 1e-15 {
y[0] = k as i32;
return;
}
let mut placed = 0usize;
let mut xy = 0f32;
let mut yy = 0f32;
if k > n / 2 {
// Pre-project onto the pyramid (rounding down) and place the rest greedily.
let r = (k as f32 - 1.0) / sum;
for j in 0..n {
// Non-negative and at most k, so the truncating cast is the floor.
let p = (abs[j] * r) as i32;
y[j] = p;
placed += p as usize;
xy += abs[j] * p as f32;
yy += (p * p) as f32;
}
}
for j in 0..np {
dy[j] = if j < n { 2.0 * y[j] as f32 + 1.0 } else { f32::INFINITY };
}
while placed < k {
// Vectorisable scores (xy + |x_j|)^2 / (yy + 2 y_j + 1) and their maximum.
for ((sc, &a), &d) in score.iter_mut().zip(abs.iter()).zip(dy.iter()) {
let t = xy + a;
*sc = t * t / (yy + d);
}
let mut lane_max = [0f32; 8];
for c in score.as_chunks::<8>().0 {
for i in 0..8 {
lane_max[i] = if c[i] > lane_max[i] { c[i] } else { lane_max[i] };
}
}
let top = lane_max.iter().fold(0f32, |m, &v| if v > m { v } else { m });
// The exact cross-multiplied test below, in index order with the first maximum winning, only
// matters for entries within rounding distance of the top score: every other entry is beaten
// by the top one whenever it is reached and never beats it afterwards. Running the test on
// those alone therefore picks the same pulse as running it on all of them.
let filter = top > 1e-30 && top.is_finite();
let lo = top * (1.0 - PVQ_SCORE_SLACK);
// Usually exactly one entry qualifies; its index falls out of a lane-wise count.
let mut count = [0u32; 8];
let mut index = [0u32; 8];
for (ci, c) in score.as_chunks::<8>().0.iter().enumerate() {
for i in 0..8 {
let hit = u32::from(c[i] >= lo);
count[i] += hit;
index[i] += hit * (ci * 8 + i) as u32;
}
}
let mut best = 0usize;
if filter && count.iter().sum::<u32>() == 1 {
best = index.iter().sum::<u32>() as usize;
} else {
let mut best_num = -1f32;
let mut best_den = 1f32;
for j in 0..n {
if !filter || score[j] >= lo {
let num = xy + abs[j];
let num = num * num;
let den = yy + 2.0 * y[j] as f32 + 1.0;
if num * best_den > best_num * den {
best_num = num;
best_den = den;
best = j;
}
}
}
}
xy += abs[best];
yy += 2.0 * y[best] as f32 + 1.0;
y[best] += 1;
dy[best] = 2.0 * y[best] as f32 + 1.0;
placed += 1;
}
for j in 0..n {
if x[j] < 0.0 {
y[j] = -y[j];
}
}
}
/// Largest band width and pulse count the encoder codes (176 coefficients, `get_pulses(40)` = 128).
const PVQ_MAX_N: usize = 176;
const PVQ_MAX_K: usize = 128;
/// Row-major `V(n, k)` for `n <= max_n`, `k <= max_k` with row stride `max_k + 1`, saturated at
/// `u32::MAX` (a codebook that large is never coded, see `rate::fits_in32`).
fn build_pvq_table(max_n: usize, max_k: usize) -> Vec<u32> {
let w = max_k + 1;
let mut v = vec![0u32; (max_n + 1) * w];
v[0] = 1;
for nn in 1..=max_n {
v[nn * w] = 1;
for kk in 1..=max_k {
let sum = v[(nn - 1) * w + kk] as u64 + v[nn * w + kk - 1] as u64 + v[(nn - 1) * w + kk - 1] as u64;
v[nn * w + kk] = sum.min(u32::MAX as u64) as u32;
}
}
v
}
fn pvq_table() -> &'static [u32] {
static TABLE: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
TABLE.get_or_init(|| build_pvq_table(PVQ_MAX_N, PVQ_MAX_K))
}
/// Encodes the PVQ codeword `y` (`sum |y| = k`) as the index the RFC 6716 §4.3.4.2 decoder maps
/// back to `y`.
pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder) {
let n = y.len();
// Shapes outside the coded range (never produced by the band layout) get a local table.
let local;
let (v, w) = if n <= PVQ_MAX_N && k <= PVQ_MAX_K {
(pvq_table(), PVQ_MAX_K + 1)
} else {
local = build_pvq_table(n, k);
(&local[..], k + 1)
};
let row = |nn: usize| &v[nn * w..(nn + 1) * w];
let total = row(n)[k] as u64;
let mut index = 0u64;
let mut kk = k;
for j in 0..n {
if kk == 0 {
break;
}
let rem = n - j;
let t = y[j].unsigned_abs() as usize;
let below = row(rem - 1);
// Codewords with |y_j| = t start at sum_{m < kk - t} V(rem-1, m) within their sign half.
let mut base: u64 = below[..kk - t].iter().map(|&x| x as u64).sum();
if y[j] < 0 {
base += (below[kk] as u64 + row(rem)[kk] as u64) / 2;
}
index += base;
kk -= t;
}
debug_assert!(total <= u32::MAX as u64);
if total >= 2 {
enc.uint(index as u32, total as u32);
}
}
pub struct BandEnc<'m, 'e> {
pub m: &'m Mode,
pub enc: &'e mut RangeEncoder,
pub i: usize,
pub spread: usize,
pub remaining_bits: i32,
iy: Vec<i32>,
tmp: Vec<f32>,
}
impl BandEnc<'_, '_> {
/// `compute_theta` for a mono split (single block): measures the energy split between the
/// two halves and codes the quantised angle with the triangular pdf.
fn compute_theta_split(&mut self, xa: &[f32], xb: &[f32], b: &mut i32, lm: i32) -> (i32, i32, i32) {
let n = xa.len() as i32;
let i = self.i;
let pulse_cap = self.m.log_n[i] + lm * (1 << BITRES);
let offset = (pulse_cap >> 1) - QTHETA_OFFSET;
let qn = compute_qn(n, *b, offset, pulse_cap, false);
let tell = self.enc.tell_frac();
let mut itheta = 0i32;
if qn != 1 {
let mid = xa.iter().map(|v| v * v).sum::<f32>().sqrt();
let side = xb.iter().map(|v| v * v).sum::<f32>().sqrt();
let ang = (side as f64).atan2(mid as f64) * std::f64::consts::FRAC_2_PI;
let it = ((ang * qn as f64 + 0.5).floor() as i32).clamp(0, qn) as u32;
let q = qn as u32;
let half = q >> 1;
let ft = (half + 1) * (half + 1);
let (fl, fs) = if it <= half { ((it * (it + 1)) >> 1, it + 1) } else { (ft - (((q + 1 - it) * (q + 2 - it)) >> 1), q + 1 - it) };
self.enc.encode(fl, fl + fs, ft);
itheta = ((it * 16384) / q) as i32;
}
let qalloc = self.enc.tell_frac() - tell;
*b -= qalloc;
let delta = if itheta == 0 {
-16384
} else if itheta == 16384 {
16384
} else {
let imid = bitexact_cos(itheta);
let iside = bitexact_cos(16384 - itheta);
frac_mul16((n - 1) << 7, bitexact_log2tan(iside, imid))
};
(itheta, delta, qalloc)
}
/// `quant_partition` (single block, encoder side).
pub fn quant_partition(&mut self, x: &[f32], mut b: i32, mut lm: i32) {
let n = x.len();
let i = self.i;
let cache = self.m.cache(lm, i);
let cache_max = cache[cache[0] as usize] as i32;
if lm != -1 && b > cache_max + 12 && n > 2 {
let half = n >> 1;
let (xa, xb) = x.split_at(half);
lm -= 1;
let (itheta, delta, qalloc) = self.compute_theta_split(xa, xb, &mut b, lm);
let mut mbits = 0.max(b.min((b - delta) / 2));
let mut sbits = b - mbits;
self.remaining_bits -= qalloc;
let mut rebalance = self.remaining_bits;
if mbits >= sbits {
self.quant_partition(xa, mbits, lm);
rebalance = mbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && itheta != 0 {
sbits += rebalance - (3 << BITRES);
}
self.quant_partition(xb, sbits, lm);
} else {
self.quant_partition(xb, sbits, lm);
rebalance = sbits - (rebalance - self.remaining_bits);
if rebalance > 3 << BITRES && itheta != 16384 {
mbits += rebalance - (3 << BITRES);
}
self.quant_partition(xa, mbits, lm);
}
return;
}
let m = self.m;
let mut q = m.bits2pulses(i, lm, b);
let mut curr_bits = m.pulses2bits(i, lm, q);
self.remaining_bits -= curr_bits;
while self.remaining_bits < 0 && q > 0 {
self.remaining_bits += curr_bits;
q -= 1;
curr_bits = m.pulses2bits(i, lm, q);
self.remaining_bits -= curr_bits;
}
if q != 0 {
let k = get_pulses(q) as usize;
let mut tmp = std::mem::take(&mut self.tmp);
tmp.clear();
tmp.extend_from_slice(x);
exp_rotation_inv(&mut tmp, n, k, self.spread);
let mut iy = std::mem::take(&mut self.iy);
iy.clear();
iy.resize(n, 0);
pvq_search(&tmp, k, &mut iy);
encode_pulses(&iy, k, self.enc);
self.iy = iy;
self.tmp = tmp;
}
}
}
/// Shape-coding controls, independent of the selected band allocation.
pub struct BandCoding {
pub spread: usize,
pub total_bits: i32,
}
/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds
/// `frame.channels` channels of `n_total` normalised MDCT coefficients each.
pub fn quant_all_bands(m: &Mode, frame: CeltFrame, x: &[f32], n_total: usize, allocation: &Allocation, coding: BandCoding, enc: &mut RangeEncoder) {
let CeltFrame { start, end, channels: c, lm } = frame;
let Allocation { pulses, dual_stereo, intensity, coded_bands, balance, .. } = allocation;
let (dual_stereo, intensity, coded_bands, mut balance) = (*dual_stereo, *intensity, *coded_bands, *balance);
let BandCoding { spread, total_bits } = coding;
let mm = 1usize << lm;
debug_assert!(c == 1 || dual_stereo || intensity <= start, "stereo frames are coded as dual stereo");
let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, iy: Vec::new(), tmp: Vec::new() };
for i in start..end {
ctx.i = i;
let xo = mm * EBANDS[i] as usize;
let n = mm * EBANDS[i + 1] as usize - xo;
let tell = ctx.enc.tell_frac();
if i != start {
balance -= tell;
}
let remaining_bits = total_bits - tell - 1;
ctx.remaining_bits = remaining_bits;
let b = if i < coded_bands {
let curr_balance = balance / 3.min(coded_bands as i32 - i as i32);
0.max(16383.min((remaining_bits + 1).min(pulses[i] + curr_balance)))
} else {
0
};
// Bands at and above `intensity` (= coded_bands) carry no bits, so they emit no symbols.
if i < coded_bands || c == 1 {
if c == 2 && dual_stereo && i < intensity {
ctx.quant_partition(&x[xo..xo + n], b / 2, lm as i32);
ctx.quant_partition(&x[n_total + xo..n_total + xo + n], b / 2, lm as i32);
} else {
ctx.quant_partition(&x[xo..xo + n], b, lm as i32);
}
}
balance += pulses[i] + tell;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::range::dec::RangeDecoder;
fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) {
let ms = -s;
if len <= stride {
return;
}
for i in 0..len - stride {
let x1 = x[i];
let x2 = x[i + stride];
x[i + stride] = c * x2 + s * x1;
x[i] = c * x1 + ms * x2;
}
if len > 2 * stride {
for i in (0..=len - 2 * stride - 1).rev() {
let x1 = x[i];
let x2 = x[i + stride];
x[i + stride] = c * x2 + s * x1;
x[i] = c * x1 + ms * x2;
}
}
}
/// The decoder's spreading rotation (single block).
fn exp_rotation(x: &mut [f32], len: usize, k: usize, spread: usize) {
const SPREAD_FACTOR: [usize; 3] = [15, 10, 5];
if 2 * k >= len || spread == 0 {
return;
}
let factor = SPREAD_FACTOR[spread - 1];
let gain = len as f32 / (len + factor * k) as f32;
let theta = 0.5 * gain * gain;
let c = (0.5 * std::f32::consts::PI * theta).cos();
let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos();
let mut stride2 = 0;
if len >= 8 {
stride2 = 1;
while stride2 * stride2 + stride2 < len {
stride2 += 1;
}
}
if stride2 != 0 {
exp_rotation1(x, len, stride2, s, c);
}
exp_rotation1(x, len, 1, c, s);
}
#[test]
fn spreading_inverse_is_exact() {
for &len in &[8usize, 16, 24, 48, 96, 176] {
for k in [1usize, 2, 3, 5] {
let orig: Vec<f32> = (0..len).map(|i| ((i * 31 % 17) as f32 - 8.0) / 8.0).collect();
let mut x = orig.clone();
exp_rotation_inv(&mut x, len, k, SPREAD_NORMAL);
exp_rotation(&mut x, len, k, SPREAD_NORMAL);
for (a, b) in x.iter().zip(&orig) {
assert!((a - b).abs() < 1e-4, "len={len} k={k}");
}
}
}
}
/// PVQ decoder of RFC 6716 §4.3.4.2 (as in FilmCraft's decoder).
fn decode_pulses(n: usize, k: usize, dec: &mut RangeDecoder) -> Vec<i32> {
let w = k + 1;
let mut v = vec![0u64; (n + 1) * w];
v[0] = 1;
for nn in 1..=n {
v[nn * w] = 1;
for kk in 1..=k {
v[nn * w + kk] = v[(nn - 1) * w + kk].saturating_add(v[nn * w + kk - 1]).saturating_add(v[(nn - 1) * w + kk - 1]);
}
}
let total = v[n * w + k];
let mut i = if total >= 2 { dec.uint(total as u32) as u64 } else { 0 };
let mut y = vec![0i32; n];
let mut kk = k;
for j in 0..n {
let rem = n - j;
if kk == 0 {
break;
}
let vv = |nn: usize, kx: usize| v[nn * w + kx];
let mut p = (vv(rem - 1, kk) + vv(rem, kk)) / 2;
let neg = i >= p;
if neg {
i -= p;
}
let k0 = kk;
p -= vv(rem - 1, kk);
while p > i && kk > 0 {
kk -= 1;
p -= vv(rem - 1, kk);
}
let mag = (k0 - kk) as i32;
y[j] = if neg { -mag } else { mag };
i -= p.min(i);
}
y
}
fn all_codewords(n: usize, k: usize) -> Vec<Vec<i32>> {
if n == 0 {
return if k == 0 { vec![vec![]] } else { vec![] };
}
let mut out = Vec::new();
for t in -(k as i32)..=(k as i32) {
for mut rest in all_codewords(n - 1, k - t.unsigned_abs() as usize) {
rest.insert(0, t);
out.push(rest);
}
}
out
}
#[test]
fn pvq_index_roundtrip_exhaustive() {
for n in 1..6usize {
for k in 1..6usize {
for y in all_codewords(n, k) {
let mut e = RangeEncoder::new();
encode_pulses(&y, k, &mut e);
let buf = e.done(16);
let mut d = RangeDecoder::new(&buf);
assert_eq!(decode_pulses(n, k, &mut d), y, "n={n} k={k}");
}
}
}
}
/// The per-call table encoder this module used before the shared table.
fn encode_pulses_reference(y: &[i32], k: usize, enc: &mut RangeEncoder) {
let n = y.len();
let w = k + 1;
let mut v = vec![0u64; (n + 1) * w];
v[0] = 1;
for nn in 1..=n {
v[nn * w] = 1;
for kk in 1..=k {
let a = v[(nn - 1) * w + kk];
let b = v[nn * w + kk - 1];
let c = v[(nn - 1) * w + kk - 1];
v[nn * w + kk] = a.saturating_add(b).saturating_add(c);
}
}
let total = v[n * w + k];
let vv = |nn: usize, kx: usize| v[nn * w + kx];
let mut index = 0u64;
let mut kk = k;
for j in 0..n {
if kk == 0 {
break;
}
let rem = n - j;
let t = y[j].unsigned_abs() as usize;
let mut base: u64 = (0..kk - t).map(|m| vv(rem - 1, m)).sum();
if y[j] < 0 {
base += (vv(rem - 1, kk) + vv(rem, kk)) / 2;
}
index += base;
kk -= t;
}
if total >= 2 {
enc.uint(index as u32, total as u32);
}
}
#[test]
fn pvq_table_encode_matches_per_call_table() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move |m: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % m
};
let mut checked = 0;
for n in (1..=PVQ_MAX_N).step_by(5).chain([PVQ_MAX_N]) {
for k in (1..=PVQ_MAX_K).step_by(3).chain([PVQ_MAX_K]) {
if crate::rate::pvq_v(n, k) > u32::MAX as u128 {
continue;
}
for _ in 0..4 {
let mut y = vec![0i32; n];
for _ in 0..k {
let at = next(n as u64) as usize;
y[at] += if next(2) == 0 { 1 } else { -1 };
}
// Opposite pulses cancel; top up so that sum |y| = k again.
let mut have: usize = y.iter().map(|v| v.unsigned_abs() as usize).sum();
while have < k {
let at = next(n as u64) as usize;
y[at] += if y[at] < 0 { -1 } else { 1 };
have += 1;
}
let (mut a, mut b) = (RangeEncoder::new(), RangeEncoder::new());
encode_pulses(&y, k, &mut a);
encode_pulses_reference(&y, k, &mut b);
assert_eq!(a.done(16), b.done(16), "n={n} k={k}");
checked += 1;
}
}
}
assert!(checked > 100, "{checked}");
}
/// The scalar greedy search the vectorised one replaced.
fn pvq_search_ref(x: &[f32], k: usize, y: &mut [i32]) {
let n = x.len();
y[..n].fill(0);
let abs: Vec<f32> = x.iter().map(|v| v.abs()).collect();
let sum: f32 = abs.iter().sum();
if !sum.is_finite() || sum <= 1e-15 {
y[0] = k as i32;
return;
}
let mut placed = 0usize;
let mut xy = 0f32;
let mut yy = 0f32;
if k > n / 2 {
let r = (k as f32 - 1.0) / sum;
for j in 0..n {
let p = (abs[j] * r).floor() as i32;
y[j] = p;
placed += p as usize;
xy += abs[j] * p as f32;
yy += (p * p) as f32;
}
}
while placed < k {
let mut best = 0usize;
let mut best_num = -1f32;
let mut best_den = 1f32;
for j in 0..n {
let num = xy + abs[j];
let num = num * num;
let den = yy + 2.0 * y[j] as f32 + 1.0;
if num * best_den > best_num * den {
best_num = num;
best_den = den;
best = j;
}
}
xy += abs[best];
yy += 2.0 * y[best] as f32 + 1.0;
y[best] += 1;
placed += 1;
}
for j in 0..n {
if x[j] < 0.0 {
y[j] = -y[j];
}
}
}
#[test]
fn pvq_search_matches_scalar_reference() {
let mut state = 0x9e3779b97f4a7c15u64;
let mut rnd = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0
};
let mut a = vec![0i32; 200];
let mut b = vec![0i32; 200];
let mut cases = 0;
for round in 0..6000 {
let n = 1 + (round * 37 + (rnd().abs() * 176.0) as usize) % 176;
let k = 1 + (rnd().abs() * 127.0) as usize;
let scale = [1.0f32, 1e-9, 1e6, 3e-3][round % 4];
let x: Vec<f32> = (0..n)
.map(|_| match round % 6 {
0 => rnd(),
1 => if rnd() > 0.8 { rnd() } else { 0.0 },
2 => (rnd() * 4.0).round() / 4.0,
3 => if rnd() > 0.0 { 1.0 } else { -1.0 },
4 => rnd().powi(5),
_ => if rnd() > 0.95 { 3.0 * rnd() } else { 1e-4 * rnd() },
} * scale)
.collect();
pvq_search(&x, k, &mut a);
pvq_search_ref(&x, k, &mut b);
assert_eq!(a[..n], b[..n], "n={n} k={k} round={round}");
cases += 1;
}
assert_eq!(cases, 6000);
}
#[test]
fn pvq_search_finds_good_direction() {
let x: Vec<f32> = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect();
let mut y = vec![0i32; 32];
for k in [1usize, 4, 16, 64] {
pvq_search(&x, k, &mut y);
assert_eq!(y.iter().map(|v| v.unsigned_abs() as usize).sum::<usize>(), k);
let xy: f32 = x.iter().zip(&y).map(|(a, &b)| a * b as f32).sum();
let yy: f32 = y.iter().map(|&b| (b * b) as f32).sum();
let xx: f32 = x.iter().map(|a| a * a).sum();
let corr = xy / (xx * yy).sqrt();
assert!(corr > if k >= 16 { 0.9 } else { 0.2 }, "k={k} corr={corr}");
}
}
}
-212
View File
@@ -1,212 +0,0 @@
//! Band energy quantisation: Laplace-coded coarse energy with inter/intra prediction, fine
//! energy and the final refinement bits (RFC 6716 §4.3.2, encoder direction).
//!
//! The quantised energies are updated with exactly the decoder's arithmetic so the prediction
//! state never drifts between encoder and decoder.
use crate::CeltFrame;
use crate::range::RangeEncoder;
use crate::rate::{Allocation, MAX_FINE_BITS};
use crate::tables::{BETA_COEF, BETA_INTRA, E_PROB_MODEL, NB_EBANDS, PRED_COEF, SMALL_ENERGY_ICDF};
const LAPLACE_MINP: u32 = 1;
const LAPLACE_NMIN: u32 = 16;
fn laplace_get_freq1(fs0: u32, decay: u32) -> u32 {
let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0;
(ft * (16384 - decay)) >> 15
}
/// Encodes a Laplace-distributed integer (`fs` = probability of 0 in Q15, `decay` in Q14).
/// Returns the value actually coded (very large magnitudes are clamped to the representable
/// range).
pub fn laplace_encode(enc: &mut RangeEncoder, value: i32, mut fs: u32, decay: u32) -> i32 {
let mut fl = 0u32;
let mut coded = value;
if value != 0 {
let s: i32 = if value < 0 { -1 } else { 0 };
let val = value.abs();
fl = fs;
fs = laplace_get_freq1(fs, decay);
let mut i = 1;
while fs > 0 && i < val {
fs *= 2;
fl += fs + 2 * LAPLACE_MINP;
fs = (fs * decay) >> 15;
i += 1;
}
if fs == 0 {
let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32;
let ndi_max = (ndi_max - s) >> 1;
let di = (val - i).min(ndi_max - 1);
fl = (fl as i32 + (2 * di + 1 + s) * LAPLACE_MINP as i32) as u32;
fs = LAPLACE_MINP.min(32768 - fl);
let mag = i + di;
coded = if s < 0 { -mag } else { mag };
} else {
fs += LAPLACE_MINP;
if s == 0 {
fl += fs;
}
}
}
enc.encode_bin(fl, fl + fs, 15);
coded
}
/// `quant_coarse_energy` for one prediction mode. `e` holds the target log2 energies (relative
/// to `E_MEANS`), `old_e` the quantised energies, updated in place. `budget` is the frame size in
/// bits.
pub fn quant_coarse_energy(frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], intra: bool, enc: &mut RangeEncoder, budget: i32) {
let CeltFrame { start, end, channels: c, lm } = frame;
let prob = &E_PROB_MODEL[lm][intra as usize];
let (coef, beta) = if intra { (0.0, BETA_INTRA) } else { (PRED_COEF[lm], BETA_COEF[lm]) };
let mut prev = [0f32; 2];
for i in start..end {
for ch in 0..c {
let idx = i + ch * NB_EBANDS;
let oldc = old_e[idx].max(-9.0);
let x = e[idx];
let f = x - coef * oldc - prev[ch];
let mut qi = (f + 0.5).floor().clamp(-64.0, 64.0) as i32;
let tell = enc.tell();
// Keep a few bits per remaining band in reserve when the budget runs out.
let bits_left = budget - tell - 3 * c as i32 * (end - i) as i32;
if i != start && bits_left < 30 {
if bits_left < 24 {
qi = qi.min(1);
}
if bits_left < 16 {
qi = qi.max(-1);
}
}
if budget - tell >= 15 {
let pi = 2 * i.min(20);
qi = laplace_encode(enc, qi, (prob[pi] as u32) << 7, (prob[pi + 1] as u32) << 6);
} else if budget - tell >= 2 {
qi = qi.clamp(-1, 1);
enc.icdf(if qi < 0 { (-2 * qi - 1) as usize } else { (2 * qi) as usize }, &SMALL_ENERGY_ICDF, 2);
} else if budget - tell >= 1 {
qi = qi.clamp(-1, 0);
enc.bit_logp(qi == -1, 1);
} else {
qi = -1;
}
let q = qi as f32;
old_e[idx] = oldc;
let tmp = coef * old_e[idx] + prev[ch] + q;
old_e[idx] = tmp;
prev[ch] = prev[ch] + q - beta * q;
}
}
}
/// `quant_fine_energy`: raw bits refining each band's quantised energy.
pub fn quant_fine_energy(frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], fine_quant: &[i32; NB_EBANDS], enc: &mut RangeEncoder) {
let CeltFrame { start, end, channels: c, .. } = frame;
for i in start..end {
let fq = fine_quant[i];
if fq <= 0 {
continue;
}
for ch in 0..c {
let idx = i + ch * NB_EBANDS;
let err = e[idx] - old_e[idx];
let levels = 1i32 << fq;
let q2 = (((err + 0.5) * levels as f32).floor() as i32).clamp(0, levels - 1);
enc.bits(q2 as u32, fq as u32);
let offset = (q2 as f32 + 0.5) * (1 << (14 - fq)) as f32 / 16384.0 - 0.5;
old_e[idx] += offset;
}
}
}
/// `quant_energy_finalise`: spends the bits left at the end of the frame on one more bit of
/// energy resolution per band, in priority order.
pub fn quant_energy_finalise(
frame: CeltFrame,
e: &[f32; 2 * NB_EBANDS],
old_e: &mut [f32; 2 * NB_EBANDS],
allocation: &Allocation,
mut bits_left: i32,
enc: &mut RangeEncoder,
) {
let CeltFrame { start, end, channels: c, .. } = frame;
let Allocation { fine_quant, fine_priority, .. } = allocation;
for prio in 0..2 {
let mut i = start;
while i < end && bits_left >= c as i32 {
if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio {
i += 1;
continue;
}
for ch in 0..c {
let idx = i + ch * NB_EBANDS;
let q2 = (e[idx] - old_e[idx] >= 0.0) as u32;
enc.bits(q2, 1);
let offset = (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 / 16384.0;
old_e[idx] += offset;
bits_left -= 1;
}
i += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::range::dec::RangeDecoder;
/// Laplace decoder of RFC 6716 §4.3.2.1 (as in FilmCraft's decoder).
fn laplace_decode(dec: &mut RangeDecoder, mut fs: u32, decay: u32) -> i32 {
let mut val = 0i32;
let fm = dec.decode(32768);
let mut fl = 0u32;
if fm >= fs {
val += 1;
fl = fs;
fs = laplace_get_freq1(fs, decay) + LAPLACE_MINP;
while fs > LAPLACE_MINP && fm >= fl + 2 * fs {
fs *= 2;
fl += fs;
fs = (((fs - 2 * LAPLACE_MINP) * decay) >> 15) + LAPLACE_MINP;
val += 1;
}
if fs <= LAPLACE_MINP {
let di = (fm - fl) >> 1;
val += di as i32;
fl += 2 * di * LAPLACE_MINP;
}
if fm < fl + fs {
val = -val;
} else {
fl += fs;
}
}
dec.update(fl, (fl + fs).min(32768), 32768);
val
}
#[test]
fn laplace_roundtrip_all_models() {
for lm in 0..4 {
for intra in 0..2 {
for band in 0..21 {
let prob = &E_PROB_MODEL[lm][intra];
let (fs, decay) = ((prob[2 * band] as u32) << 7, (prob[2 * band + 1] as u32) << 6);
let vals: Vec<i32> = (-64..=64).collect();
let mut e = RangeEncoder::new();
let coded: Vec<i32> = vals.iter().map(|&v| laplace_encode(&mut e, v, fs, decay)).collect();
let size = (e.tell() as usize).div_ceil(8);
let buf = e.done(size);
let mut d = RangeDecoder::new(&buf);
for (&v, &c) in vals.iter().zip(&coded) {
assert!(c == v || (c.signum() == v.signum() && c.abs() < v.abs()), "clamp {v} -> {c}");
assert_eq!(laplace_decode(&mut d, fs, decay), c, "lm={lm} intra={intra} band={band} v={v}");
}
}
}
}
}
}
-553
View File
@@ -1,553 +0,0 @@
//! Clean-room pure-Rust Opus encoder (RFC 6716 SILK, hybrid and CELT modes; RFC 7845 `OpusHead`).
//!
//! Produces 20 ms Opus packets from 48 kHz float input, mono or stereo. The coding mode and
//! audio bandwidth are chosen once per stream from the per-channel bitrate and the
//! [`Application`] (see the crate README for the table):
//!
//! - **SILK** (narrowband/mediumband/wideband): linear-predictive speech coding at an internal
//! rate of 8/12/16 kHz; packet sizes vary around the target bitrate.
//! - **Hybrid** (super-wideband/fullband): SILK wideband codes 0–8 kHz and CELT codes the bands
//! above in the same range-coded frame; constant packet size.
//! - **CELT** (fullband): MDCT transform coding; constant packet size.
//!
//! Layer L0: no dependencies beyond `std`; no `unsafe`; builds for `wasm32-unknown-unknown`.
//!
//! ```
//! use effectcraft_opusenc::{Application, Mode, OpusEncoder};
//! let mut enc = OpusEncoder::new(2, 128_000);
//! let pcm = vec![0.0f32; OpusEncoder::FRAME_SIZE * 2];
//! let packet = enc.encode_float(&pcm);
//! assert_eq!(packet[0] >> 3, 31); // CELT-only, fullband, 20 ms
//! assert_eq!(enc.opus_head().len(), 19);
//! let voip = OpusEncoder::with_application(1, 16_000, Application::Voip);
//! assert_eq!(voip.mode(), Mode::Silk);
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod bands;
mod energy;
mod mdct;
mod range;
mod rate;
mod resample;
mod silk;
mod tables;
use std::sync::OnceLock;
use bands::{BandCoding, SPREAD_NORMAL, quant_all_bands};
use energy::{quant_coarse_energy, quant_energy_finalise, quant_fine_energy};
use mdct::Mdct;
use range::{BITRES, RangeEncoder};
use rate::{AllocationInput, Mode as CeltMode, compute_allocation};
use resample::Downsampler;
use silk::SilkEncoder;
use tables::{E_MEANS, EBANDS, NB_EBANDS, OVERLAP, PREEMPH, SPREAD_ICDF, TF_SELECT_TABLE, TRIM_ICDF};
/// Band range, channel count and transform size shared by CELT coding stages.
#[derive(Clone, Copy)]
struct CeltFrame {
start: usize,
end: usize,
channels: usize,
lm: usize,
}
/// Samples per channel in one 20 ms frame at 48 kHz.
const N: usize = 960;
/// LM of a 20 ms frame (8 short blocks).
const LM: usize = 3;
/// Smallest CELT payload the encoder produces (bytes).
const MIN_FRAME_BYTES: usize = 16;
/// Largest payload allowed in one frame (RFC 6716 §3.4, R2).
const MAX_FRAME_BYTES: usize = 1275;
/// First CELT band coded in hybrid frames (8 kHz).
const HYBRID_START_BAND: usize = 17;
fn celt_mode() -> &'static CeltMode {
static MODE: OnceLock<CeltMode> = OnceLock::new();
MODE.get_or_init(CeltMode::new)
}
/// Intended use of the stream; selects the mode/bandwidth table.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Application {
/// General audio (music, mixed content): CELT unless the bitrate is low.
#[default]
Audio,
/// Speech: SILK and hybrid over a wider bitrate range, narrower bandwidths at low rates.
Voip,
}
/// Opus coding mode (RFC 6716 §2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Mode {
/// MDCT transform coding only.
Celt,
/// Linear-prediction coding only.
Silk,
/// SILK below 8 kHz plus CELT above.
Hybrid,
}
/// Coded audio bandwidth (RFC 6716 §2, Table 1).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Bandwidth {
/// 4 kHz (8 kHz sampling).
Narrowband,
/// 6 kHz (12 kHz sampling).
Mediumband,
/// 8 kHz (16 kHz sampling).
Wideband,
/// 12 kHz (24 kHz sampling).
SuperWideband,
/// 20 kHz (48 kHz sampling).
Fullband,
}
/// Mode and bandwidth for a per-channel bitrate (bits per second per channel).
fn choose_mode(app: Application, per_channel: u32) -> (Mode, Bandwidth) {
match app {
Application::Voip => match per_channel {
0..10_000 => (Mode::Silk, Bandwidth::Narrowband),
10_000..12_000 => (Mode::Silk, Bandwidth::Mediumband),
12_000..18_000 => (Mode::Silk, Bandwidth::Wideband),
18_000..28_000 => (Mode::Hybrid, Bandwidth::SuperWideband),
28_000..40_000 => (Mode::Hybrid, Bandwidth::Fullband),
_ => (Mode::Celt, Bandwidth::Fullband),
},
Application::Audio => match per_channel {
0..16_000 => (Mode::Silk, Bandwidth::Wideband),
16_000..36_000 => (Mode::Hybrid, Bandwidth::Fullband),
_ => (Mode::Celt, Bandwidth::Fullband),
},
}
}
/// SILK side of a SILK-only or hybrid stream.
struct SilkPath {
enc: SilkEncoder,
down: Vec<Downsampler>,
/// Bits per frame aimed at (excluding the TOC byte in SILK-only mode).
target_bits: f64,
/// Bits saved (positive) or overspent by previous frames (SILK-only mode).
reservoir: f64,
}
/// Opus encoder for one mono or stereo stream at 48 kHz.
pub struct OpusEncoder {
channels: usize,
application: Application,
mode: Mode,
bandwidth: Bandwidth,
/// Requested bitrate (clamped), bits per second.
bitrate_bps: u32,
/// Payload bytes per packet in CELT and hybrid modes (the packet is one byte longer: the
/// TOC).
frame_bytes: usize,
mdct: Mdct,
/// Last input sample of each channel (pre-emphasis filter memory, ×32768).
preemph_mem: [f32; 2],
/// Last `OVERLAP` pre-emphasised samples of each channel.
hist: Vec<f32>,
/// Quantised band energies, exactly as the decoder holds them.
old_band_e: [f32; 2 * NB_EBANDS],
block: Vec<f32>,
freq: Vec<f32>,
silk: Option<SilkPath>,
}
impl OpusEncoder {
/// Samples per channel per packet (20 ms at 48 kHz).
pub const FRAME_SIZE: usize = N;
/// Creates a general-audio encoder ([`Application::Audio`]) for `channels` (1 or 2)
/// channels of 48 kHz audio at `bitrate_bps` (total for all channels).
pub fn new(channels: u8, bitrate_bps: u32) -> Self {
Self::with_application(channels, bitrate_bps, Application::Audio)
}
/// Creates an encoder for `channels` (1 or 2) channels of 48 kHz audio at `bitrate_bps`
/// (total for all channels; clamped to 6 kb/s per channel – 510 kb/s), choosing the mode
/// and bandwidth for `application`.
pub fn with_application(channels: u8, bitrate_bps: u32, application: Application) -> Self {
let c = channels.max(1) as u32;
let (mode, bandwidth) = choose_mode(application, bitrate_bps.clamp(6_000 * c, 510_000) / c);
Self::build(channels, bitrate_bps, application, mode, bandwidth)
}
/// Creates an encoder with an explicit mode and bandwidth instead of the application's
/// table. Valid combinations: SILK with narrowband, mediumband or wideband; hybrid with
/// super-wideband or fullband; CELT with fullband.
///
/// # Panics
/// On any other combination, or when `channels` is not 1 or 2.
pub fn with_mode(channels: u8, bitrate_bps: u32, mode: Mode, bandwidth: Bandwidth) -> Self {
let ok = match mode {
Mode::Silk => bandwidth <= Bandwidth::Wideband,
Mode::Hybrid => bandwidth >= Bandwidth::SuperWideband,
Mode::Celt => bandwidth == Bandwidth::Fullband,
};
assert!(ok, "unsupported mode/bandwidth combination {mode:?}/{bandwidth:?}");
Self::build(channels, bitrate_bps, Application::Audio, mode, bandwidth)
}
fn build(channels: u8, bitrate_bps: u32, application: Application, mode: Mode, bandwidth: Bandwidth) -> Self {
assert!(channels == 1 || channels == 2, "Opus family-0 streams have 1 or 2 channels");
let c = channels as usize;
let bitrate_bps = bitrate_bps.clamp(6_000 * c as u32, 510_000);
let packet_bytes = (bitrate_bps as usize).div_ceil(400);
let frame_bytes = packet_bytes.saturating_sub(1).clamp(MIN_FRAME_BYTES, MAX_FRAME_BYTES);
let silk = match mode {
Mode::Celt => None,
Mode::Silk | Mode::Hybrid => {
let fs_khz = match bandwidth {
Bandwidth::Narrowband => 8,
Bandwidth::Mediumband => 12,
_ => 16,
};
let target_bits = if mode == Mode::Silk {
bitrate_bps as f64 / 50.0 - 8.0
} else {
// SILK gets most of a hybrid packet; CELT codes 8 kHz and up with the rest.
let per = (bitrate_bps / c as u32) as f64;
let share = if bandwidth == Bandwidth::SuperWideband { 0.72 } else { 0.62 };
c as f64 * (per * share).min(per - 6_000.0).max(per * 0.5) / 50.0
};
Some(SilkPath {
enc: SilkEncoder::new(fs_khz, c),
down: (0..c).map(|_| Downsampler::new(fs_khz as u32 * 1000)).collect(),
target_bits,
reservoir: 0.0,
})
}
};
OpusEncoder {
channels: c,
application,
mode,
bandwidth,
bitrate_bps,
frame_bytes,
mdct: Mdct::new(N),
preemph_mem: [0.0; 2],
hist: vec![0.0; c * OVERLAP],
old_band_e: [0.0; 2 * NB_EBANDS],
block: vec![0.0; N + OVERLAP],
freq: vec![0.0; c * N],
silk,
}
}
/// Number of channels.
pub fn channels(&self) -> u8 {
self.channels as u8
}
/// The application the encoder was created for.
pub fn application(&self) -> Application {
self.application
}
/// Coding mode of every packet of the stream.
pub fn mode(&self) -> Mode {
self.mode
}
/// Coded audio bandwidth of every packet of the stream.
pub fn bandwidth(&self) -> Bandwidth {
self.bandwidth
}
/// Bitrate in bits per second: the constant packet size × 50 packets per second in CELT
/// and hybrid modes, the (average) target in SILK mode.
pub fn bitrate(&self) -> u32 {
match self.mode {
Mode::Silk => self.bitrate_bps,
_ => ((self.frame_bytes + 1) * 8 * 50) as u32,
}
}
/// Samples at 48 kHz the decoder must discard from the start of the stream (the `OpusHead`
/// pre-skip): the encoder's total delay. CELT: the 120-sample MDCT overlap. SILK/hybrid:
/// the decimator (83 samples, 88 for narrowband) plus the decoder's SILK delay (one
/// internal-rate sample and the resampler delay of RFC 6716 Table 54), which also rounds
/// to 120 samples.
pub fn pre_skip(&self) -> u16 {
let (fs, table54_ms) = match (self.mode, self.bandwidth) {
(Mode::Celt, _) => return OVERLAP as u16,
(_, Bandwidth::Narrowband) => (8_000, 0.538),
(_, Bandwidth::Mediumband) => (12_000, 0.692),
_ => (16_000, 0.706),
};
(resample::delay(fs) as f64 + 48_000.0 / fs as f64 + table54_ms * 48.0).round() as u16
}
/// The 19-byte `OpusHead` identification header (RFC 7845 §5.1): version 1, channel count,
/// pre-skip, input sample rate 48000, output gain 0, channel mapping family 0.
pub fn opus_head(&self) -> Vec<u8> {
let mut h = Vec::with_capacity(19);
h.extend_from_slice(b"OpusHead");
h.push(1);
h.push(self.channels as u8);
h.extend_from_slice(&self.pre_skip().to_le_bytes());
h.extend_from_slice(&48_000u32.to_le_bytes());
h.extend_from_slice(&0i16.to_le_bytes());
h.push(0);
h
}
/// TOC byte (RFC 6716 §3.1, Table 2) of a 20 ms single-frame packet.
fn toc(&self) -> u8 {
let config: u8 = match (self.mode, self.bandwidth) {
(Mode::Silk, Bandwidth::Narrowband) => 1,
(Mode::Silk, Bandwidth::Mediumband) => 5,
(Mode::Silk, _) => 9,
(Mode::Hybrid, Bandwidth::SuperWideband) => 13,
(Mode::Hybrid, _) => 15,
(Mode::Celt, _) => 31,
};
(config << 3) | if self.channels == 2 { 4 } else { 0 }
}
/// Encodes one 20 ms frame of interleaved f32 samples in [-1, 1] (exactly
/// `FRAME_SIZE * channels` values) and returns one Opus packet.
pub fn encode_float(&mut self, pcm: &[f32]) -> Vec<u8> {
let c = self.channels;
assert_eq!(pcm.len(), N * c, "encode_float takes exactly FRAME_SIZE samples per channel");
let mut packet = vec![self.toc()];
match self.mode {
Mode::Celt => {
let (log_e, silence) = self.celt_analysis(pcm);
let len = self.frame_bytes;
packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0..NB_EBANDS, &log_e, silence));
}
Mode::Silk => {
let x = self.silk_input(pcm);
// The SILK state exists whenever the mode uses SILK (set with the mode).
if let Some(sp) = self.silk.as_mut() {
let target = sp.target_bits + 0.25 * sp.reservoir;
let mut enc = RangeEncoder::new();
sp.enc.encode(&x, target.max(24.0), (MAX_FRAME_BYTES * 8) as i32, &mut enc);
let bytes = (enc.tell() as usize).div_ceil(8).max(2);
let lim = 4.0 * sp.target_bits;
sp.reservoir = (sp.reservoir + sp.target_bits - (bytes * 8) as f64).clamp(-lim, lim);
packet.extend_from_slice(&enc.done(bytes));
}
}
Mode::Hybrid => {
let x = self.silk_input(pcm);
let len = self.frame_bytes;
let total = (len * 8) as i32;
let celt_min = (total / 5).max(80);
let mut enc = RangeEncoder::new();
if let Some(sp) = self.silk.as_mut() {
sp.enc.encode(&x, sp.target_bits, total - celt_min, &mut enc);
}
// No redundancy (RFC 6716 §4.5.1); the flag is present when there is room.
if enc.tell() + 17 + 20 <= total {
enc.bit_logp(false, 12);
}
let (log_e, _) = self.celt_analysis(pcm);
let end = if self.bandwidth == Bandwidth::SuperWideband { 19 } else { NB_EBANDS };
packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND..end, &log_e, false));
}
}
packet
}
/// Decimates the input to the SILK internal rate (16-bit scale), one vector per channel.
fn silk_input(&mut self, pcm: &[f32]) -> Vec<Vec<f32>> {
let c = self.channels;
let Some(sp) = self.silk.as_mut() else { return vec![vec![]; c] };
let mut out = Vec::with_capacity(c);
let mut tmp = vec![0f32; N];
for ch in 0..c {
for (j, t) in tmp.iter_mut().enumerate() {
let s = pcm[j * c + ch];
*t = if s.is_finite() { s.clamp(-1.0, 1.0) * 32768.0 } else { 0.0 };
}
let mut y = Vec::with_capacity(N / 3);
sp.down[ch].process(&tmp, &mut y);
out.push(y);
}
out
}
/// Pre-emphasis, the MDCT, band energies (log2, relative to `E_MEANS`) and normalised
/// bands; returns the energies and whether the frame is digital silence.
fn celt_analysis(&mut self, pcm: &[f32]) -> ([f32; 2 * NB_EBANDS], bool) {
let c = self.channels;
let mut log_e = [0f32; 2 * NB_EBANDS];
let mut peak = 0f32;
for ch in 0..c {
self.block[..OVERLAP].copy_from_slice(&self.hist[ch * OVERLAP..(ch + 1) * OVERLAP]);
let mut mem = self.preemph_mem[ch];
for j in 0..N {
let s = pcm[j * c + ch];
let s = if s.is_finite() { s.clamp(-2.0, 2.0) * 32768.0 } else { 0.0 };
let v = s - PREEMPH * mem;
mem = s;
self.block[OVERLAP + j] = v;
}
self.preemph_mem[ch] = mem;
self.hist[ch * OVERLAP..(ch + 1) * OVERLAP].copy_from_slice(&self.block[N..]);
peak = self.block.iter().fold(peak, |p, v| p.max(v.abs()));
let freq = &mut self.freq[ch * N..(ch + 1) * N];
self.mdct.forward(&self.block, freq);
for i in 0..NB_EBANDS {
let lo = (EBANDS[i] as usize) << LM;
let hi = (EBANDS[i + 1] as usize) << LM;
let e = (1e-27f32 + freq[lo..hi].iter().map(|v| v * v).sum::<f32>()).sqrt();
log_e[ch * NB_EBANDS + i] = e.log2() - E_MEANS[i];
let g = 1.0 / e;
for v in freq[lo..hi].iter_mut() {
*v *= g;
}
}
}
(log_e, peak < 1e-4)
}
/// Codes one CELT frame (RFC 6716 §4.3, in bitstream order) of `len` bytes into `enc`
/// (which already holds the SILK frame in hybrid mode), coding bands `start..end`, and
/// finalises the frame.
fn encode_celt(&mut self, mut enc: RangeEncoder, len: usize, bands: std::ops::Range<usize>, log_e: &[f32; 2 * NB_EBANDS], silence: bool) -> Vec<u8> {
let m = celt_mode();
let c = self.channels;
let frame = CeltFrame { start: bands.start, end: bands.end, channels: c, lm: LM };
let CeltFrame { start, end, .. } = frame;
if c == 1 {
for i in 0..NB_EBANDS {
self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[NB_EBANDS + i]);
}
}
if silence && start == 0 {
// The silence flag; the decoder treats every remaining bit as consumed.
enc.bit_logp(true, 15);
self.old_band_e = [-28.0; 2 * NB_EBANDS];
return enc.done(2);
}
let total_bits_raw = len as i32 * 8;
if enc.tell() == 1 {
enc.bit_logp(false, 15);
}
// No pitch post-filter (only signalled in CELT-only frames).
if start == 0 && enc.tell() + 16 <= total_bits_raw {
enc.bit_logp(false, 1);
}
// Long blocks only.
if enc.tell() + 3 <= total_bits_raw {
enc.bit_logp(false, 3);
}
// Coarse energy, choosing intra or inter prediction by trial (whichever is cheaper).
if enc.tell() + 3 <= total_bits_raw {
let mut enc_intra = enc.clone();
let mut old_intra = self.old_band_e;
enc_intra.bit_logp(true, 3);
quant_coarse_energy(frame, log_e, &mut old_intra, true, &mut enc_intra, total_bits_raw);
enc.bit_logp(false, 3);
let mut old_inter = self.old_band_e;
quant_coarse_energy(frame, log_e, &mut old_inter, false, &mut enc, total_bits_raw);
if enc_intra.tell_frac() < enc.tell_frac() {
enc = enc_intra;
self.old_band_e = old_intra;
} else {
self.old_band_e = old_inter;
}
} else {
quant_coarse_energy(frame, log_e, &mut self.old_band_e, false, &mut enc, total_bits_raw);
}
// TF resolution: no changes.
{
let mut budget = total_bits_raw;
let mut tell = enc.tell();
let mut logp = 4;
let tf_select_rsv = LM > 0 && tell + logp < budget;
budget -= tf_select_rsv as i32;
for _ in start..end {
if tell + logp <= budget {
enc.bit_logp(false, logp as u32);
tell = enc.tell();
}
logp = 5;
}
if tf_select_rsv && TF_SELECT_TABLE[LM][0] != TF_SELECT_TABLE[LM][2] {
enc.bit_logp(false, 1);
}
}
if enc.tell() + 4 <= total_bits_raw {
enc.icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5);
}
// Dynamic allocation: no boosts.
let cap = m.init_caps(LM, c);
let offsets = [0i32; NB_EBANDS];
let total_bits = total_bits_raw << BITRES;
let mut tellf = enc.tell_frac();
for &cp in cap.iter().take(end).skip(start) {
if tellf + (6 << BITRES) < total_bits && 0 < cp {
enc.bit_logp(false, 6);
tellf = enc.tell_frac();
}
}
let alloc_trim = 5;
if tellf + (6 << BITRES) <= total_bits {
enc.icdf(alloc_trim as usize, &TRIM_ICDF, 7);
}
let bits = (total_bits_raw << BITRES) - enc.tell_frac() - 1;
let alloc = compute_allocation(m, frame, AllocationInput { offsets: &offsets, cap: &cap, trim: alloc_trim, bits }, &mut enc);
quant_fine_energy(frame, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc);
quant_all_bands(m, frame, &self.freq, N, &alloc, BandCoding { spread: SPREAD_NORMAL, total_bits: total_bits_raw << BITRES }, &mut enc);
let bits_left = total_bits_raw - enc.tell();
quant_energy_finalise(frame, log_e, &mut self.old_band_e, &alloc, bits_left, &mut enc);
debug_assert!(enc.tell() <= total_bits_raw, "frame overflow: {} > {}", enc.tell(), total_bits_raw);
if c == 1 {
let (a, b) = self.old_band_e.split_at_mut(NB_EBANDS);
b.copy_from_slice(a);
}
// The decoder forgets the energies of bands it did not code.
for ch in 0..2 {
for i in (0..start).chain(end..NB_EBANDS) {
self.old_band_e[ch * NB_EBANDS + i] = 0.0;
}
}
enc.done(len)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn opus_head_layout() {
let e = OpusEncoder::new(2, 96_000);
let h = e.opus_head();
assert_eq!(&h[..8], b"OpusHead");
assert_eq!(h[8], 1);
assert_eq!(h[9], 2);
assert_eq!(u16::from_le_bytes([h[10], h[11]]), e.pre_skip());
assert_eq!(u32::from_le_bytes([h[12], h[13], h[14], h[15]]), 48_000);
assert_eq!(&h[16..], &[0, 0, 0]);
}
#[test]
fn packet_sizes_follow_bitrate() {
for (ch, rate) in [(1u8, 64_000u32), (2, 128_000), (2, 256_000)] {
let mut e = OpusEncoder::new(ch, rate);
let pcm: Vec<f32> = (0..N * ch as usize).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
let p = e.encode_float(&pcm);
assert_eq!(p.len(), rate as usize / 400);
assert_eq!(p[0], 0xF8 | if ch == 2 { 4 } else { 0 });
assert_eq!(e.bitrate(), rate);
}
}
#[test]
fn silence_is_a_tiny_packet() {
let mut e = OpusEncoder::new(1, 64_000);
let p = e.encode_float(&vec![0.0; N]);
assert_eq!(p.len(), 3);
}
}
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more