Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M0.3–M0.8: geom, color, frame, media generators, project model, edit algebra, CPU renderer

Brandon Thomas8d83799cc0cf
diff --git a/.gitignore b/.gitignore
index 5d401fb19..81d7e8b75 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@ plan/
/dist
/log
.DS_Store
+.claude/worktrees/
diff --git a/Cargo.lock b/Cargo.lock
index 4f3edd481..11a1cadba 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -29,12 +35,76 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -51,6 +121,21 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
[[package]]
name = "filmcraft-bitstream"
version = "0.1.0"
@@ -66,6 +151,27 @@ dependencies = [
"serde",
]
+[[package]]
+name = "filmcraft-edit"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-media",
+ "filmcraft-project",
+ "filmcraft-time",
+ "proptest",
+ "thiserror",
+]
+
+[[package]]
+name = "filmcraft-frame"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-color",
+ "filmcraft-time",
+ "rayon",
+ "serde",
+]
+
[[package]]
name = "filmcraft-geom"
version = "0.1.0"
@@ -74,6 +180,47 @@ dependencies = [
"serde",
]
+[[package]]
+name = "filmcraft-media"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-color",
+ "filmcraft-frame",
+ "filmcraft-time",
+ "image",
+ "rayon",
+ "serde",
+ "thiserror",
+]
+
+[[package]]
+name = "filmcraft-project"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-color",
+ "filmcraft-geom",
+ "filmcraft-media",
+ "filmcraft-time",
+ "proptest",
+ "serde",
+ "serde_json",
+ "thiserror",
+]
+
+[[package]]
+name = "filmcraft-render"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-color",
+ "filmcraft-frame",
+ "filmcraft-geom",
+ "filmcraft-media",
+ "filmcraft-project",
+ "filmcraft-time",
+ "image",
+ "rayon",
+]
+
[[package]]
name = "filmcraft-time"
version = "0.1.0"
@@ -82,6 +229,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -111,6 +269,56 @@ dependencies = [
"r-efi 6.0.0",
]
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "tiff",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error 2.0.1",
+]
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -135,6 +343,36 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -150,6 +388,19 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -187,12 +438,24 @@ dependencies = [
"unarray",
]
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quote"
version = "1.0.47"
@@ -252,6 +515,26 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "regex-syntax"
version = "0.8.11"
@@ -278,7 +561,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
- "quick-error",
+ "quick-error 1.2.3",
"tempfile",
"wait-timeout",
]
@@ -326,6 +609,12 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
[[package]]
name = "syn"
version = "2.0.119"
@@ -361,6 +650,40 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error 2.0.1",
+ "weezl",
+ "zune-jpeg",
+]
+
[[package]]
name = "unarray"
version = "0.1.4"
@@ -391,6 +714,12 @@ dependencies = [
"wit-bindgen",
]
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -439,8 +768,29 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
diff --git a/Cargo.toml b/Cargo.toml
index 2c249a925..014d733d4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,9 @@ unsafe_code = "deny"
[workspace.lints.clippy]
dbg_macro = "warn"
todo = "warn"
+too_many_arguments = "allow"
+needless_range_loop = "allow"
+type_complexity = "allow"
[profile.dev.package."*"]
opt-level = 2
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index 179adb7b4..0ba386d25 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -1 +1,436 @@
-//! placeholder
+//! Colour science for FilmCraft: YUV matrices, transfer functions, colour metadata and LUTs.
+//!
+//! The compositor works in **linear-light, premultiplied RGBA f32** in the sequence working space
+//! (Rec.709 primaries by default). Decoded frames carry [`ColorInfo`] so conversions are explicit.
+
+use serde::{Deserialize, Serialize};
+use std::sync::OnceLock;
+
+/// YUV ↔ RGB matrix coefficients.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Matrix {
+ Bt601,
+ #[default]
+ Bt709,
+ Bt2020Ncl,
+}
+
+impl Matrix {
+ /// (Kr, Kb) luma coefficients.
+ pub fn kr_kb(self) -> (f32, f32) {
+ match self {
+ Matrix::Bt601 => (0.299, 0.114),
+ Matrix::Bt709 => (0.2126, 0.0722),
+ Matrix::Bt2020Ncl => (0.2627, 0.0593),
+ }
+ }
+ /// From an ISO/IEC 23091-2 `matrix_coefficients` code.
+ pub fn from_code(c: u8) -> Option<Matrix> {
+ match c {
+ 1 => Some(Matrix::Bt709),
+ 5 | 6 => Some(Matrix::Bt601),
+ 9 | 10 => Some(Matrix::Bt2020Ncl),
+ _ => None,
+ }
+ }
+}
+
+/// Transfer characteristics.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Transfer {
+ /// BT.709 / BT.1886 display (we use pure 2.4 gamma for display-referred decode, as NLEs do).
+ #[default]
+ Bt709,
+ Srgb,
+ Linear,
+ /// SMPTE ST 2084.
+ Pq,
+ /// ARIB STD-B67.
+ Hlg,
+}
+
+impl Transfer {
+ pub fn from_code(c: u8) -> Option<Transfer> {
+ match c {
+ 1 | 6 | 14 | 15 => Some(Transfer::Bt709),
+ 13 => Some(Transfer::Srgb),
+ 8 => Some(Transfer::Linear),
+ 16 => Some(Transfer::Pq),
+ 18 => Some(Transfer::Hlg),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Primaries {
+ #[default]
+ Bt709,
+ Bt601_625,
+ Bt601_525,
+ Bt2020,
+ P3D65,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Range {
+ /// 16–235 (8-bit) "video" range.
+ #[default]
+ Limited,
+ Full,
+}
+
+/// Colour metadata attached to frames.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct ColorInfo {
+ pub matrix: Matrix,
+ pub transfer: Transfer,
+ pub primaries: Primaries,
+ pub range: Range,
+}
+
+impl ColorInfo {
+ pub const SRGB_FULL: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Srgb, primaries: Primaries::Bt709, range: Range::Full };
+ pub const REC709: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };
+}
+
+/// Convert normalised Y'CbCr (Y in 0..1, Cb/Cr in -0.5..0.5) to non-linear R'G'B'.
+#[inline]
+pub fn ycbcr_to_rgb(y: f32, cb: f32, cr: f32, m: Matrix) -> [f32; 3] {
+ let (kr, kb) = m.kr_kb();
+ let kg = 1.0 - kr - kb;
+ let r = y + 2.0 * (1.0 - kr) * cr;
+ let b = y + 2.0 * (1.0 - kb) * cb;
+ let g = (y - kr * r - kb * b) / kg;
+ [r, g, b]
+}
+
+/// Convert non-linear R'G'B' to normalised Y'CbCr.
+#[inline]
+pub fn rgb_to_ycbcr(r: f32, g: f32, b: f32, m: Matrix) -> [f32; 3] {
+ let (kr, kb) = m.kr_kb();
+ let kg = 1.0 - kr - kb;
+ let y = kr * r + kg * g + kb * b;
+ [y, (b - y) / (2.0 * (1.0 - kb)), (r - y) / (2.0 * (1.0 - kr))]
+}
+
+/// Normalise an integer code value to (Y 0..1, C -0.5..0.5) given bit depth and range.
+#[inline]
+pub fn normalize_y(v: u32, bits: u32, range: Range) -> f32 {
+ let scale = (1u32 << (bits - 8)) as f32;
+ match range {
+ Range::Limited => (v as f32 - 16.0 * scale) / (219.0 * scale),
+ Range::Full => v as f32 / ((1u32 << bits) - 1) as f32,
+ }
+}
+#[inline]
+pub fn normalize_c(v: u32, bits: u32, range: Range) -> f32 {
+ let scale = (1u32 << (bits - 8)) as f32;
+ match range {
+ Range::Limited => (v as f32 - 128.0 * scale) / (224.0 * scale),
+ Range::Full => (v as f32 - (1u32 << (bits - 1)) as f32) / ((1u32 << bits) - 1) as f32,
+ }
+}
+
+/// sRGB electro-optical transfer (encoded → linear).
+#[inline]
+pub fn srgb_to_linear(v: f32) -> f32 {
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+#[inline]
+pub fn linear_to_srgb(v: f32) -> f32 {
+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
+}
+
+/// Encoded → linear for a transfer function (display-referred; PQ normalised to 100 nits = 1.0).
+pub fn to_linear(v: f32, t: Transfer) -> f32 {
+ match t {
+ Transfer::Srgb => srgb_to_linear(v),
+ // Premiere treats Rec.709 as display gamma 2.4 in its colour-managed pipeline; the
+ // sRGB curve is visually identical for UI previews and keeps round-trips exact.
+ Transfer::Bt709 => srgb_to_linear(v),
+ Transfer::Linear => v,
+ Transfer::Pq => pq_eotf(v) * 100.0,
+ Transfer::Hlg => hlg_inverse_oetf(v),
+ }
+}
+
+pub fn from_linear(v: f32, t: Transfer) -> f32 {
+ match t {
+ Transfer::Srgb | Transfer::Bt709 => linear_to_srgb(v),
+ Transfer::Linear => v,
+ Transfer::Pq => pq_inverse_eotf(v / 100.0),
+ Transfer::Hlg => hlg_oetf(v),
+ }
+}
+
+/// SMPTE ST 2084 EOTF, output normalised to 10 000 nits = 1.0.
+pub fn pq_eotf(e: f32) -> f32 {
+ let (m1, m2) = (0.159_301_76_f32, 78.84375_f32);
+ let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32);
+ let p = e.max(0.0).powf(1.0 / m2);
+ ((p - c1).max(0.0) / (c2 - c3 * p)).powf(1.0 / m1)
+}
+pub fn pq_inverse_eotf(y: f32) -> f32 {
+ let (m1, m2) = (0.159_301_76_f32, 78.84375_f32);
+ let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32);
+ let p = y.max(0.0).powf(m1);
+ ((c1 + c2 * p) / (1.0 + c3 * p)).powf(m2)
+}
+pub fn hlg_oetf(l: f32) -> f32 {
+ let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32);
+ if l <= 1.0 / 12.0 { (3.0 * l.max(0.0)).sqrt() } else { a * (12.0 * l - b).ln() + c }
+}
+pub fn hlg_inverse_oetf(e: f32) -> f32 {
+ let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32);
+ if e <= 0.5 { e * e / 3.0 } else { (((e - c) / a).exp() + b) / 12.0 }
+}
+
+/// 256-entry table: sRGB-encoded u8 → linear f32.
+pub fn srgb_u8_to_linear_table() -> &'static [f32; 256] {
+ static T: OnceLock<[f32; 256]> = OnceLock::new();
+ T.get_or_init(|| std::array::from_fn(|i| srgb_to_linear(i as f32 / 255.0)))
+}
+
+/// 4096-entry table: linear (0..1, quantised to 12 bits) → sRGB-encoded u8.
+pub fn linear_to_srgb_u8_table() -> &'static [u8; 4096] {
+ static T: OnceLock<[u8; 4096]> = OnceLock::new();
+ T.get_or_init(|| std::array::from_fn(|i| (linear_to_srgb(i as f32 / 4095.0) * 255.0 + 0.5).clamp(0.0, 255.0) as u8))
+}
+
+#[inline]
+pub fn linear_to_srgb_u8(v: f32) -> u8 {
+ let i = (v.clamp(0.0, 1.0) * 4095.0 + 0.5) as usize;
+ linear_to_srgb_u8_table()[i]
+}
+
+/// Rec.709 luma of a linear or encoded RGB triple.
+#[inline]
+pub fn luma709(r: f32, g: f32, b: f32) -> f32 {
+ 0.2126 * r + 0.7152 * g + 0.0722 * b
+}
+
+/// RGB (0..1) → HSL (h in 0..1).
+pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] {
+ let max = r.max(g).max(b);
+ let min = r.min(g).min(b);
+ let l = (max + min) / 2.0;
+ if (max - min).abs() < 1e-7 {
+ return [0.0, 0.0, l];
+ }
+ let d = max - min;
+ let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
+ let h = if max == r {
+ (g - b) / d + if g < b { 6.0 } else { 0.0 }
+ } else if max == g {
+ (b - r) / d + 2.0
+ } else {
+ (r - g) / d + 4.0
+ };
+ [h / 6.0, s, l]
+}
+
+pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] {
+ if s <= 0.0 {
+ return [l, l, l];
+ }
+ let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
+ let p = 2.0 * l - q;
+ let f = |mut t: f32| {
+ t = t.rem_euclid(1.0);
+ if t < 1.0 / 6.0 {
+ p + (q - p) * 6.0 * t
+ } else if t < 0.5 {
+ q
+ } else if t < 2.0 / 3.0 {
+ p + (q - p) * (2.0 / 3.0 - t) * 6.0
+ } else {
+ p
+ }
+ };
+ [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)]
+}
+
+/// A 3D LUT (from a `.cube` file), applied to encoded RGB in 0..1.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Lut3d {
+ pub title: String,
+ pub size: usize,
+ pub domain_min: [f32; 3],
+ pub domain_max: [f32; 3],
+ /// `size³` entries, red fastest.
+ pub data: Vec<[f32; 3]>,
+}
+
+impl Lut3d {
+ pub fn identity(size: usize) -> Self {
+ let n = (size - 1) as f32;
+ let mut data = Vec::with_capacity(size * size * size);
+ for b in 0..size {
+ for g in 0..size {
+ for r in 0..size {
+ data.push([r as f32 / n, g as f32 / n, b as f32 / n]);
+ }
+ }
+ }
+ Lut3d { title: "identity".into(), size, domain_min: [0.0; 3], domain_max: [1.0; 3], data }
+ }
+
+ /// Parse the Adobe/Resolve `.cube` text format (3D LUTs).
+ pub fn parse_cube(text: &str) -> Result<Lut3d, String> {
+ let mut size = 0usize;
+ let mut title = String::new();
+ let mut dmin = [0.0f32; 3];
+ let mut dmax = [1.0f32; 3];
+ let mut data = Vec::new();
+ for line in text.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ let mut it = line.split_whitespace();
+ let key = it.next().unwrap_or("");
+ match key {
+ "TITLE" => title = line[5..].trim().trim_matches('"').to_string(),
+ "LUT_3D_SIZE" => size = it.next().and_then(|v| v.parse().ok()).ok_or("bad LUT_3D_SIZE")?,
+ "LUT_1D_SIZE" => return Err("1D .cube LUTs are not supported yet".into()),
+ "DOMAIN_MIN" | "DOMAIN_MAX" => {
+ let v: Vec<f32> = it.filter_map(|x| x.parse().ok()).collect();
+ if v.len() != 3 {
+ return Err(format!("bad {key}"));
+ }
+ let t = if key == "DOMAIN_MIN" { &mut dmin } else { &mut dmax };
+ t.copy_from_slice(&v);
+ }
+ _ => {
+ let v: Vec<f32> = line.split_whitespace().filter_map(|x| x.parse().ok()).collect();
+ if v.len() == 3 {
+ data.push([v[0], v[1], v[2]]);
+ }
+ }
+ }
+ }
+ if size < 2 || data.len() != size * size * size {
+ return Err(format!("expected {}³ entries, found {}", size, data.len()));
+ }
+ Ok(Lut3d { title, size, domain_min: dmin, domain_max: dmax, data })
+ }
+
+ pub fn to_cube(&self) -> String {
+ let mut s = format!("TITLE \"{}\"\nLUT_3D_SIZE {}\n", self.title, self.size);
+ for d in &self.data {
+ s += &format!("{:.6} {:.6} {:.6}\n", d[0], d[1], d[2]);
+ }
+ s
+ }
+
+ /// Trilinear lookup.
+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
+ let n = self.size;
+ let m = (n - 1) as f32;
+ let mut idx = [0usize; 3];
+ let mut frac = [0f32; 3];
+ for c in 0..3 {
+ let t = ((rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c])).clamp(0.0, 1.0) * m;
+ let i = (t.floor() as usize).min(n - 2);
+ idx[c] = i;
+ frac[c] = t - i as f32;
+ }
+ let at = |r: usize, g: usize, b: usize| self.data[r + g * n + b * n * n];
+ let mut out = [0f32; 3];
+ for (k, o) in out.iter_mut().enumerate() {
+ let c = |dr, dg, db| at(idx[0] + dr, idx[1] + dg, idx[2] + db)[k];
+ let x00 = c(0, 0, 0) + (c(1, 0, 0) - c(0, 0, 0)) * frac[0];
+ let x10 = c(0, 1, 0) + (c(1, 1, 0) - c(0, 1, 0)) * frac[0];
+ let x01 = c(0, 0, 1) + (c(1, 0, 1) - c(0, 0, 1)) * frac[0];
+ let x11 = c(0, 1, 1) + (c(1, 1, 1) - c(0, 1, 1)) * frac[0];
+ let y0 = x00 + (x10 - x00) * frac[1];
+ let y1 = x01 + (x11 - x01) * frac[1];
+ *o = y0 + (y1 - y0) * frac[2];
+ }
+ out
+ }
+}
+
+/// Parse `#rrggbb` / `#rrggbbaa` into 0..1 floats.
+pub fn parse_hex(s: &str) -> Option<[f32; 4]> {
+ let s = s.trim().trim_start_matches('#');
+ let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0);
+ match s.len() {
+ 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]),
+ 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]),
+ _ => None,
+ }
+}
+
+pub fn to_hex(c: [f32; 4]) -> String {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ if c[3] >= 0.999 {
+ format!("#{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]))
+ } else {
+ format!("#{:02x}{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]), q(c[3]))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ycbcr_roundtrip() {
+ for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
+ let rgb = [0.8, 0.3, 0.1];
+ let y = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m);
+ let back = ycbcr_to_rgb(y[0], y[1], y[2], m);
+ for k in 0..3 {
+ assert!((rgb[k] - back[k]).abs() < 1e-5);
+ }
+ }
+ }
+
+ #[test]
+ fn limited_range_levels() {
+ assert_eq!(normalize_y(16, 8, Range::Limited), 0.0);
+ assert_eq!(normalize_y(235, 8, Range::Limited), 1.0);
+ assert_eq!(normalize_y(940, 10, Range::Limited), 1.0);
+ assert_eq!(normalize_c(128, 8, Range::Limited), 0.0);
+ }
+
+ #[test]
+ fn transfer_roundtrips() {
+ for t in [Transfer::Srgb, Transfer::Pq, Transfer::Hlg, Transfer::Linear] {
+ for v in [0.0, 0.1, 0.5, 0.9] {
+ let l = to_linear(v, t);
+ assert!((from_linear(l, t) - v).abs() < 1e-3, "{t:?} {v}");
+ }
+ }
+ assert_eq!(linear_to_srgb_u8(1.0), 255);
+ assert_eq!(linear_to_srgb_u8(0.0), 0);
+ assert_eq!(linear_to_srgb_u8(srgb_u8_to_linear_table()[128]), 128);
+ }
+
+ #[test]
+ fn hsl_roundtrip() {
+ let c = [0.2, 0.6, 0.9];
+ let h = rgb_to_hsl(c[0], c[1], c[2]);
+ let b = hsl_to_rgb(h[0], h[1], h[2]);
+ for k in 0..3 {
+ assert!((c[k] - b[k]).abs() < 1e-5);
+ }
+ }
+
+ #[test]
+ fn cube_identity() {
+ let lut = Lut3d::identity(17);
+ let parsed = Lut3d::parse_cube(&lut.to_cube()).unwrap();
+ let v = parsed.apply([0.3, 0.55, 0.91]);
+ assert!((v[0] - 0.3).abs() < 1e-4 && (v[1] - 0.55).abs() < 1e-4 && (v[2] - 0.91).abs() < 1e-4);
+ assert!(Lut3d::parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());
+ }
+
+ #[test]
+ fn hex() {
+ assert_eq!(parse_hex("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0, 1.0]));
+ assert_eq!(to_hex([1.0, 0.0, 0.0, 1.0]), "#ff0000");
+ }
+}
diff --git a/crates/edit/Cargo.toml b/crates/edit/Cargo.toml
new file mode 100644
index 000000000..558316110
--- /dev/null
+++ b/crates/edit/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "filmcraft-edit"
+description = "Pure timeline edit algebra: insert, overwrite, razor, ripple, roll, slip, slide, rate stretch, lift, extract"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-project = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+proptest = { workspace = true }
+filmcraft-media = { workspace = true }
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
new file mode 100644
index 000000000..bcf70a053
--- /dev/null
+++ b/crates/edit/src/lib.rs
@@ -0,0 +1,668 @@
+//! Timeline edit algebra.
+//!
+//! Every function takes a `&mut Sequence` (the engine passes a copy-on-write clone) and either
+//! applies the whole edit or returns an error leaving the sequence untouched (functions validate
+//! first, or work on a clone). Track items never overlap afterwards (checked in tests).
+//!
+//! Semantics follow Premiere Pro:
+//! - **Overwrite** replaces whatever is under the new item on its track.
+//! - **Insert** pushes material right on the target tracks *and every sync-locked, unlocked track*.
+//! - **Lift** leaves a gap; **Extract** closes it (ripple) on targeted + sync-locked tracks.
+//! - **Ripple delete** removes items and closes the gap; fails if a sync-locked track has material in
+//! the gap (it would lose sync).
+//! - Trims: regular, ripple, roll, slip, slide and rate stretch, all limited by media handles and
+//! neighbouring items.
+//!
+//! Keyframes are stored in media time, so trims and splits never need to move them.
+
+use std::collections::HashMap;
+
+use filmcraft_project::{ClipId, ItemId, Sequence, Track, TrackId, TrackItem, Transition, TransitionId};
+use filmcraft_time::{Tick, TimeRange};
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum EditError {
+ #[error("no such track item {0:?}")]
+ NoItem(ClipId),
+ #[error("no such track {0:?}")]
+ NoTrack(TrackId),
+ #[error("track is locked")]
+ Locked,
+ #[error("this edit would break sync on a sync-locked track")]
+ SyncLockConflict,
+ #[error("not enough media (handles) for this trim")]
+ NoHandles,
+ #[error("edit would make a clip shorter than one frame")]
+ TooShort,
+ #[error("nothing to do")]
+ Nothing,
+ #[error("{0}")]
+ Other(String),
+}
+
+pub type Result<T> = std::result::Result<T, EditError>;
+
+/// Supplies fresh ids and media durations to edits.
+pub struct EditCtx<'a> {
+ pub next_id: &'a mut u64,
+ /// Media duration of a project item (None = unlimited, e.g. stills / adjustment layers).
+ pub media_duration: &'a dyn Fn(ItemId) -> Option<Tick>,
+ /// Minimum item duration (one sequence frame).
+ pub min_duration: Tick,
+}
+
+impl EditCtx<'_> {
+ pub fn alloc(&mut self) -> u64 {
+ let v = *self.next_id;
+ *self.next_id += 1;
+ v
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Edge {
+ In,
+ Out,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TrimMode {
+ Regular,
+ Ripple,
+}
+
+// ---------------------------------------------------------------------------------------------
+// Track-level primitives
+// ---------------------------------------------------------------------------------------------
+
+/// Split the item strictly containing `t` into two. Returns the new (right) item's id.
+/// `links` maps old link groups to the new group for right-hand pieces (so linked partners split
+/// in the same operation stay linked to each other).
+pub fn split_track_at(track: &mut Track, t: Tick, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) -> Option<ClipId> {
+ let idx = track.items.iter().position(|i| i.start < t && t < i.end())?;
+ let left = &mut track.items[idx];
+ let mut right = left.clone();
+ let cut = t - left.start;
+ left.duration = cut;
+ let new_id = ClipId(ctx.alloc());
+ right.id = new_id;
+ right.start = t;
+ right.duration -= cut;
+ if !right.reverse && right.frame_hold.is_none() {
+ right.source_in += Tick((cut.0 as f64 * right.speed.abs()).round() as i64);
+ } else if right.reverse {
+ // reversed: the left piece now shows the later media; keep content continuous
+ let left_ref = &mut track.items[idx];
+ let consumed = Tick((cut.0 as f64 * left_ref.speed.abs()).round() as i64);
+ let total_src = Tick(((cut + right.duration).0 as f64 * left_ref.speed.abs()).round() as i64);
+ right.source_in = left_ref.source_in;
+ left_ref.source_in += total_src - consumed;
+ }
+ if let Some(l) = right.link {
+ let nl = *links.entry(l).or_insert_with(|| ctx.alloc());
+ right.link = Some(nl);
+ }
+ // transitions: those after the cut that referenced the left piece now reference the right one;
+ // a transition spanning the cut on this clip's interior is removed.
+ let old_id = track.items[idx].id;
+ track
+ .transitions
+ .retain(|tr| !(tr.start < t && t < tr.end() && (tr.from == Some(old_id) || tr.to == Some(old_id)) && !(tr.from.is_some() && tr.to.is_some())));
+ for tr in &mut track.transitions {
+ if tr.start >= t && tr.from == Some(old_id) {
+ tr.from = Some(new_id);
+ }
+ }
+ track.items.insert(idx + 1, right);
+ Some(new_id)
+}
+
+/// Remove all material in `range` on a track (splitting items at the boundaries).
+pub fn clear_track_range(track: &mut Track, range: TimeRange, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) -> Vec<ClipId> {
+ if range.is_empty() {
+ return Vec::new();
+ }
+ split_track_at(track, range.start, ctx, links);
+ split_track_at(track, range.end(), ctx, links);
+ let mut removed = Vec::new();
+ track.items.retain(|i| {
+ let inside = i.start >= range.start && i.end() <= range.end();
+ if inside {
+ removed.push(i.id);
+ }
+ !inside
+ });
+ remove_orphan_transitions(track);
+ removed
+}
+
+/// Shift every item starting at or after `at` by `delta`.
+pub fn shift_track_from(track: &mut Track, at: Tick, delta: Tick) {
+ for i in &mut track.items {
+ if i.start >= at {
+ i.start += delta;
+ }
+ }
+ for tr in &mut track.transitions {
+ if tr.start >= at || (tr.end() > at && tr.from.is_none()) {
+ tr.start += delta;
+ }
+ }
+ track.sort();
+}
+
+/// Open a gap of `dur` at `at` (splitting an item that spans `at`).
+pub fn insert_track_gap(track: &mut Track, at: Tick, dur: Tick, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) {
+ split_track_at(track, at, ctx, links);
+ shift_track_from(track, at, dur);
+}
+
+/// Whether `range` holds no items on a track.
+pub fn track_range_empty(track: &Track, range: TimeRange) -> bool {
+ !track.items.iter().any(|i| i.range().overlaps(&range))
+}
+
+/// Drop transitions whose clips no longer exist or are no longer adjacent to them.
+pub fn remove_orphan_transitions(track: &mut Track) {
+ let ids: HashMap<ClipId, (Tick, Tick)> = track.items.iter().map(|i| (i.id, (i.start, i.end()))).collect();
+ track.transitions.retain(|tr| {
+ let from_ok = tr.from.is_none_or(|f| ids.contains_key(&f));
+ let to_ok = tr.to.is_none_or(|t| ids.contains_key(&t));
+ from_ok && to_ok && (tr.from.is_some() || tr.to.is_some())
+ });
+}
+
+fn place(track: &mut Track, item: TrackItem) {
+ let idx = track.items.partition_point(|i| i.start <= item.start);
+ track.items.insert(idx, item);
+}
+
+// ---------------------------------------------------------------------------------------------
+// Sequence edits
+// ---------------------------------------------------------------------------------------------
+
+fn track_mut(seq: &mut Sequence, id: TrackId) -> Result<&mut Track> {
+ seq.track_mut(id).ok_or(EditError::NoTrack(id))
+}
+
+/// Overwrite edits: each item replaces material on its track.
+pub fn overwrite(seq: &mut Sequence, placements: Vec<(TrackId, TrackItem)>, ctx: &mut EditCtx) -> Result<Vec<ClipId>> {
+ let mut links = HashMap::new();
+ let mut ids = Vec::new();
+ for (tid, _) in &placements {
+ if track_mut(seq, *tid)?.locked {
+ return Err(EditError::Locked);
+ }
+ }
+ for (tid, item) in placements {
+ let t = track_mut(seq, tid)?;
+ clear_track_range(t, item.range(), ctx, &mut links);
+ ids.push(item.id);
+ place(t, item);
+ }
+ Ok(ids)
+}
+
+/// Insert edits: open a gap on target tracks and all sync-locked unlocked tracks, then place.
+pub fn insert(seq: &mut Sequence, placements: Vec<(TrackId, TrackItem)>, ctx: &mut EditCtx) -> Result<Vec<ClipId>> {
+ if placements.is_empty() {
+ return Err(EditError::Nothing);
+ }
+ for (tid, _) in &placements {
+ if track_mut(seq, *tid)?.locked {
+ return Err(EditError::Locked);
+ }
+ }
+ let at = placements.iter().map(|p| p.1.start).min().unwrap_or_default();
+ let dur = placements.iter().map(|p| p.1.end()).max().unwrap_or_default() - at;
+ let targets: Vec<TrackId> = placements.iter().map(|p| p.0).collect();
+ let mut links = HashMap::new();
+ for t in seq.all_tracks_mut() {
+ if !t.locked && (targets.contains(&t.id) || t.sync_lock) {
+ insert_track_gap(t, at, dur, ctx, &mut links);
+ }
+ }
+ let mut ids = Vec::new();
+ for (tid, item) in placements {
+ let t = track_mut(seq, tid)?;
+ ids.push(item.id);
+ place(t, item);
+ }
+ Ok(ids)
+}
+
+/// Add Edit (razor) at `t` on the given tracks (all unlocked tracks when empty). Returns new ids.
+pub fn razor(seq: &mut Sequence, tracks: &[TrackId], t: Tick, ctx: &mut EditCtx) -> Vec<ClipId> {
+ let mut links = HashMap::new();
+ let mut out = Vec::new();
+ for tr in seq.all_tracks_mut() {
+ if tr.locked || (!tracks.is_empty() && !tracks.contains(&tr.id)) {
+ continue;
+ }
+ if let Some(id) = split_track_at(tr, t, ctx, &mut links) {
+ out.push(id);
+ }
+ }
+ out
+}
+
+/// Razor only the given items (and their linked partners if listed) at `t`.
+pub fn razor_items(seq: &mut Sequence, items: &[ClipId], t: Tick, ctx: &mut EditCtx) -> Vec<ClipId> {
+ let tracks: Vec<TrackId> = items.iter().filter_map(|c| seq.find_item(*c).map(|(tid, _)| tid)).collect();
+ let mut links = HashMap::new();
+ let mut out = Vec::new();
+ for tr in seq.all_tracks_mut() {
+ if tr.locked || !tracks.contains(&tr.id) {
+ continue;
+ }
+ // only split if the item at t is one of ours
+ if tr.item_at(t).is_some_and(|i| items.contains(&i.id))
+ && let Some(id) = split_track_at(tr, t, ctx, &mut links)
+ {
+ out.push(id);
+ }
+ }
+ out
+}
+
+/// Lift: remove `range` on tracks, leaving a gap.
+pub fn lift(seq: &mut Sequence, tracks: &[TrackId], range: TimeRange, ctx: &mut EditCtx) -> Vec<ClipId> {
+ let mut links = HashMap::new();
+ let mut removed = Vec::new();
+ for tr in seq.all_tracks_mut() {
+ if !tr.locked && tracks.contains(&tr.id) {
+ removed.extend(clear_track_range(tr, range, ctx, &mut links));
+ }
+ }
+ removed
+}
+
+/// Extract: remove `range` on targeted and sync-locked tracks and close the gap.
+pub fn extract(seq: &mut Sequence, tracks: &[TrackId], range: TimeRange, ctx: &mut EditCtx) -> Vec<ClipId> {
+ let mut links = HashMap::new();
+ let mut removed = Vec::new();
+ for tr in seq.all_tracks_mut() {
+ if tr.locked || !(tracks.contains(&tr.id) || tr.sync_lock) {
+ continue;
+ }
+ removed.extend(clear_track_range(tr, range, ctx, &mut links));
+ shift_track_from(tr, range.end(), -range.duration);
+ }
+ removed
+}
+
+/// Delete track items (leaving gaps).
+pub fn delete_items(seq: &mut Sequence, items: &[ClipId]) -> usize {
+ let mut n = 0;
+ for tr in seq.all_tracks_mut() {
+ if tr.locked {
+ continue;
+ }
+ let before = tr.items.len();
+ tr.items.retain(|i| !items.contains(&i.id));
+ n += before - tr.items.len();
+ remove_orphan_transitions(tr);
+ }
+ n
+}
+
+/// Ripple delete track items: remove them and close the resulting gaps.
+pub fn ripple_delete_items(seq: &mut Sequence, items: &[ClipId]) -> Result<()> {
+ // Collect per-track ranges to close (merged), processed right-to-left.
+ let mut ranges: Vec<(TrackId, TimeRange)> = Vec::new();
+ for c in items {
+ let (tid, it) = seq.find_item(*c).ok_or(EditError::NoItem(*c))?;
+ ranges.push((tid, it.range()));
+ }
+ // Group identical ranges across tracks (linked A/V) into one ripple.
+ let mut spans: Vec<TimeRange> = ranges.iter().map(|r| r.1).collect();
+ spans.sort_by_key(|r| (r.start, r.duration));
+ spans.dedup();
+ let mut work = seq.clone();
+ delete_items(&mut work, items);
+ let affected: Vec<TrackId> = ranges.iter().map(|r| r.0).collect();
+ for span in spans.iter().rev() {
+ // the gap actually closable: from span.start to the next material on affected tracks
+ for tr in work.all_tracks_mut() {
+ if tr.locked {
+ continue;
+ }
+ let on_affected = affected.contains(&tr.id);
+ if !on_affected && !tr.sync_lock {
+ continue;
+ }
+ if !on_affected && !track_range_empty(tr, *span) {
+ return Err(EditError::SyncLockConflict);
+ }
+ shift_track_from(tr, span.end(), -span.duration);
+ }
+ }
+ *seq = work;
+ Ok(())
+}
+
+/// Close the gap containing `t` on a track (Ripple Delete on a gap).
+pub fn close_gap(seq: &mut Sequence, track: TrackId, t: Tick) -> Result<()> {
+ let tr = seq.track(track).ok_or(EditError::NoTrack(track))?;
+ if tr.item_at(t).is_some() {
+ return Err(EditError::Nothing);
+ }
+ let prev_end = tr.items.iter().filter(|i| i.end() <= t).map(|i| i.end()).max().unwrap_or(Tick::ZERO);
+ let next_start = tr.items.iter().filter(|i| i.start > t).map(|i| i.start).min().ok_or(EditError::Nothing)?;
+ let gap = TimeRange::from_bounds(prev_end, next_start);
+ let mut work = seq.clone();
+ for tr in work.all_tracks_mut() {
+ if tr.locked {
+ continue;
+ }
+ if tr.id != track {
+ if !tr.sync_lock {
+ continue;
+ }
+ if !track_range_empty(tr, gap) {
+ return Err(EditError::SyncLockConflict);
+ }
+ }
+ shift_track_from(tr, gap.end(), -gap.duration);
+ }
+ *seq = work;
+ Ok(())
+}
+
+/// Move items by (track, time) offsets with overwrite (default drag) or insert (Cmd-drag) semantics.
+/// `moves`: (item, destination track, new start).
+pub fn move_items(seq: &mut Sequence, moves: &[(ClipId, TrackId, Tick)], insert_mode: bool, ctx: &mut EditCtx) -> Result<()> {
+ let mut work = seq.clone();
+ let mut placed = Vec::new();
+ for (c, dest, start) in moves {
+ let (_, it) = work.find_item(*c).ok_or(EditError::NoItem(*c))?;
+ let mut it = it.clone();
+ if work.track(*dest).ok_or(EditError::NoTrack(*dest))?.locked {
+ return Err(EditError::Locked);
+ }
+ it.start = (*start).max(Tick::ZERO);
+ placed.push((*dest, it));
+ }
+ // carry transitions with moved clips? Premiere drops transitions whose partner is not moved.
+ delete_items(&mut work, &moves.iter().map(|m| m.0).collect::<Vec<_>>());
+ if insert_mode {
+ insert(&mut work, placed, ctx)?;
+ } else {
+ overwrite(&mut work, placed, ctx)?;
+ }
+ *seq = work;
+ Ok(())
+}
+
+fn media_len(ctx: &EditCtx, item: &TrackItem) -> Option<Tick> {
+ if item.frame_hold.is_some() {
+ return None;
+ }
+ (ctx.media_duration)(item.item)
+}
+
+fn src_of(dur: Tick, speed: f64) -> Tick {
+ Tick((dur.0 as f64 * speed.abs()).round() as i64)
+}
+
+/// Neighbours on the same track: (previous end, next start).
+fn neighbours(track: &Track, id: ClipId) -> (Tick, Tick) {
+ let idx = track.items.iter().position(|i| i.id == id).unwrap_or(0);
+ let prev_end = if idx > 0 { track.items[idx - 1].end() } else { Tick::ZERO };
+ let next_start = track.items.get(idx + 1).map(|i| i.start).unwrap_or(Tick::MAX);
+ (prev_end, next_start)
+}
+
+/// Compute the clamped delta a trim may apply (for UI feedback while dragging).
+pub fn clamp_trim(seq: &Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta: Tick, ctx: &EditCtx) -> Result<Tick> {
+ let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let tr = seq.track(tid).ok_or(EditError::NoTrack(tid))?;
+ let (prev_end, next_start) = neighbours(tr, clip);
+ let media = media_len(ctx, it);
+ let speed = it.speed.abs().max(1e-9);
+ let mut d = delta;
+ match edge {
+ Edge::In => {
+ // extending left (d<0) needs media before source_in; shortening needs min duration
+ let max_ext = Tick((it.source_in.0 as f64 / speed).floor() as i64);
+ let lo = if mode == TrimMode::Regular { (-(it.start - prev_end)).max(-max_ext) } else { -max_ext };
+ let hi = it.duration - ctx.min_duration;
+ d = d.clamp(if it.frame_hold.is_some() { Tick::MIN } else { lo }, hi);
+ }
+ Edge::Out => {
+ let lo = -(it.duration - ctx.min_duration);
+ let mut hi = if mode == TrimMode::Regular { next_start - it.end() } else { Tick::MAX };
+ if let Some(m) = media {
+ let remain = Tick(((m - it.source_out()).0 as f64 / speed).floor() as i64);
+ hi = hi.min(remain);
+ }
+ d = d.clamp(lo, hi.max(lo));
+ }
+ }
+ Ok(d)
+}
+
+/// Trim one edge of an item (Selection-tool edge drag = Regular; Ripple tool = Ripple).
+/// Linked partners should be trimmed by the caller with the same delta.
+pub fn trim(seq: &mut Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {
+ let d = clamp_trim(seq, clip, edge, mode, delta, ctx)?;
+ if d == Tick::ZERO {
+ return Ok(d);
+ }
+ let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let old_end = it.end();
+ let old_start = it.start;
+ let speed = it.speed.abs();
+ let mut work = seq.clone();
+ {
+ let (_, it) = work.find_item_mut(clip).ok_or(EditError::NoItem(clip))?;
+ match edge {
+ Edge::In => {
+ if !it.reverse && it.frame_hold.is_none() {
+ it.source_in += src_of(d, speed);
+ }
+ it.duration -= d;
+ if mode == TrimMode::Regular {
+ it.start += d;
+ }
+ }
+ Edge::Out => {
+ if it.reverse {
+ it.source_in -= src_of(d, speed);
+ }
+ it.duration += d;
+ }
+ }
+ }
+ if mode == TrimMode::Ripple {
+ let (at, shift) = match edge {
+ Edge::In => (old_start + Tick(1), -d),
+ Edge::Out => (old_end, d),
+ };
+ for tr in work.all_tracks_mut() {
+ if tr.locked {
+ continue;
+ }
+ if tr.id == tid || tr.sync_lock {
+ if tr.id != tid && shift < Tick::ZERO && !track_range_empty(tr, TimeRange::new(at + shift - Tick(if edge == Edge::In { 1 } else { 0 }), -shift))
+ {
+ return Err(EditError::SyncLockConflict);
+ }
+ let from = if edge == Edge::In { old_start + Tick(1) } else { old_end };
+ for i in &mut tr.items {
+ if i.id != clip && i.start >= from {
+ i.start += shift;
+ }
+ }
+ tr.sort();
+ }
+ }
+ }
+ work.check().map_err(EditError::Other)?;
+ *seq = work;
+ Ok(d)
+}
+
+/// Rolling edit between two adjacent items on one track: moves the cut by `delta`.
+pub fn roll(seq: &mut Sequence, left: ClipId, right: ClipId, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {
+ let (_, l) = seq.find_item(left).ok_or(EditError::NoItem(left))?;
+ let (_, r) = seq.find_item(right).ok_or(EditError::NoItem(right))?;
+ if l.end() != r.start {
+ return Err(EditError::Other("items are not adjacent".into()));
+ }
+ let mut d = delta;
+ // left out-point limits
+ d = d.max(-(l.duration - ctx.min_duration)).min(r.duration - ctx.min_duration);
+ if let Some(m) = media_len(ctx, l) {
+ d = d.min(Tick(((m - l.source_out()).0 as f64 / l.speed.abs()).floor() as i64));
+ }
+ d = d.max(-Tick((r.source_in.0 as f64 / r.speed.abs()).floor() as i64));
+ if d == Tick::ZERO {
+ return Ok(d);
+ }
+ let (ls, rs) = (l.speed.abs(), r.speed.abs());
+ {
+ let (_, l) = seq.find_item_mut(left).ok_or(EditError::NoItem(left))?;
+ l.duration += d;
+ }
+ {
+ let (_, r) = seq.find_item_mut(right).ok_or(EditError::NoItem(right))?;
+ r.start += d;
+ r.duration -= d;
+ r.source_in += src_of(d, rs);
+ }
+ let _ = ls;
+ Ok(d)
+}
+
+/// Slip: change which part of the media an item shows without moving it.
+pub fn slip(seq: &mut Sequence, clip: ClipId, delta_media: Tick, ctx: &mut EditCtx) -> Result<Tick> {
+ let (_, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let used = src_of(it.duration, it.speed);
+ let max_in = media_len(ctx, it).map(|m| m - used).unwrap_or(Tick::MAX);
+ let new_in = (it.source_in + delta_media).clamp(Tick::ZERO, max_in.max(Tick::ZERO));
+ let d = new_in - it.source_in;
+ let (_, it) = seq.find_item_mut(clip).ok_or(EditError::NoItem(clip))?;
+ it.source_in = new_in;
+ Ok(d)
+}
+
+/// Slide: move an item between its neighbours, trimming them to keep the gapless span.
+pub fn slide(seq: &mut Sequence, clip: ClipId, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {
+ let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let it = it.clone();
+ let tr = seq.track(tid).ok_or(EditError::NoTrack(tid))?;
+ let idx = tr.items.iter().position(|i| i.id == clip).ok_or(EditError::NoItem(clip))?;
+ let prev = idx.checked_sub(1).map(|i| tr.items[i].clone()).filter(|p| p.end() == it.start);
+ let next = tr.items.get(idx + 1).cloned().filter(|n| n.start == it.end());
+ let mut d = delta;
+ if let Some(p) = &prev {
+ d = d.max(-(p.duration - ctx.min_duration));
+ if let Some(m) = media_len(ctx, p) {
+ d = d.min(Tick(((m - p.source_out()).0 as f64 / p.speed.abs()).floor() as i64));
+ }
+ } else {
+ d = d.max(-(it.start - neighbours(tr, clip).0));
+ }
+ if let Some(n) = &next {
+ d = d.min(n.duration - ctx.min_duration);
+ d = d.max(-Tick((n.source_in.0 as f64 / n.speed.abs()).floor() as i64));
+ } else {
+ d = d.min(neighbours(tr, clip).1 - it.end());
+ }
+ if d == Tick::ZERO {
+ return Ok(d);
+ }
+ let t = seq.track_mut(tid).ok_or(EditError::NoTrack(tid))?;
+ if let Some(p) = prev {
+ let pi = t.item_mut(p.id).ok_or(EditError::NoItem(p.id))?;
+ pi.duration += d;
+ }
+ if let Some(n) = next {
+ let ni = t.item_mut(n.id).ok_or(EditError::NoItem(n.id))?;
+ ni.start += d;
+ ni.duration -= d;
+ ni.source_in += src_of(d, n.speed);
+ }
+ let me = t.item_mut(clip).ok_or(EditError::NoItem(clip))?;
+ me.start += d;
+ Ok(d)
+}
+
+/// Rate stretch: change an item's duration by dragging an edge, adjusting speed to keep the same media.
+pub fn rate_stretch(seq: &mut Sequence, clip: ClipId, edge: Edge, delta: Tick, ctx: &mut EditCtx) -> Result<f64> {
+ let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let tr = seq.track(tid).ok_or(EditError::NoTrack(tid))?;
+ let (prev_end, next_start) = neighbours(tr, clip);
+ let src_len = it.source_out() - it.source_in;
+ let d = match edge {
+ Edge::Out => delta.clamp(-(it.duration - ctx.min_duration), next_start - it.end()),
+ Edge::In => delta.clamp(-(it.start - prev_end), it.duration - ctx.min_duration),
+ };
+ let new_dur = match edge {
+ Edge::Out => it.duration + d,
+ Edge::In => it.duration - d,
+ };
+ let speed = src_len.0 as f64 / new_dur.0 as f64;
+ let (_, it) = seq.find_item_mut(clip).ok_or(EditError::NoItem(clip))?;
+ if edge == Edge::In {
+ it.start += d;
+ }
+ it.duration = new_dur;
+ it.speed = speed;
+ Ok(speed)
+}
+
+/// Set speed/duration (Clip ▸ Speed/Duration…). `ripple` shifts following material.
+pub fn set_speed(seq: &mut Sequence, clip: ClipId, speed: f64, reverse: bool, ripple: bool, ctx: &mut EditCtx) -> Result<()> {
+ if speed <= 0.0 {
+ return Err(EditError::Other("speed must be positive".into()));
+ }
+ let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
+ let src_len = it.source_out() - it.source_in;
+ let mut new_dur = Tick((src_len.0 as f64 / speed).round() as i64).max(ctx.min_duration);
+ let old_end = it.end();
+ let tr = seq.track(tid).ok_or(EditError::NoTrack(tid))?;
+ let (_, next_start) = neighbours(tr, clip);
+ if !ripple {
+ new_dur = new_dur.min(next_start - it.start);
+ }
+ let delta = new_dur - it.duration;
+ {
+ let (_, it) = seq.find_item_mut(clip).ok_or(EditError::NoItem(clip))?;
+ it.speed = speed;
+ it.reverse = reverse;
+ it.duration = new_dur;
+ }
+ if ripple && delta != Tick::ZERO {
+ for tr in seq.all_tracks_mut() {
+ if !tr.locked && (tr.id == tid || tr.sync_lock) {
+ for i in &mut tr.items {
+ if i.id != clip && i.start >= old_end {
+ i.start += delta;
+ }
+ }
+ tr.sort();
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Add a transition at the cut between `from` and `to` (or at a single clip edge).
+pub fn add_transition(seq: &mut Sequence, track: TrackId, mut tr: Transition, ctx: &mut EditCtx) -> Result<TransitionId> {
+ let t = seq.track_mut(track).ok_or(EditError::NoTrack(track))?;
+ if t.locked {
+ return Err(EditError::Locked);
+ }
+ tr.id = TransitionId(ctx.alloc());
+ // Replace an existing transition at the same place.
+ t.transitions.retain(|x| !(x.range().overlaps(&tr.range()) && (x.from == tr.from || x.to == tr.to)));
+ let id = tr.id;
+ t.transitions.push(tr);
+ t.sort();
+ Ok(id)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
new file mode 100644
index 000000000..b9d41d4d6
--- /dev/null
+++ b/crates/edit/src/tests.rs
@@ -0,0 +1,315 @@
+use super::*;
+use filmcraft_project::{Label, Project, SequenceSettings, TrackKind};
+use filmcraft_time::FrameRate;
+use proptest::prelude::*;
+
+const R: FrameRate = FrameRate::FPS_24;
+
+fn f(n: i64) -> Tick {
+ R.tick_of(n)
+}
+
+struct Fx {
+ seq: Sequence,
+ next: u64,
+}
+
+fn media(_: ItemId) -> Option<Tick> {
+ Some(f(1000))
+}
+
+impl Fx {
+ fn new() -> Self {
+ let mut p = Project::new("t");
+ let s = p.new_sequence("s", SequenceSettings { frame_rate: R, ..Default::default() }, 3, 2, None);
+ let seq = p.sequence(s).unwrap().clone();
+ Self { seq, next: 10_000 }
+ }
+ fn ctx<'a>(next: &'a mut u64) -> EditCtx<'a> {
+ EditCtx { next_id: next, media_duration: &media, min_duration: f(1) }
+ }
+ fn v(&self, i: usize) -> TrackId {
+ self.seq.video_tracks[i].id
+ }
+ fn a(&self, i: usize) -> TrackId {
+ self.seq.audio_tracks[i].id
+ }
+ fn item(&mut self, start: i64, dur: i64, src_in: i64) -> TrackItem {
+ self.next += 1;
+ TrackItem {
+ id: ClipId(self.next),
+ item: ItemId(1),
+ name: format!("c{}", self.next),
+ label: Label::Iris,
+ start: f(start),
+ duration: f(dur),
+ source_in: f(src_in),
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: vec![],
+ markers: vec![],
+ gain_db: 0.0,
+ frame_hold: None,
+ scale_to_frame: false,
+ }
+ }
+ fn put(&mut self, track: TrackId, start: i64, dur: i64, src_in: i64) -> ClipId {
+ let it = self.item(start, dur, src_in);
+ let id = it.id;
+ let mut n = self.next;
+ overwrite(&mut self.seq, vec![(track, it)], &mut Self::ctx(&mut n)).unwrap();
+ self.next = n;
+ id
+ }
+ fn spans(&self, track: TrackId) -> Vec<(i64, i64)> {
+ self.seq.track(track).unwrap().items.iter().map(|i| (R.frame_at(i.start), R.frame_at(i.duration))).collect()
+ }
+}
+
+#[test]
+fn overwrite_splits_underlying() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ fx.put(v1, 0, 100, 0);
+ fx.put(v1, 40, 20, 500);
+ assert_eq!(fx.spans(v1), vec![(0, 40), (40, 20), (60, 40)]);
+ let right = &fx.seq.track(v1).unwrap().items[2];
+ assert_eq!(right.source_in, f(60), "right remainder keeps media continuity");
+ fx.seq.check().unwrap();
+}
+
+#[test]
+fn insert_ripples_sync_locked_tracks() {
+ let mut fx = Fx::new();
+ let (v1, v2, a1) = (fx.v(0), fx.v(1), fx.a(0));
+ fx.put(v1, 0, 50, 0);
+ fx.put(v2, 60, 10, 0);
+ fx.put(a1, 0, 100, 0);
+ fx.seq.track_mut(v2).unwrap().sync_lock = false;
+ let it = fx.item(20, 10, 0);
+ let mut n = fx.next;
+ insert(&mut fx.seq, vec![(v1, it)], &mut Fx::ctx(&mut n)).unwrap();
+ fx.next = n;
+ assert_eq!(fx.spans(v1), vec![(0, 20), (20, 10), (30, 30)]);
+ assert_eq!(fx.spans(a1), vec![(0, 20), (30, 80)], "sync-locked audio split and shifted");
+ assert_eq!(fx.spans(v2), vec![(60, 10)], "not sync-locked: untouched");
+}
+
+#[test]
+fn razor_keeps_content_continuous() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ let c = fx.put(v1, 10, 100, 200);
+ let before = fx.seq.find_item(c).unwrap().1.source_time_at(f(70));
+ let mut n = fx.next;
+ let new = razor(&mut fx.seq, &[], f(50), &mut Fx::ctx(&mut n));
+ assert_eq!(new.len(), 1);
+ let right = fx.seq.find_item(new[0]).unwrap().1;
+ assert_eq!(right.source_time_at(f(70)), before);
+ assert_eq!(fx.spans(v1), vec![(10, 40), (50, 60)]);
+}
+
+#[test]
+fn extract_and_lift() {
+ let mut fx = Fx::new();
+ let (v1, a1) = (fx.v(0), fx.a(0));
+ fx.put(v1, 0, 100, 0);
+ fx.put(a1, 0, 100, 0);
+ let mut n = fx.next;
+ lift(&mut fx.seq, &[v1], TimeRange::new(f(10), f(10)), &mut Fx::ctx(&mut n));
+ assert_eq!(fx.spans(v1), vec![(0, 10), (20, 80)]);
+ extract(&mut fx.seq, &[v1], TimeRange::new(f(30), f(10)), &mut Fx::ctx(&mut n));
+ assert_eq!(fx.spans(v1), vec![(0, 10), (20, 10), (30, 60)]);
+ assert_eq!(fx.spans(a1), vec![(0, 30), (30, 60)]);
+}
+
+#[test]
+fn ripple_delete_and_conflict() {
+ let mut fx = Fx::new();
+ let (v1, a1) = (fx.v(0), fx.a(0));
+ let a = fx.put(v1, 0, 10, 0);
+ fx.put(v1, 10, 10, 0);
+ ripple_delete_items(&mut fx.seq, &[a]).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 10)]);
+ // audio under the gap blocks the ripple
+ let b = fx.put(v1, 20, 10, 0);
+ fx.put(a1, 22, 3, 0);
+ assert_eq!(ripple_delete_items(&mut fx.seq, &[b]), Err(EditError::SyncLockConflict));
+ assert_eq!(fx.spans(v1), vec![(0, 10), (20, 10)], "unchanged on failure");
+}
+
+#[test]
+fn close_gap_works() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ fx.put(v1, 0, 10, 0);
+ fx.put(v1, 25, 10, 0);
+ close_gap(&mut fx.seq, v1, f(15)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 10), (10, 10)]);
+}
+
+#[test]
+fn regular_trim_respects_neighbours_and_handles() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ let a = fx.put(v1, 0, 10, 5);
+ fx.put(v1, 12, 10, 0);
+ let mut n = fx.next;
+ // out: only 2 frames of space before the neighbour
+ let d = trim(&mut fx.seq, a, Edge::Out, TrimMode::Regular, f(5), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(d, f(2));
+ // in: 5 frames of head handle, but item starts at 0 so no space to the left
+ let d = trim(&mut fx.seq, a, Edge::In, TrimMode::Regular, -f(3), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(d, Tick::ZERO);
+ let d = trim(&mut fx.seq, a, Edge::In, TrimMode::Regular, f(3), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(d, f(3));
+ assert_eq!(fx.seq.find_item(a).unwrap().1.source_in, f(8));
+ fx.seq.check().unwrap();
+}
+
+#[test]
+fn ripple_trim_shifts_following() {
+ let mut fx = Fx::new();
+ let (v1, a1) = (fx.v(0), fx.a(0));
+ let a = fx.put(v1, 0, 10, 0);
+ fx.put(v1, 10, 10, 0);
+ fx.put(a1, 30, 5, 0);
+ let mut n = fx.next;
+ trim(&mut fx.seq, a, Edge::Out, TrimMode::Ripple, f(4), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 14), (14, 10)]);
+ assert_eq!(fx.spans(a1), vec![(34, 5)]);
+ trim(&mut fx.seq, a, Edge::In, TrimMode::Ripple, f(2), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 12), (12, 10)]);
+}
+
+#[test]
+fn roll_slip_slide() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ let a = fx.put(v1, 0, 10, 10);
+ let b = fx.put(v1, 10, 10, 10);
+ let c = fx.put(v1, 20, 10, 10);
+ let mut n = fx.next;
+ roll(&mut fx.seq, a, b, f(3), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 13), (13, 7), (20, 10)]);
+ assert_eq!(fx.seq.find_item(b).unwrap().1.source_in, f(13));
+ let d = slip(&mut fx.seq, c, -f(50), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(d, -f(10), "slip clamps at media start");
+ slide(&mut fx.seq, b, f(2), &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 15), (15, 7), (22, 8)]);
+ fx.seq.check().unwrap();
+}
+
+#[test]
+fn rate_stretch_and_speed() {
+ let mut fx = Fx::new();
+ let v1 = fx.v(0);
+ let a = fx.put(v1, 0, 10, 0);
+ let mut n = fx.next;
+ let s = rate_stretch(&mut fx.seq, a, Edge::Out, f(10), &mut Fx::ctx(&mut n)).unwrap();
+ assert!((s - 0.5).abs() < 1e-9);
+ set_speed(&mut fx.seq, a, 2.0, false, true, &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![(0, 5)]);
+}
+
+#[test]
+fn move_with_insert_and_overwrite() {
+ let mut fx = Fx::new();
+ let (v1, v2) = (fx.v(0), fx.v(1));
+ let a = fx.put(v1, 0, 10, 0);
+ fx.put(v2, 0, 30, 0);
+ let mut n = fx.next;
+ move_items(&mut fx.seq, &[(a, v2, f(5))], false, &mut Fx::ctx(&mut n)).unwrap();
+ assert_eq!(fx.spans(v1), vec![]);
+ assert_eq!(fx.spans(v2), vec![(0, 5), (5, 10), (15, 15)]);
+}
+
+#[derive(Debug, Clone)]
+enum Op {
+ Over(usize, i64, i64),
+ Ins(usize, i64, i64),
+ Razor(i64),
+ Extract(i64, i64),
+ TrimOut(usize, i64),
+ Ripple(usize),
+}
+
+fn op() -> impl Strategy<Value = Op> {
+ prop_oneof![
+ (0usize..3, 0i64..200, 1i64..50).prop_map(|(t, s, d)| Op::Over(t, s, d)),
+ (0usize..3, 0i64..200, 1i64..50).prop_map(|(t, s, d)| Op::Ins(t, s, d)),
+ (0i64..250).prop_map(Op::Razor),
+ (0i64..200, 1i64..30).prop_map(|(s, d)| Op::Extract(s, d)),
+ (0usize..20, -20i64..20).prop_map(|(i, d)| Op::TrimOut(i, d)),
+ (0usize..20).prop_map(Op::Ripple),
+ ]
+}
+
+proptest! {
+ #[test]
+ fn never_overlaps(ops in proptest::collection::vec(op(), 1..40)) {
+ let mut fx = Fx::new();
+ let tracks = [fx.v(0), fx.v(1), fx.a(0)];
+ for o in ops {
+ let mut n = fx.next;
+ match o {
+ Op::Over(t, s, d) => { let it = fx.item(s, d, 0); n = fx.next; let _ = overwrite(&mut fx.seq, vec![(tracks[t], it)], &mut Fx::ctx(&mut n)); }
+ Op::Ins(t, s, d) => { let it = fx.item(s, d, 0); n = fx.next; let _ = insert(&mut fx.seq, vec![(tracks[t], it)], &mut Fx::ctx(&mut n)); }
+ Op::Razor(t) => { razor(&mut fx.seq, &[], f(t), &mut Fx::ctx(&mut n)); }
+ Op::Extract(s, d) => { extract(&mut fx.seq, &[tracks[0]], TimeRange::new(f(s), f(d)), &mut Fx::ctx(&mut n)); }
+ Op::TrimOut(i, d) => {
+ let ids: Vec<ClipId> = fx.seq.all_tracks().flat_map(|t| t.items.iter().map(|x| x.id)).collect();
+ if let Some(c) = ids.get(i) { let _ = trim(&mut fx.seq, *c, Edge::Out, TrimMode::Regular, f(d), &mut Fx::ctx(&mut n)); }
+ }
+ Op::Ripple(i) => {
+ let ids: Vec<ClipId> = fx.seq.all_tracks().flat_map(|t| t.items.iter().map(|x| x.id)).collect();
+ if let Some(c) = ids.get(i) { let _ = ripple_delete_items(&mut fx.seq, &[*c]); }
+ }
+ }
+ fx.next = fx.next.max(n);
+ prop_assert!(fx.seq.check().is_ok(), "{:?}", fx.seq.check());
+ for t in fx.seq.all_tracks() { for i in &t.items { prop_assert!(i.start >= Tick::ZERO); } }
+ }
+ }
+
+ #[test]
+ fn insert_then_extract_is_identity(s in 0i64..100, d in 1i64..40) {
+ let mut fx = Fx::new();
+ let (v1, a1) = (fx.v(0), fx.a(0));
+ fx.put(v1, 0, 60, 0);
+ fx.put(v1, 70, 30, 100);
+ fx.put(a1, 10, 80, 0);
+ let before: Vec<Vec<(i64, i64)>> = [v1, a1].iter().map(|t| fx.spans(*t)).collect();
+ let it = fx.item(s, d, 0);
+ let mut n = fx.next;
+ insert(&mut fx.seq, vec![(v1, it)], &mut Fx::ctx(&mut n)).unwrap();
+ extract(&mut fx.seq, &[v1], TimeRange::new(f(s), f(d)), &mut Fx::ctx(&mut n));
+ // content ranges are identical after merging split pieces
+ for (k, t) in [v1, a1].iter().enumerate() {
+ let merged = merge(fx.spans(*t));
+ prop_assert_eq!(merged, merge(before[k].clone()));
+ }
+ }
+}
+
+fn merge(v: Vec<(i64, i64)>) -> Vec<(i64, i64)> {
+ let mut out: Vec<(i64, i64)> = Vec::new();
+ for (s, d) in v {
+ if let Some(last) = out.last_mut()
+ && last.0 + last.1 == s
+ {
+ last.1 += d;
+ continue;
+ }
+ out.push((s, d));
+ }
+ out
+}
+
+#[test]
+fn unused_kind_import() {
+ let _ = TrackKind::Video;
+}
diff --git a/crates/frame/Cargo.toml b/crates/frame/Cargo.toml
new file mode 100644
index 000000000..ed3431d4e
--- /dev/null
+++ b/crates/frame/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "filmcraft-frame"
+description = "Video frames and audio buffers with explicit colour metadata"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-color = { workspace = true }
+filmcraft-time = { workspace = true }
+rayon = { workspace = true }
+serde = { workspace = true }
diff --git a/crates/frame/src/lib.rs b/crates/frame/src/lib.rs
new file mode 100644
index 000000000..771a1fd8d
--- /dev/null
+++ b/crates/frame/src/lib.rs
@@ -0,0 +1,336 @@
+//! Video frames and audio buffers.
+//!
+//! - [`VideoFrame`]: decoded or rendered pictures. Planar Y'CbCr (8 or 16-bit containers) straight
+//! from decoders, sRGB-encoded RGBA8 from stills/generators, or linear premultiplied RGBA f32 in the
+//! compositor. Pixel data is `Arc`-shared so caches, monitors and export share frames for free.
+//! - [`AudioBuffer`]: planar f32 samples.
+
+use std::sync::Arc;
+
+use filmcraft_color::{ColorInfo, Matrix, Range, linear_to_srgb_u8, normalize_c, normalize_y, srgb_u8_to_linear_table, to_linear, ycbcr_to_rgb};
+use filmcraft_time::Tick;
+use rayon::prelude::*;
+use serde::{Deserialize, Serialize};
+
+/// Chroma subsampling of planar Y'CbCr.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Chroma {
+ C420,
+ C422,
+ C444,
+}
+
+impl Chroma {
+ /// (horizontal shift, vertical shift)
+ pub fn shifts(self) -> (u32, u32) {
+ match self {
+ Chroma::C420 => (1, 1),
+ Chroma::C422 => (1, 0),
+ Chroma::C444 => (0, 0),
+ }
+ }
+ pub fn label(self) -> &'static str {
+ match self {
+ Chroma::C420 => "4:2:0",
+ Chroma::C422 => "4:2:2",
+ Chroma::C444 => "4:4:4",
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub enum PixelData {
+ /// Straight-alpha, sRGB/709-encoded RGBA, 8 bits per channel.
+ Rgba8(Arc<Vec<u8>>),
+ /// Premultiplied, linear-light RGBA f32 (compositor working format).
+ RgbaF32(Arc<Vec<f32>>),
+ /// 8-bit planar Y'CbCr (optionally with an alpha plane).
+ Yuv8 { planes: [Arc<Vec<u8>>; 3], chroma: Chroma, alpha: Option<Arc<Vec<u8>>> },
+ /// 9–16-bit planar Y'CbCr stored in u16 (`bits` significant bits).
+ Yuv16 { planes: [Arc<Vec<u16>>; 3], chroma: Chroma, bits: u32, alpha: Option<Arc<Vec<u16>>> },
+}
+
+#[derive(Clone, Debug)]
+pub struct VideoFrame {
+ pub width: u32,
+ pub height: u32,
+ pub data: PixelData,
+ pub color: ColorInfo,
+ /// Pixel aspect ratio (num, den).
+ pub par: (u32, u32),
+ /// Presentation time in media time (informational).
+ pub pts: Tick,
+}
+
+impl VideoFrame {
+ pub fn rgba8(width: u32, height: u32, data: Vec<u8>) -> Self {
+ debug_assert_eq!(data.len(), (width * height * 4) as usize);
+ Self { width, height, data: PixelData::Rgba8(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO }
+ }
+ pub fn rgba_f32(width: u32, height: u32, data: Vec<f32>) -> Self {
+ debug_assert_eq!(data.len(), (width * height * 4) as usize);
+ Self { width, height, data: PixelData::RgbaF32(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO }
+ }
+ pub fn transparent_f32(width: u32, height: u32) -> Self {
+ Self::rgba_f32(width, height, vec![0.0; (width * height * 4) as usize])
+ }
+ pub fn with_pts(mut self, pts: Tick) -> Self {
+ self.pts = pts;
+ self
+ }
+
+ pub fn format_label(&self) -> String {
+ match &self.data {
+ PixelData::Rgba8(_) => "RGBA 8-bit".into(),
+ PixelData::RgbaF32(_) => "RGBA 32-bit float".into(),
+ PixelData::Yuv8 { chroma, .. } => format!("YUV {} 8-bit", chroma.label()),
+ PixelData::Yuv16 { chroma, bits, .. } => format!("YUV {} {bits}-bit", chroma.label()),
+ }
+ }
+
+ /// Approximate memory footprint in bytes (for caches).
+ pub fn byte_size(&self) -> usize {
+ match &self.data {
+ PixelData::Rgba8(d) => d.len(),
+ PixelData::RgbaF32(d) => d.len() * 4,
+ PixelData::Yuv8 { planes, alpha, .. } => planes.iter().map(|p| p.len()).sum::<usize>() + alpha.as_ref().map_or(0, |a| a.len()),
+ PixelData::Yuv16 { planes, alpha, .. } => (planes.iter().map(|p| p.len()).sum::<usize>() + alpha.as_ref().map_or(0, |a| a.len())) * 2,
+ }
+ }
+
+ /// Convert to premultiplied linear RGBA f32 (the compositor's working format).
+ pub fn to_linear_f32(&self) -> Vec<f32> {
+ let (w, h) = (self.width as usize, self.height as usize);
+ let mut out = vec![0f32; w * h * 4];
+ match &self.data {
+ PixelData::RgbaF32(d) => out.copy_from_slice(d),
+ PixelData::Rgba8(d) => {
+ let lut = srgb_u8_to_linear_table();
+ out.par_chunks_mut(w * 4).zip(d.par_chunks(w * 4)).for_each(|(o, s)| {
+ for (o, s) in o.chunks_exact_mut(4).zip(s.chunks_exact(4)) {
+ let a = s[3] as f32 / 255.0;
+ o[0] = lut[s[0] as usize] * a;
+ o[1] = lut[s[1] as usize] * a;
+ o[2] = lut[s[2] as usize] * a;
+ o[3] = a;
+ }
+ });
+ }
+ PixelData::Yuv8 { planes, chroma, alpha } => {
+ let (sx, sy) = chroma.shifts();
+ let cw = w.div_ceil(1 << sx);
+ let info = self.color;
+ // Precompute per-code tables for Y and C.
+ let ytab: Vec<f32> = (0..256).map(|v| normalize_y(v, 8, info.range)).collect();
+ let ctab: Vec<f32> = (0..256).map(|v| normalize_c(v, 8, info.range)).collect();
+ out.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ let yrow = &planes[0][y * w..y * w + w];
+ let cy = y >> sy;
+ let urow = &planes[1][cy * cw..cy * cw + cw];
+ let vrow = &planes[2][cy * cw..cy * cw + cw];
+ for x in 0..w {
+ let cx = x >> sx;
+ let rgb = ycbcr_to_rgb(ytab[yrow[x] as usize], ctab[urow[cx] as usize], ctab[vrow[cx] as usize], info.matrix);
+ let a = alpha.as_ref().map_or(1.0, |al| al[y * w + x] as f32 / 255.0);
+ let o = &mut row[x * 4..x * 4 + 4];
+ o[0] = to_linear(rgb[0].clamp(0.0, 1.0), info.transfer) * a;
+ o[1] = to_linear(rgb[1].clamp(0.0, 1.0), info.transfer) * a;
+ o[2] = to_linear(rgb[2].clamp(0.0, 1.0), info.transfer) * a;
+ o[3] = a;
+ }
+ });
+ }
+ PixelData::Yuv16 { planes, chroma, bits, alpha } => {
+ let (sx, sy) = chroma.shifts();
+ let cw = w.div_ceil(1 << sx);
+ let info = self.color;
+ let bits = *bits;
+ let amax = ((1u32 << bits) - 1) as f32;
+ out.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ let cy = y >> sy;
+ for x in 0..w {
+ let cx = x >> sx;
+ let yy = normalize_y(planes[0][y * w + x] as u32, bits, info.range);
+ let u = normalize_c(planes[1][cy * cw + cx] as u32, bits, info.range);
+ let v = normalize_c(planes[2][cy * cw + cx] as u32, bits, info.range);
+ let rgb = ycbcr_to_rgb(yy, u, v, info.matrix);
+ let a = alpha.as_ref().map_or(1.0, |al| al[y * w + x] as f32 / amax);
+ let o = &mut row[x * 4..x * 4 + 4];
+ o[0] = to_linear(rgb[0].clamp(0.0, 1.0), info.transfer) * a;
+ o[1] = to_linear(rgb[1].clamp(0.0, 1.0), info.transfer) * a;
+ o[2] = to_linear(rgb[2].clamp(0.0, 1.0), info.transfer) * a;
+ o[3] = a;
+ }
+ });
+ }
+ }
+ out
+ }
+
+ /// Convert to straight-alpha sRGB RGBA8 for display (fast paths for 8-bit sources).
+ pub fn to_rgba8(&self) -> Vec<u8> {
+ let (w, h) = (self.width as usize, self.height as usize);
+ match &self.data {
+ PixelData::Rgba8(d) => d.as_ref().clone(),
+ PixelData::Yuv8 { planes, chroma, alpha: None }
+ if matches!(self.color.transfer, filmcraft_color::Transfer::Bt709 | filmcraft_color::Transfer::Srgb) =>
+ {
+ // Direct display path: Y'CbCr → R'G'B' without linearisation.
+ let (sx, sy) = chroma.shifts();
+ let cw = w.div_ceil(1 << sx);
+ let (kr, kb) = self.color.matrix.kr_kb();
+ let kg = 1.0 - kr - kb;
+ let (ys, yo, cs) = match self.color.range {
+ Range::Limited => (255.0 / 219.0, 16.0, 255.0 / 224.0),
+ Range::Full => (1.0, 0.0, 1.0),
+ };
+ let (crr, cbb) = (2.0 * (1.0 - kr) * cs, 2.0 * (1.0 - kb) * cs);
+ let (cgr, cgb) = (crr * kr / kg, cbb * kb / kg);
+ let mut out = vec![0u8; w * h * 4];
+ out.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ let cy = y >> sy;
+ let yrow = &planes[0][y * w..y * w + w];
+ let urow = &planes[1][cy * cw..cy * cw + cw];
+ let vrow = &planes[2][cy * cw..cy * cw + cw];
+ for x in 0..w {
+ let yy = (yrow[x] as f32 - yo) * ys;
+ let u = urow[x >> sx] as f32 - 128.0;
+ let v = vrow[x >> sx] as f32 - 128.0;
+ let o = &mut row[x * 4..x * 4 + 4];
+ o[0] = (yy + crr * v).round().clamp(0.0, 255.0) as u8;
+ o[1] = (yy - cgr * v - cgb * u).round().clamp(0.0, 255.0) as u8;
+ o[2] = (yy + cbb * u).round().clamp(0.0, 255.0) as u8;
+ o[3] = 255;
+ }
+ });
+ out
+ }
+ _ => {
+ let lin = self.to_linear_f32();
+ let mut out = vec![0u8; w * h * 4];
+ out.par_chunks_mut(w * 4).zip(lin.par_chunks(w * 4)).for_each(|(o, s)| linear_premul_to_srgb8(s, o));
+ out
+ }
+ }
+ }
+
+ /// Luma plane (8-bit, for scopes/thumbnails analysis).
+ pub fn luma8(&self) -> Vec<u8> {
+ match &self.data {
+ PixelData::Yuv8 { planes, .. } => planes[0].as_ref().clone(),
+ _ => self.to_rgba8().chunks_exact(4).map(|p| (0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32) as u8).collect(),
+ }
+ }
+}
+
+/// Convert a row of premultiplied linear f32 RGBA into straight sRGB RGBA8.
+pub fn linear_premul_to_srgb8(src: &[f32], dst: &mut [u8]) {
+ for (s, o) in src.chunks_exact(4).zip(dst.chunks_exact_mut(4)) {
+ let a = s[3].clamp(0.0, 1.0);
+ if a <= 0.0 {
+ o.copy_from_slice(&[0, 0, 0, 0]);
+ continue;
+ }
+ let inv = 1.0 / a;
+ o[0] = linear_to_srgb_u8(s[0] * inv);
+ o[1] = linear_to_srgb_u8(s[1] * inv);
+ o[2] = linear_to_srgb_u8(s[2] * inv);
+ o[3] = (a * 255.0 + 0.5) as u8;
+ }
+}
+
+/// Planar f32 audio.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct AudioBuffer {
+ pub sample_rate: u32,
+ /// One Vec per channel, all the same length.
+ pub channels: Vec<Vec<f32>>,
+}
+
+impl AudioBuffer {
+ pub fn silence(sample_rate: u32, channels: usize, frames: usize) -> Self {
+ Self { sample_rate, channels: vec![vec![0.0; frames]; channels] }
+ }
+ pub fn frames(&self) -> usize {
+ self.channels.first().map_or(0, Vec::len)
+ }
+ pub fn channel_count(&self) -> usize {
+ self.channels.len()
+ }
+ /// Mix `other` into self with gain (channel counts are matched by wrapping/mono-spreading).
+ pub fn mix_from(&mut self, other: &AudioBuffer, gains: &[f32]) {
+ let n = self.frames().min(other.frames());
+ for (c, dst) in self.channels.iter_mut().enumerate() {
+ let src = &other.channels[if other.channels.len() == 1 { 0 } else { c % other.channels.len() }];
+ let g = gains.get(c).copied().unwrap_or(1.0);
+ for i in 0..n {
+ dst[i] += src[i] * g;
+ }
+ }
+ }
+ /// Interleave into a single Vec (for audio output / encoders).
+ pub fn interleaved(&self) -> Vec<f32> {
+ let n = self.frames();
+ let c = self.channels.len();
+ let mut out = vec![0.0; n * c];
+ for (ci, ch) in self.channels.iter().enumerate() {
+ for (i, s) in ch.iter().enumerate() {
+ out[i * c + ci] = *s;
+ }
+ }
+ out
+ }
+ /// Peak absolute sample per channel.
+ pub fn peaks(&self) -> Vec<f32> {
+ self.channels.iter().map(|c| c.iter().fold(0f32, |m, s| m.max(s.abs()))).collect()
+ }
+}
+
+/// Matrix used when a decoder does not signal one: BT.601 for SD, BT.709 otherwise (common practice).
+pub fn default_matrix(width: u32, height: u32) -> Matrix {
+ if width <= 1024 && height <= 576 { Matrix::Bt601 } else { Matrix::Bt709 }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rgba8_roundtrip_through_linear() {
+ let px: Vec<u8> = (0..=255u8).flat_map(|v| [v, 255 - v, v / 2, 255]).collect();
+ let f = VideoFrame::rgba8(256, 1, px.clone());
+ let lin = f.to_linear_f32();
+ let back = VideoFrame::rgba_f32(256, 1, lin).to_rgba8();
+ assert_eq!(back, px);
+ }
+
+ #[test]
+ fn yuv_grey_is_grey() {
+ let (w, h) = (4, 2);
+ let y = Arc::new(vec![126u8; w * h]);
+ let u = Arc::new(vec![128u8; 2]);
+ let v = Arc::new(vec![128u8; 2]);
+ let f = VideoFrame {
+ width: 4,
+ height: 2,
+ data: PixelData::Yuv8 { planes: [y, u, v], chroma: Chroma::C420, alpha: None },
+ color: ColorInfo::REC709,
+ par: (1, 1),
+ pts: Tick::ZERO,
+ };
+ let rgb = f.to_rgba8();
+ assert_eq!(&rgb[0..4], &[128, 128, 128, 255]);
+ // slow path agrees within 1
+ let slow = VideoFrame::rgba_f32(4, 2, f.to_linear_f32()).to_rgba8();
+ assert!((slow[0] as i32 - 128).abs() <= 1);
+ }
+
+ #[test]
+ fn audio_mix() {
+ let mut a = AudioBuffer::silence(48000, 2, 4);
+ let b = AudioBuffer { sample_rate: 48000, channels: vec![vec![0.5; 4]] };
+ a.mix_from(&b, &[1.0, 0.5]);
+ assert_eq!(a.channels[1][0], 0.25);
+ assert_eq!(a.interleaved()[..2], [0.5, 0.25]);
+ }
+}
diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs
index 179adb7b4..ca4ce6bcf 100644
--- a/crates/geom/src/lib.rs
+++ b/crates/geom/src/lib.rs
@@ -1 +1,192 @@
-//! placeholder
+//! 2D geometry for FilmCraft: vectors, rectangles and affine transforms (Motion effect math).
+
+use serde::{Deserialize, Serialize};
+use std::ops::{Add, Mul, Sub};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Vec2 {
+ pub x: f64,
+ pub y: f64,
+}
+
+impl Vec2 {
+ pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
+ pub const fn new(x: f64, y: f64) -> Self {
+ Self { x, y }
+ }
+ pub fn length(self) -> f64 {
+ self.x.hypot(self.y)
+ }
+ pub fn lerp(self, o: Vec2, t: f64) -> Vec2 {
+ Vec2::new(self.x + (o.x - self.x) * t, self.y + (o.y - self.y) * t)
+ }
+}
+impl Add for Vec2 {
+ type Output = Vec2;
+ fn add(self, o: Vec2) -> Vec2 {
+ Vec2::new(self.x + o.x, self.y + o.y)
+ }
+}
+impl Sub for Vec2 {
+ type Output = Vec2;
+ fn sub(self, o: Vec2) -> Vec2 {
+ Vec2::new(self.x - o.x, self.y - o.y)
+ }
+}
+impl Mul<f64> for Vec2 {
+ type Output = Vec2;
+ fn mul(self, s: f64) -> Vec2 {
+ Vec2::new(self.x * s, self.y * s)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Rect {
+ pub x: f64,
+ pub y: f64,
+ pub w: f64,
+ pub h: f64,
+}
+
+impl Rect {
+ pub const fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
+ Self { x, y, w, h }
+ }
+ pub fn right(&self) -> f64 {
+ self.x + self.w
+ }
+ pub fn bottom(&self) -> f64 {
+ self.y + self.h
+ }
+ pub fn contains(&self, p: Vec2) -> bool {
+ p.x >= self.x && p.y >= self.y && p.x < self.right() && p.y < self.bottom()
+ }
+ pub fn intersect(&self, o: &Rect) -> Option<Rect> {
+ let x0 = self.x.max(o.x);
+ let y0 = self.y.max(o.y);
+ let x1 = self.right().min(o.right());
+ let y1 = self.bottom().min(o.bottom());
+ (x1 > x0 && y1 > y0).then(|| Rect::new(x0, y0, x1 - x0, y1 - y0))
+ }
+ pub fn union(&self, o: &Rect) -> Rect {
+ let x0 = self.x.min(o.x);
+ let y0 = self.y.min(o.y);
+ Rect::new(x0, y0, self.right().max(o.right()) - x0, self.bottom().max(o.bottom()) - y0)
+ }
+ /// Fit `inner` (w,h) inside this rect preserving aspect, centered.
+ pub fn fit(&self, w: f64, h: f64) -> Rect {
+ let s = (self.w / w).min(self.h / h);
+ let (fw, fh) = (w * s, h * s);
+ Rect::new(self.x + (self.w - fw) / 2.0, self.y + (self.h - fh) / 2.0, fw, fh)
+ }
+}
+
+/// Affine transform `[a c e; b d f; 0 0 1]` mapping (x, y) → (a x + c y + e, b x + d y + f).
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Affine {
+ pub a: f64,
+ pub b: f64,
+ pub c: f64,
+ pub d: f64,
+ pub e: f64,
+ pub f: f64,
+}
+
+impl Default for Affine {
+ fn default() -> Self {
+ Self::IDENTITY
+ }
+}
+
+impl Affine {
+ pub const IDENTITY: Affine = Affine { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };
+ pub fn translate(x: f64, y: f64) -> Self {
+ Affine { e: x, f: y, ..Self::IDENTITY }
+ }
+ pub fn scale(sx: f64, sy: f64) -> Self {
+ Affine { a: sx, d: sy, ..Self::IDENTITY }
+ }
+ /// Rotation by `deg` degrees, clockwise on screen (y down), matching Premiere's Rotation.
+ pub fn rotate_deg(deg: f64) -> Self {
+ let (s, c) = deg.to_radians().sin_cos();
+ Affine { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 }
+ }
+ /// `self * o`: apply `o` first, then `self`.
+ pub fn then_apply(&self, o: &Affine) -> Affine {
+ // result = self ∘ o
+ Affine {
+ a: self.a * o.a + self.c * o.b,
+ b: self.b * o.a + self.d * o.b,
+ c: self.a * o.c + self.c * o.d,
+ d: self.b * o.c + self.d * o.d,
+ e: self.a * o.e + self.c * o.f + self.e,
+ f: self.b * o.e + self.d * o.f + self.f,
+ }
+ }
+ pub fn apply(&self, p: Vec2) -> Vec2 {
+ Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f)
+ }
+ pub fn determinant(&self) -> f64 {
+ self.a * self.d - self.b * self.c
+ }
+ pub fn inverse(&self) -> Option<Affine> {
+ let det = self.determinant();
+ if det.abs() < 1e-12 {
+ return None;
+ }
+ let inv = 1.0 / det;
+ let a = self.d * inv;
+ let b = -self.b * inv;
+ let c = -self.c * inv;
+ let d = self.a * inv;
+ Some(Affine { a, b, c, d, e: -(a * self.e + c * self.f), f: -(b * self.e + d * self.f) })
+ }
+ pub fn is_identity(&self) -> bool {
+ *self == Self::IDENTITY
+ }
+ /// Bounding box of a transformed rect.
+ pub fn bounds(&self, r: &Rect) -> Rect {
+ let pts = [Vec2::new(r.x, r.y), Vec2::new(r.right(), r.y), Vec2::new(r.x, r.bottom()), Vec2::new(r.right(), r.bottom())].map(|p| self.apply(p));
+ let x0 = pts.iter().map(|p| p.x).fold(f64::INFINITY, f64::min);
+ let y0 = pts.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
+ let x1 = pts.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max);
+ let y1 = pts.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max);
+ Rect::new(x0, y0, x1 - x0, y1 - y0)
+ }
+
+ /// Premiere's Motion effect: the source's anchor point is placed at `position` (sequence pixels),
+ /// scaled by `scale` (1.0 = 100%) around the anchor and rotated by `rotation_deg`.
+ pub fn motion(position: Vec2, scale: Vec2, rotation_deg: f64, anchor: Vec2) -> Affine {
+ Affine::translate(position.x, position.y)
+ .then_apply(&Affine::rotate_deg(rotation_deg))
+ .then_apply(&Affine::scale(scale.x, scale.y))
+ .then_apply(&Affine::translate(-anchor.x, -anchor.y))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn inverse_roundtrip() {
+ let m = Affine::motion(Vec2::new(960.0, 540.0), Vec2::new(1.5, 0.75), 33.0, Vec2::new(100.0, 50.0));
+ let inv = m.inverse().unwrap();
+ let p = Vec2::new(12.0, -7.0);
+ let q = inv.apply(m.apply(p));
+ assert!((p - q).length() < 1e-9);
+ }
+
+ #[test]
+ fn motion_anchor_lands_on_position() {
+ let m = Affine::motion(Vec2::new(960.0, 540.0), Vec2::new(2.0, 2.0), 90.0, Vec2::new(10.0, 20.0));
+ let p = m.apply(Vec2::new(10.0, 20.0));
+ assert!((p - Vec2::new(960.0, 540.0)).length() < 1e-9);
+ }
+
+ #[test]
+ fn fit_rect() {
+ let r = Rect::new(0.0, 0.0, 200.0, 100.0).fit(16.0, 9.0);
+ assert!((r.h - 100.0).abs() < 1e-9 && (r.w - 177.777).abs() < 0.01);
+ }
+}
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
new file mode 100644
index 000000000..29c63d931
--- /dev/null
+++ b/crates/media/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "filmcraft-media"
+description = "Media sources: probing, decoding traits, frame cache, generators, stills"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-color = { workspace = true }
+filmcraft-frame = { workspace = true }
+rayon = { workspace = true }
+serde = { workspace = true }
+thiserror = { workspace = true }
+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "tiff", "bmp"] }
diff --git a/crates/media/examples/demo_frames.rs b/crates/media/examples/demo_frames.rs
new file mode 100644
index 000000000..1d1b4a24e
--- /dev/null
+++ b/crates/media/examples/demo_frames.rs
@@ -0,0 +1,20 @@
+//! Writes a contact sheet of the generator outputs: `cargo run -p filmcraft-media --example demo_frames -- out.png`
+use filmcraft_media::generators::{DemoScene, Generator, render};
+use filmcraft_time::FrameRate;
+
+fn main() {
+ let out = std::env::args().nth(1).unwrap_or_else(|| "demo_frames.png".into());
+ let (w, h) = (480u32, 270u32);
+ let mut gens: Vec<Generator> = DemoScene::ALL.iter().map(|s| Generator::Demo(*s)).collect();
+ gens.push(Generator::BarsAndTone);
+ gens.push(Generator::CountingLeader);
+ let cols = 4;
+ let rows = gens.len().div_ceil(cols);
+ let mut sheet = image::RgbaImage::new(w * cols as u32, h * rows as u32);
+ for (i, g) in gens.iter().enumerate() {
+ let px = render(g, w, h, 3.3, 79, FrameRate::FPS_23_976);
+ let img = image::RgbaImage::from_raw(w, h, px).unwrap();
+ image::imageops::overlay(&mut sheet, &img, ((i % cols) as u32 * w) as i64, ((i / cols) as u32 * h) as i64);
+ }
+ sheet.save(&out).unwrap();
+}
diff --git a/crates/media/src/cache.rs b/crates/media/src/cache.rs
new file mode 100644
index 000000000..ef533e239
--- /dev/null
+++ b/crates/media/src/cache.rs
@@ -0,0 +1,126 @@
+//! A byte-budgeted LRU cache of decoded/rendered frames, shared by monitors, thumbnails and export.
+
+use std::collections::HashMap;
+use std::hash::Hash;
+use std::sync::{Arc, Mutex};
+
+use filmcraft_frame::VideoFrame;
+
+struct Entry {
+ frame: Arc<VideoFrame>,
+ bytes: usize,
+ stamp: u64,
+}
+
+struct Inner<K> {
+ map: HashMap<K, Entry>,
+ bytes: usize,
+ clock: u64,
+ hits: u64,
+ misses: u64,
+}
+
+pub struct FrameCache<K: Eq + Hash + Clone = (u64, i64, u16)> {
+ inner: Mutex<Inner<K>>,
+ budget: usize,
+}
+
+impl<K: Eq + Hash + Clone> FrameCache<K> {
+ pub fn new(budget_bytes: usize) -> Self {
+ Self { inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, clock: 0, hits: 0, misses: 0 }), budget: budget_bytes }
+ }
+
+ pub fn get(&self, k: &K) -> Option<Arc<VideoFrame>> {
+ let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ g.clock += 1;
+ let c = g.clock;
+ match g.map.get_mut(k) {
+ Some(e) => {
+ e.stamp = c;
+ let f = e.frame.clone();
+ g.hits += 1;
+ Some(f)
+ }
+ None => {
+ g.misses += 1;
+ None
+ }
+ }
+ }
+
+ pub fn insert(&self, k: K, frame: Arc<VideoFrame>) {
+ let bytes = frame.byte_size();
+ let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ g.clock += 1;
+ let stamp = g.clock;
+ if let Some(old) = g.map.insert(k, Entry { frame, bytes, stamp }) {
+ g.bytes -= old.bytes;
+ }
+ g.bytes += bytes;
+ if g.bytes > self.budget {
+ // Evict oldest entries until under 90% of budget.
+ let mut v: Vec<(u64, K, usize)> = g.map.iter().map(|(k, e)| (e.stamp, k.clone(), e.bytes)).collect();
+ v.sort_unstable_by_key(|x| x.0);
+ let target = self.budget * 9 / 10;
+ for (_, k, b) in v {
+ if g.bytes <= target {
+ break;
+ }
+ g.map.remove(&k);
+ g.bytes -= b;
+ }
+ }
+ }
+
+ pub fn get_or_insert_with<E>(&self, k: K, f: impl FnOnce() -> Result<Arc<VideoFrame>, E>) -> Result<Arc<VideoFrame>, E> {
+ if let Some(v) = self.get(&k) {
+ return Ok(v);
+ }
+ let v = f()?;
+ self.insert(k, v.clone());
+ Ok(v)
+ }
+
+ pub fn clear(&self) {
+ let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ g.map.clear();
+ g.bytes = 0;
+ }
+
+ pub fn retain(&self, mut keep: impl FnMut(&K) -> bool) {
+ let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ let mut freed = 0;
+ g.map.retain(|k, e| {
+ let k2 = keep(k);
+ if !k2 {
+ freed += e.bytes;
+ }
+ k2
+ });
+ g.bytes -= freed;
+ }
+
+ /// (entries, bytes, hits, misses)
+ pub fn stats(&self) -> (usize, usize, u64, u64) {
+ let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ (g.map.len(), g.bytes, g.hits, g.misses)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn evicts_lru() {
+ let c: FrameCache<u32> = FrameCache::new(4 * 4 * 3);
+ for i in 0..3 {
+ c.insert(i, Arc::new(VideoFrame::rgba8(2, 2, vec![0; 16])));
+ }
+ assert!(c.get(&0).is_some()); // touch 0
+ c.insert(3, Arc::new(VideoFrame::rgba8(2, 2, vec![0; 16])));
+ assert!(c.get(&0).is_some());
+ assert!(c.get(&1).is_none());
+ assert!(c.stats().1 <= 48);
+ }
+}
diff --git a/crates/media/src/digits.rs b/crates/media/src/digits.rs
new file mode 100644
index 000000000..a853b243b
--- /dev/null
+++ b/crates/media/src/digits.rs
@@ -0,0 +1,69 @@
+//! Tiny seven-segment digit renderer (for burn-ins and the counting leader; no font needed).
+
+/// Segment masks for 0-9, then ':' (10), '-' (11), ';' (12).
+const SEGS: [u8; 10] = [0b0111111, 0b0000110, 0b1011011, 0b1001111, 0b1100110, 0b1101101, 0b1111101, 0b0000111, 0b1111111, 0b1101111];
+
+/// Draw `text` (digits, ':' ';' '-' and ' ') into an RGBA8 buffer at (x, y) with digit height `h`.
+pub fn draw_text(buf: &mut [u8], width: usize, height: usize, x: i32, y: i32, h: i32, text: &str, color: [u8; 4]) {
+ let w = h / 2;
+ let t = (h / 10).max(1);
+ let mut cx = x;
+ for ch in text.chars() {
+ match ch {
+ '0'..='9' => {
+ let m = SEGS[(ch as u8 - b'0') as usize];
+ let half = h / 2;
+ let segs: [(i32, i32, i32, i32); 7] = [
+ (cx, y, w, t), // a top
+ (cx + w - t, y, t, half), // b upper right
+ (cx + w - t, y + half, t, half), // c lower right
+ (cx, y + h - t, w, t), // d bottom
+ (cx, y + half, t, half), // e lower left
+ (cx, y, t, half), // f upper left
+ (cx, y + half - t / 2, w, t), // g middle
+ ];
+ for (i, r) in segs.iter().enumerate() {
+ if m & (1 << i) != 0 {
+ fill_rect(buf, width, height, r.0, r.1, r.2, r.3, color);
+ }
+ }
+ cx += w + t * 2;
+ }
+ ':' | ';' => {
+ fill_rect(buf, width, height, cx, y + h / 4, t, t, color);
+ let y2 = y + h * 3 / 4 - t;
+ fill_rect(buf, width, height, cx, y2, t, if ch == ';' { t * 2 } else { t }, color);
+ cx += t * 3;
+ }
+ '-' => {
+ fill_rect(buf, width, height, cx, y + h / 2 - t / 2, w, t, color);
+ cx += w + t * 2;
+ }
+ _ => cx += w + t * 2,
+ }
+ }
+}
+
+/// Width in pixels that [`draw_text`] will use.
+pub fn text_width(h: i32, text: &str) -> i32 {
+ let w = h / 2;
+ let t = (h / 10).max(1);
+ text.chars().map(|c| if c == ':' || c == ';' { t * 3 } else { w + t * 2 }).sum()
+}
+
+pub fn fill_rect(buf: &mut [u8], width: usize, height: usize, x: i32, y: i32, w: i32, h: i32, c: [u8; 4]) {
+ let x0 = x.max(0) as usize;
+ let y0 = y.max(0) as usize;
+ let x1 = ((x + w).max(0) as usize).min(width);
+ let y1 = ((y + h).max(0) as usize).min(height);
+ for yy in y0..y1 {
+ for xx in x0..x1 {
+ let i = (yy * width + xx) * 4;
+ let a = c[3] as u32;
+ for k in 0..3 {
+ buf[i + k] = ((buf[i + k] as u32 * (255 - a) + c[k] as u32 * a) / 255) as u8;
+ }
+ buf[i + 3] = buf[i + 3].max(c[3]);
+ }
+ }
+}
diff --git a/crates/media/src/generators.rs b/crates/media/src/generators.rs
new file mode 100644
index 000000000..59654fecc
--- /dev/null
+++ b/crates/media/src/generators.rs
@@ -0,0 +1,580 @@
+//! Synthetic media: Bars and Tone, Color Matte, Black/Transparent Video, Universal Counting Leader,
+//! and procedural demo scenes (so the editor has beautiful moving footage with no files at all).
+//!
+//! Every generator is a pure function of (settings, media time, output scale): deterministic and
+//! resolution-independent, so low-resolution playback renders directly at the reduced size.
+
+use std::f32::consts::{PI, TAU};
+use std::sync::Arc;
+
+use filmcraft_color::ColorInfo;
+use filmcraft_frame::{AudioBuffer, VideoFrame};
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
+use rayon::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::digits::{draw_text, text_width};
+use crate::{AudioStreamInfo, FrameCache, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, VideoStreamInfo};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum DemoScene {
+ Aurora,
+ OceanSunset,
+ CityNight,
+ Dunes,
+ Plasma,
+ Forest,
+}
+
+impl DemoScene {
+ pub const ALL: [DemoScene; 6] = [DemoScene::OceanSunset, DemoScene::Aurora, DemoScene::CityNight, DemoScene::Dunes, DemoScene::Forest, DemoScene::Plasma];
+ pub fn file_name(self) -> &'static str {
+ match self {
+ DemoScene::Aurora => "Aurora_Timelapse.mp4",
+ DemoScene::OceanSunset => "Ocean_Sunset.mp4",
+ DemoScene::CityNight => "City_Night_Drive.mp4",
+ DemoScene::Dunes => "Desert_Dunes.mp4",
+ DemoScene::Plasma => "Neon_Loop.mov",
+ DemoScene::Forest => "Misty_Forest.mp4",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum Generator {
+ BarsAndTone,
+ ColorMatte {
+ color: [f32; 4],
+ },
+ BlackVideo,
+ TransparentVideo,
+ CountingLeader,
+ Demo(DemoScene),
+ /// Pure audio tone (Hz, dBFS).
+ Tone {
+ hz: f32,
+ db: f32,
+ },
+}
+
+impl Generator {
+ pub fn label(&self) -> String {
+ match self {
+ Generator::BarsAndTone => "Bars and Tone".into(),
+ Generator::ColorMatte { .. } => "Color Matte".into(),
+ Generator::BlackVideo => "Black Video".into(),
+ Generator::TransparentVideo => "Transparent Video".into(),
+ Generator::CountingLeader => "Universal Counting Leader".into(),
+ Generator::Demo(d) => d.file_name().into(),
+ Generator::Tone { hz, .. } => format!("Tone {hz} Hz"),
+ }
+ }
+ fn has_audio(&self) -> bool {
+ matches!(self, Generator::BarsAndTone | Generator::CountingLeader | Generator::Demo(_) | Generator::Tone { .. })
+ }
+ fn has_video(&self) -> bool {
+ !matches!(self, Generator::Tone { .. })
+ }
+}
+
+/// A generator bound to a frame size/rate/duration.
+pub struct GeneratorSource {
+ pub generator: Generator,
+ info: MediaInfo,
+ cache: FrameCache<(i64, u16)>,
+}
+
+impl GeneratorSource {
+ pub fn new(generator: Generator, width: u32, height: u32, rate: FrameRate, duration: Tick) -> Self {
+ let video = generator.has_video().then(|| VideoStreamInfo {
+ width,
+ height,
+ frame_rate: rate,
+ par: (1, 1),
+ codec: match &generator {
+ Generator::Demo(_) => "H.264 (synthetic)".into(),
+ _ => "Synthetic".into(),
+ },
+ pixel_format: "RGBA 8-bit".into(),
+ color: ColorInfo::SRGB_FULL,
+ has_alpha: matches!(generator, Generator::TransparentVideo),
+ bitrate: None,
+ });
+ let audio =
+ generator.has_audio().then(|| AudioStreamInfo { sample_rate: 48_000, channels: 2, codec: "PCM (synthetic)".into(), bits_per_sample: Some(32) });
+ let info = MediaInfo {
+ name: generator.label(),
+ kind: if matches!(generator, Generator::Demo(_)) { MediaKind::Movie } else { MediaKind::Synthetic },
+ duration,
+ video,
+ audio,
+ container: if matches!(generator, Generator::Demo(_)) { "Synthetic MPEG-4".into() } else { "Synthetic".into() },
+ start_timecode: None,
+ file_size: None,
+ };
+ Self { generator, info, cache: FrameCache::new(256 << 20) }
+ }
+
+ pub fn with_name(mut self, name: &str) -> Self {
+ self.info.name = name.to_string();
+ self
+ }
+
+ /// The default demo clip for a scene (1080p, 23.976, 12–20 s).
+ pub fn demo(scene: DemoScene) -> Self {
+ let secs = match scene {
+ DemoScene::OceanSunset => 18,
+ DemoScene::Aurora => 16,
+ DemoScene::CityNight => 14,
+ DemoScene::Dunes => 15,
+ DemoScene::Plasma => 10,
+ DemoScene::Forest => 12,
+ };
+ Self::new(Generator::Demo(scene), 1920, 1080, FrameRate::FPS_23_976, Tick(secs * TICKS_PER_SECOND))
+ }
+}
+
+impl MediaSource for GeneratorSource {
+ fn info(&self) -> &MediaInfo {
+ &self.info
+ }
+
+ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {
+ let v = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?;
+ let rate = v.frame_rate;
+ let frame = rate.frame_at(req.time.max(Tick::ZERO));
+ let scale = req.scale.clamp(1.0 / 64.0, 1.0);
+ let bucket = (scale * 64.0).round() as u16;
+ let s = bucket as f32 / 64.0;
+ let (w, h) = (((v.width as f32 * s).round() as u32).max(2), ((v.height as f32 * s).round() as u32).max(2));
+ let t = rate.tick_of(frame).seconds() as f32;
+ self.cache.get_or_insert_with((frame, bucket), || {
+ let px = render(&self.generator, w, h, t, frame, rate);
+ Ok(Arc::new(VideoFrame::rgba8(w, h, px).with_pts(rate.tick_of(frame))))
+ })
+ }
+
+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
+ if !self.generator.has_audio() {
+ return Err(MediaError::NoStream("audio"));
+ }
+ let mut out = AudioBuffer::silence(sample_rate, 2, frames);
+ let sr = sample_rate as f32;
+ let total = self.info.duration.to_units_floor(sample_rate as i64);
+ for i in 0..frames {
+ let n = start + i as i64;
+ if n < 0 || n >= total {
+ continue;
+ }
+ let t = n as f32 / sr;
+ let (l, r) = audio_sample(&self.generator, t, n);
+ out.channels[0][i] = l;
+ out.channels[1][i] = r;
+ }
+ Ok(out)
+ }
+}
+
+fn db(db: f32) -> f32 {
+ 10f32.powf(db / 20.0)
+}
+
+fn hash(n: i64) -> f32 {
+ let mut x = n as u64 ^ 0x9E37_79B9_7F4A_7C15;
+ x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ x ^= x >> 31;
+ (x >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0
+}
+
+fn audio_sample(g: &Generator, t: f32, n: i64) -> (f32, f32) {
+ match g {
+ Generator::BarsAndTone => {
+ let s = (TAU * 1000.0 * t).sin() * db(-20.0);
+ (s, s)
+ }
+ Generator::Tone { hz, db: d } => {
+ let s = (TAU * hz * t).sin() * db(*d);
+ (s, s)
+ }
+ Generator::CountingLeader => {
+ // 1 kHz beep for one frame at each second mark (the "2-pop" style beep).
+ let frac = t.fract();
+ let s = if frac < 1.0 / 24.0 { (TAU * 1000.0 * t).sin() * db(-20.0) } else { 0.0 };
+ (s, s)
+ }
+ Generator::Demo(scene) => demo_audio(*scene, t, n),
+ _ => (0.0, 0.0),
+ }
+}
+
+fn demo_audio(scene: DemoScene, t: f32, n: i64) -> (f32, f32) {
+ // A slow pad: chord tones with gentle detune + scene texture.
+ let chord: &[f32] = match scene {
+ DemoScene::OceanSunset => &[220.0, 277.18, 329.63, 440.0],
+ DemoScene::Aurora => &[196.0, 246.94, 293.66, 369.99],
+ DemoScene::CityNight => &[110.0, 164.81, 207.65, 246.94],
+ DemoScene::Dunes => &[146.83, 220.0, 261.63, 329.63],
+ DemoScene::Plasma => &[130.81, 196.0, 261.63, 311.13],
+ DemoScene::Forest => &[174.61, 220.0, 261.63, 349.23],
+ };
+ let env = 0.6 + 0.4 * (TAU * t / 8.0).sin();
+ let mut l = 0.0;
+ let mut r = 0.0;
+ for (i, f) in chord.iter().enumerate() {
+ let ph = TAU * f * t;
+ let trem = 0.8 + 0.2 * (TAU * (0.2 + i as f32 * 0.07) * t).sin();
+ l += (ph * 1.002).sin() * trem;
+ r += (ph * 0.998).sin() * trem;
+ }
+ let noise = hash(n)
+ * match scene {
+ DemoScene::OceanSunset => 0.25 * (0.5 + 0.5 * (TAU * t / 6.0).sin()).powi(2),
+ DemoScene::Forest => 0.05,
+ DemoScene::CityNight => 0.08,
+ _ => 0.02,
+ };
+ // A soft kick in the city/plasma scenes to make waveforms interesting.
+ let beat = if matches!(scene, DemoScene::CityNight | DemoScene::Plasma) {
+ let bt = (t * 2.0).fract() / 2.0;
+ (TAU * 55.0 * bt).sin() * (-bt * 18.0).exp() * 0.9
+ } else {
+ 0.0
+ };
+ let g = 0.09 * env;
+ (l * g + noise + beat, r * g + noise * 0.9 + beat)
+}
+
+fn lerp3(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]
+}
+
+fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+fn vnoise(x: f32, y: f32) -> f32 {
+ let (xi, yi) = (x.floor(), y.floor());
+ let (xf, yf) = (x - xi, y - yi);
+ let h = |a: f32, b: f32| hash((a as i64).wrapping_mul(73_856_093) ^ (b as i64).wrapping_mul(19_349_663));
+ let u = xf * xf * (3.0 - 2.0 * xf);
+ let v = yf * yf * (3.0 - 2.0 * yf);
+ let a = h(xi, yi);
+ let b = h(xi + 1.0, yi);
+ let c = h(xi, yi + 1.0);
+ let d = h(xi + 1.0, yi + 1.0);
+ (a + (b - a) * u) + ((c + (d - c) * u) - (a + (b - a) * u)) * v
+}
+
+fn fbm(x: f32, y: f32, oct: u32) -> f32 {
+ let mut s = 0.0;
+ let mut a = 0.5;
+ let (mut fx, mut fy) = (x, y);
+ for _ in 0..oct {
+ s += a * vnoise(fx, fy);
+ fx = fx * 2.03 + 1.7;
+ fy = fy * 2.01 + 9.2;
+ a *= 0.5;
+ }
+ s
+}
+
+fn to8(c: [f32; 3]) -> [u8; 4] {
+ [(c[0].clamp(0.0, 1.0) * 255.0) as u8, (c[1].clamp(0.0, 1.0) * 255.0) as u8, (c[2].clamp(0.0, 1.0) * 255.0) as u8, 255]
+}
+
+/// Render a generator frame as straight-alpha sRGB RGBA8.
+pub fn render(g: &Generator, w: u32, h: u32, t: f32, frame: i64, rate: FrameRate) -> Vec<u8> {
+ let (wu, hu) = (w as usize, h as usize);
+ let mut px = vec![0u8; wu * hu * 4];
+ match g {
+ Generator::BarsAndTone => bars(&mut px, wu, hu),
+ Generator::ColorMatte { color } => {
+ let c = [(color[0] * 255.0) as u8, (color[1] * 255.0) as u8, (color[2] * 255.0) as u8, (color[3] * 255.0) as u8];
+ px.chunks_exact_mut(4).for_each(|p| p.copy_from_slice(&c));
+ }
+ Generator::BlackVideo => px.chunks_exact_mut(4).for_each(|p| p.copy_from_slice(&[0, 0, 0, 255])),
+ Generator::TransparentVideo | Generator::Tone { .. } => {}
+ Generator::CountingLeader => leader(&mut px, wu, hu, t, frame, rate),
+ Generator::Demo(scene) => {
+ let scene = *scene;
+ px.par_chunks_mut(wu * 4).enumerate().for_each(|(y, row)| {
+ let v = y as f32 / hu as f32;
+ for x in 0..wu {
+ let u = x as f32 / wu as f32;
+ let c = demo_pixel(scene, u, v, wu as f32 / hu as f32, t);
+ row[x * 4..x * 4 + 4].copy_from_slice(&to8(c));
+ }
+ });
+ }
+ }
+ px
+}
+
+fn bars(px: &mut [u8], w: usize, h: usize) {
+ // SMPTE RP 219-style HD bars (75% bars, 40% grey side panels, ramp row, PLUGE row).
+ let g40 = [104, 104, 104, 255];
+ let bars75: [[u8; 4]; 7] =
+ [[191, 191, 191, 255], [191, 191, 0, 255], [0, 191, 191, 255], [0, 191, 0, 255], [191, 0, 191, 255], [191, 0, 0, 255], [0, 0, 191, 255]];
+ let side = w / 8;
+ let bw = (w - 2 * side) as f32 / 7.0;
+ let r1 = h * 7 / 12;
+ let r2 = r1 + h / 12;
+ let r3 = r2 + h / 12;
+ for y in 0..h {
+ for x in 0..w {
+ let c: [u8; 4] = if y < r1 {
+ if x < side || x >= w - side { g40 } else { bars75[(((x - side) as f32 / bw) as usize).min(6)] }
+ } else if y < r2 {
+ if x < side {
+ [0, 255, 255, 255]
+ } else if x >= w - side {
+ [0, 0, 255, 255]
+ } else if x < side + bw as usize {
+ [235, 235, 235, 255]
+ } else {
+ [191, 191, 191, 255]
+ }
+ } else if y < r3 {
+ if x < side {
+ [255, 255, 0, 255]
+ } else if x >= w - side {
+ [255, 0, 0, 255]
+ } else {
+ let v = ((x - side) as f32 / (w - 2 * side) as f32 * 255.0) as u8;
+ [v, v, v, 255]
+ }
+ } else {
+ let fx = x as f32 / w as f32;
+ let v: u8 = if fx < 0.125 {
+ 38
+ } else if fx < 0.3 {
+ 0
+ } else if fx < 0.5 {
+ 255
+ } else if fx < 0.65 {
+ 0
+ } else if fx < 0.68 {
+ 5
+ } else if fx < 0.71 {
+ 0
+ } else if fx < 0.74 {
+ 10
+ } else if fx < 0.875 {
+ 0
+ } else {
+ 38
+ };
+ [v, v, v, 255]
+ };
+ px[(y * w + x) * 4..(y * w + x) * 4 + 4].copy_from_slice(&c);
+ }
+ }
+}
+
+fn leader(px: &mut [u8], w: usize, h: usize, t: f32, _frame: i64, _rate: FrameRate) {
+ // 8-second countdown: number = 8 - floor(t), sweep angle = fract(t).
+ let n = (8 - t.floor() as i64).clamp(2, 8);
+ let sweep = t.fract() * TAU;
+ let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
+ let r_out = h as f32 * 0.42;
+ px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let dx = x as f32 - cx;
+ let dy = y as f32 - cy;
+ let d = (dx * dx + dy * dy).sqrt();
+ let ang = (dx.atan2(-dy) + TAU) % TAU;
+ let mut c = if ang < sweep { [0.55, 0.55, 0.55] } else { [0.78, 0.78, 0.78] };
+ let ring = |r: f32, wdt: f32| (d - r).abs() < wdt;
+ if ring(r_out, 3.0) || ring(r_out * 0.86, 2.0) || dx.abs() < 1.5 || dy.abs() < 1.5 {
+ c = [0.1, 0.1, 0.1];
+ }
+ if d > r_out + 3.0 {
+ c = [0.2, 0.2, 0.2];
+ }
+ row[x * 4..x * 4 + 4].copy_from_slice(&to8(c));
+ }
+ });
+ let dh = (h as i32) / 3;
+ let s = n.to_string();
+ let tw = text_width(dh, &s);
+ draw_text(px, w, h, (w as i32 - tw) / 2, (h as i32 - dh) / 2, dh, &s, [20, 20, 20, 255]);
+}
+
+fn demo_pixel(scene: DemoScene, u: f32, v: f32, aspect: f32, t: f32) -> [f32; 3] {
+ match scene {
+ DemoScene::OceanSunset => {
+ let horizon = 0.58;
+ let sun = [0.5 + 0.02 * (t * 0.05).sin(), 0.42 + t * 0.006];
+ if v < horizon {
+ let k = v / horizon;
+ let mut c = lerp3([0.16, 0.10, 0.32], [0.98, 0.52, 0.28], k.powf(1.6));
+ c = lerp3(c, [1.0, 0.82, 0.55], smoothstep(0.75, 1.0, k) * 0.6);
+ let dx = (u - sun[0]) * aspect;
+ let dy = v - sun[1];
+ let d = (dx * dx + dy * dy).sqrt();
+ let glow = (-d * 9.0).exp();
+ c = lerp3(c, [1.0, 0.93, 0.75], glow * 0.8);
+ if d < 0.055 {
+ c = [1.0, 0.95, 0.82];
+ }
+ // wispy clouds
+ let cl = fbm(u * 4.0 + t * 0.02, v * 14.0, 4);
+ let cm = smoothstep(0.15, 0.45, cl) * smoothstep(0.1, 0.45, v) * (1.0 - smoothstep(0.45, 0.55, v));
+ lerp3(c, [0.55, 0.28, 0.35], cm * 0.55)
+ } else {
+ let k = (v - horizon) / (1.0 - horizon);
+ let mut c = lerp3([0.35, 0.18, 0.28], [0.03, 0.05, 0.12], k.powf(0.7));
+ let wave = fbm(u * 18.0 * (1.0 - k * 0.6) + t * 0.3, (v - horizon) * 90.0 / (0.3 + k) - t * 1.4, 3);
+ let dx = (u - sun[0]) * aspect;
+ let path = (-dx * dx * 160.0 / (0.2 + k * 2.0)).exp();
+ let sparkle = smoothstep(0.05, 0.4, wave) * path;
+ c = lerp3(c, [1.0, 0.78, 0.5], sparkle * (1.0 - k * 0.5));
+ lerp3(c, [0.9, 0.5, 0.35], path * 0.25 * (1.0 - k))
+ }
+ }
+ DemoScene::Aurora => {
+ let mut c = lerp3([0.01, 0.02, 0.08], [0.02, 0.1, 0.18], v);
+ // stars
+ let sx = (u * 900.0).floor();
+ let sy = (v * 500.0).floor();
+ let st = hash((sx as i64) * 7919 + sy as i64 * 104_729);
+ if st > 0.994 && v < 0.7 {
+ let tw = 0.6 + 0.4 * (t * 3.0 + st * 100.0).sin();
+ c = lerp3(c, [0.9, 0.95, 1.0], tw);
+ }
+ // aurora curtains
+ for (i, col) in [[0.2, 1.0, 0.55], [0.55, 0.3, 1.0], [0.1, 0.9, 0.8]].iter().enumerate() {
+ let fi = i as f32;
+ let base = 0.28 + 0.08 * fi + 0.06 * (u * 3.0 + t * 0.15 + fi).sin() + 0.05 * fbm(u * 3.0 + t * 0.05, fi, 3);
+ let dy = v - base;
+ let ray = 0.5 + 0.5 * fbm(u * 40.0 + t * 0.4 + fi * 10.0, fi, 2);
+ let a = (-dy * dy * 90.0).exp() * if dy > 0.0 { 1.0 } else { (dy * 12.0).exp() } * ray;
+ c = lerp3(c, *col, (a * 0.8).min(1.0));
+ }
+ // mountains
+ let m = 0.72 + 0.08 * fbm(u * 3.0, 3.3, 5) + 0.05 * (u * 5.0).sin();
+ if v > m {
+ let snow = smoothstep(0.02, 0.0, v - m) * 0.3;
+ c = lerp3([0.02, 0.03, 0.05], [0.4, 0.5, 0.6], snow);
+ }
+ // reflection lake
+ if v > 0.9 {
+ c = lerp3(c, [0.05, 0.25, 0.2], 0.3 * (1.0 + (v * 400.0 + t * 4.0).sin()) * 0.5);
+ }
+ c
+ }
+ DemoScene::CityNight => {
+ let mut c = lerp3([0.05, 0.02, 0.15], [0.55, 0.2, 0.35], v.powf(2.2));
+ let layers = [(0.15, 0.55, [0.12, 0.08, 0.2], 0.02), (0.28, 0.62, [0.07, 0.05, 0.12], 0.05), (0.45, 0.7, [0.03, 0.02, 0.06], 0.12)];
+ for (li, (bw, base, col, speed)) in layers.iter().enumerate() {
+ let x = u * aspect / bw + t * speed;
+ let bi = x.floor();
+ let hgt = base - 0.32 * (0.5 + 0.5 * hash(bi as i64 * 31 + li as i64));
+ if v > hgt {
+ c = *col;
+ let wx = (x.fract() * 6.0).floor();
+ let wy = ((v - hgt) * 70.0).floor();
+ let lit = hash((bi as i64) * 1000 + wx as i64 * 37 + wy as i64 * 101 + li as i64);
+ if (x.fract() * 6.0).fract() < 0.55 && ((v - hgt) * 70.0).fract() < 0.5 && lit > 0.35 && x.fract() > 0.08 && x.fract() < 0.92 {
+ let warm = [1.0, 0.8 + 0.1 * lit, 0.45];
+ c = lerp3(c, warm, 0.35 + 0.35 * (li as f32 / 2.0));
+ }
+ }
+ }
+ // light trails on the road
+ if v > 0.86 {
+ c = [0.04, 0.03, 0.06];
+ for k in 0..6 {
+ let lane = 0.88 + k as f32 * 0.02;
+ let d = (v - lane).abs();
+ let streak = (u * 6.0 - t * (1.5 + k as f32 * 0.4) + k as f32).fract();
+ let col = if k % 2 == 0 { [1.0, 0.25, 0.2] } else { [1.0, 0.9, 0.7] };
+ c = lerp3(c, col, (-d * 900.0).exp() * smoothstep(0.0, 0.8, streak));
+ }
+ }
+ c
+ }
+ DemoScene::Dunes => {
+ let mut c = lerp3([0.35, 0.6, 0.9], [0.98, 0.85, 0.65], smoothstep(0.0, 0.5, v));
+ let sun_d = ((u - 0.75) * aspect).hypot(v - 0.22);
+ c = lerp3(c, [1.0, 0.97, 0.85], (-sun_d * 14.0).exp());
+ for k in 0..4 {
+ let fk = k as f32;
+ let x = u * (1.0 + fk * 0.6) + t * 0.01 * (fk + 1.0);
+ let ridge = 0.45 + fk * 0.12 + 0.06 * (x * 6.0 + fk).sin() + 0.03 * fbm(x * 4.0, fk, 3);
+ if v > ridge {
+ let shade = 0.5 + 0.5 * ((x * 6.0 + fk).cos());
+ let base = lerp3([0.78, 0.45, 0.22], [0.98, 0.72, 0.45], shade);
+ c = lerp3(base, [0.55, 0.28, 0.15], (v - ridge).min(0.2) * 2.0 * (fk / 3.0));
+ }
+ }
+ c
+ }
+ DemoScene::Plasma => {
+ let x = u * aspect * 3.0;
+ let y = v * 3.0;
+ let p = (x + t).sin() + (y * 1.3 - t * 0.7).sin() + ((x + y + t * 0.5).sin()) + ((x * x + y * y).sqrt() * 2.0 - t * 1.2).sin();
+ let h = p * 0.25 + t * 0.05;
+ [0.5 + 0.5 * (PI * h).sin(), 0.5 + 0.5 * (PI * h + 2.1).sin() * 0.6, 0.5 + 0.5 * (PI * h + 4.2).sin()]
+ }
+ DemoScene::Forest => {
+ let mut c = lerp3([0.75, 0.82, 0.8], [0.35, 0.45, 0.4], v);
+ // god rays
+ let ray = 0.5 + 0.5 * fbm(u * 8.0 - v * 3.0 + t * 0.05, 1.0, 2);
+ c = lerp3(c, [1.0, 0.97, 0.85], ray * (1.0 - v) * 0.35);
+ for k in 0..5 {
+ let fk = k as f32;
+ let depth = 1.0 - fk / 5.0;
+ let spacing = 0.12 + fk * 0.03;
+ let x = u / spacing + t * 0.03 * (fk + 1.0) + fk * 3.3;
+ let trunk_x = x.fract();
+ let tw = 0.08 + 0.05 * (1.0 - depth);
+ let id = x.floor();
+ if (trunk_x - 0.5).abs() < tw && hash(id as i64 * 13 + k) > -0.2 {
+ let dark = lerp3([0.45, 0.5, 0.48], [0.05, 0.07, 0.05], 1.0 - depth * 0.8);
+ c = lerp3(c, dark, 0.85);
+ }
+ }
+ let mist = smoothstep(0.55, 1.0, v) * (0.6 + 0.4 * fbm(u * 3.0 + t * 0.1, v * 5.0, 3));
+ lerp3(c, [0.85, 0.88, 0.86], mist * 0.6)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn deterministic_and_scaled() {
+ let g = GeneratorSource::demo(DemoScene::OceanSunset);
+ let a = g.video_frame(FrameRequest { time: Tick(TICKS_PER_SECOND), scale: 0.25 }).unwrap();
+ assert_eq!((a.width, a.height), (480, 270));
+ let b = render(&Generator::Demo(DemoScene::OceanSunset), 480, 270, FrameRate::FPS_23_976.tick_of(23).seconds() as f32, 23, FrameRate::FPS_23_976);
+ assert_eq!(a.to_rgba8(), b);
+ }
+
+ #[test]
+ fn bars_values() {
+ let px = render(&Generator::BarsAndTone, 800, 600, 0.0, 0, FrameRate::FPS_25);
+ // first bar after the side panel is 75% white
+ let i = (10 * 800 + 150) * 4;
+ assert_eq!(&px[i..i + 4], &[191, 191, 191, 255]);
+ let g = GeneratorSource::new(Generator::BarsAndTone, 800, 600, FrameRate::FPS_25, Tick(TICKS_PER_SECOND));
+ let a = g.audio(0, 480, 48000).unwrap();
+ let peak = a.peaks()[0];
+ assert!((peak - db(-20.0)).abs() < 1e-3);
+ }
+
+ #[test]
+ fn all_scenes_render() {
+ for s in DemoScene::ALL {
+ let px = render(&Generator::Demo(s), 64, 36, 1.5, 36, FrameRate::FPS_24);
+ assert!(px.chunks_exact(4).any(|p| p[0] > 20 || p[1] > 20 || p[2] > 20));
+ }
+ let px = render(&Generator::CountingLeader, 64, 36, 1.5, 36, FrameRate::FPS_24);
+ assert_eq!(px.len(), 64 * 36 * 4);
+ }
+}
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
new file mode 100644
index 000000000..d71d951ee
--- /dev/null
+++ b/crates/media/src/lib.rs
@@ -0,0 +1,185 @@
+//! Media sources for FilmCraft.
+//!
+//! A [`MediaSource`] is anything that yields video frames and/or audio for a media time: decoded
+//! files (containers + codecs), stills, image sequences and synthetic generators (bars & tone,
+//! colour mattes, counting leader, procedural demo scenes). Sources are `Send + Sync`; decoder state
+//! lives behind interior mutability so monitors, thumbnails, playback and export can share them.
+//!
+//! Time passed to a source is **media time** (0 = first frame of the media), in ticks.
+
+pub mod cache;
+pub mod digits;
+pub mod generators;
+pub mod still;
+pub mod wav;
+
+use std::path::Path;
+use std::sync::Arc;
+
+use filmcraft_color::ColorInfo;
+use filmcraft_frame::{AudioBuffer, VideoFrame};
+use filmcraft_time::{FrameRate, Tick};
+use serde::{Deserialize, Serialize};
+
+pub use cache::FrameCache;
+pub use generators::{DemoScene, Generator};
+
+#[derive(Debug, thiserror::Error)]
+pub enum MediaError {
+ #[error("unsupported media: {0}")]
+ Unsupported(String),
+ #[error("I/O error: {0}")]
+ Io(String),
+ #[error("decode error: {0}")]
+ Decode(String),
+ #[error("no {0} stream")]
+ NoStream(&'static str),
+ #[error("media offline: {0}")]
+ Offline(String),
+}
+
+pub type Result<T> = std::result::Result<T, MediaError>;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum MediaKind {
+ /// Video, possibly with audio.
+ Movie,
+ AudioOnly,
+ Still,
+ ImageSequence,
+ Synthetic,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct VideoStreamInfo {
+ pub width: u32,
+ pub height: u32,
+ pub frame_rate: FrameRate,
+ pub par: (u32, u32),
+ pub codec: String,
+ pub pixel_format: String,
+ pub color: ColorInfo,
+ pub has_alpha: bool,
+ /// Bitrate in bits/s when known.
+ pub bitrate: Option<u64>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct AudioStreamInfo {
+ pub sample_rate: u32,
+ pub channels: u32,
+ pub codec: String,
+ pub bits_per_sample: Option<u32>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct MediaInfo {
+ pub name: String,
+ pub kind: MediaKind,
+ /// Media duration. Stills report a default duration (the still-image default preference).
+ pub duration: Tick,
+ pub video: Option<VideoStreamInfo>,
+ pub audio: Option<AudioStreamInfo>,
+ pub container: String,
+ /// Timecode of the first frame (in frames at `video.frame_rate`), if the file carries one.
+ pub start_timecode: Option<i64>,
+ pub file_size: Option<u64>,
+}
+
+impl MediaInfo {
+ pub fn frame_rate(&self) -> FrameRate {
+ self.video.as_ref().map(|v| v.frame_rate).unwrap_or_default()
+ }
+ pub fn has_video(&self) -> bool {
+ self.video.is_some()
+ }
+ pub fn has_audio(&self) -> bool {
+ self.audio.is_some()
+ }
+}
+
+/// A request for a video frame.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FrameRequest {
+ /// Media time.
+ pub time: Tick,
+ /// Desired scale relative to full resolution (1.0 = full). Sources may return a larger frame.
+ pub scale: f32,
+}
+
+impl FrameRequest {
+ pub fn full(time: Tick) -> Self {
+ Self { time, scale: 1.0 }
+ }
+}
+
+pub trait MediaSource: Send + Sync {
+ fn info(&self) -> &MediaInfo;
+ /// The frame displayed at media time `req.time`.
+ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>>;
+ /// `frames` audio frames starting at sample index `start` (at `sample_rate`, media time).
+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer>;
+}
+
+pub type SharedSource = Arc<dyn MediaSource>;
+
+/// File extensions we recognise at import (the media browser filters on these).
+pub const STILL_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp"];
+pub const AUDIO_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "mp3", "m4a", "aac", "flac", "ogg", "opus"];
+pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "avi", "mxf", "mts", "m2ts", "ts", "mpg", "mpeg", "3gp", "y4m"];
+
+pub fn is_importable(path: &Path) -> bool {
+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
+ STILL_EXTENSIONS.contains(&ext.as_str()) || AUDIO_EXTENSIONS.contains(&ext.as_str()) || VIDEO_EXTENSIONS.contains(&ext.as_str())
+}
+
+/// A pluggable opener (containers/codecs register themselves here from higher-level crates).
+pub type Opener = fn(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource>>;
+
+/// Open media from bytes, trying `extra` openers first, then the built-in ones (stills, WAV).
+pub fn open_bytes(name: &str, bytes: Arc<[u8]>, extra: &[Opener]) -> Result<SharedSource> {
+ for o in extra {
+ if let Some(r) = o(name, bytes.clone()) {
+ return r;
+ }
+ }
+ if wav::sniff(&bytes) {
+ return Ok(Arc::new(wav::WavSource::parse(name, bytes)?));
+ }
+ if still::sniff(&bytes) {
+ return Ok(Arc::new(still::StillSource::decode(name, &bytes)?));
+ }
+ Err(MediaError::Unsupported(format!("{name}: unrecognised format")))
+}
+
+/// Open a file from disk (native only).
+#[cfg(not(target_arch = "wasm32"))]
+pub fn open_path(path: &Path, extra: &[Opener]) -> Result<SharedSource> {
+ let bytes = std::fs::read(path).map_err(|e| MediaError::Io(format!("{}: {e}", path.display())))?;
+ let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
+ open_bytes(&name, bytes.into(), extra)
+}
+
+/// A source that renders nothing (used for offline media): the "Media Offline" slate.
+pub struct OfflineSource {
+ pub info: MediaInfo,
+}
+
+impl MediaSource for OfflineSource {
+ fn info(&self) -> &MediaInfo {
+ &self.info
+ }
+ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {
+ let v = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?;
+ let s = req.scale.clamp(0.02, 1.0);
+ let (w, h) = (((v.width as f32 * s) as u32).max(2), ((v.height as f32 * s) as u32).max(2));
+ let mut px = vec![0u8; (w * h * 4) as usize];
+ for p in px.chunks_exact_mut(4) {
+ p.copy_from_slice(&[140, 16, 16, 255]);
+ }
+ Ok(Arc::new(VideoFrame::rgba8(w, h, px).with_pts(req.time)))
+ }
+ fn audio(&self, _start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
+ Ok(AudioBuffer::silence(sample_rate, self.info.audio.as_ref().map_or(2, |a| a.channels as usize), frames))
+ }
+}
diff --git a/crates/media/src/still.rs b/crates/media/src/still.rs
new file mode 100644
index 000000000..933811dd9
--- /dev/null
+++ b/crates/media/src/still.rs
@@ -0,0 +1,73 @@
+//! Still images (PNG, JPEG, GIF (first frame), WebP, TIFF, BMP) as media sources.
+
+use std::sync::Arc;
+
+use filmcraft_frame::VideoFrame;
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
+
+use crate::{FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, VideoStreamInfo};
+
+/// Default still duration (Premiere's preference default is 5 seconds).
+pub const DEFAULT_STILL_DURATION: Tick = Tick(5 * TICKS_PER_SECOND);
+
+pub fn sniff(b: &[u8]) -> bool {
+ b.starts_with(b"\x89PNG")
+ || b.starts_with(&[0xFF, 0xD8, 0xFF])
+ || b.starts_with(b"GIF8")
+ || (b.len() > 12 && &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP")
+ || b.starts_with(b"II*\0")
+ || b.starts_with(b"MM\0*")
+ || b.starts_with(b"BM")
+}
+
+pub struct StillSource {
+ info: MediaInfo,
+ frame: Arc<VideoFrame>,
+}
+
+impl StillSource {
+ pub fn decode(name: &str, bytes: &[u8]) -> Result<Self> {
+ let img = image::load_from_memory(bytes).map_err(|e| MediaError::Decode(format!("{name}: {e}")))?;
+ let has_alpha = img.color().has_alpha();
+ let rgba = img.to_rgba8();
+ let (w, h) = rgba.dimensions();
+ Ok(Self::from_rgba(name, w, h, rgba.into_raw(), has_alpha, bytes.len() as u64))
+ }
+
+ pub fn from_rgba(name: &str, w: u32, h: u32, rgba: Vec<u8>, has_alpha: bool, file_size: u64) -> Self {
+ let codec = name.rsplit('.').next().unwrap_or("image").to_ascii_uppercase();
+ let info = MediaInfo {
+ name: name.to_string(),
+ kind: MediaKind::Still,
+ duration: DEFAULT_STILL_DURATION,
+ video: Some(VideoStreamInfo {
+ width: w,
+ height: h,
+ frame_rate: FrameRate::FPS_29_97,
+ par: (1, 1),
+ codec,
+ pixel_format: if has_alpha { "RGBA 8-bit".into() } else { "RGB 8-bit".into() },
+ color: filmcraft_color::ColorInfo::SRGB_FULL,
+ has_alpha,
+ bitrate: None,
+ }),
+ audio: None,
+ container: "Image".into(),
+ start_timecode: None,
+ file_size: Some(file_size),
+ };
+ Self { info, frame: Arc::new(VideoFrame::rgba8(w, h, rgba)) }
+ }
+}
+
+impl MediaSource for StillSource {
+ fn info(&self) -> &MediaInfo {
+ &self.info
+ }
+ fn video_frame(&self, _req: FrameRequest) -> Result<Arc<VideoFrame>> {
+ Ok(self.frame.clone())
+ }
+ fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<filmcraft_frame::AudioBuffer> {
+ Err(MediaError::NoStream("audio"))
+ }
+}
diff --git a/crates/media/src/wav.rs b/crates/media/src/wav.rs
new file mode 100644
index 000000000..07e1cae4f
--- /dev/null
+++ b/crates/media/src/wav.rs
@@ -0,0 +1,176 @@
+//! Minimal WAV (RIFF/RF64 PCM 8/16/24/32-bit int, 32/64-bit float) source. The full `riff` crate
+//! (BWF metadata, AIFF) will replace this.
+
+use std::sync::Arc;
+
+use filmcraft_frame::{AudioBuffer, VideoFrame};
+use filmcraft_time::Tick;
+
+use crate::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result};
+
+pub fn sniff(b: &[u8]) -> bool {
+ b.len() >= 12 && (&b[0..4] == b"RIFF" || &b[0..4] == b"RF64") && &b[8..12] == b"WAVE"
+}
+
+pub struct WavSource {
+ info: MediaInfo,
+ bytes: Arc<[u8]>,
+ data_off: usize,
+ data_len: usize,
+ channels: usize,
+ bits: u16,
+ float: bool,
+ rate: u32,
+}
+
+fn le16(b: &[u8], o: usize) -> u16 {
+ u16::from_le_bytes([b[o], b[o + 1]])
+}
+fn le32(b: &[u8], o: usize) -> u32 {
+ u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
+}
+
+impl WavSource {
+ pub fn parse(name: &str, bytes: Arc<[u8]>) -> Result<Self> {
+ let b = &bytes[..];
+ let mut pos = 12;
+ let mut fmt = None;
+ let mut data = None;
+ while pos + 8 <= b.len() {
+ let id = &b[pos..pos + 4];
+ let mut len = le32(b, pos + 4) as usize;
+ let body = pos + 8;
+ if id == b"data" && (len == 0xFFFF_FFFF || body + len > b.len()) {
+ len = b.len() - body;
+ }
+ if body + len > b.len() {
+ break;
+ }
+ match id {
+ b"fmt " if len >= 16 => {
+ let mut tag = le16(b, body);
+ let ch = le16(b, body + 2);
+ let rate = le32(b, body + 4);
+ let bits = le16(b, body + 14);
+ if tag == 0xFFFE && len >= 40 {
+ tag = le16(b, body + 24);
+ }
+ fmt = Some((tag, ch, rate, bits));
+ }
+ b"data" => data = Some((body, len)),
+ _ => {}
+ }
+ pos = body + len + (len & 1);
+ }
+ let (tag, ch, rate, bits) = fmt.ok_or_else(|| MediaError::Decode(format!("{name}: missing fmt chunk")))?;
+ let (off, len) = data.ok_or_else(|| MediaError::Decode(format!("{name}: missing data chunk")))?;
+ let float = tag == 3;
+ if !(tag == 1 || float) || ch == 0 || !matches!(bits, 8 | 16 | 24 | 32 | 64) {
+ return Err(MediaError::Unsupported(format!("{name}: WAV format tag {tag}, {bits} bits")));
+ }
+ let frame_bytes = ch as usize * bits as usize / 8;
+ let frames = len / frame_bytes;
+ let info = MediaInfo {
+ name: name.into(),
+ kind: MediaKind::AudioOnly,
+ duration: Tick::from_units(frames as i64, rate as i64),
+ video: None,
+ audio: Some(AudioStreamInfo {
+ sample_rate: rate,
+ channels: ch as u32,
+ codec: if float { "PCM float".into() } else { "PCM".into() },
+ bits_per_sample: Some(bits as u32),
+ }),
+ container: "WAV".into(),
+ start_timecode: None,
+ file_size: Some(b.len() as u64),
+ };
+ Ok(Self { info, data_off: off, data_len: frames * frame_bytes, channels: ch as usize, bits, float, rate, bytes })
+ }
+
+ fn sample(&self, frame: usize, ch: usize) -> f32 {
+ let bps = self.bits as usize / 8;
+ let o = self.data_off + (frame * self.channels + ch) * bps;
+ let b = &self.bytes;
+ match (self.bits, self.float) {
+ (8, _) => (b[o] as f32 - 128.0) / 128.0,
+ (16, _) => i16::from_le_bytes([b[o], b[o + 1]]) as f32 / 32768.0,
+ (24, _) => ((i32::from_le_bytes([0, b[o], b[o + 1], b[o + 2]]) >> 8) as f32) / 8_388_608.0,
+ (32, false) => i32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) as f32 / 2_147_483_648.0,
+ (32, true) => f32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]),
+ (64, true) => f64::from_le_bytes(b[o..o + 8].try_into().unwrap_or([0; 8])) as f32,
+ _ => 0.0,
+ }
+ }
+}
+
+impl MediaSource for WavSource {
+ fn info(&self) -> &MediaInfo {
+ &self.info
+ }
+ fn video_frame(&self, _req: FrameRequest) -> Result<Arc<VideoFrame>> {
+ Err(MediaError::NoStream("video"))
+ }
+ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
+ let total = self.data_len / (self.channels * self.bits as usize / 8);
+ let mut out = AudioBuffer::silence(sample_rate, self.channels, frames);
+ // Linear-interpolating resample when rates differ (the audio crate provides sinc resampling).
+ let ratio = self.rate as f64 / sample_rate as f64;
+ for i in 0..frames {
+ let src = (start + i as i64) as f64 * ratio;
+ if src < 0.0 {
+ continue;
+ }
+ let i0 = src.floor() as usize;
+ if i0 >= total {
+ break;
+ }
+ let fr = (src - i0 as f64) as f32;
+ for c in 0..self.channels {
+ let a = self.sample(i0, c);
+ let b = if i0 + 1 < total { self.sample(i0 + 1, c) } else { a };
+ out.channels[c][i] = a + (b - a) * fr;
+ }
+ }
+ Ok(out)
+ }
+}
+
+/// Encode interleaved f32 samples as a 16-bit PCM WAV file.
+pub fn write_wav16(samples: &[f32], channels: u16, rate: u32) -> Vec<u8> {
+ let data_len = samples.len() * 2;
+ let mut v = Vec::with_capacity(44 + data_len);
+ v.extend_from_slice(b"RIFF");
+ v.extend_from_slice(&((36 + data_len) as u32).to_le_bytes());
+ v.extend_from_slice(b"WAVEfmt ");
+ v.extend_from_slice(&16u32.to_le_bytes());
+ v.extend_from_slice(&1u16.to_le_bytes());
+ v.extend_from_slice(&channels.to_le_bytes());
+ v.extend_from_slice(&rate.to_le_bytes());
+ v.extend_from_slice(&(rate * channels as u32 * 2).to_le_bytes());
+ v.extend_from_slice(&(channels * 2).to_le_bytes());
+ v.extend_from_slice(&16u16.to_le_bytes());
+ v.extend_from_slice(b"data");
+ v.extend_from_slice(&(data_len as u32).to_le_bytes());
+ for s in samples {
+ v.extend_from_slice(&((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
+ }
+ v
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn roundtrip() {
+ let s: Vec<f32> = (0..200).map(|i| ((i as f32) * 0.1).sin() * 0.5).collect();
+ let bytes = write_wav16(&s, 2, 48000);
+ let src = WavSource::parse("t.wav", bytes.into()).unwrap();
+ assert_eq!(src.info().audio.as_ref().unwrap().channels, 2);
+ let a = src.audio(0, 100, 48000).unwrap();
+ assert!((a.channels[0][3] - s[6]).abs() < 1e-4);
+ assert!((a.channels[1][3] - s[7]).abs() < 1e-4);
+ assert_eq!(src.info().duration, Tick::from_units(100, 48000));
+ }
+}
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
new file mode 100644
index 000000000..29f430127
--- /dev/null
+++ b/crates/project/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "filmcraft-project"
+description = "FilmCraft document model: projects, bins, clips, sequences, tracks, effects, keyframes, markers"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-geom = { workspace = true }
+filmcraft-color = { workspace = true }
+filmcraft-media = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+proptest = { workspace = true }
diff --git a/crates/project/src/effect.rs b/crates/project/src/effect.rs
new file mode 100644
index 000000000..57e27e185
--- /dev/null
+++ b/crates/project/src/effect.rs
@@ -0,0 +1,937 @@
+//! Effect definitions (parameter schemas, categories) and effect instances on track items.
+//!
+//! Definitions are data: the Effects panel tree, the Effect Controls rows and the MCP schema are
+//! all generated from [`EffectDef`]. Pixel/audio implementations live in the render/audio crates
+//! and are looked up by `EffectDef::id`.
+
+use std::collections::BTreeMap;
+use std::sync::OnceLock;
+
+use filmcraft_geom::Vec2;
+use serde::{Deserialize, Serialize};
+
+use crate::keyframe::{Param, ParamValue};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum EffectKind {
+ Video,
+ Audio,
+ VideoTransition,
+ AudioTransition,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize)]
+pub enum ParamKind {
+ /// Scalar with a slider range (`soft_*` is the slider range; hard min/max clamp typed values).
+ Float {
+ min: f64,
+ max: f64,
+ soft_min: f64,
+ soft_max: f64,
+ unit: &'static str,
+ decimals: u8,
+ },
+ Point,
+ Color,
+ Bool,
+ Choice(&'static [&'static str]),
+ Angle,
+ Text,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize)]
+pub struct ParamDef {
+ pub id: &'static str,
+ pub label: &'static str,
+ pub kind: ParamKind,
+ pub default: ParamValue,
+ /// Can have keyframes (the stopwatch appears).
+ pub animatable: bool,
+ /// Group (twirl) label within the effect, e.g. "Basic Correction".
+ pub group: Option<&'static str>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize)]
+pub struct EffectDef {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub kind: EffectKind,
+ /// Effects-panel folder path, e.g. `["Video Effects", "Blur & Sharpen"]`.
+ pub category: &'static [&'static str],
+ pub params: Vec<ParamDef>,
+ /// Intrinsic (fixed) effects appear on every clip and cannot be deleted.
+ pub intrinsic: bool,
+ /// GPU accelerated badge in the Effects panel.
+ pub accelerated: bool,
+ /// 32-bit colour badge.
+ pub float32: bool,
+ /// YUV badge.
+ pub yuv: bool,
+}
+
+impl EffectDef {
+ pub fn param(&self, id: &str) -> Option<&ParamDef> {
+ self.params.iter().find(|p| p.id == id)
+ }
+ pub fn instance(&self) -> EffectInstance {
+ EffectInstance {
+ effect: self.id.to_string(),
+ enabled: true,
+ params: self.params.iter().map(|p| (p.id.to_string(), Param::new(p.default.clone()))).collect(),
+ masks: Vec::new(),
+ }
+ }
+}
+
+/// A mask on an effect (ellipse / 4-point polygon / bezier), in clip pixel space.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Mask {
+ pub name: String,
+ pub shape: MaskShape,
+ pub feather: Param,
+ pub opacity: Param,
+ pub expansion: Param,
+ pub inverted: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum MaskShape {
+ Ellipse { center: Vec2, radius: Vec2 },
+ Polygon(Vec<Vec2>),
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct EffectInstance {
+ pub effect: String,
+ pub enabled: bool,
+ pub params: BTreeMap<String, Param>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub masks: Vec<Mask>,
+}
+
+impl EffectInstance {
+ pub fn def(&self) -> Option<&'static EffectDef> {
+ find_effect(&self.effect)
+ }
+ pub fn param(&self, id: &str) -> Option<&Param> {
+ self.params.get(id)
+ }
+ pub fn param_mut(&mut self, id: &str) -> Option<&mut Param> {
+ self.params.get_mut(id)
+ }
+ pub fn f64_at(&self, id: &str, t: filmcraft_time::Tick) -> f64 {
+ self.params.get(id).map(|p| p.f64_at(t)).or_else(|| self.def().and_then(|d| d.param(id)).and_then(|p| p.default.as_f64())).unwrap_or(0.0)
+ }
+ pub fn vec2_at(&self, id: &str, t: filmcraft_time::Tick) -> Vec2 {
+ self.params.get(id).map(|p| p.vec2_at(t)).unwrap_or_default()
+ }
+ pub fn is_animated(&self) -> bool {
+ self.params.values().any(Param::is_animated)
+ }
+}
+
+pub const BLEND_MODES: &[&str] = &[
+ "Normal",
+ "Dissolve",
+ "Darken",
+ "Multiply",
+ "Color Burn",
+ "Linear Burn",
+ "Darker Color",
+ "Lighten",
+ "Screen",
+ "Color Dodge",
+ "Linear Dodge (Add)",
+ "Lighter Color",
+ "Overlay",
+ "Soft Light",
+ "Hard Light",
+ "Vivid Light",
+ "Linear Light",
+ "Pin Light",
+ "Hard Mix",
+ "Difference",
+ "Exclusion",
+ "Subtract",
+ "Divide",
+ "Hue",
+ "Saturation",
+ "Color",
+ "Luminosity",
+];
+
+fn f(id: &'static str, label: &'static str, def: f64, min: f64, max: f64, unit: &'static str) -> ParamDef {
+ ParamDef {
+ id,
+ label,
+ kind: ParamKind::Float { min, max, soft_min: min, soft_max: max, unit, decimals: 1 },
+ default: ParamValue::Float(def),
+ animatable: true,
+ group: None,
+ }
+}
+fn fs(id: &'static str, label: &'static str, def: f64, (min, max): (f64, f64), (smin, smax): (f64, f64), unit: &'static str, decimals: u8) -> ParamDef {
+ ParamDef {
+ id,
+ label,
+ kind: ParamKind::Float { min, max, soft_min: smin, soft_max: smax, unit, decimals },
+ default: ParamValue::Float(def),
+ animatable: true,
+ group: None,
+ }
+}
+fn pt(id: &'static str, label: &'static str, x: f64, y: f64) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Point, default: ParamValue::Vec2(Vec2::new(x, y)), animatable: true, group: None }
+}
+fn col(id: &'static str, label: &'static str, c: [f32; 4]) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Color, default: ParamValue::Color(c), animatable: true, group: None }
+}
+fn b(id: &'static str, label: &'static str, v: bool) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Bool, default: ParamValue::Bool(v), animatable: false, group: None }
+}
+fn ch(id: &'static str, label: &'static str, opts: &'static [&'static str], def: u32) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Choice(opts), default: ParamValue::Choice(def), animatable: false, group: None }
+}
+fn ang(id: &'static str, label: &'static str, def: f64) -> ParamDef {
+ ParamDef { id, label, kind: ParamKind::Angle, default: ParamValue::Float(def), animatable: true, group: None }
+}
+fn grp(mut p: ParamDef, g: &'static str) -> ParamDef {
+ p.group = Some(g);
+ p
+}
+
+fn video(id: &'static str, name: &'static str, cat: &'static [&'static str], params: Vec<ParamDef>) -> EffectDef {
+ EffectDef { id, name, kind: EffectKind::Video, category: cat, params, intrinsic: false, accelerated: true, float32: true, yuv: false }
+}
+fn vtrans(id: &'static str, name: &'static str, cat: &'static [&'static str], params: Vec<ParamDef>) -> EffectDef {
+ EffectDef { id, name, kind: EffectKind::VideoTransition, category: cat, params, intrinsic: false, accelerated: true, float32: true, yuv: false }
+}
+fn audio(id: &'static str, name: &'static str, cat: &'static [&'static str], params: Vec<ParamDef>) -> EffectDef {
+ EffectDef { id, name, kind: EffectKind::Audio, category: cat, params, intrinsic: false, accelerated: false, float32: true, yuv: false }
+}
+
+const ADJUST: &[&str] = &["Video Effects", "Adjust"];
+const BLUR: &[&str] = &["Video Effects", "Blur & Sharpen"];
+const COLOR_CORR: &[&str] = &["Video Effects", "Color Correction"];
+const DISTORT: &[&str] = &["Video Effects", "Distort"];
+const GENERATE: &[&str] = &["Video Effects", "Generate"];
+const IMAGE_CONTROL: &[&str] = &["Video Effects", "Image Control"];
+const KEYING: &[&str] = &["Video Effects", "Keying"];
+const NOISE: &[&str] = &["Video Effects", "Noise & Grain"];
+const PERSPECTIVE: &[&str] = &["Video Effects", "Perspective"];
+const STYLIZE: &[&str] = &["Video Effects", "Stylize"];
+const TRANSFORM: &[&str] = &["Video Effects", "Transform"];
+const VIDEO: &[&str] = &["Video Effects", "Video"];
+const DISSOLVE: &[&str] = &["Video Transitions", "Dissolve"];
+const IRIS: &[&str] = &["Video Transitions", "Iris"];
+const SLIDE: &[&str] = &["Video Transitions", "Slide"];
+const WIPE: &[&str] = &["Video Transitions", "Wipe"];
+const ZOOM: &[&str] = &["Video Transitions", "Zoom"];
+const PAGE_PEEL: &[&str] = &["Video Transitions", "Page Peel"];
+const MOTION3D: &[&str] = &["Video Transitions", "3D Motion"];
+const A_AMP: &[&str] = &["Audio Effects", "Amplitude and Compression"];
+const A_DELAY: &[&str] = &["Audio Effects", "Delay and Echo"];
+const A_FILTER: &[&str] = &["Audio Effects", "Filter and EQ"];
+const A_NOISE: &[&str] = &["Audio Effects", "Noise Reduction/Restoration"];
+const A_REVERB: &[&str] = &["Audio Effects", "Reverb"];
+const A_SPECIAL: &[&str] = &["Audio Effects", "Special"];
+const A_TIME: &[&str] = &["Audio Effects", "Time and Pitch"];
+const A_TRANS: &[&str] = &["Audio Transitions", "Crossfade"];
+
+const DIR_OPTS: &[&str] = &["From North", "From East", "From South", "From West"];
+
+fn build_effects() -> Vec<EffectDef> {
+ let mut v = vec![
+ // ---- intrinsic ----
+ EffectDef {
+ id: "motion",
+ name: "Motion",
+ kind: EffectKind::Video,
+ category: &[],
+ params: vec![
+ pt("position", "Position", f64::NAN, f64::NAN),
+ fs("scale", "Scale", 100.0, (0.0, 10000.0), (0.0, 100.0), "", 1),
+ fs("scale_width", "Scale Width", 100.0, (0.0, 10000.0), (0.0, 100.0), "", 1),
+ b("uniform_scale", "Uniform Scale", true),
+ ang("rotation", "Rotation", 0.0),
+ pt("anchor", "Anchor Point", f64::NAN, f64::NAN),
+ fs("anti_flicker", "Anti-flicker Filter", 0.0, (0.0, 1.0), (0.0, 1.0), "", 2),
+ ],
+ intrinsic: true,
+ accelerated: true,
+ float32: true,
+ yuv: true,
+ },
+ EffectDef {
+ id: "opacity",
+ name: "Opacity",
+ kind: EffectKind::Video,
+ category: &[],
+ params: vec![fs("opacity", "Opacity", 100.0, (0.0, 100.0), (0.0, 100.0), "%", 1), ch("blend", "Blend Mode", BLEND_MODES, 0)],
+ intrinsic: true,
+ accelerated: true,
+ float32: true,
+ yuv: true,
+ },
+ EffectDef {
+ id: "time_remap",
+ name: "Time Remapping",
+ kind: EffectKind::Video,
+ category: &[],
+ params: vec![fs("speed", "Speed", 100.0, (-10000.0, 10000.0), (0.0, 200.0), "%", 2)],
+ intrinsic: true,
+ accelerated: true,
+ float32: true,
+ yuv: true,
+ },
+ EffectDef {
+ id: "volume",
+ name: "Volume",
+ kind: EffectKind::Audio,
+ category: &[],
+ params: vec![b("bypass", "Bypass", false), fs("level", "Level", 0.0, (-287.5, 15.0), (-60.0, 15.0), "dB", 1)],
+ intrinsic: true,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ EffectDef {
+ id: "channel_volume",
+ name: "Channel Volume",
+ kind: EffectKind::Audio,
+ category: &[],
+ params: vec![
+ b("bypass", "Bypass", false),
+ fs("left", "Left", 0.0, (-287.5, 6.0), (-60.0, 6.0), "dB", 1),
+ fs("right", "Right", 0.0, (-287.5, 6.0), (-60.0, 6.0), "dB", 1),
+ ],
+ intrinsic: true,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ EffectDef {
+ id: "panner",
+ name: "Panner",
+ kind: EffectKind::Audio,
+ category: &[],
+ params: vec![fs("balance", "Balance", 0.0, (-100.0, 100.0), (-100.0, 100.0), "", 1)],
+ intrinsic: true,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ // ---- video effects ----
+ video(
+ "brightness_contrast",
+ "Brightness & Contrast",
+ COLOR_CORR,
+ vec![f("brightness", "Brightness", 0.0, -100.0, 100.0, ""), f("contrast", "Contrast", 0.0, -100.0, 100.0, "")],
+ ),
+ video(
+ "tint",
+ "Tint",
+ COLOR_CORR,
+ vec![
+ col("black", "Map Black To", [0.0, 0.0, 0.0, 1.0]),
+ col("white", "Map White To", [1.0, 1.0, 1.0, 1.0]),
+ f("amount", "Amount to Tint", 100.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "color_balance",
+ "Color Balance",
+ COLOR_CORR,
+ vec![
+ f("shadow_r", "Shadow Red Balance", 0.0, -100.0, 100.0, ""),
+ f("shadow_g", "Shadow Green Balance", 0.0, -100.0, 100.0, ""),
+ f("shadow_b", "Shadow Blue Balance", 0.0, -100.0, 100.0, ""),
+ f("mid_r", "Midtone Red Balance", 0.0, -100.0, 100.0, ""),
+ f("mid_g", "Midtone Green Balance", 0.0, -100.0, 100.0, ""),
+ f("mid_b", "Midtone Blue Balance", 0.0, -100.0, 100.0, ""),
+ f("hi_r", "Highlight Red Balance", 0.0, -100.0, 100.0, ""),
+ f("hi_g", "Highlight Green Balance", 0.0, -100.0, 100.0, ""),
+ f("hi_b", "Highlight Blue Balance", 0.0, -100.0, 100.0, ""),
+ b("preserve", "Preserve Luminosity", false),
+ ],
+ ),
+ video(
+ "leave_color",
+ "Leave Color",
+ COLOR_CORR,
+ vec![
+ f("amount", "Amount to Decolor", 0.0, 0.0, 100.0, "%"),
+ col("color", "Color To Leave", [1.0, 0.0, 0.0, 1.0]),
+ f("tolerance", "Tolerance", 15.0, 0.0, 100.0, "%"),
+ f("softness", "Edge Softness", 0.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "change_to_color",
+ "Change to Color",
+ COLOR_CORR,
+ vec![
+ col("from", "From", [1.0, 0.0, 0.0, 1.0]),
+ col("to", "To", [0.0, 0.0, 1.0, 1.0]),
+ f("hue_tol", "Hue Tolerance", 5.0, 0.0, 100.0, "%"),
+ f("softness", "Softness", 50.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "lumetri",
+ "Lumetri Color",
+ COLOR_CORR,
+ vec![
+ grp(f("temperature", "Temperature", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(f("tint", "Tint", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(fs("exposure", "Exposure", 0.0, (-5.0, 5.0), (-5.0, 5.0), "", 1), "Basic Correction"),
+ grp(f("contrast", "Contrast", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(f("highlights", "Highlights", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(f("shadows", "Shadows", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(f("whites", "Whites", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(f("blacks", "Blacks", 0.0, -100.0, 100.0, ""), "Basic Correction"),
+ grp(fs("saturation", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "Basic Correction"),
+ grp(f("faded_film", "Faded Film", 0.0, 0.0, 100.0, ""), "Creative"),
+ grp(f("sharpen", "Sharpen", 0.0, -100.0, 100.0, ""), "Creative"),
+ grp(f("vibrance", "Vibrance", 0.0, -100.0, 100.0, ""), "Creative"),
+ grp(fs("creative_sat", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1), "Creative"),
+ grp(col("shadow_tint", "Shadow Tint", [0.5, 0.5, 0.5, 1.0]), "Creative"),
+ grp(col("highlight_tint", "Highlight Tint", [0.5, 0.5, 0.5, 1.0]), "Creative"),
+ grp(f("vignette_amount", "Amount", 0.0, -5.0, 5.0, ""), "Vignette"),
+ grp(f("vignette_midpoint", "Midpoint", 50.0, 0.0, 100.0, ""), "Vignette"),
+ grp(f("vignette_roundness", "Roundness", 0.0, -100.0, 100.0, ""), "Vignette"),
+ grp(f("vignette_feather", "Feather", 50.0, 0.0, 100.0, ""), "Vignette"),
+ ],
+ ),
+ video(
+ "gaussian_blur",
+ "Gaussian Blur",
+ BLUR,
+ vec![
+ fs("blurriness", "Blurriness", 0.0, (0.0, 3000.0), (0.0, 100.0), "", 1),
+ ch("dimensions", "Blur Dimensions", &["Horizontal and Vertical", "Horizontal", "Vertical"], 0),
+ b("repeat_edge", "Repeat Edge Pixels", false),
+ ],
+ ),
+ video(
+ "directional_blur",
+ "Directional Blur",
+ BLUR,
+ vec![ang("direction", "Direction", 0.0), fs("length", "Blur Length", 0.0, (0.0, 1000.0), (0.0, 20.0), "", 1)],
+ ),
+ video("sharpen", "Sharpen", BLUR, vec![fs("amount", "Sharpen Amount", 0.0, (0.0, 4000.0), (0.0, 100.0), "", 0)]),
+ video(
+ "unsharp_mask",
+ "Unsharp Mask",
+ BLUR,
+ vec![
+ fs("amount", "Amount", 50.0, (0.0, 500.0), (0.0, 500.0), "", 0),
+ fs("radius", "Radius", 1.0, (0.1, 250.0), (0.1, 250.0), "", 1),
+ fs("threshold", "Threshold", 0.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ ],
+ ),
+ video("camera_blur", "Camera Blur", BLUR, vec![f("percent", "Percent Blur", 0.0, 0.0, 100.0, "")]),
+ video("black_white", "Black & White", IMAGE_CONTROL, vec![]),
+ video(
+ "color_pass",
+ "Color Pass",
+ IMAGE_CONTROL,
+ vec![col("color", "Color", [1.0, 0.0, 0.0, 1.0]), f("similarity", "Similarity", 10.0, 0.0, 100.0, ""), b("reverse", "Reverse", false)],
+ ),
+ video("gamma_correction", "Gamma Correction", IMAGE_CONTROL, vec![fs("gamma", "Gamma", 10.0, (1.0, 28.0), (1.0, 28.0), "", 0)]),
+ video(
+ "invert",
+ "Invert",
+ &["Video Effects", "Channel"],
+ vec![ch("channel", "Channel", &["RGB", "Red", "Green", "Blue", "Alpha"], 0), f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%")],
+ ),
+ video(
+ "levels",
+ "Levels",
+ ADJUST,
+ vec![
+ fs("in_black", "(RGB) Input Black Level", 0.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("in_white", "(RGB) Input White Level", 255.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("out_black", "(RGB) Output Black Level", 0.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("out_white", "(RGB) Output White Level", 255.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("gamma", "(RGB) Gamma", 100.0, (10.0, 1000.0), (10.0, 300.0), "", 0),
+ ],
+ ),
+ video(
+ "proc_amp",
+ "ProcAmp",
+ ADJUST,
+ vec![
+ f("brightness", "Brightness", 0.0, -100.0, 100.0, ""),
+ fs("contrast", "Contrast", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1),
+ ang("hue", "Hue", 0.0),
+ fs("saturation", "Saturation", 100.0, (0.0, 200.0), (0.0, 200.0), "", 1),
+ ],
+ ),
+ video(
+ "extract",
+ "Extract",
+ ADJUST,
+ vec![
+ fs("black", "Black Input Level", 0.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("white", "White Input Level", 255.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ f("softness", "Softness", 0.0, 0.0, 100.0, ""),
+ b("invert", "Invert", false),
+ ],
+ ),
+ video("posterize", "Posterize", STYLIZE, vec![fs("levels", "Level", 7.0, (2.0, 255.0), (2.0, 32.0), "", 0)]),
+ video(
+ "mosaic",
+ "Mosaic",
+ STYLIZE,
+ vec![
+ fs("horizontal", "Horizontal Blocks", 10.0, (1.0, 4000.0), (1.0, 200.0), "", 0),
+ fs("vertical", "Vertical Blocks", 10.0, (1.0, 4000.0), (1.0, 200.0), "", 0),
+ b("sharp", "Sharp Colors", false),
+ ],
+ ),
+ video("find_edges", "Find Edges", STYLIZE, vec![b("invert", "Invert", false), f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%")]),
+ video(
+ "emboss",
+ "Emboss",
+ STYLIZE,
+ vec![
+ ang("direction", "Direction", 45.0),
+ fs("relief", "Relief", 1.8, (0.0, 10.0), (0.0, 10.0), "", 1),
+ f("contrast", "Contrast", 100.0, 0.0, 500.0, ""),
+ f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video("replicate", "Replicate", STYLIZE, vec![fs("count", "Count", 2.0, (2.0, 16.0), (2.0, 16.0), "", 0)]),
+ video(
+ "strobe",
+ "Strobe Light",
+ STYLIZE,
+ vec![
+ col("color", "Strobe Color", [1.0, 1.0, 1.0, 1.0]),
+ f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%"),
+ fs("duration", "Strobe Duration (secs)", 0.05, (0.0, 30.0), (0.0, 1.0), "", 2),
+ fs("period", "Strobe Period (secs)", 0.5, (0.0, 30.0), (0.0, 2.0), "", 2),
+ ],
+ ),
+ video(
+ "noise",
+ "Noise",
+ NOISE,
+ vec![f("amount", "Amount of Noise", 0.0, 0.0, 100.0, "%"), b("color", "Use Color Noise", true), b("clip", "Clipping", true)],
+ ),
+ video("median", "Median", NOISE, vec![fs("radius", "Radius", 0.0, (0.0, 100.0), (0.0, 20.0), "", 0)]),
+ video(
+ "crop",
+ "Crop",
+ TRANSFORM,
+ vec![
+ f("left", "Left", 0.0, 0.0, 100.0, "%"),
+ f("top", "Top", 0.0, 0.0, 100.0, "%"),
+ f("right", "Right", 0.0, 0.0, 100.0, "%"),
+ f("bottom", "Bottom", 0.0, 0.0, 100.0, "%"),
+ b("zoom", "Zoom", false),
+ fs("feather", "Edge Feather", 0.0, (0.0, 1000.0), (0.0, 100.0), "", 0),
+ ],
+ ),
+ video("horizontal_flip", "Horizontal Flip", TRANSFORM, vec![]),
+ video("vertical_flip", "Vertical Flip", TRANSFORM, vec![]),
+ video("edge_feather", "Edge Feather", TRANSFORM, vec![fs("amount", "Amount", 0.0, (0.0, 100.0), (0.0, 100.0), "", 0)]),
+ video(
+ "transform",
+ "Transform",
+ DISTORT,
+ vec![
+ pt("anchor", "Anchor Point", f64::NAN, f64::NAN),
+ pt("position", "Position", f64::NAN, f64::NAN),
+ b("uniform_scale", "Uniform Scale", true),
+ fs("scale_height", "Scale Height", 100.0, (0.0, 10000.0), (0.0, 600.0), "", 1),
+ fs("scale_width", "Scale Width", 100.0, (0.0, 10000.0), (0.0, 600.0), "", 1),
+ f("skew", "Skew", 0.0, -70.0, 70.0, ""),
+ ang("skew_axis", "Skew Axis", 0.0),
+ ang("rotation", "Rotation", 0.0),
+ f("opacity", "Opacity", 100.0, 0.0, 100.0, ""),
+ f("shutter_angle", "Shutter Angle", 0.0, 0.0, 360.0, ""),
+ ],
+ ),
+ video("mirror", "Mirror", DISTORT, vec![pt("center", "Reflection Center", f64::NAN, f64::NAN), ang("angle", "Reflection Angle", 0.0)]),
+ video("offset", "Offset", DISTORT, vec![pt("shift", "Shift Center To", f64::NAN, f64::NAN), f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%")]),
+ video(
+ "lens_distortion",
+ "Lens Distortion",
+ DISTORT,
+ vec![
+ f("curvature", "Curvature", 0.0, -100.0, 100.0, ""),
+ f("v_decentering", "Vertical Decentering", 0.0, -100.0, 100.0, ""),
+ f("h_decentering", "Horizontal Decentering", 0.0, -100.0, 100.0, ""),
+ ],
+ ),
+ video(
+ "twirl",
+ "Twirl",
+ DISTORT,
+ vec![
+ ang("angle", "Angle", 50.0),
+ fs("radius", "Twirl Radius", 30.0, (0.0, 100.0), (0.0, 100.0), "", 1),
+ pt("center", "Twirl Center", f64::NAN, f64::NAN),
+ ],
+ ),
+ video(
+ "wave_warp",
+ "Wave Warp",
+ DISTORT,
+ vec![
+ fs("height", "Wave Height", 10.0, (-4000.0, 4000.0), (-100.0, 100.0), "", 0),
+ fs("width", "Wave Width", 40.0, (1.0, 4000.0), (1.0, 400.0), "", 0),
+ ang("direction", "Direction", 90.0),
+ fs("speed", "Wave Speed", 1.0, (-100.0, 100.0), (-10.0, 10.0), "", 1),
+ ],
+ ),
+ video(
+ "basic_3d",
+ "Basic 3D",
+ PERSPECTIVE,
+ vec![ang("swivel", "Swivel", 0.0), ang("tilt", "Tilt", 0.0), fs("distance", "Distance to Image", 0.0, (-10000.0, 10000.0), (-100.0, 100.0), "", 1)],
+ ),
+ video(
+ "drop_shadow",
+ "Drop Shadow",
+ PERSPECTIVE,
+ vec![
+ col("color", "Shadow Color", [0.0, 0.0, 0.0, 1.0]),
+ f("opacity", "Opacity", 50.0, 0.0, 100.0, "%"),
+ ang("direction", "Direction", 135.0),
+ fs("distance", "Distance", 5.0, (0.0, 4000.0), (0.0, 120.0), "", 1),
+ fs("softness", "Softness", 0.0, (0.0, 1000.0), (0.0, 250.0), "", 1),
+ b("only", "Shadow Only", false),
+ ],
+ ),
+ video(
+ "bevel_alpha",
+ "Bevel Alpha",
+ PERSPECTIVE,
+ vec![
+ fs("thickness", "Edge Thickness", 2.0, (0.0, 200.0), (0.0, 10.0), "", 1),
+ ang("angle", "Light Angle", -60.0),
+ col("color", "Light Color", [1.0, 1.0, 1.0, 1.0]),
+ f("intensity", "Light Intensity", 40.0, 0.0, 100.0, ""),
+ ],
+ ),
+ video(
+ "ultra_key",
+ "Ultra Key",
+ KEYING,
+ vec![
+ col("key_color", "Key Color", [0.0, 0.8, 0.2, 1.0]),
+ ch("output", "Output", &["Composite", "Alpha Channel", "Color Channel"], 0),
+ ch("setting", "Setting", &["Default", "Relaxed", "Aggressive", "Custom"], 0),
+ grp(f("transparency", "Transparency", 45.0, 0.0, 100.0, ""), "Matte Generation"),
+ grp(f("highlight", "Highlight", 10.0, 0.0, 100.0, ""), "Matte Generation"),
+ grp(f("shadow", "Shadow", 50.0, 0.0, 100.0, ""), "Matte Generation"),
+ grp(f("tolerance", "Tolerance", 50.0, 0.0, 100.0, ""), "Matte Generation"),
+ grp(f("pedestal", "Pedestal", 10.0, 0.0, 100.0, ""), "Matte Generation"),
+ grp(f("choke", "Choke", 0.0, 0.0, 100.0, ""), "Matte Cleanup"),
+ grp(f("soften", "Soften", 0.0, 0.0, 100.0, ""), "Matte Cleanup"),
+ grp(f("spill", "Spill", 50.0, 0.0, 100.0, ""), "Spill Suppression"),
+ ],
+ ),
+ video(
+ "track_matte",
+ "Track Matte Key",
+ KEYING,
+ vec![
+ ch("matte", "Matte", &["None", "Video 1", "Video 2", "Video 3", "Video 4"], 0),
+ ch("composite", "Composite Using", &["Matte Alpha", "Matte Luma"], 0),
+ b("reverse", "Reverse", false),
+ ],
+ ),
+ video(
+ "color_key",
+ "Color Key",
+ KEYING,
+ vec![
+ col("color", "Key Color", [0.0, 0.0, 1.0, 1.0]),
+ fs("tolerance", "Color Tolerance", 0.0, (0.0, 255.0), (0.0, 255.0), "", 0),
+ fs("thin", "Edge Thin", 0.0, (-5.0, 5.0), (-5.0, 5.0), "", 0),
+ fs("feather", "Edge Feather", 0.0, (0.0, 50.0), (0.0, 50.0), "", 1),
+ ],
+ ),
+ video("luma_key", "Luma Key", KEYING, vec![f("threshold", "Threshold", 0.0, 0.0, 100.0, "%"), f("cutoff", "Cutoff", 0.0, 0.0, 100.0, "%")]),
+ video(
+ "four_color_gradient",
+ "4-Color Gradient",
+ GENERATE,
+ vec![
+ col("c1", "Color 1", [1.0, 1.0, 0.0, 1.0]),
+ col("c2", "Color 2", [0.0, 1.0, 0.0, 1.0]),
+ col("c3", "Color 3", [1.0, 0.0, 1.0, 1.0]),
+ col("c4", "Color 4", [0.0, 0.0, 1.0, 1.0]),
+ f("blend", "Blend", 100.0, 1.0, 1000.0, ""),
+ f("opacity", "Opacity", 100.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "ramp",
+ "Ramp",
+ GENERATE,
+ vec![
+ pt("start", "Start of Ramp", f64::NAN, 0.0),
+ col("start_color", "Start Color", [0.0, 0.0, 0.0, 1.0]),
+ pt("end", "End of Ramp", f64::NAN, f64::NAN),
+ col("end_color", "End Color", [1.0, 1.0, 1.0, 1.0]),
+ ch("shape", "Ramp Shape", &["Linear Ramp", "Radial Ramp"], 0),
+ f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "circle",
+ "Circle",
+ GENERATE,
+ vec![
+ pt("center", "Center", f64::NAN, f64::NAN),
+ fs("radius", "Radius", 75.0, (0.0, 4000.0), (0.0, 400.0), "", 1),
+ col("color", "Color", [1.0, 1.0, 1.0, 1.0]),
+ f("opacity", "Opacity", 100.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "grid",
+ "Grid",
+ GENERATE,
+ vec![
+ fs("size", "Width", 60.0, (1.0, 4000.0), (1.0, 400.0), "", 0),
+ fs("border", "Border", 2.0, (0.0, 100.0), (0.0, 20.0), "", 1),
+ col("color", "Color", [1.0, 1.0, 1.0, 1.0]),
+ f("opacity", "Opacity", 100.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "lens_flare",
+ "Lens Flare",
+ GENERATE,
+ vec![
+ pt("center", "Flare Center", f64::NAN, f64::NAN),
+ f("brightness", "Flare Brightness", 100.0, 0.0, 300.0, "%"),
+ f("blend", "Blend With Original", 0.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "timecode",
+ "Timecode",
+ VIDEO,
+ vec![
+ pt("position", "Position", f64::NAN, f64::NAN),
+ fs("size", "Size", 15.0, (1.0, 100.0), (1.0, 50.0), "%", 1),
+ f("opacity", "Opacity", 100.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ video(
+ "clip_name",
+ "Clip Name",
+ VIDEO,
+ vec![pt("position", "Position", f64::NAN, f64::NAN), fs("size", "Size", 15.0, (1.0, 100.0), (1.0, 50.0), "%", 1)],
+ ),
+ video("simple_text", "Simple Text", VIDEO, vec![]),
+ // ---- video transitions ----
+ vtrans("cross_dissolve", "Cross Dissolve", DISSOLVE, vec![]),
+ vtrans("additive_dissolve", "Additive Dissolve", DISSOLVE, vec![]),
+ vtrans("dip_to_black", "Dip to Black", DISSOLVE, vec![]),
+ vtrans("dip_to_white", "Dip to White", DISSOLVE, vec![]),
+ vtrans("film_dissolve", "Film Dissolve", DISSOLVE, vec![]),
+ vtrans("morph_cut", "Morph Cut", DISSOLVE, vec![]),
+ vtrans("non_additive_dissolve", "Non-Additive Dissolve", DISSOLVE, vec![]),
+ vtrans("iris_box", "Iris Box", IRIS, vec![]),
+ vtrans("iris_cross", "Iris Cross", IRIS, vec![]),
+ vtrans("iris_diamond", "Iris Diamond", IRIS, vec![]),
+ vtrans("iris_round", "Iris Round", IRIS, vec![]),
+ vtrans("push", "Push", SLIDE, vec![ch("direction", "Direction", DIR_OPTS, 3)]),
+ vtrans("slide", "Slide", SLIDE, vec![ch("direction", "Direction", DIR_OPTS, 3)]),
+ vtrans("split", "Split", SLIDE, vec![]),
+ vtrans("center_split", "Center Split", SLIDE, vec![]),
+ vtrans("band_slide", "Band Slide", SLIDE, vec![]),
+ vtrans("whip", "Whip", SLIDE, vec![ch("direction", "Direction", DIR_OPTS, 3)]),
+ vtrans("wipe", "Wipe", WIPE, vec![ch("direction", "Direction", DIR_OPTS, 3)]),
+ vtrans("barn_doors", "Barn Doors", WIPE, vec![]),
+ vtrans("clock_wipe", "Clock Wipe", WIPE, vec![]),
+ vtrans("gradient_wipe", "Gradient Wipe", WIPE, vec![f("softness", "Softness", 10.0, 0.0, 100.0, "")]),
+ vtrans("inset", "Inset", WIPE, vec![]),
+ vtrans("radial_wipe", "Radial Wipe", WIPE, vec![]),
+ vtrans("venetian_blinds", "Venetian Blinds", WIPE, vec![]),
+ vtrans("checker_wipe", "Checker Wipe", WIPE, vec![]),
+ vtrans("cross_zoom", "Cross Zoom", ZOOM, vec![]),
+ vtrans("page_peel", "Page Peel", PAGE_PEEL, vec![]),
+ vtrans("page_turn", "Page Turn", PAGE_PEEL, vec![]),
+ vtrans("cube_spin", "Cube Spin", MOTION3D, vec![]),
+ vtrans("flip_over", "Flip Over", MOTION3D, vec![]),
+ // ---- audio effects ----
+ audio("amplify", "Amplify", A_AMP, vec![fs("gain", "Gain", 0.0, (-96.0, 48.0), (-24.0, 24.0), "dB", 1)]),
+ audio(
+ "dynamics",
+ "Dynamics Processing",
+ A_AMP,
+ vec![
+ fs("threshold", "Threshold", -20.0, (-60.0, 0.0), (-60.0, 0.0), "dB", 1),
+ fs("ratio", "Ratio", 4.0, (1.0, 30.0), (1.0, 30.0), ":1", 1),
+ fs("attack", "Attack", 10.0, (0.1, 500.0), (0.1, 500.0), "ms", 1),
+ fs("release", "Release", 100.0, (1.0, 5000.0), (1.0, 5000.0), "ms", 0),
+ ],
+ ),
+ audio(
+ "hard_limiter",
+ "Hard Limiter",
+ A_AMP,
+ vec![
+ fs("max", "Maximum Amplitude", -0.1, (-30.0, 0.0), (-30.0, 0.0), "dB", 1),
+ fs("boost", "Input Boost", 0.0, (-30.0, 30.0), (-30.0, 30.0), "dB", 1),
+ fs("lookahead", "Look-Ahead Time", 7.0, (0.0, 30.0), (0.0, 30.0), "ms", 1),
+ fs("release", "Release Time", 100.0, (1.0, 1000.0), (1.0, 1000.0), "ms", 0),
+ ],
+ ),
+ audio("multiband_compressor", "Multiband Compressor", A_AMP, vec![]),
+ audio("channel_mixer_a", "Channel Mixer", A_AMP, vec![]),
+ audio(
+ "delay",
+ "Delay",
+ A_DELAY,
+ vec![
+ fs("delay", "Delay", 1.0, (0.0, 2.0), (0.0, 2.0), "s", 2),
+ f("feedback", "Feedback", 0.0, 0.0, 100.0, "%"),
+ f("mix", "Mix", 50.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ audio("analog_delay", "Analog Delay", A_DELAY, vec![]),
+ audio(
+ "parametric_eq",
+ "Parametric Equalizer",
+ A_FILTER,
+ vec![
+ fs("low_freq", "Low Frequency", 100.0, (20.0, 20000.0), (20.0, 1000.0), "Hz", 0),
+ fs("low_gain", "Low Gain", 0.0, (-24.0, 24.0), (-24.0, 24.0), "dB", 1),
+ fs("mid_freq", "Mid Frequency", 1000.0, (20.0, 20000.0), (200.0, 8000.0), "Hz", 0),
+ fs("mid_gain", "Mid Gain", 0.0, (-24.0, 24.0), (-24.0, 24.0), "dB", 1),
+ fs("mid_q", "Mid Q", 1.0, (0.1, 20.0), (0.1, 10.0), "", 2),
+ fs("high_freq", "High Frequency", 8000.0, (20.0, 20000.0), (2000.0, 20000.0), "Hz", 0),
+ fs("high_gain", "High Gain", 0.0, (-24.0, 24.0), (-24.0, 24.0), "dB", 1),
+ ],
+ ),
+ audio("highpass", "Highpass", A_FILTER, vec![fs("cutoff", "Cutoff", 80.0, (20.0, 20000.0), (20.0, 2000.0), "Hz", 0)]),
+ audio("lowpass", "Lowpass", A_FILTER, vec![fs("cutoff", "Cutoff", 8000.0, (20.0, 20000.0), (500.0, 20000.0), "Hz", 0)]),
+ audio(
+ "bandpass",
+ "Bandpass",
+ A_FILTER,
+ vec![fs("center", "Center", 1000.0, (20.0, 20000.0), (20.0, 20000.0), "Hz", 0), fs("q", "Q", 1.0, (0.1, 20.0), (0.1, 20.0), "", 2)],
+ ),
+ audio("notch", "Notch Filter", A_FILTER, vec![]),
+ audio("simple_eq", "Simple Parametric EQ", A_FILTER, vec![]),
+ audio("graphic_eq", "Graphic Equalizer (10 Bands)", A_FILTER, vec![]),
+ audio("denoise", "DeNoise", A_NOISE, vec![f("amount", "Amount", 40.0, 0.0, 100.0, "%")]),
+ audio("dehummer", "DeHummer", A_NOISE, vec![ch("freq", "Frequency", &["50 Hz", "60 Hz"], 1), f("gain", "Gain", -40.0, -80.0, 0.0, "dB")]),
+ audio("declicker", "Automatic Click Remover", A_NOISE, vec![]),
+ audio("dereverb", "DeReverb", A_NOISE, vec![]),
+ audio(
+ "studio_reverb",
+ "Studio Reverb",
+ A_REVERB,
+ vec![
+ f("room", "Room Size", 50.0, 0.0, 100.0, "%"),
+ f("decay", "Decay", 50.0, 0.0, 100.0, "%"),
+ f("damping", "High Frequency Damping", 50.0, 0.0, 100.0, "%"),
+ f("dry", "Dry", 90.0, 0.0, 100.0, "%"),
+ f("wet", "Wet", 35.0, 0.0, 100.0, "%"),
+ ],
+ ),
+ audio("convolution_reverb", "Convolution Reverb", A_REVERB, vec![]),
+ audio("surround_reverb", "Surround Reverb", A_REVERB, vec![]),
+ audio("loudness_radar", "Loudness Meter", A_SPECIAL, vec![]),
+ audio("invert_a", "Invert", A_SPECIAL, vec![]),
+ audio(
+ "pitch_shifter",
+ "Pitch Shifter",
+ A_TIME,
+ vec![fs("semitones", "Semi-tones", 0.0, (-12.0, 12.0), (-12.0, 12.0), "", 0), fs("cents", "Cents", 0.0, (-100.0, 100.0), (-100.0, 100.0), "", 0)],
+ ),
+ EffectDef {
+ id: "constant_power",
+ name: "Constant Power",
+ kind: EffectKind::AudioTransition,
+ category: A_TRANS,
+ params: vec![],
+ intrinsic: false,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ EffectDef {
+ id: "constant_gain",
+ name: "Constant Gain",
+ kind: EffectKind::AudioTransition,
+ category: A_TRANS,
+ params: vec![],
+ intrinsic: false,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ EffectDef {
+ id: "exponential_fade",
+ name: "Exponential Fade",
+ kind: EffectKind::AudioTransition,
+ category: A_TRANS,
+ params: vec![],
+ intrinsic: false,
+ accelerated: false,
+ float32: true,
+ yuv: false,
+ },
+ ];
+ // YUV badge for the colour/intrinsic set
+ for e in &mut v {
+ if matches!(e.id, "brightness_contrast" | "proc_amp" | "crop" | "gaussian_blur" | "tint" | "lumetri") {
+ e.yuv = true;
+ }
+ }
+ v
+}
+
+pub fn effect_defs() -> &'static [EffectDef] {
+ static DEFS: OnceLock<Vec<EffectDef>> = OnceLock::new();
+ DEFS.get_or_init(build_effects)
+}
+
+pub fn find_effect(id: &str) -> Option<&'static EffectDef> {
+ effect_defs().iter().find(|e| e.id == id)
+}
+
+/// Case-insensitive lookup by id or display name.
+pub fn find_effect_by_name(name: &str) -> Option<&'static EffectDef> {
+ let n = name.to_ascii_lowercase();
+ effect_defs().iter().find(|e| e.id == n || e.name.to_ascii_lowercase() == n)
+}
+
+/// Intrinsic video effects every video track item carries (Motion, Opacity, Time Remapping).
+pub fn intrinsic_video() -> Vec<EffectInstance> {
+ ["motion", "opacity", "time_remap"].iter().filter_map(|id| find_effect(id)).map(EffectDef::instance).collect()
+}
+
+pub fn intrinsic_audio() -> Vec<EffectInstance> {
+ ["volume", "channel_volume", "panner"].iter().filter_map(|id| find_effect(id)).map(EffectDef::instance).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unique_ids_and_defaults() {
+ let mut ids = std::collections::HashSet::new();
+ for e in effect_defs() {
+ assert!(ids.insert(e.id), "duplicate {}", e.id);
+ let inst = e.instance();
+ assert_eq!(inst.params.len(), e.params.len());
+ }
+ assert!(effect_defs().len() > 90);
+ assert_eq!(find_effect_by_name("Gaussian Blur").unwrap().id, "gaussian_blur");
+ assert_eq!(intrinsic_video().len(), 3);
+ }
+}
diff --git a/crates/project/src/keyframe.rs b/crates/project/src/keyframe.rs
new file mode 100644
index 000000000..1d9b0662a
--- /dev/null
+++ b/crates/project/src/keyframe.rs
@@ -0,0 +1,334 @@
+//! Keyframed parameters.
+//!
+//! A parameter is a static value or a list of keyframes (clip-relative ticks). Interpolation per
+//! keyframe governs the segment leaving it: Linear, Hold, Bezier (with influence/speed handles),
+//! Auto Bezier, Continuous Bezier, Ease In/Out (Bezier presets) — Premiere's temporal set.
+
+use filmcraft_geom::Vec2;
+use filmcraft_time::Tick;
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum ParamValue {
+ Float(f64),
+ Vec2(Vec2),
+ Color([f32; 4]),
+ Bool(bool),
+ Choice(u32),
+ Text(String),
+}
+
+impl ParamValue {
+ pub fn as_f64(&self) -> Option<f64> {
+ match self {
+ ParamValue::Float(v) => Some(*v),
+ ParamValue::Choice(c) => Some(*c as f64),
+ ParamValue::Bool(b) => Some(*b as u8 as f64),
+ _ => None,
+ }
+ }
+ pub fn as_vec2(&self) -> Option<Vec2> {
+ match self {
+ ParamValue::Vec2(v) => Some(*v),
+ _ => None,
+ }
+ }
+ pub fn as_color(&self) -> Option<[f32; 4]> {
+ match self {
+ ParamValue::Color(c) => Some(*c),
+ _ => None,
+ }
+ }
+ pub fn as_bool(&self) -> Option<bool> {
+ match self {
+ ParamValue::Bool(b) => Some(*b),
+ _ => None,
+ }
+ }
+ /// Whether values of this kind can be interpolated (others hold).
+ pub fn interpolates(&self) -> bool {
+ matches!(self, ParamValue::Float(_) | ParamValue::Vec2(_) | ParamValue::Color(_))
+ }
+ fn components(&self) -> Vec<f64> {
+ match self {
+ ParamValue::Float(v) => vec![*v],
+ ParamValue::Vec2(v) => vec![v.x, v.y],
+ ParamValue::Color(c) => c.iter().map(|&x| x as f64).collect(),
+ _ => vec![],
+ }
+ }
+ fn from_components(template: &ParamValue, c: &[f64]) -> ParamValue {
+ match template {
+ ParamValue::Float(_) => ParamValue::Float(c[0]),
+ ParamValue::Vec2(_) => ParamValue::Vec2(Vec2::new(c[0], c[1])),
+ ParamValue::Color(_) => ParamValue::Color([c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32]),
+ other => other.clone(),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Interpolation {
+ #[default]
+ Linear,
+ Hold,
+ Bezier,
+ AutoBezier,
+ ContinuousBezier,
+ EaseIn,
+ EaseOut,
+}
+
+impl Interpolation {
+ pub const ALL: [Interpolation; 7] = [
+ Interpolation::Linear,
+ Interpolation::Bezier,
+ Interpolation::AutoBezier,
+ Interpolation::ContinuousBezier,
+ Interpolation::Hold,
+ Interpolation::EaseIn,
+ Interpolation::EaseOut,
+ ];
+ pub fn label(self) -> &'static str {
+ match self {
+ Interpolation::Linear => "Linear",
+ Interpolation::Hold => "Hold",
+ Interpolation::Bezier => "Bezier",
+ Interpolation::AutoBezier => "Auto Bezier",
+ Interpolation::ContinuousBezier => "Continuous Bezier",
+ Interpolation::EaseIn => "Ease In",
+ Interpolation::EaseOut => "Ease Out",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Keyframe {
+ /// Time relative to the start of the track item (clip time).
+ pub time: Tick,
+ pub value: ParamValue,
+ /// Interpolation of the segment leaving this keyframe.
+ pub interp: Interpolation,
+ /// Temporal ease: influence (0..1) of the outgoing/incoming handles.
+ #[serde(default = "default_influence")]
+ pub out_influence: f64,
+ #[serde(default = "default_influence")]
+ pub in_influence: f64,
+}
+
+fn default_influence() -> f64 {
+ 1.0 / 3.0
+}
+
+impl Keyframe {
+ pub fn new(time: Tick, value: ParamValue) -> Self {
+ Self { time, value, interp: Interpolation::Linear, out_influence: default_influence(), in_influence: default_influence() }
+ }
+}
+
+/// A (possibly animated) parameter.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Param {
+ pub value: ParamValue,
+ /// Sorted by time. Empty = static.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub keyframes: Vec<Keyframe>,
+}
+
+impl Param {
+ pub fn new(value: ParamValue) -> Self {
+ Self { value, keyframes: Vec::new() }
+ }
+ pub fn is_animated(&self) -> bool {
+ !self.keyframes.is_empty()
+ }
+
+ /// Set a value at `t`: updates the static value, or adds/replaces a keyframe when animated.
+ pub fn set_at(&mut self, t: Tick, value: ParamValue) {
+ if self.keyframes.is_empty() {
+ self.value = value;
+ return;
+ }
+ match self.keyframes.binary_search_by_key(&t, |k| k.time) {
+ Ok(i) => self.keyframes[i].value = value,
+ Err(i) => {
+ let interp = self.keyframes.get(i.saturating_sub(1)).map(|k| k.interp).unwrap_or_default();
+ let mut k = Keyframe::new(t, value);
+ k.interp = interp;
+ self.keyframes.insert(i, k);
+ }
+ }
+ }
+
+ /// Toggle animation (the stopwatch): on → one keyframe at `t` with the current value; off → keep value at `t`.
+ pub fn toggle_animation(&mut self, t: Tick) {
+ if self.keyframes.is_empty() {
+ self.keyframes.push(Keyframe::new(t, self.value.clone()));
+ } else {
+ self.value = self.value_at(t);
+ self.keyframes.clear();
+ }
+ }
+
+ pub fn add_keyframe(&mut self, t: Tick) {
+ let v = self.value_at(t);
+ if self.keyframes.is_empty() {
+ self.value = v.clone();
+ }
+ self.set_at_force(t, v);
+ }
+
+ fn set_at_force(&mut self, t: Tick, value: ParamValue) {
+ match self.keyframes.binary_search_by_key(&t, |k| k.time) {
+ Ok(i) => self.keyframes[i].value = value,
+ Err(i) => self.keyframes.insert(i, Keyframe::new(t, value)),
+ }
+ }
+
+ pub fn remove_keyframe_at(&mut self, t: Tick) -> bool {
+ if let Ok(i) = self.keyframes.binary_search_by_key(&t, |k| k.time) {
+ let removed = self.keyframes.remove(i);
+ if self.keyframes.is_empty() {
+ self.value = removed.value;
+ }
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Evaluate at clip time `t`.
+ pub fn value_at(&self, t: Tick) -> ParamValue {
+ let k = &self.keyframes;
+ if k.is_empty() {
+ return self.value.clone();
+ }
+ if t <= k[0].time {
+ return k[0].value.clone();
+ }
+ let last = &k[k.len() - 1];
+ if t >= last.time {
+ return last.value.clone();
+ }
+ let i = match k.binary_search_by_key(&t, |kf| kf.time) {
+ Ok(i) => return k[i].value.clone(),
+ Err(i) => i - 1,
+ };
+ let (a, b) = (&k[i], &k[i + 1]);
+ if a.interp == Interpolation::Hold || !a.value.interpolates() {
+ return a.value.clone();
+ }
+ let span = (b.time - a.time).0 as f64;
+ let u = (t - a.time).0 as f64 / span;
+ let e = ease(a, b, u);
+ let ca = a.value.components();
+ let cb = b.value.components();
+ let c: Vec<f64> = ca.iter().zip(&cb).map(|(x, y)| x + (y - x) * e).collect();
+ ParamValue::from_components(&a.value, &c)
+ }
+
+ pub fn f64_at(&self, t: Tick) -> f64 {
+ self.value_at(t).as_f64().unwrap_or(0.0)
+ }
+ pub fn vec2_at(&self, t: Tick) -> Vec2 {
+ self.value_at(t).as_vec2().unwrap_or_default()
+ }
+
+ /// Previous/next keyframe times for navigation.
+ pub fn prev_keyframe(&self, t: Tick) -> Option<Tick> {
+ self.keyframes.iter().rev().map(|k| k.time).find(|&k| k < t)
+ }
+ pub fn next_keyframe(&self, t: Tick) -> Option<Tick> {
+ self.keyframes.iter().map(|k| k.time).find(|&k| k > t)
+ }
+}
+
+/// Temporal easing for u∈[0,1] between two keyframes (1D cubic Bezier in time/value space).
+fn ease(a: &Keyframe, b: &Keyframe, u: f64) -> f64 {
+ let out_ease = matches!(a.interp, Interpolation::Bezier | Interpolation::AutoBezier | Interpolation::ContinuousBezier | Interpolation::EaseOut);
+ let in_ease = matches!(b.interp, Interpolation::Bezier | Interpolation::AutoBezier | Interpolation::ContinuousBezier | Interpolation::EaseIn)
+ || matches!(a.interp, Interpolation::Bezier | Interpolation::ContinuousBezier);
+ if !out_ease && !in_ease {
+ return u;
+ }
+ // Control points in normalized (time, value) space; flat handles = ease (velocity 0).
+ let x1 = if out_ease { a.out_influence.clamp(0.01, 1.0) } else { 1.0 / 3.0 };
+ let y1 = if out_ease { 0.0 } else { 1.0 / 3.0 };
+ let x2 = if in_ease { 1.0 - b.in_influence.clamp(0.01, 1.0) } else { 2.0 / 3.0 };
+ let y2 = if in_ease { 1.0 } else { 2.0 / 3.0 };
+ cubic_bezier_y_for_x(x1, y1, x2, y2, u)
+}
+
+/// Solve a CSS-style cubic-bezier(x1,y1,x2,y2) for y at x (Newton + bisection).
+pub fn cubic_bezier_y_for_x(x1: f64, y1: f64, x2: f64, y2: f64, x: f64) -> f64 {
+ let bx = |s: f64| 3.0 * (1.0 - s) * (1.0 - s) * s * x1 + 3.0 * (1.0 - s) * s * s * x2 + s * s * s;
+ let by = |s: f64| 3.0 * (1.0 - s) * (1.0 - s) * s * y1 + 3.0 * (1.0 - s) * s * s * y2 + s * s * s;
+ let dbx = |s: f64| 3.0 * (1.0 - s) * (1.0 - s) * x1 + 6.0 * (1.0 - s) * s * (x2 - x1) + 3.0 * s * s * (1.0 - x2);
+ let mut s = x;
+ for _ in 0..8 {
+ let d = dbx(s);
+ if d.abs() < 1e-9 {
+ break;
+ }
+ let ns = s - (bx(s) - x) / d;
+ if !(0.0..=1.0).contains(&ns) {
+ break;
+ }
+ s = ns;
+ }
+ if (bx(s) - x).abs() > 1e-7 {
+ let (mut lo, mut hi) = (0.0, 1.0);
+ for _ in 0..60 {
+ s = (lo + hi) / 2.0;
+ if bx(s) < x { lo = s } else { hi = s }
+ }
+ }
+ by(s)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn linear_and_hold() {
+ let mut p = Param::new(ParamValue::Float(0.0));
+ p.toggle_animation(Tick(0));
+ p.set_at(Tick(100), ParamValue::Float(10.0));
+ assert_eq!(p.f64_at(Tick(50)), 5.0);
+ assert_eq!(p.f64_at(Tick(-5)), 0.0);
+ assert_eq!(p.f64_at(Tick(500)), 10.0);
+ p.keyframes[0].interp = Interpolation::Hold;
+ assert_eq!(p.f64_at(Tick(99)), 0.0);
+ }
+
+ #[test]
+ fn bezier_eases() {
+ let mut p = Param::new(ParamValue::Vec2(Vec2::new(0.0, 0.0)));
+ p.toggle_animation(Tick(0));
+ p.set_at(Tick(1000), ParamValue::Vec2(Vec2::new(100.0, 50.0)));
+ p.keyframes[0].interp = Interpolation::Bezier;
+ p.keyframes[1].interp = Interpolation::Bezier;
+ let early = p.vec2_at(Tick(100)).x;
+ let mid = p.vec2_at(Tick(500)).x;
+ assert!(early < 10.0, "ease-in start should be slow: {early}");
+ assert!((mid - 50.0).abs() < 1.0, "symmetric ease midpoint: {mid}");
+ // monotonic
+ let mut last = -1.0;
+ for i in 0..=100 {
+ let v = p.vec2_at(Tick(i * 10)).x;
+ assert!(v >= last - 1e-9);
+ last = v;
+ }
+ }
+
+ #[test]
+ fn toggle_off_keeps_value() {
+ let mut p = Param::new(ParamValue::Float(1.0));
+ p.toggle_animation(Tick(0));
+ p.set_at(Tick(10), ParamValue::Float(3.0));
+ p.toggle_animation(Tick(5));
+ assert!(!p.is_animated());
+ assert_eq!(p.value, ParamValue::Float(2.0));
+ }
+}
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
new file mode 100644
index 000000000..43a06a327
--- /dev/null
+++ b/crates/project/src/lib.rs
@@ -0,0 +1,939 @@
+//! The FilmCraft document model.
+//!
+//! A [`Project`] owns a tree of bins and a flat map of [`ProjectItem`]s (media clips, sequences,
+//! synthetic items). A [`Sequence`] has video and audio [`Track`]s holding [`TrackItem`]s (clip
+//! instances) and [`Transition`]s. Everything is plain serde data; the engine wraps the project in an
+//! `Arc` and edits copy-on-write, so undo snapshots and background readers are free.
+//!
+//! Time: timeline positions are sequence ticks; `source_in` is media time.
+
+pub mod effect;
+pub mod keyframe;
+
+use std::collections::BTreeMap;
+
+use filmcraft_geom::Vec2;
+use filmcraft_media::{Generator, MediaInfo};
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick, TimeRange};
+use serde::{Deserialize, Serialize};
+
+pub use effect::{EffectDef, EffectInstance, EffectKind, ParamDef, ParamKind, effect_defs, find_effect};
+pub use keyframe::{Interpolation, Keyframe, Param, ParamValue};
+
+macro_rules! id_type {
+ ($name:ident) => {
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+ #[serde(transparent)]
+ pub struct $name(pub u64);
+ };
+}
+id_type!(ItemId);
+id_type!(BinId);
+id_type!(TrackId);
+id_type!(ClipId);
+id_type!(TransitionId);
+id_type!(MarkerId);
+
+/// Premiere-style label colours (names from the Label menu; values are our own).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Label {
+ Violet,
+ Iris,
+ Caribbean,
+ Lavender,
+ Cerulean,
+ Forest,
+ Rose,
+ Mango,
+ Purple,
+ Blue,
+ Teal,
+ Magenta,
+ Tan,
+ Green,
+ Brown,
+ Yellow,
+}
+
+impl Label {
+ pub const ALL: [Label; 16] = [
+ Label::Violet,
+ Label::Iris,
+ Label::Caribbean,
+ Label::Lavender,
+ Label::Cerulean,
+ Label::Forest,
+ Label::Rose,
+ Label::Mango,
+ Label::Purple,
+ Label::Blue,
+ Label::Teal,
+ Label::Magenta,
+ Label::Tan,
+ Label::Green,
+ Label::Brown,
+ Label::Yellow,
+ ];
+ pub fn name(self) -> &'static str {
+ match self {
+ Label::Violet => "Violet",
+ Label::Iris => "Iris",
+ Label::Caribbean => "Caribbean",
+ Label::Lavender => "Lavender",
+ Label::Cerulean => "Cerulean",
+ Label::Forest => "Forest",
+ Label::Rose => "Rose",
+ Label::Mango => "Mango",
+ Label::Purple => "Purple",
+ Label::Blue => "Blue",
+ Label::Teal => "Teal",
+ Label::Magenta => "Magenta",
+ Label::Tan => "Tan",
+ Label::Green => "Green",
+ Label::Brown => "Brown",
+ Label::Yellow => "Yellow",
+ }
+ }
+ pub fn rgb(self) -> [u8; 3] {
+ match self {
+ Label::Violet => [166, 137, 219],
+ Label::Iris => [138, 151, 230],
+ Label::Caribbean => [37, 185, 148],
+ Label::Lavender => [224, 143, 222],
+ Label::Cerulean => [55, 161, 209],
+ Label::Forest => [96, 163, 57],
+ Label::Rose => [225, 92, 124],
+ Label::Mango => [237, 150, 58],
+ Label::Purple => [146, 83, 196],
+ Label::Blue => [60, 104, 229],
+ Label::Teal => [36, 145, 157],
+ Label::Magenta => [224, 71, 172],
+ Label::Tan => [199, 167, 124],
+ Label::Green => [78, 173, 72],
+ Label::Brown => [150, 97, 58],
+ Label::Yellow => [228, 208, 66],
+ }
+ }
+ pub fn from_name(s: &str) -> Option<Label> {
+ Self::ALL.iter().copied().find(|l| l.name().eq_ignore_ascii_case(s))
+ }
+}
+
+/// Where an item's pixels/samples come from.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum MediaRef {
+ /// A file on disk (native) or a named blob (web).
+ File { path: String },
+ /// A synthetic generator (Bars and Tone, Color Matte, demo footage…).
+ Generator(Generator),
+}
+
+/// Overrides applied when interpreting footage (Modify ▸ Interpret Footage).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Interpretation {
+ pub frame_rate: Option<FrameRate>,
+ pub par: Option<(u32, u32)>,
+ pub ignore_alpha: bool,
+ pub invert_alpha: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct MediaClip {
+ pub media: MediaRef,
+ pub info: MediaInfo,
+ pub interpret: Interpretation,
+ /// Source in/out marks (media time).
+ pub mark_in: Option<Tick>,
+ pub mark_out: Option<Tick>,
+ pub markers: Vec<Marker>,
+ pub offline: bool,
+ /// Proxy media, if attached.
+ pub proxy: Option<MediaRef>,
+}
+
+impl MediaClip {
+ pub fn frame_rate(&self) -> FrameRate {
+ self.interpret.frame_rate.unwrap_or_else(|| self.info.frame_rate())
+ }
+ pub fn duration(&self) -> Tick {
+ self.info.duration
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[allow(clippy::large_enum_variant)]
+pub enum ItemKind {
+ Media(MediaClip),
+ Sequence(Box<Sequence>),
+ /// A subclip: a media item restricted to a range.
+ Subclip {
+ parent: ItemId,
+ range: TimeRange,
+ },
+ AdjustmentLayer {
+ width: u32,
+ height: u32,
+ rate: FrameRate,
+ duration: Tick,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ProjectItem {
+ pub id: ItemId,
+ pub name: String,
+ pub label: Label,
+ pub kind: ItemKind,
+ /// Free-form metadata (Description, Scene, Shot, Log Note…).
+ #[serde(default)]
+ pub metadata: BTreeMap<String, String>,
+ /// Import time counter (for "Date Created"/sorting), not wall clock.
+ #[serde(default)]
+ pub created: u64,
+}
+
+impl ProjectItem {
+ pub fn as_media(&self) -> Option<&MediaClip> {
+ match &self.kind {
+ ItemKind::Media(m) => Some(m),
+ _ => None,
+ }
+ }
+ pub fn as_media_mut(&mut self) -> Option<&mut MediaClip> {
+ match &mut self.kind {
+ ItemKind::Media(m) => Some(m),
+ _ => None,
+ }
+ }
+ pub fn as_sequence(&self) -> Option<&Sequence> {
+ match &self.kind {
+ ItemKind::Sequence(s) => Some(s),
+ _ => None,
+ }
+ }
+ pub fn as_sequence_mut(&mut self) -> Option<&mut Sequence> {
+ match &mut self.kind {
+ ItemKind::Sequence(s) => Some(s),
+ _ => None,
+ }
+ }
+ pub fn has_video(&self) -> bool {
+ match &self.kind {
+ ItemKind::Media(m) => m.info.has_video(),
+ ItemKind::Sequence(_) | ItemKind::AdjustmentLayer { .. } => true,
+ ItemKind::Subclip { .. } => true,
+ }
+ }
+ pub fn has_audio(&self) -> bool {
+ match &self.kind {
+ ItemKind::Media(m) => m.info.has_audio(),
+ ItemKind::Sequence(s) => !s.audio_tracks.is_empty(),
+ _ => false,
+ }
+ }
+ pub fn duration(&self) -> Tick {
+ match &self.kind {
+ ItemKind::Media(m) => m.duration(),
+ ItemKind::Sequence(s) => s.duration(),
+ ItemKind::Subclip { range, .. } => range.duration,
+ ItemKind::AdjustmentLayer { duration, .. } => *duration,
+ }
+ }
+ pub fn frame_rate(&self) -> FrameRate {
+ match &self.kind {
+ ItemKind::Media(m) => m.frame_rate(),
+ ItemKind::Sequence(s) => s.settings.frame_rate,
+ ItemKind::AdjustmentLayer { rate, .. } => *rate,
+ ItemKind::Subclip { .. } => FrameRate::default(),
+ }
+ }
+ /// Human-readable media type for the Project panel "Media Type" column.
+ pub fn type_label(&self) -> &'static str {
+ match &self.kind {
+ ItemKind::Media(m) => match m.info.kind {
+ filmcraft_media::MediaKind::Movie => "Movie",
+ filmcraft_media::MediaKind::AudioOnly => "Audio",
+ filmcraft_media::MediaKind::Still => "Still Image",
+ filmcraft_media::MediaKind::ImageSequence => "Image Sequence",
+ filmcraft_media::MediaKind::Synthetic => "Synthetic",
+ },
+ ItemKind::Sequence(_) => "Sequence",
+ ItemKind::Subclip { .. } => "Subclip",
+ ItemKind::AdjustmentLayer { .. } => "Adjustment Layer",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum BinEntry {
+ Item(ItemId),
+ Bin(Bin),
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Bin {
+ pub id: BinId,
+ pub name: String,
+ pub children: Vec<BinEntry>,
+}
+
+impl Bin {
+ pub fn find_bin_mut(&mut self, id: BinId) -> Option<&mut Bin> {
+ if self.id == id {
+ return Some(self);
+ }
+ for c in &mut self.children {
+ if let BinEntry::Bin(b) = c
+ && let Some(f) = b.find_bin_mut(id)
+ {
+ return Some(f);
+ }
+ }
+ None
+ }
+ pub fn find_bin(&self, id: BinId) -> Option<&Bin> {
+ if self.id == id {
+ return Some(self);
+ }
+ self.children.iter().find_map(|c| if let BinEntry::Bin(b) = c { b.find_bin(id) } else { None })
+ }
+ /// Remove an item anywhere in the tree.
+ pub fn remove_item(&mut self, id: ItemId) -> bool {
+ let before = self.children.len();
+ self.children.retain(|c| !matches!(c, BinEntry::Item(i) if *i == id));
+ if self.children.len() != before {
+ return true;
+ }
+ self.children.iter_mut().any(|c| if let BinEntry::Bin(b) = c { b.remove_item(id) } else { false })
+ }
+ /// All items in this bin and sub-bins.
+ pub fn all_items(&self, out: &mut Vec<ItemId>) {
+ for c in &self.children {
+ match c {
+ BinEntry::Item(i) => out.push(*i),
+ BinEntry::Bin(b) => b.all_items(out),
+ }
+ }
+ }
+ /// The bin containing an item.
+ pub fn parent_of(&self, id: ItemId) -> Option<BinId> {
+ for c in &self.children {
+ match c {
+ BinEntry::Item(i) if *i == id => return Some(self.id),
+ BinEntry::Bin(b) => {
+ if let Some(p) = b.parent_of(id) {
+ return Some(p);
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum MarkerKind {
+ #[default]
+ Comment,
+ Chapter,
+ Segmentation,
+ WebLink,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Marker {
+ pub id: MarkerId,
+ pub start: Tick,
+ pub duration: Tick,
+ pub name: String,
+ pub comment: String,
+ pub kind: MarkerKind,
+ pub color: Label,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum TrackKind {
+ #[default]
+ Video,
+ Audio,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum AudioChannels {
+ Mono,
+ #[default]
+ Stereo,
+ Surround51,
+ Adaptive,
+}
+
+/// A clip instance on a track.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct TrackItem {
+ pub id: ClipId,
+ pub item: ItemId,
+ pub name: String,
+ pub label: Label,
+ /// Timeline position (sequence ticks).
+ pub start: Tick,
+ /// Duration on the timeline.
+ pub duration: Tick,
+ /// Media time of the first frame shown.
+ pub source_in: Tick,
+ /// Playback speed (1.0 = 100%). Negative = reverse.
+ pub speed: f64,
+ #[serde(default)]
+ pub reverse: bool,
+ pub enabled: bool,
+ /// Linked partner items (video ↔ audio of the same source).
+ #[serde(default)]
+ pub link: Option<u64>,
+ #[serde(default)]
+ pub group: Option<u64>,
+ pub effects: Vec<EffectInstance>,
+ #[serde(default)]
+ pub markers: Vec<Marker>,
+ /// Clip gain in dB (Audio Gain dialog), separate from the Volume effect.
+ #[serde(default)]
+ pub gain_db: f64,
+ /// Frame hold: media time frozen (Frame Hold Options).
+ #[serde(default)]
+ pub frame_hold: Option<Tick>,
+ /// Scale to frame size (Set to Frame Size / Scale to Frame Size).
+ #[serde(default)]
+ pub scale_to_frame: bool,
+}
+
+impl TrackItem {
+ pub fn end(&self) -> Tick {
+ self.start + self.duration
+ }
+ pub fn range(&self) -> TimeRange {
+ TimeRange::new(self.start, self.duration)
+ }
+ /// Media time displayed at timeline time `t` (ignores time remapping keyframes).
+ pub fn source_time_at(&self, t: Tick) -> Tick {
+ if let Some(h) = self.frame_hold {
+ return h;
+ }
+ let rel = t - self.start;
+ let scaled = Tick((rel.0 as f64 * self.speed.abs()).round() as i64);
+ if self.reverse {
+ self.source_in + Tick((self.duration.0 as f64 * self.speed.abs()).round() as i64) - scaled - Tick(1)
+ } else {
+ self.source_in + scaled
+ }
+ }
+ /// Media time consumed by the item (the source out point).
+ pub fn source_out(&self) -> Tick {
+ self.source_in + Tick((self.duration.0 as f64 * self.speed.abs()).round() as i64)
+ }
+ pub fn effect(&self, id: &str) -> Option<&EffectInstance> {
+ self.effects.iter().find(|e| e.effect == id)
+ }
+ pub fn effect_mut(&mut self, id: &str) -> Option<&mut EffectInstance> {
+ self.effects.iter_mut().find(|e| e.effect == id)
+ }
+ /// Standard (non-intrinsic) effects applied, for the fx badge.
+ pub fn has_standard_effects(&self) -> bool {
+ self.effects.iter().any(|e| e.def().is_some_and(|d| !d.intrinsic))
+ }
+ pub fn has_modified_intrinsics(&self) -> bool {
+ self.effects.iter().any(|e| {
+ e.def().is_some_and(|d| d.intrinsic)
+ && (e.is_animated()
+ || e.def().is_some_and(|d| d.params.iter().any(|p| e.params.get(p.id).is_some_and(|v| !param_eq_default(&v.value, &p.default)))))
+ })
+ }
+}
+
+fn param_eq_default(v: &ParamValue, d: &ParamValue) -> bool {
+ match (v, d) {
+ (ParamValue::Vec2(_), ParamValue::Vec2(dd)) if dd.x.is_nan() => true,
+ _ => v == d,
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum TransitionAlign {
+ #[default]
+ CenterAtCut,
+ StartAtCut,
+ EndAtCut,
+}
+
+/// A transition on a track. `at` is the cut point (or clip edge for single-sided transitions).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Transition {
+ pub id: TransitionId,
+ pub effect: EffectInstance,
+ /// Timeline range covered by the transition.
+ pub start: Tick,
+ pub duration: Tick,
+ /// Outgoing clip (left) and incoming clip (right); one may be None (fade from/to nothing).
+ pub from: Option<ClipId>,
+ pub to: Option<ClipId>,
+ pub align: TransitionAlign,
+ #[serde(default)]
+ pub reverse: bool,
+}
+
+impl Transition {
+ pub fn end(&self) -> Tick {
+ self.start + self.duration
+ }
+ pub fn range(&self) -> TimeRange {
+ TimeRange::new(self.start, self.duration)
+ }
+ /// Progress 0..1 at timeline `t`.
+ pub fn progress(&self, t: Tick) -> f64 {
+ if self.duration.0 <= 0 {
+ return 1.0;
+ }
+ (((t - self.start).0 as f64) / self.duration.0 as f64).clamp(0.0, 1.0)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Track {
+ pub id: TrackId,
+ pub kind: TrackKind,
+ pub name: String,
+ pub items: Vec<TrackItem>,
+ pub transitions: Vec<Transition>,
+ pub locked: bool,
+ pub sync_lock: bool,
+ /// Video: eye (output) toggle. Audio: not muted.
+ pub enabled: bool,
+ pub muted: bool,
+ pub solo: bool,
+ /// Audio track channel format.
+ pub channels: AudioChannels,
+ /// Audio track volume (dB) and pan (-100..100) for the Track Mixer.
+ pub volume_db: f64,
+ pub pan: f64,
+ /// Track-level audio effects (mixer inserts).
+ #[serde(default)]
+ pub effects: Vec<EffectInstance>,
+}
+
+impl Track {
+ pub fn new(id: TrackId, kind: TrackKind, name: String) -> Self {
+ Self {
+ id,
+ kind,
+ name,
+ items: Vec::new(),
+ transitions: Vec::new(),
+ locked: false,
+ sync_lock: true,
+ enabled: true,
+ muted: false,
+ solo: false,
+ channels: AudioChannels::Stereo,
+ volume_db: 0.0,
+ pan: 0.0,
+ effects: Vec::new(),
+ }
+ }
+ pub fn end(&self) -> Tick {
+ self.items.iter().map(|i| i.end()).max().unwrap_or(Tick::ZERO)
+ }
+ /// Item covering time `t`.
+ pub fn item_at(&self, t: Tick) -> Option<&TrackItem> {
+ // items are sorted by start
+ let idx = self.items.partition_point(|i| i.start <= t);
+ idx.checked_sub(1).map(|i| &self.items[i]).filter(|i| t < i.end())
+ }
+ pub fn item(&self, id: ClipId) -> Option<&TrackItem> {
+ self.items.iter().find(|i| i.id == id)
+ }
+ pub fn item_mut(&mut self, id: ClipId) -> Option<&mut TrackItem> {
+ self.items.iter_mut().find(|i| i.id == id)
+ }
+ pub fn sort(&mut self) {
+ self.items.sort_by_key(|i| i.start);
+ self.transitions.sort_by_key(|t| t.start);
+ }
+ /// Invariant check: items do not overlap.
+ pub fn check(&self) -> Result<(), String> {
+ for w in self.items.windows(2) {
+ if w[0].end() > w[1].start {
+ return Err(format!("{}: items {:?} and {:?} overlap", self.name, w[0].id, w[1].id));
+ }
+ }
+ for i in &self.items {
+ if i.duration.0 <= 0 {
+ return Err(format!("{}: item {:?} has non-positive duration", self.name, i.id));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct SequenceSettings {
+ pub width: u32,
+ pub height: u32,
+ pub frame_rate: FrameRate,
+ pub par: (u32, u32),
+ pub sample_rate: u32,
+ pub drop_frame: bool,
+ /// Editing mode / preset name shown in the settings dialog.
+ pub preset: String,
+ pub audio_master: AudioChannels,
+ /// Preview file codec name.
+ pub preview_codec: String,
+ pub max_bit_depth: bool,
+ pub max_render_quality: bool,
+ /// Working colour space.
+ pub working_space: String,
+}
+
+impl Default for SequenceSettings {
+ fn default() -> Self {
+ Self {
+ width: 1920,
+ height: 1080,
+ frame_rate: FrameRate::FPS_23_976,
+ par: (1, 1),
+ sample_rate: 48_000,
+ drop_frame: false,
+ preset: "HD 1080p 23.976".into(),
+ audio_master: AudioChannels::Stereo,
+ preview_codec: "ProRes 422".into(),
+ max_bit_depth: false,
+ max_render_quality: false,
+ working_space: "Rec. 709".into(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Sequence {
+ pub settings: SequenceSettings,
+ pub video_tracks: Vec<Track>,
+ pub audio_tracks: Vec<Track>,
+ pub markers: Vec<Marker>,
+ pub mark_in: Option<Tick>,
+ pub mark_out: Option<Tick>,
+ /// Work area bar (optional; Premiere hides it by default now).
+ pub work_area: Option<TimeRange>,
+ /// Timecode of the first frame (frames), "Start Time" in Sequence settings.
+ pub start_timecode: i64,
+ /// Master audio volume (dB).
+ #[serde(default)]
+ pub master_volume_db: f64,
+ #[serde(default)]
+ pub master_effects: Vec<EffectInstance>,
+}
+
+impl Sequence {
+ pub fn duration(&self) -> Tick {
+ self.video_tracks.iter().chain(&self.audio_tracks).map(Track::end).max().unwrap_or(Tick::ZERO)
+ }
+ pub fn tracks(&self, kind: TrackKind) -> &Vec<Track> {
+ match kind {
+ TrackKind::Video => &self.video_tracks,
+ TrackKind::Audio => &self.audio_tracks,
+ }
+ }
+ pub fn tracks_mut(&mut self, kind: TrackKind) -> &mut Vec<Track> {
+ match kind {
+ TrackKind::Video => &mut self.video_tracks,
+ TrackKind::Audio => &mut self.audio_tracks,
+ }
+ }
+ pub fn all_tracks(&self) -> impl Iterator<Item = &Track> {
+ self.video_tracks.iter().chain(self.audio_tracks.iter())
+ }
+ pub fn all_tracks_mut(&mut self) -> impl Iterator<Item = &mut Track> {
+ self.video_tracks.iter_mut().chain(self.audio_tracks.iter_mut())
+ }
+ pub fn track(&self, id: TrackId) -> Option<&Track> {
+ self.all_tracks().find(|t| t.id == id)
+ }
+ pub fn track_mut(&mut self, id: TrackId) -> Option<&mut Track> {
+ self.all_tracks_mut().find(|t| t.id == id)
+ }
+ /// Find a track item anywhere: (track id, item).
+ pub fn find_item(&self, id: ClipId) -> Option<(TrackId, &TrackItem)> {
+ self.all_tracks().find_map(|t| t.item(id).map(|i| (t.id, i)))
+ }
+ pub fn find_item_mut(&mut self, id: ClipId) -> Option<(TrackId, &mut TrackItem)> {
+ self.all_tracks_mut().find_map(|t| {
+ let tid = t.id;
+ t.item_mut(id).map(|i| (tid, i))
+ })
+ }
+ pub fn frame_rate(&self) -> FrameRate {
+ self.settings.frame_rate
+ }
+ /// Sorted, de-duplicated edit points (clip boundaries) on all tracks.
+ pub fn edit_points(&self) -> Vec<Tick> {
+ let mut v: Vec<Tick> = self.all_tracks().flat_map(|t| t.items.iter().flat_map(|i| [i.start, i.end()])).collect();
+ v.sort_unstable();
+ v.dedup();
+ v
+ }
+ pub fn check(&self) -> Result<(), String> {
+ for t in self.all_tracks() {
+ t.check()?;
+ }
+ Ok(())
+ }
+}
+
+/// Project-level settings.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ProjectSettings {
+ pub renderer: String,
+ pub video_display: filmcraft_time::TimeDisplay,
+ pub audio_display_samples: bool,
+ pub default_still_duration: Tick,
+ pub default_transition_duration_frames: i64,
+ pub default_audio_transition_duration: Tick,
+}
+
+impl Default for ProjectSettings {
+ fn default() -> Self {
+ Self {
+ renderer: "FilmCraft GPU Acceleration (wgpu)".into(),
+ video_display: filmcraft_time::TimeDisplay::Timecode,
+ audio_display_samples: true,
+ default_still_duration: Tick(5 * TICKS_PER_SECOND),
+ default_transition_duration_frames: 24,
+ default_audio_transition_duration: Tick(TICKS_PER_SECOND),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Project {
+ pub name: String,
+ pub settings: ProjectSettings,
+ pub root: Bin,
+ pub items: BTreeMap<ItemId, ProjectItem>,
+ /// Monotonic id source for all id types.
+ pub next_id: u64,
+ /// Format version of the serialized project.
+ pub version: u32,
+}
+
+pub const PROJECT_VERSION: u32 = 1;
+
+impl Default for Project {
+ fn default() -> Self {
+ Self::new("Untitled")
+ }
+}
+
+impl Project {
+ pub fn new(name: &str) -> Self {
+ Self {
+ name: name.into(),
+ settings: ProjectSettings::default(),
+ root: Bin { id: BinId(0), name: name.into(), children: Vec::new() },
+ items: BTreeMap::new(),
+ next_id: 1,
+ version: PROJECT_VERSION,
+ }
+ }
+
+ pub fn alloc_id(&mut self) -> u64 {
+ let id = self.next_id;
+ self.next_id += 1;
+ id
+ }
+
+ /// Add an item to a bin (root when None / not found).
+ pub fn add_item(&mut self, name: &str, label: Label, kind: ItemKind, bin: Option<BinId>) -> ItemId {
+ let id = ItemId(self.alloc_id());
+ let created = id.0;
+ self.items.insert(id, ProjectItem { id, name: name.into(), label, kind, metadata: BTreeMap::new(), created });
+ if let Some(b) = bin.and_then(|b| self.root.find_bin_mut(b)) {
+ b.children.push(BinEntry::Item(id));
+ } else {
+ self.root.children.push(BinEntry::Item(id));
+ }
+ id
+ }
+
+ pub fn add_bin(&mut self, name: &str, parent: Option<BinId>) -> BinId {
+ let id = BinId(self.alloc_id());
+ let bin = Bin { id, name: name.into(), children: Vec::new() };
+ match parent.and_then(|p| self.root.find_bin_mut(p)) {
+ Some(p) => p.children.push(BinEntry::Bin(bin)),
+ None => self.root.children.push(BinEntry::Bin(bin)),
+ }
+ id
+ }
+
+ pub fn item(&self, id: ItemId) -> Option<&ProjectItem> {
+ self.items.get(&id)
+ }
+ pub fn item_mut(&mut self, id: ItemId) -> Option<&mut ProjectItem> {
+ self.items.get_mut(&id)
+ }
+ pub fn sequence(&self, id: ItemId) -> Option<&Sequence> {
+ self.items.get(&id).and_then(ProjectItem::as_sequence)
+ }
+ pub fn sequence_mut(&mut self, id: ItemId) -> Option<&mut Sequence> {
+ self.items.get_mut(&id).and_then(ProjectItem::as_sequence_mut)
+ }
+ pub fn sequences(&self) -> impl Iterator<Item = &ProjectItem> {
+ self.items.values().filter(|i| matches!(i.kind, ItemKind::Sequence(_)))
+ }
+
+ /// Create an empty sequence with `v` video and `a` audio tracks.
+ pub fn new_sequence(&mut self, name: &str, settings: SequenceSettings, v: usize, a: usize, bin: Option<BinId>) -> ItemId {
+ let mut seq = Sequence {
+ settings,
+ video_tracks: Vec::new(),
+ audio_tracks: Vec::new(),
+ markers: Vec::new(),
+ mark_in: None,
+ mark_out: None,
+ work_area: None,
+ start_timecode: 0,
+ master_volume_db: 0.0,
+ master_effects: Vec::new(),
+ };
+ for i in 0..v {
+ let id = TrackId(self.alloc_id());
+ seq.video_tracks.push(Track::new(id, TrackKind::Video, format!("Video {}", i + 1)));
+ }
+ for i in 0..a {
+ let id = TrackId(self.alloc_id());
+ seq.audio_tracks.push(Track::new(id, TrackKind::Audio, format!("Audio {}", i + 1)));
+ }
+ self.add_item(name, Label::Forest, ItemKind::Sequence(Box::new(seq)), bin)
+ }
+
+ /// Build a track item for `item` placed at `start` covering `source` range (media time).
+ pub fn make_track_item(&mut self, item: ItemId, kind: TrackKind, start: Tick, source: TimeRange, seq_rate: FrameRate) -> Option<TrackItem> {
+ let it = self.items.get(&item)?;
+ let name = it.name.clone();
+ let label = if kind == TrackKind::Audio && !matches!(it.kind, ItemKind::Sequence(_)) { Label::Forest } else { it.label };
+ let effects = match kind {
+ TrackKind::Video => effect::intrinsic_video(),
+ TrackKind::Audio => effect::intrinsic_audio(),
+ };
+ let id = ClipId(self.alloc_id());
+ let dur = seq_rate.snap_nearest(source.duration).max(seq_rate.frame_duration());
+ Some(TrackItem {
+ id,
+ item,
+ name,
+ label,
+ start,
+ duration: dur,
+ source_in: source.start,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects,
+ markers: Vec::new(),
+ gain_db: 0.0,
+ frame_hold: None,
+ scale_to_frame: false,
+ })
+ }
+
+ pub fn to_json(&self) -> String {
+ serde_json::to_string_pretty(self).unwrap_or_default()
+ }
+ pub fn from_json(s: &str) -> Result<Project, String> {
+ let p: Project = serde_json::from_str(s).map_err(|e| e.to_string())?;
+ if p.version > PROJECT_VERSION {
+ return Err(format!("project version {} is newer than this FilmCraft ({PROJECT_VERSION})", p.version));
+ }
+ Ok(p)
+ }
+}
+
+/// Resolve NaN "auto" point defaults (frame centre / source centre) in an effect instance.
+pub fn resolve_auto_points(e: &mut EffectInstance, frame: (u32, u32), source: (u32, u32)) {
+ for (k, p) in e.params.iter_mut() {
+ if let ParamValue::Vec2(v) = &mut p.value {
+ let (w, h) = if k == "anchor" { source } else { frame };
+ if v.x.is_nan() {
+ v.x = w as f64 / 2.0;
+ }
+ if v.y.is_nan() {
+ v.y = if k == "end" { h as f64 } else { h as f64 / 2.0 };
+ }
+ }
+ }
+ let _ = Vec2::ZERO;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_media::{DemoScene, MediaSource};
+
+ fn demo_project() -> (Project, ItemId, ItemId) {
+ let mut p = Project::new("Test");
+ let src = filmcraft_media::generators::GeneratorSource::demo(DemoScene::OceanSunset);
+ let info = src.info().clone();
+ let clip = p.add_item(
+ "Ocean_Sunset.mp4",
+ Label::Iris,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::Generator(Generator::Demo(DemoScene::OceanSunset)),
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ );
+ let seq = p.new_sequence("Sequence 01", SequenceSettings::default(), 3, 3, None);
+ (p, clip, seq)
+ }
+
+ #[test]
+ fn json_roundtrip() {
+ let (mut p, clip, seq) = demo_project();
+ let rate = p.sequence(seq).unwrap().settings.frame_rate;
+ let mut ti = p.make_track_item(clip, TrackKind::Video, Tick::ZERO, TimeRange::new(Tick::ZERO, Tick(5 * TICKS_PER_SECOND)), rate).unwrap();
+ for e in &mut ti.effects {
+ resolve_auto_points(e, (1920, 1080), (1920, 1080));
+ }
+ p.sequence_mut(seq).unwrap().video_tracks[0].items.push(ti);
+ let s = p.to_json();
+ let q = Project::from_json(&s).unwrap();
+ assert_eq!(p, q);
+ assert!(q.sequence(seq).unwrap().check().is_ok());
+ }
+
+ #[test]
+ fn item_at_and_source_time() {
+ let (mut p, clip, seq) = demo_project();
+ let rate = FrameRate::FPS_24;
+ let mut a = p.make_track_item(clip, TrackKind::Video, Tick(0), TimeRange::new(Tick(1000), rate.tick_of(48)), rate).unwrap();
+ a.speed = 2.0;
+ let t = &mut p.sequence_mut(seq).unwrap().video_tracks[0];
+ t.items.push(a.clone());
+ assert_eq!(t.item_at(rate.tick_of(10)).unwrap().id, a.id);
+ assert!(t.item_at(rate.tick_of(48)).is_none());
+ assert_eq!(a.source_time_at(rate.tick_of(10)), Tick(1000) + rate.tick_of(20));
+ }
+
+ #[test]
+ fn bins() {
+ let mut p = Project::new("x");
+ let b = p.add_bin("Footage", None);
+ let i = p.add_item("a", Label::Iris, ItemKind::AdjustmentLayer { width: 10, height: 10, rate: FrameRate::FPS_24, duration: Tick(1) }, Some(b));
+ assert_eq!(p.root.parent_of(i), Some(b));
+ assert!(p.root.remove_item(i));
+ assert_eq!(p.root.parent_of(i), None);
+ }
+}
diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml
new file mode 100644
index 000000000..9893ec6dc
--- /dev/null
+++ b/crates/render/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "filmcraft-render"
+description = "Sequence evaluation and CPU reference compositor (linear-light premultiplied f32)"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-geom = { workspace = true }
+filmcraft-color = { workspace = true }
+filmcraft-frame = { workspace = true }
+filmcraft-media = { workspace = true }
+filmcraft-project = { workspace = true }
+rayon = { workspace = true }
+
+[dev-dependencies]
+image = { version = "0.25", default-features = false, features = ["png"] }
diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs
new file mode 100644
index 000000000..b40294925
--- /dev/null
+++ b/crates/render/src/audio.rs
@@ -0,0 +1,162 @@
+//! Sequence audio mixdown (clip gain → Volume/Channel Volume/Panner → track volume/pan →
+//! master), with audio transitions, mute/solo, speed changes (varispeed resampling).
+//!
+//! The dedicated `audio` crate (M7) adds the effect DSP, submixes and meters; this module is the
+//! reference mixer used by playback and export.
+
+use filmcraft_frame::AudioBuffer;
+use filmcraft_project::{Project, Sequence, TrackItem};
+use filmcraft_time::{Tick, TimeRange};
+
+use crate::{SourceProvider, transitions};
+
+pub fn db_to_gain(db: f64) -> f32 {
+ if db <= -96.0 { 0.0 } else { 10f64.powf(db / 20.0) as f32 }
+}
+
+/// Mix `frames` stereo samples of sequence audio starting at sample `start` (sequence rate).
+pub fn mix_sequence(project: &Project, seq: &Sequence, start: i64, frames: usize, sources: &dyn SourceProvider) -> AudioBuffer {
+ let sr = seq.settings.sample_rate;
+ let mut out = AudioBuffer::silence(sr, 2, frames);
+ let range = TimeRange::from_bounds(Tick::from_units(start, sr as i64), Tick::from_units(start + frames as i64, sr as i64));
+ let any_solo = seq.audio_tracks.iter().any(|t| t.solo);
+ for track in &seq.audio_tracks {
+ if track.muted || (any_solo && !track.solo) {
+ continue;
+ }
+ let mut tbuf = AudioBuffer::silence(sr, 2, frames);
+ for item in track.items.iter().filter(|i| i.enabled && i.range().overlaps(&range)) {
+ mix_item(project, item, start, frames, sr, sources, &mut tbuf, 1.0);
+ }
+ // audio transitions: attenuate the covered region of each side
+ for tr in &track.transitions {
+ if !tr.range().overlaps(&range) {
+ continue;
+ }
+ // Re-mix: recompute the covered samples with crossfade gains.
+ let from = tr.from.and_then(|id| track.item(id));
+ let to = tr.to.and_then(|id| track.item(id));
+ let s0 = tr.start.to_units_floor(sr as i64).max(start);
+ let s1 = tr.end().to_units_floor(sr as i64).min(start + frames as i64);
+ if s1 <= s0 {
+ continue;
+ }
+ let n = (s1 - s0) as usize;
+ let off = (s0 - start) as usize;
+ for ch in tbuf.channels.iter_mut() {
+ ch[off..off + n].fill(0.0);
+ }
+ let mut a = AudioBuffer::silence(sr, 2, n);
+ let mut b = AudioBuffer::silence(sr, 2, n);
+ if let Some(f) = from {
+ mix_item(project, f, s0, n, sr, sources, &mut a, 1.0);
+ }
+ if let Some(tt) = to {
+ mix_item(project, tt, s0, n, sr, sources, &mut b, 1.0);
+ }
+ let dur = (tr.end() - tr.start).to_units_floor(sr as i64).max(1) as f32;
+ let base = (s0 - tr.start.to_units_floor(sr as i64)) as f32;
+ for i in 0..n {
+ let p = (base + i as f32) / dur;
+ let (ga, gb) = transitions::audio_gains(&tr.effect.effect, p);
+ for c in 0..2 {
+ tbuf.channels[c][off + i] += a.channels[c][i] * ga + b.channels[c][i] * gb;
+ }
+ }
+ }
+ let g = db_to_gain(track.volume_db);
+ let pan = (track.pan / 100.0).clamp(-1.0, 1.0) as f32;
+ let (gl, gr) = pan_gains(pan);
+ out.mix_from(&tbuf, &[g * gl, g * gr]);
+ }
+ let mg = db_to_gain(seq.master_volume_db);
+ if (mg - 1.0).abs() > 1e-6 {
+ for ch in &mut out.channels {
+ for s in ch.iter_mut() {
+ *s *= mg;
+ }
+ }
+ }
+ out
+}
+
+/// -3 dB constant-power pan law, normalised so centre = unity.
+fn pan_gains(pan: f32) -> (f32, f32) {
+ let a = (pan + 1.0) * std::f32::consts::FRAC_PI_4;
+ let k = std::f32::consts::SQRT_2;
+ ((a.cos() * k).min(1.0), (a.sin() * k).min(1.0))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn mix_item(project: &Project, item: &TrackItem, start: i64, frames: usize, sr: u32, sources: &dyn SourceProvider, out: &mut AudioBuffer, extra: f32) {
+ let Some(src) = sources.source(item.item) else { return };
+ if !src.info().has_audio() {
+ // nested sequences
+ if let Some(nested) = project.sequence(item.item) {
+ let rel0 = start - item.start.to_units_floor(sr as i64) + item.source_in.to_units_floor(sr as i64);
+ let b = mix_sequence(project, nested, rel0, frames, sources);
+ out.mix_from(&b, &[extra, extra]);
+ }
+ return;
+ }
+ let item_s0 = item.start.to_units_floor(sr as i64);
+ let item_s1 = item.end().to_units_floor(sr as i64);
+ let a0 = start.max(item_s0);
+ let a1 = (start + frames as i64).min(item_s1);
+ if a1 <= a0 {
+ return;
+ }
+ let n = (a1 - a0) as usize;
+ let speed = item.speed.abs().max(1e-6);
+ let src_start_ticks = item.source_time_at(Tick::from_units(a0, sr as i64));
+ let buf = if (speed - 1.0).abs() < 1e-9 && !item.reverse {
+ src.audio(src_start_ticks.to_units_floor(sr as i64), n, sr).ok()
+ } else {
+ // varispeed: read a longer span and resample linearly
+ let span = ((n as f64) * speed).ceil() as usize + 2;
+ let s0 = if item.reverse { src_start_ticks.to_units_floor(sr as i64) - span as i64 } else { src_start_ticks.to_units_floor(sr as i64) };
+ src.audio(s0, span, sr).ok().map(|raw| {
+ let mut b = AudioBuffer::silence(sr, raw.channel_count(), n);
+ for (c, ch) in raw.channels.iter().enumerate() {
+ for i in 0..n {
+ let pos = if item.reverse { span as f64 - 1.0 - i as f64 * speed } else { i as f64 * speed };
+ let i0 = pos.floor().max(0.0) as usize;
+ let fr = (pos - i0 as f64) as f32;
+ let a = ch.get(i0).copied().unwrap_or(0.0);
+ let bb = ch.get(i0 + 1).copied().unwrap_or(a);
+ b.channels[c][i] = a + (bb - a) * fr;
+ }
+ }
+ b
+ })
+ };
+ let Some(buf) = buf else { return };
+ // gains: clip gain × Volume (keyframed, per 64-sample block) × channel volume × panner
+ let clip_gain = db_to_gain(item.gain_db);
+ let vol = item.effect("volume").filter(|e| e.enabled && !e.param("bypass").and_then(|p| p.value.as_bool()).unwrap_or(false));
+ let chv = item.effect("channel_volume").filter(|e| e.enabled && !e.param("bypass").and_then(|p| p.value.as_bool()).unwrap_or(false));
+ let pan = item.effect("panner").filter(|e| e.enabled);
+ let off = (a0 - start) as usize;
+ let stereo_src = buf.channel_count() >= 2;
+ for blk in (0..n).step_by(64) {
+ let t_tl = Tick::from_units(a0 + blk as i64, sr as i64);
+ let mt = item.source_time_at(t_tl);
+ let v = vol.map(|e| db_to_gain(e.f64_at("level", mt))).unwrap_or(1.0);
+ let (cl, cr) = chv.map(|e| (db_to_gain(e.f64_at("left", mt)), db_to_gain(e.f64_at("right", mt)))).unwrap_or((1.0, 1.0));
+ let (pl, pr) = pan.map(|e| pan_gains((e.f64_at("balance", mt) / 100.0) as f32)).unwrap_or((1.0, 1.0));
+ let g = clip_gain * v * extra;
+ let end = (blk + 64).min(n);
+ for i in blk..end {
+ let l = buf.channels[0][i];
+ let r = if stereo_src { buf.channels[1][i] } else { l };
+ out.channels[0][off + i] += l * g * cl * pl;
+ out.channels[1][off + i] += r * g * cr * pr;
+ }
+ }
+}
+
+/// Peak (min, max) pairs per bucket of `bucket` samples for channel `ch` — waveform display.
+pub fn peaks(buf: &AudioBuffer, ch: usize, bucket: usize) -> Vec<(f32, f32)> {
+ let Some(c) = buf.channels.get(ch) else { return Vec::new() };
+ c.chunks(bucket.max(1)).map(|b| b.iter().fold((0f32, 0f32), |(lo, hi), s| (lo.min(*s), hi.max(*s)))).collect()
+}
diff --git a/crates/render/src/blend.rs b/crates/render/src/blend.rs
new file mode 100644
index 000000000..06f0f5d52
--- /dev/null
+++ b/crates/render/src/blend.rs
@@ -0,0 +1,306 @@
+//! Blend modes (Premiere's 27), composited on premultiplied linear-light images.
+//!
+//! Normal is computed in linear light. The other modes are defined on display-encoded values (as
+//! artists expect from every editing app), so their math runs on sRGB-encoded straight colour and
+//! the result is converted back to linear. Formulas follow the W3C Compositing and Blending spec.
+
+use filmcraft_color::{linear_to_srgb, srgb_to_linear};
+use rayon::prelude::*;
+
+use crate::image::Image;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Blend {
+ Normal,
+ Dissolve,
+ Darken,
+ Multiply,
+ ColorBurn,
+ LinearBurn,
+ DarkerColor,
+ Lighten,
+ Screen,
+ ColorDodge,
+ LinearDodge,
+ LighterColor,
+ Overlay,
+ SoftLight,
+ HardLight,
+ VividLight,
+ LinearLight,
+ PinLight,
+ HardMix,
+ Difference,
+ Exclusion,
+ Subtract,
+ Divide,
+ Hue,
+ Saturation,
+ Color,
+ Luminosity,
+}
+
+impl Blend {
+ pub const ALL: [Blend; 27] = [
+ Blend::Normal,
+ Blend::Dissolve,
+ Blend::Darken,
+ Blend::Multiply,
+ Blend::ColorBurn,
+ Blend::LinearBurn,
+ Blend::DarkerColor,
+ Blend::Lighten,
+ Blend::Screen,
+ Blend::ColorDodge,
+ Blend::LinearDodge,
+ Blend::LighterColor,
+ Blend::Overlay,
+ Blend::SoftLight,
+ Blend::HardLight,
+ Blend::VividLight,
+ Blend::LinearLight,
+ Blend::PinLight,
+ Blend::HardMix,
+ Blend::Difference,
+ Blend::Exclusion,
+ Blend::Subtract,
+ Blend::Divide,
+ Blend::Hue,
+ Blend::Saturation,
+ Blend::Color,
+ Blend::Luminosity,
+ ];
+ /// Index into `filmcraft_project::effect::BLEND_MODES`.
+ pub fn from_index(i: u32) -> Blend {
+ Self::ALL.get(i as usize).copied().unwrap_or(Blend::Normal)
+ }
+}
+
+#[inline]
+fn sep(mode: Blend, b: f32, s: f32) -> f32 {
+ match mode {
+ Blend::Darken => b.min(s),
+ Blend::Multiply => b * s,
+ Blend::ColorBurn => {
+ if b >= 1.0 {
+ 1.0
+ } else if s <= 0.0 {
+ 0.0
+ } else {
+ 1.0 - ((1.0 - b) / s).min(1.0)
+ }
+ }
+ Blend::LinearBurn => (b + s - 1.0).max(0.0),
+ Blend::Lighten => b.max(s),
+ Blend::Screen => b + s - b * s,
+ Blend::ColorDodge => {
+ if b <= 0.0 {
+ 0.0
+ } else if s >= 1.0 {
+ 1.0
+ } else {
+ (b / (1.0 - s)).min(1.0)
+ }
+ }
+ Blend::LinearDodge => (b + s).min(1.0),
+ Blend::Overlay => sep(Blend::HardLight, s, b),
+ Blend::HardLight => {
+ if s <= 0.5 {
+ b * 2.0 * s
+ } else {
+ sep(Blend::Screen, b, 2.0 * s - 1.0)
+ }
+ }
+ Blend::SoftLight => {
+ if s <= 0.5 {
+ b - (1.0 - 2.0 * s) * b * (1.0 - b)
+ } else {
+ let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() };
+ b + (2.0 * s - 1.0) * (d - b)
+ }
+ }
+ Blend::VividLight => {
+ if s <= 0.5 {
+ sep(Blend::ColorBurn, b, 2.0 * s)
+ } else {
+ sep(Blend::ColorDodge, b, 2.0 * s - 1.0)
+ }
+ }
+ Blend::LinearLight => (b + 2.0 * s - 1.0).clamp(0.0, 1.0),
+ Blend::PinLight => {
+ if s <= 0.5 {
+ b.min(2.0 * s)
+ } else {
+ b.max(2.0 * s - 1.0)
+ }
+ }
+ Blend::HardMix => {
+ if sep(Blend::VividLight, b, s) >= 0.5 {
+ 1.0
+ } else {
+ 0.0
+ }
+ }
+ Blend::Difference => (b - s).abs(),
+ Blend::Exclusion => b + s - 2.0 * b * s,
+ Blend::Subtract => (b - s).max(0.0),
+ Blend::Divide => {
+ if s <= 0.0 {
+ 1.0
+ } else {
+ (b / s).min(1.0)
+ }
+ }
+ _ => s,
+ }
+}
+
+#[inline]
+fn lum(c: [f32; 3]) -> f32 {
+ 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
+}
+fn clip_color(c: [f32; 3]) -> [f32; 3] {
+ let l = lum(c);
+ let n = c[0].min(c[1]).min(c[2]);
+ let x = c[0].max(c[1]).max(c[2]);
+ let mut o = c;
+ if n < 0.0 {
+ for v in &mut o {
+ *v = l + (*v - l) * l / (l - n).max(1e-6);
+ }
+ }
+ if x > 1.0 {
+ for v in &mut o {
+ *v = l + (*v - l) * (1.0 - l) / (x - l).max(1e-6);
+ }
+ }
+ o
+}
+fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {
+ let d = l - lum(c);
+ clip_color([c[0] + d, c[1] + d, c[2] + d])
+}
+fn sat(c: [f32; 3]) -> f32 {
+ c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
+}
+fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
+ let mx = c[0].max(c[1]).max(c[2]);
+ let mn = c[0].min(c[1]).min(c[2]);
+ if mx - mn <= 1e-6 {
+ return [0.0; 3];
+ }
+ let mut o = [0.0; 3];
+ for k in 0..3 {
+ o[k] = (c[k] - mn) * s / (mx - mn);
+ }
+ o
+}
+
+/// Blend function B(Cb, Cs) on straight, display-encoded colour.
+pub fn blend_rgb(mode: Blend, b: [f32; 3], s: [f32; 3]) -> [f32; 3] {
+ match mode {
+ Blend::Hue => set_lum(set_sat(s, sat(b)), lum(b)),
+ Blend::Saturation => set_lum(set_sat(b, sat(s)), lum(b)),
+ Blend::Color => set_lum(s, lum(b)),
+ Blend::Luminosity => set_lum(b, lum(s)),
+ Blend::DarkerColor => {
+ if lum(s) < lum(b) {
+ s
+ } else {
+ b
+ }
+ }
+ Blend::LighterColor => {
+ if lum(s) > lum(b) {
+ s
+ } else {
+ b
+ }
+ }
+ m => [sep(m, b[0], s[0]), sep(m, b[1], s[1]), sep(m, b[2], s[2])],
+ }
+}
+
+fn hash2(x: usize, y: usize) -> f32 {
+ let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
+ h ^= h >> 31;
+ h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ h ^= h >> 29;
+ (h >> 40) as f32 / (1u64 << 24) as f32
+}
+
+/// Composite `src` over `dst` (same size) with `opacity` and `mode`.
+pub fn composite(dst: &mut Image, src: &Image, opacity: f32, mode: Blend) {
+ debug_assert_eq!((dst.w, dst.h), (src.w, src.h));
+ let w = dst.w;
+ dst.px.par_chunks_mut(w * 4).zip(src.px.par_chunks(w * 4)).enumerate().for_each(|(y, (d, s))| {
+ for x in 0..w {
+ let i = x * 4;
+ let mut sp = [s[i] * opacity, s[i + 1] * opacity, s[i + 2] * opacity, s[i + 3] * opacity];
+ let sa = sp[3];
+ if sa <= 0.0 {
+ continue;
+ }
+ if mode == Blend::Dissolve {
+ if hash2(x, y) >= sa {
+ continue;
+ }
+ sp = [sp[0] / sa, sp[1] / sa, sp[2] / sa, 1.0];
+ }
+ let da = d[i + 3];
+ if mode == Blend::Normal || mode == Blend::Dissolve || da <= 0.0 {
+ let k = 1.0 - sp[3];
+ for c in 0..4 {
+ d[i + c] = sp[c] + d[i + c] * k;
+ }
+ continue;
+ }
+ let sa = sp[3];
+ let cs = [linear_to_srgb(sp[0] / sa), linear_to_srgb(sp[1] / sa), linear_to_srgb(sp[2] / sa)];
+ let cb = [linear_to_srgb(d[i] / da), linear_to_srgb(d[i + 1] / da), linear_to_srgb(d[i + 2] / da)];
+ let bl = blend_rgb(mode, cb, cs);
+ for c in 0..3 {
+ let mixed = srgb_to_linear(bl[c].clamp(0.0, 1.0));
+ d[i + c] = sp[c] * (1.0 - da) + d[i + c] * (1.0 - sa) + sa * da * mixed;
+ }
+ d[i + 3] = sa + da - sa * da;
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normal_over() {
+ let mut d = Image::filled(2, 1, [0.5, 0.0, 0.0, 1.0]);
+ let s = Image::filled(2, 1, [0.0, 0.25, 0.0, 0.5]);
+ composite(&mut d, &s, 1.0, Blend::Normal);
+ assert_eq!(d.get(0, 0), [0.25, 0.25, 0.0, 1.0]);
+ }
+
+ #[test]
+ fn multiply_white_is_identity() {
+ let base = [0.2, 0.4, 0.6, 1.0];
+ let mut d = Image::filled(1, 1, base);
+ let s = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]);
+ composite(&mut d, &s, 1.0, Blend::Multiply);
+ let p = d.get(0, 0);
+ for k in 0..3 {
+ assert!((p[k] - base[k]).abs() < 1e-4);
+ }
+ }
+
+ #[test]
+ fn all_modes_stay_in_range() {
+ for m in Blend::ALL {
+ let mut d = Image::filled(4, 4, [0.3, 0.1, 0.7, 1.0]);
+ let s = Image::filled(4, 4, [0.4, 0.4, 0.1, 0.8]);
+ composite(&mut d, &s, 0.9, m);
+ for v in &d.px {
+ assert!(v.is_finite() && *v >= -1e-5 && *v <= 1.0001, "{m:?} {v}");
+ }
+ }
+ }
+}
diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rs
new file mode 100644
index 000000000..a32d4b3ae
--- /dev/null
+++ b/crates/render/src/effects.rs
@@ -0,0 +1,1166 @@
+//! CPU reference implementations of the video effects in `filmcraft_project::effect`.
+//!
+//! Effects operate in place on a layer [`Image`] (premultiplied linear f32). Spatial parameters are
+//! authored in full-resolution clip pixels; `FxCtx::px_scale` converts them to the working image
+//! (so ½/¼ playback resolution renders the same look). Colour-grading math runs on display-encoded
+//! straight colour where artists expect it (contrast, levels, posterize), linear light elsewhere.
+
+use filmcraft_color::{hsl_to_rgb, linear_to_srgb, luma709, rgb_to_hsl, srgb_to_linear};
+use filmcraft_geom::{Affine, Vec2};
+use filmcraft_project::{EffectInstance, ParamValue};
+use filmcraft_time::Tick;
+use rayon::prelude::*;
+
+use crate::image::Image;
+
+/// Context for evaluating an effect at a time.
+pub struct FxCtx<'a> {
+ /// Media time used to evaluate keyframes.
+ pub t: Tick,
+ /// Working-image pixels per full-resolution clip pixel.
+ pub px_scale: f32,
+ /// Seconds since the clip start (for animated generators such as Noise/Strobe).
+ pub seconds: f64,
+ /// Formatted sequence timecode (for the Timecode effect).
+ pub timecode: &'a str,
+ pub clip_name: &'a str,
+}
+
+fn f(e: &EffectInstance, id: &str, cx: &FxCtx) -> f32 {
+ e.f64_at(id, cx.t) as f32
+}
+fn b(e: &EffectInstance, id: &str) -> bool {
+ e.param(id).and_then(|p| p.value.as_bool()).unwrap_or(false)
+}
+fn choice(e: &EffectInstance, id: &str) -> u32 {
+ match e.param(id).map(|p| &p.value) {
+ Some(ParamValue::Choice(c)) => *c,
+ _ => 0,
+ }
+}
+fn color(e: &EffectInstance, id: &str, cx: &FxCtx) -> [f32; 4] {
+ e.param(id).and_then(|p| p.value_at(cx.t).as_color()).unwrap_or([1.0; 4])
+}
+/// A point param in working-image pixels; NaN components default to the image centre.
+fn point(e: &EffectInstance, id: &str, cx: &FxCtx, img: &Image) -> Vec2 {
+ let v = e.param(id).map(|p| p.vec2_at(cx.t)).unwrap_or(Vec2::new(f64::NAN, f64::NAN));
+ Vec2::new(
+ if v.x.is_nan() { img.w as f64 / 2.0 } else { v.x * cx.px_scale as f64 },
+ if v.y.is_nan() { img.h as f64 / 2.0 } else { v.y * cx.px_scale as f64 },
+ )
+}
+
+#[inline]
+fn enc(c: [f32; 3]) -> [f32; 3] {
+ [linear_to_srgb(c[0].max(0.0)), linear_to_srgb(c[1].max(0.0)), linear_to_srgb(c[2].max(0.0))]
+}
+#[inline]
+fn dec(c: [f32; 3]) -> [f32; 3] {
+ [srgb_to_linear(c[0].clamp(0.0, 1.0)), srgb_to_linear(c[1].clamp(0.0, 1.0)), srgb_to_linear(c[2].clamp(0.0, 1.0))]
+}
+
+fn hash3(x: usize, y: usize, z: u64) -> f32 {
+ let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ z.wrapping_mul(0x1656_67B1_9E37_79F9);
+ h ^= h >> 31;
+ h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ h ^= h >> 29;
+ (h >> 40) as f32 / (1u64 << 24) as f32
+}
+
+/// Apply one effect. Unknown/unimplemented ids are a no-op (they still round-trip in the project).
+pub fn apply(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
+ if !e.enabled || img.w == 0 || img.h == 0 {
+ return;
+ }
+ match e.effect.as_str() {
+ "brightness_contrast" => {
+ let br = f(e, "brightness", cx) / 100.0 * 0.4;
+ let co = 1.0 + f(e, "contrast", cx) / 100.0;
+ img.map_rgb(|c, _, _| {
+ let c = enc(c);
+ dec(c.map(|v| (v - 0.5) * co + 0.5 + br))
+ });
+ }
+ "proc_amp" => {
+ let br = f(e, "brightness", cx) / 100.0 * 0.4;
+ let co = f(e, "contrast", cx) / 100.0;
+ let hue = f(e, "hue", cx) / 360.0;
+ let sat = f(e, "saturation", cx) / 100.0;
+ img.map_rgb(|c, _, _| {
+ let c = enc(c);
+ let mut hsl = rgb_to_hsl(c[0], c[1], c[2]);
+ hsl[0] = (hsl[0] + hue).rem_euclid(1.0);
+ hsl[1] = (hsl[1] * sat).clamp(0.0, 1.0);
+ let c = hsl_to_rgb(hsl[0], hsl[1], hsl[2]);
+ dec(c.map(|v| (v - 0.5) * co + 0.5 + br))
+ });
+ }
+ "tint" => {
+ let bl = color(e, "black", cx);
+ let wh = color(e, "white", cx);
+ let amt = f(e, "amount", cx) / 100.0;
+ img.map_rgb(|c, _, _| {
+ let l = linear_to_srgb(luma709(c[0], c[1], c[2]).max(0.0));
+ let t = [bl[0] + (wh[0] - bl[0]) * l, bl[1] + (wh[1] - bl[1]) * l, bl[2] + (wh[2] - bl[2]) * l];
+ let e = enc(c);
+ dec([e[0] + (t[0] - e[0]) * amt, e[1] + (t[1] - e[1]) * amt, e[2] + (t[2] - e[2]) * amt])
+ });
+ }
+ "black_white" => img.map_rgb(|c, _, _| {
+ let l = luma709(c[0], c[1], c[2]);
+ [l, l, l]
+ }),
+ "color_balance" => {
+ let g = |k: &str| f(e, k, cx) / 100.0 * 0.25;
+ let sh = [g("shadow_r"), g("shadow_g"), g("shadow_b")];
+ let md = [g("mid_r"), g("mid_g"), g("mid_b")];
+ let hi = [g("hi_r"), g("hi_g"), g("hi_b")];
+ let preserve = b(e, "preserve");
+ img.map_rgb(|c, _, _| {
+ let c = enc(c);
+ let l = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
+ let ws = (1.0 - l).powi(2);
+ let wh = l.powi(2);
+ let wm = 1.0 - ws - wh;
+ let mut o = [0.0; 3];
+ for k in 0..3 {
+ o[k] = c[k] + sh[k] * ws + md[k] * wm.max(0.0) + hi[k] * wh;
+ }
+ if preserve {
+ let l2 = 0.2126 * o[0] + 0.7152 * o[1] + 0.0722 * o[2];
+ let d = l - l2;
+ o = o.map(|v| v + d);
+ }
+ dec(o)
+ });
+ }
+ "leave_color" => {
+ let amt = f(e, "amount", cx) / 100.0;
+ let key = color(e, "color", cx);
+ let tol = f(e, "tolerance", cx) / 100.0;
+ let soft = f(e, "softness", cx) / 100.0 + 1e-4;
+ let kh = rgb_to_hsl(key[0], key[1], key[2])[0];
+ img.map_rgb(|c, _, _| {
+ let ec = enc(c);
+ let h = rgb_to_hsl(ec[0], ec[1], ec[2])[0];
+ let d = (h - kh).abs().min(1.0 - (h - kh).abs()) * 2.0;
+ let keep = 1.0 - ((d - tol) / soft).clamp(0.0, 1.0);
+ let l = luma709(c[0], c[1], c[2]);
+ let k = amt * (1.0 - keep);
+ [c[0] + (l - c[0]) * k, c[1] + (l - c[1]) * k, c[2] + (l - c[2]) * k]
+ });
+ }
+ "change_to_color" => {
+ let from = color(e, "from", cx);
+ let to = color(e, "to", cx);
+ let tol = f(e, "hue_tol", cx) / 100.0;
+ let soft = f(e, "softness", cx) / 100.0 * 0.3 + 1e-4;
+ let fh = rgb_to_hsl(from[0], from[1], from[2])[0];
+ let th = rgb_to_hsl(to[0], to[1], to[2])[0];
+ img.map_rgb(|c, _, _| {
+ let ec = enc(c);
+ let mut hsl = rgb_to_hsl(ec[0], ec[1], ec[2]);
+ let d = (hsl[0] - fh).abs().min(1.0 - (hsl[0] - fh).abs());
+ let w = 1.0 - ((d - tol) / soft).clamp(0.0, 1.0);
+ hsl[0] = (hsl[0] + (th - fh) * w).rem_euclid(1.0);
+ dec(hsl_to_rgb(hsl[0], hsl[1], hsl[2]))
+ });
+ }
+ "color_pass" => {
+ let key = color(e, "color", cx);
+ let sim = f(e, "similarity", cx) / 100.0;
+ let rev = b(e, "reverse");
+ img.map_rgb(|c, _, _| {
+ let ec = enc(c);
+ let d = ((ec[0] - key[0]).powi(2) + (ec[1] - key[1]).powi(2) + (ec[2] - key[2]).powi(2)).sqrt();
+ let pass = (d <= sim * 1.2) != rev;
+ if pass {
+ c
+ } else {
+ let l = luma709(c[0], c[1], c[2]);
+ [l, l, l]
+ }
+ });
+ }
+ "gamma_correction" => {
+ let g = f(e, "gamma", cx) / 10.0;
+ img.map_rgb(|c, _, _| dec(enc(c).map(|v| v.max(0.0).powf(g))));
+ }
+ "levels" => {
+ let ib = f(e, "in_black", cx) / 255.0;
+ let iw = (f(e, "in_white", cx) / 255.0).max(ib + 1e-3);
+ let ob = f(e, "out_black", cx) / 255.0;
+ let ow = f(e, "out_white", cx) / 255.0;
+ let g = 100.0 / f(e, "gamma", cx).max(1.0);
+ img.map_rgb(|c, _, _| dec(enc(c).map(|v| ob + (((v - ib) / (iw - ib)).clamp(0.0, 1.0)).powf(g) * (ow - ob))));
+ }
+ "extract" => {
+ let lo = f(e, "black", cx) / 255.0;
+ let hi = f(e, "white", cx) / 255.0;
+ let soft = f(e, "softness", cx) / 100.0 * 0.2 + 1e-4;
+ let inv = b(e, "invert");
+ img.map_rgb(|c, _, _| {
+ let l = linear_to_srgb(luma709(c[0], c[1], c[2]).max(0.0));
+ let inside = ((l - lo) / soft).clamp(0.0, 1.0).min(((hi - l) / soft).clamp(0.0, 1.0));
+ let v = if inv { 1.0 - inside } else { inside };
+ [v, v, v]
+ });
+ }
+ "invert" => {
+ let ch = choice(e, "channel");
+ let blend = f(e, "blend", cx) / 100.0;
+ if ch == 4 {
+ img.px.par_chunks_mut(4).for_each(|p| {
+ let a = p[3];
+ let na = 1.0 - a;
+ let k = if a > 1e-6 { na / a } else { 0.0 };
+ for c in &mut p[..3] {
+ *c *= k;
+ }
+ p[3] = na * (1.0 - blend) + a * blend;
+ });
+ } else {
+ img.map_rgb(|c, _, _| {
+ let ec = enc(c);
+ let mut o = ec;
+ for k in 0..3 {
+ if ch == 0 || ch as usize == k + 1 {
+ o[k] = 1.0 - ec[k];
+ }
+ }
+ dec([o[0] + (ec[0] - o[0]) * blend, o[1] + (ec[1] - o[1]) * blend, o[2] + (ec[2] - o[2]) * blend])
+ });
+ }
+ }
+ "posterize" => {
+ let n = f(e, "levels", cx).max(2.0) - 1.0;
+ img.map_rgb(|c, _, _| dec(enc(c).map(|v| (v * n).round() / n)));
+ }
+ "lumetri" => lumetri(img, e, cx),
+ "gaussian_blur" => {
+ let r = f(e, "blurriness", cx) * cx.px_scale * 0.5;
+ let dims = choice(e, "dimensions");
+ let repeat = b(e, "repeat_edge");
+ gaussian(img, if dims == 2 { 0.0 } else { r }, if dims == 1 { 0.0 } else { r }, repeat);
+ }
+ "camera_blur" => {
+ let r = f(e, "percent", cx) * cx.px_scale * 0.3;
+ gaussian(img, r, r, true);
+ }
+ "directional_blur" => {
+ let len = f(e, "length", cx) * cx.px_scale * 2.0;
+ let dir = (f(e, "direction", cx) as f64).to_radians();
+ directional_blur(img, len, dir);
+ }
+ "sharpen" => {
+ let amt = f(e, "amount", cx) / 100.0;
+ unsharp(img, 1.0 * cx.px_scale.max(0.35), amt, 0.0);
+ }
+ "unsharp_mask" => {
+ let amt = f(e, "amount", cx) / 100.0;
+ let r = f(e, "radius", cx) * cx.px_scale;
+ let th = f(e, "threshold", cx) / 255.0;
+ unsharp(img, r, amt, th);
+ }
+ "median" => {
+ let r = (f(e, "radius", cx) * cx.px_scale).round().clamp(0.0, 4.0) as isize;
+ if r > 0 {
+ median(img, r);
+ }
+ }
+ "noise" => {
+ let amt = f(e, "amount", cx) / 100.0;
+ let colored = b(e, "color");
+ let clip = b(e, "clip");
+ let frame = (cx.seconds * 30.0) as u64;
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let p = &mut row[x * 4..x * 4 + 4];
+ let a = p[3];
+ if a <= 0.0 {
+ continue;
+ }
+ let n0 = hash3(x, y, frame) - 0.5;
+ let ns = if colored { [n0, hash3(x, y, frame + 7777) - 0.5, hash3(x, y, frame + 99_991) - 0.5] } else { [n0; 3] };
+ let c = enc([p[0] / a, p[1] / a, p[2] / a]);
+ let mut o = [c[0] + ns[0] * amt, c[1] + ns[1] * amt, c[2] + ns[2] * amt];
+ if clip {
+ o = o.map(|v| v.clamp(0.0, 1.0));
+ }
+ let o = dec(o);
+ p[0] = o[0] * a;
+ p[1] = o[1] * a;
+ p[2] = o[2] * a;
+ }
+ });
+ }
+ "mosaic" => {
+ let bx = f(e, "horizontal", cx).max(1.0) as usize;
+ let by = f(e, "vertical", cx).max(1.0) as usize;
+ mosaic(img, bx, by);
+ }
+ "find_edges" => {
+ let inv = b(e, "invert");
+ let blend = f(e, "blend", cx) / 100.0;
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let l = |dx: isize, dy: isize| {
+ let p = src.get_clamped(x as isize + dx, y as isize + dy);
+ luma709(p[0], p[1], p[2])
+ };
+ let gx = l(1, -1) + 2.0 * l(1, 0) + l(1, 1) - l(-1, -1) - 2.0 * l(-1, 0) - l(-1, 1);
+ let gy = l(-1, 1) + 2.0 * l(0, 1) + l(1, 1) - l(-1, -1) - 2.0 * l(0, -1) - l(1, -1);
+ let mut m = (gx * gx + gy * gy).sqrt().min(1.0);
+ if !inv {
+ m = 1.0 - m;
+ }
+ let o = src.get(x, y);
+ let a = o[3];
+ for k in 0..3 {
+ row[x * 4 + k] = m * a * (1.0 - blend) + o[k] * blend;
+ }
+ }
+ });
+ }
+ "emboss" => {
+ let dir = (f(e, "direction", cx) as f64).to_radians();
+ let relief = f(e, "relief", cx) * cx.px_scale.max(0.25);
+ let contrast = f(e, "contrast", cx) / 100.0;
+ let blend = f(e, "blend", cx) / 100.0;
+ let (dx, dy) = ((dir.cos() as f32) * relief, (-dir.sin() as f32) * relief);
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let a = src.sample_bilinear_clamped(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy);
+ let bq = src.sample_bilinear_clamped(x as f32 + 0.5 - dx, y as f32 + 0.5 - dy);
+ let v = srgb_to_linear((0.5 + (luma709(a[0], a[1], a[2]) - luma709(bq[0], bq[1], bq[2])) * contrast * 2.0).clamp(0.0, 1.0));
+ let o = src.get(x, y);
+ for k in 0..3 {
+ row[x * 4 + k] = v * o[3] * (1.0 - blend) + o[k] * blend;
+ }
+ }
+ });
+ }
+ "replicate" => {
+ let n = f(e, "count", cx).clamp(1.0, 16.0) as usize;
+ let src = img.clone();
+ let (w, h) = (img.w, img.h);
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let u = (x * n) % w;
+ let v = (y * n) % h;
+ let s = src.sample_bilinear_clamped((u as f32 + 0.5) + (n as f32 - 1.0) * 0.5 / n as f32, v as f32 + 0.5);
+ row[x * 4..x * 4 + 4].copy_from_slice(&s);
+ }
+ });
+ }
+ "strobe" => {
+ let period = f(e, "period", cx).max(0.001) as f64;
+ let dur = f(e, "duration", cx) as f64;
+ if (cx.seconds % period) < dur {
+ let c = color(e, "color", cx);
+ let blend = f(e, "blend", cx) / 100.0;
+ let lc = dec([c[0], c[1], c[2]]);
+ img.map_rgb(|o, _, _| [lc[0] + (o[0] - lc[0]) * blend, lc[1] + (o[1] - lc[1]) * blend, lc[2] + (o[2] - lc[2]) * blend]);
+ }
+ }
+ "crop" => {
+ let l = f(e, "left", cx) / 100.0;
+ let t = f(e, "top", cx) / 100.0;
+ let r = f(e, "right", cx) / 100.0;
+ let bt = f(e, "bottom", cx) / 100.0;
+ let feather = f(e, "feather", cx) * cx.px_scale;
+ if b(e, "zoom") && l + r < 0.99 && t + bt < 0.99 {
+ let src = img.clone();
+ let (w, h) = (img.w as f64, img.h as f64);
+ let m =
+ Affine::scale(1.0 / (1.0 - (l + r) as f64), 1.0 / (1.0 - (t + bt) as f64)).then_apply(&Affine::translate(-(l as f64) * w, -(t as f64) * h));
+ *img = src.transformed(img.w, img.h, &m);
+ } else {
+ crop(img, l, t, r, bt, feather);
+ }
+ }
+ "horizontal_flip" => {
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).for_each(|row| {
+ for x in 0..w / 2 {
+ for k in 0..4 {
+ row.swap(x * 4 + k, (w - 1 - x) * 4 + k);
+ }
+ }
+ });
+ }
+ "vertical_flip" => {
+ let (w, h) = (img.w, img.h);
+ for y in 0..h / 2 {
+ let (a, bb) = img.px.split_at_mut((h - 1 - y) * w * 4);
+ a[y * w * 4..(y + 1) * w * 4].swap_with_slice(&mut bb[..w * 4]);
+ }
+ }
+ "edge_feather" => {
+ let amt = f(e, "amount", cx) / 100.0 * (img.w.min(img.h) as f32) * 0.5;
+ crop(img, 0.0, 0.0, 0.0, 0.0, amt);
+ }
+ "transform" => {
+ let anchor = point(e, "anchor", cx, img);
+ let pos = point(e, "position", cx, img);
+ let sh = f(e, "scale_height", cx) as f64 / 100.0;
+ let sw = if b(e, "uniform_scale") { sh } else { f(e, "scale_width", cx) as f64 / 100.0 };
+ let rot = f(e, "rotation", cx) as f64;
+ let skew = (f(e, "skew", cx) as f64).to_radians().tan();
+ let skew_axis = f(e, "skew_axis", cx) as f64;
+ let op = f(e, "opacity", cx) / 100.0;
+ let sk = Affine::rotate_deg(skew_axis)
+ .then_apply(&Affine { a: 1.0, b: 0.0, c: skew, d: 1.0, e: 0.0, f: 0.0 })
+ .then_apply(&Affine::rotate_deg(-skew_axis));
+ let m = Affine::translate(pos.x, pos.y)
+ .then_apply(&Affine::rotate_deg(rot))
+ .then_apply(&sk)
+ .then_apply(&Affine::scale(sw, sh))
+ .then_apply(&Affine::translate(-anchor.x, -anchor.y));
+ let mut out = img.transformed(img.w, img.h, &m);
+ out.scale_alpha(op);
+ *img = out;
+ }
+ "mirror" => {
+ let c = point(e, "center", cx, img);
+ let ang = (f(e, "angle", cx) as f64).to_radians();
+ let (nx, ny) = (ang.cos(), ang.sin());
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
+ let d = (px - c.x) * nx + (py - c.y) * ny;
+ if d > 0.0 {
+ let (rx, ry) = (px - 2.0 * d * nx, py - 2.0 * d * ny);
+ row[x * 4..x * 4 + 4].copy_from_slice(&src.sample_bilinear(rx as f32, ry as f32));
+ }
+ }
+ });
+ }
+ "offset" => {
+ let s = point(e, "shift", cx, img);
+ let (dx, dy) = (s.x - img.w as f64 / 2.0, s.y - img.h as f64 / 2.0);
+ let blend = f(e, "blend", cx) / 100.0;
+ let src = img.clone();
+ let (w, h) = (img.w as f64, img.h as f64);
+ let wi = img.w;
+ img.px.par_chunks_mut(wi * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..wi {
+ let u = (x as f64 + 0.5 - dx).rem_euclid(w);
+ let v = (y as f64 + 0.5 - dy).rem_euclid(h);
+ let p = src.sample_bilinear_clamped(u as f32, v as f32);
+ let o = src.get(x, y);
+ for k in 0..4 {
+ row[x * 4 + k] = p[k] + (o[k] - p[k]) * blend;
+ }
+ }
+ });
+ }
+ "twirl" => {
+ let c = point(e, "center", cx, img);
+ let ang = (f(e, "angle", cx) as f64).to_radians();
+ let rad = f(e, "radius", cx) as f64 / 100.0 * (img.w.min(img.h) as f64);
+ warp(img, |x, y| {
+ let (dx, dy) = (x - c.x, y - c.y);
+ let d = (dx * dx + dy * dy).sqrt();
+ if d >= rad {
+ return (x, y);
+ }
+ let k = 1.0 - d / rad;
+ let a = ang * k * k;
+ let (s, co) = a.sin_cos();
+ (c.x + dx * co - dy * s, c.y + dx * s + dy * co)
+ });
+ }
+ "wave_warp" => {
+ let hgt = f(e, "height", cx) as f64 * cx.px_scale as f64;
+ let wid = (f(e, "width", cx) as f64 * cx.px_scale as f64).max(1.0);
+ let dir = (f(e, "direction", cx) as f64).to_radians();
+ let phase = cx.seconds * f(e, "speed", cx) as f64 * std::f64::consts::TAU;
+ let (ux, uy) = (dir.sin(), -dir.cos());
+ warp(img, |x, y| {
+ let along = x * ux + y * uy;
+ let off = hgt * (along / wid * std::f64::consts::TAU - phase).sin();
+ (x - uy * off, y + ux * off)
+ });
+ }
+ "lens_distortion" => {
+ let k = f(e, "curvature", cx) as f64 / 100.0;
+ let (cxp, cyp) = (
+ img.w as f64 / 2.0 + f(e, "h_decentering", cx) as f64 / 100.0 * img.w as f64 / 2.0,
+ img.h as f64 / 2.0 + f(e, "v_decentering", cx) as f64 / 100.0 * img.h as f64 / 2.0,
+ );
+ let norm = (img.w as f64 / 2.0).hypot(img.h as f64 / 2.0);
+ warp(img, |x, y| {
+ let (dx, dy) = ((x - cxp) / norm, (y - cyp) / norm);
+ let r2 = dx * dx + dy * dy;
+ let s = 1.0 - k * r2;
+ (cxp + dx * s * norm, cyp + dy * s * norm)
+ });
+ }
+ "basic_3d" => {
+ let sw = (f(e, "swivel", cx) as f64).to_radians();
+ let tl = (f(e, "tilt", cx) as f64).to_radians();
+ let dist = f(e, "distance", cx) as f64;
+ let (w, h) = (img.w as f64, img.h as f64);
+ let focal = w.max(h) * 1.2;
+ // inverse perspective mapping: ray through (x,y) intersected with rotated plane
+ warp_opt(img, |x, y| {
+ let (px, py) = (x - w / 2.0, y - h / 2.0);
+ let (ss, cs) = sw.sin_cos();
+ let (st, ct) = tl.sin_cos();
+ // plane normal after rotation (Ry(swivel) * Rx(tilt)) of (0,0,1)
+ let n = [ss * ct, -st, cs * ct];
+ let u = [cs, 0.0, -ss];
+ let v = [ss * st, ct, cs * st];
+ let z0 = focal + dist * 10.0;
+ let dir = [px, py, focal];
+ let denom = n[0] * dir[0] + n[1] * dir[1] + n[2] * dir[2];
+ if denom.abs() < 1e-9 {
+ return None;
+ }
+ let tt = (n[2] * z0) / denom;
+ if tt <= 0.0 {
+ return None;
+ }
+ let hit = [dir[0] * tt, dir[1] * tt, dir[2] * tt - z0];
+ let su = hit[0] * u[0] + hit[1] * u[1] + hit[2] * u[2];
+ let sv = hit[0] * v[0] + hit[1] * v[1] + hit[2] * v[2];
+ Some((su + w / 2.0, sv + h / 2.0))
+ });
+ }
+ "drop_shadow" => {
+ let c = color(e, "color", cx);
+ let op = f(e, "opacity", cx) / 100.0;
+ let dir = (f(e, "direction", cx) as f64).to_radians();
+ let dist = f(e, "distance", cx) as f64 * cx.px_scale as f64;
+ let soft = f(e, "softness", cx) * cx.px_scale * 0.5;
+ let only = b(e, "only");
+ let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist);
+ let lc = dec([c[0], c[1], c[2]]);
+ let mut sh = img.transformed(img.w, img.h, &Affine::translate(dx, dy));
+ sh.px.par_chunks_mut(4).for_each(|p| {
+ let a = p[3] * op;
+ p[0] = lc[0] * a;
+ p[1] = lc[1] * a;
+ p[2] = lc[2] * a;
+ p[3] = a;
+ });
+ if soft > 0.3 {
+ gaussian(&mut sh, soft, soft, false);
+ }
+ if !only {
+ crate::blend::composite(&mut sh, img, 1.0, crate::blend::Blend::Normal);
+ }
+ *img = sh;
+ }
+ "bevel_alpha" => {
+ let th = f(e, "thickness", cx) * cx.px_scale;
+ let ang = (f(e, "angle", cx) as f64).to_radians();
+ let inten = f(e, "intensity", cx) / 100.0;
+ let src = img.clone();
+ let (lx, ly) = (ang.cos() as f32, -ang.sin() as f32);
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let a = |dx: f32, dy: f32| src.sample_bilinear_clamped(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy)[3];
+ let gx = a(th, 0.0) - a(-th, 0.0);
+ let gy = a(0.0, th) - a(0.0, -th);
+ let shade = -(gx * lx + gy * ly) * inten;
+ let p = &mut row[x * 4..x * 4 + 4];
+ for k in 0..3 {
+ p[k] = (p[k] + shade * p[3]).clamp(0.0, p[3]);
+ }
+ }
+ });
+ }
+ "ultra_key" | "color_key" => key(img, e, cx),
+ "luma_key" => {
+ let th = f(e, "threshold", cx) / 100.0;
+ let cut = f(e, "cutoff", cx) / 100.0;
+ img.px.par_chunks_mut(4).for_each(|p| {
+ if p[3] <= 0.0 {
+ return;
+ }
+ let l = linear_to_srgb(luma709(p[0] / p[3], p[1] / p[3], p[2] / p[3]).max(0.0));
+ let a = if l <= cut {
+ 0.0
+ } else if l >= th.max(cut + 1e-3) {
+ 1.0
+ } else {
+ (l - cut) / (th - cut).max(1e-3)
+ };
+ for v in p.iter_mut() {
+ *v *= a;
+ }
+ });
+ }
+ "four_color_gradient" => {
+ let cs = [color(e, "c1", cx), color(e, "c2", cx), color(e, "c3", cx), color(e, "c4", cx)];
+ let op = f(e, "opacity", cx) / 100.0;
+ let (w, h) = (img.w as f32, img.h as f32);
+ let pts = [(0.25 * w, 0.25 * h), (0.75 * w, 0.25 * h), (0.25 * w, 0.75 * h), (0.75 * w, 0.75 * h)];
+ let blend_exp = 1.0 + f(e, "blend", cx) / 100.0;
+ fill_over(img, op, |x, y| {
+ let mut acc = [0.0f32; 3];
+ let mut wsum = 0.0;
+ for (i, p) in pts.iter().enumerate() {
+ let d = ((x - p.0).powi(2) + (y - p.1).powi(2)).sqrt().max(1.0);
+ let wgt = 1.0 / d.powf(blend_exp);
+ for k in 0..3 {
+ acc[k] += cs[i][k] * wgt;
+ }
+ wsum += wgt;
+ }
+ dec(acc.map(|v| v / wsum))
+ });
+ }
+ "ramp" => {
+ let s = point(e, "start", cx, img);
+ let en = point(e, "end", cx, img);
+ let sc = color(e, "start_color", cx);
+ let ec = color(e, "end_color", cx);
+ let radial = choice(e, "shape") == 1;
+ let blend = f(e, "blend", cx) / 100.0;
+ let (vx, vy) = (en.x - s.x, en.y - s.y);
+ let len2 = (vx * vx + vy * vy).max(1e-9);
+ fill_over(img, 1.0 - blend, |x, y| {
+ let t = if radial {
+ ((x as f64 - s.x).hypot(y as f64 - s.y) / len2.sqrt()) as f32
+ } else {
+ (((x as f64 - s.x) * vx + (y as f64 - s.y) * vy) / len2) as f32
+ }
+ .clamp(0.0, 1.0);
+ dec([sc[0] + (ec[0] - sc[0]) * t, sc[1] + (ec[1] - sc[1]) * t, sc[2] + (ec[2] - sc[2]) * t])
+ });
+ }
+ "circle" => {
+ let c = point(e, "center", cx, img);
+ let r = f(e, "radius", cx) * cx.px_scale;
+ let col = color(e, "color", cx);
+ let op = f(e, "opacity", cx) / 100.0;
+ let lc = dec([col[0], col[1], col[2]]);
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let d = ((x as f64 + 0.5 - c.x).hypot(y as f64 + 0.5 - c.y)) as f32;
+ let a = (r - d + 0.5).clamp(0.0, 1.0) * op;
+ if a > 0.0 {
+ let p = &mut row[x * 4..x * 4 + 4];
+ for k in 0..3 {
+ p[k] = lc[k] * a + p[k] * (1.0 - a);
+ }
+ p[3] = a + p[3] * (1.0 - a);
+ }
+ }
+ });
+ }
+ "grid" => {
+ let size = (f(e, "size", cx) * cx.px_scale).max(1.0);
+ let border = f(e, "border", cx) * cx.px_scale;
+ let col = color(e, "color", cx);
+ let op = f(e, "opacity", cx) / 100.0;
+ let lc = dec([col[0], col[1], col[2]]);
+ let w = img.w;
+ let (ox, oy) = (img.w as f32 / 2.0, img.h as f32 / 2.0);
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let gx = ((x as f32 - ox).rem_euclid(size)).min(size - (x as f32 - ox).rem_euclid(size));
+ let gy = ((y as f32 - oy).rem_euclid(size)).min(size - (y as f32 - oy).rem_euclid(size));
+ let a = ((border * 0.5 - gx.min(gy) + 0.5).clamp(0.0, 1.0)) * op;
+ if a > 0.0 {
+ let p = &mut row[x * 4..x * 4 + 4];
+ for k in 0..3 {
+ p[k] = lc[k] * a + p[k] * (1.0 - a);
+ }
+ p[3] = a + p[3] * (1.0 - a);
+ }
+ }
+ });
+ }
+ "lens_flare" => {
+ let c = point(e, "center", cx, img);
+ let br = f(e, "brightness", cx) / 100.0;
+ let blend = f(e, "blend", cx) / 100.0;
+ let (w, h) = (img.w as f64, img.h as f64);
+ let (mx, my) = (w / 2.0, h / 2.0);
+ let scale = w.max(h);
+ let wi = img.w;
+ img.px.par_chunks_mut(wi * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..wi {
+ let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
+ let d = (px - c.x).hypot(py - c.y) / scale;
+ let mut add = [1.0f32, 0.9, 0.7].map(|k| k * (0.35 * (-d * 18.0).exp() + 0.08 * (-d * 3.0).exp()) as f32);
+ for (i, (t, rad, tint)) in [(0.5, 0.05, [0.4f32, 0.6, 1.0]), (1.3, 0.03, [1.0, 0.5, 0.3]), (1.7, 0.08, [0.4, 1.0, 0.5])].iter().enumerate()
+ {
+ let gx = c.x + (mx - c.x) * 2.0 * t / 2.0 * 2.0;
+ let gy = c.y + (my - c.y) * 2.0 * t / 2.0 * 2.0;
+ let dd = (px - gx).hypot(py - gy) / scale;
+ let ring = (1.0 - ((dd - rad) / 0.01).abs()).max(0.0) as f32 * 0.15 + if dd < *rad { 0.06 } else { 0.0 };
+ let _ = i;
+ for k in 0..3 {
+ add[k] += tint[k] * ring;
+ }
+ }
+ let p = &mut row[x * 4..x * 4 + 4];
+ for k in 0..3 {
+ p[k] += add[k] * br * (1.0 - blend) * p[3].max(0.0);
+ }
+ }
+ });
+ }
+ "timecode" | "clip_name" => {
+ let text = if e.effect == "timecode" {
+ cx.timecode.to_string()
+ } else {
+ cx.clip_name.chars().filter(|c| c.is_ascii_digit() || *c == ':' || *c == '-').collect()
+ };
+ let pos = point(e, "position", cx, img);
+ let size = (f(e, "size", cx) / 100.0 * img.h as f32 * 0.5).max(6.0) as i32;
+ burn_text(img, &text, pos, size);
+ }
+ _ => {}
+ }
+}
+
+fn burn_text(img: &mut Image, text: &str, pos: Vec2, size: i32) {
+ let tw = filmcraft_media::digits::text_width(size, text);
+ let (w, h) = (img.w, img.h);
+ let mut buf = vec![0u8; w * h * 4];
+ let x = pos.x as i32 - tw / 2;
+ let y = pos.y as i32 - size / 2;
+ filmcraft_media::digits::fill_rect(&mut buf, w, h, x - size / 4, y - size / 4, tw + size / 2, size + size / 2, [0, 0, 0, 200]);
+ filmcraft_media::digits::draw_text(&mut buf, w, h, x, y, size, text, [255, 255, 255, 255]);
+ img.px.par_chunks_mut(w * 4).zip(buf.par_chunks(w * 4)).for_each(|(d, s)| {
+ for (d, s) in d.chunks_exact_mut(4).zip(s.chunks_exact(4)) {
+ let a = s[3] as f32 / 255.0;
+ if a > 0.0 {
+ for k in 0..3 {
+ d[k] = srgb_to_linear(s[k] as f32 / 255.0) * a + d[k] * (1.0 - a);
+ }
+ d[3] = a + d[3] * (1.0 - a);
+ }
+ }
+ });
+}
+
+/// Fill an opaque generated colour over the image at `op` opacity (Generate category).
+fn fill_over(img: &mut Image, op: f32, f: impl Fn(f32, f32) -> [f32; 3] + Sync) {
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let c = f(x as f32 + 0.5, y as f32 + 0.5);
+ let p = &mut row[x * 4..x * 4 + 4];
+ for k in 0..3 {
+ p[k] = c[k] * op + p[k] * (1.0 - op);
+ }
+ p[3] = op + p[3] * (1.0 - op);
+ }
+ });
+}
+
+fn warp(img: &mut Image, f: impl Fn(f64, f64) -> (f64, f64) + Sync) {
+ warp_opt(img, |x, y| Some(f(x, y)));
+}
+
+fn warp_opt(img: &mut Image, f: impl Fn(f64, f64) -> Option<(f64, f64)> + Sync) {
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let p = match f(x as f64 + 0.5, y as f64 + 0.5) {
+ Some((u, v)) => src.sample_bilinear(u as f32, v as f32),
+ None => [0.0; 4],
+ };
+ row[x * 4..x * 4 + 4].copy_from_slice(&p);
+ }
+ });
+}
+
+fn crop(img: &mut Image, l: f32, t: f32, r: f32, b: f32, feather: f32) {
+ let (w, h) = (img.w as f32, img.h as f32);
+ let (x0, x1, y0, y1) = (l * w, w * (1.0 - r), t * h, h * (1.0 - b));
+ let fe = feather.max(0.0);
+ let wi = img.w;
+ img.px.par_chunks_mut(wi * 4).enumerate().for_each(|(y, row)| {
+ let py = y as f32 + 0.5;
+ for x in 0..wi {
+ let px = x as f32 + 0.5;
+ let d = (px - x0).min(x1 - px).min(py - y0).min(y1 - py);
+ let a = if fe > 0.0 { (d / fe).clamp(0.0, 1.0) } else { (d + 0.5).clamp(0.0, 1.0) };
+ if a < 1.0 {
+ for v in &mut row[x * 4..x * 4 + 4] {
+ *v *= a;
+ }
+ }
+ }
+ });
+}
+
+fn key(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
+ let ultra = e.effect == "ultra_key";
+ let kc = if ultra { color(e, "key_color", cx) } else { color(e, "color", cx) };
+ let kycc = filmcraft_color::rgb_to_ycbcr(kc[0], kc[1], kc[2], filmcraft_color::Matrix::Bt709);
+ let (tol, soft, spill, output) = if ultra {
+ let tol = 0.05 + f(e, "tolerance", cx) / 100.0 * 0.25 + f(e, "transparency", cx) / 100.0 * 0.05;
+ (tol, 0.05 + f(e, "soften", cx) / 100.0 * 0.2 + f(e, "pedestal", cx) / 100.0 * 0.05, f(e, "spill", cx) / 100.0, choice(e, "output"))
+ } else {
+ (f(e, "tolerance", cx) / 255.0 * 0.6 + 0.01, f(e, "feather", cx) / 50.0 * 0.2 + 0.01, 0.0, 0)
+ };
+ let dom = if kc[1] >= kc[0] && kc[1] >= kc[2] {
+ 1
+ } else if kc[2] >= kc[0] {
+ 2
+ } else {
+ 0
+ };
+ img.px.par_chunks_mut(4).for_each(|p| {
+ if p[3] <= 0.0 {
+ return;
+ }
+ let c = enc([p[0] / p[3], p[1] / p[3], p[2] / p[3]]);
+ let ycc = filmcraft_color::rgb_to_ycbcr(c[0], c[1], c[2], filmcraft_color::Matrix::Bt709);
+ let d = ((ycc[1] - kycc[1]).powi(2) + (ycc[2] - kycc[2]).powi(2)).sqrt() + (ycc[0] - kycc[0]).abs() * 0.15;
+ let alpha = ((d - tol) / soft).clamp(0.0, 1.0);
+ let mut o = c;
+ if spill > 0.0 {
+ let others = (o[(dom + 1) % 3] + o[(dom + 2) % 3]) / 2.0;
+ if o[dom] > others {
+ o[dom] -= (o[dom] - others) * spill;
+ }
+ }
+ let a = p[3] * alpha;
+ let lo = dec(o);
+ match output {
+ 1 => {
+ p.copy_from_slice(&[alpha * p[3], alpha * p[3], alpha * p[3], p[3]]);
+ }
+ _ => {
+ p[0] = lo[0] * a;
+ p[1] = lo[1] * a;
+ p[2] = lo[2] * a;
+ p[3] = a;
+ }
+ }
+ });
+}
+
+fn lumetri(img: &mut Image, e: &EffectInstance, cx: &FxCtx) {
+ let temp = f(e, "temperature", cx) / 100.0;
+ let tint = f(e, "tint", cx) / 100.0;
+ let exposure = 2f32.powf(f(e, "exposure", cx));
+ let contrast = f(e, "contrast", cx) / 100.0;
+ let hl = f(e, "highlights", cx) / 100.0;
+ let sh = f(e, "shadows", cx) / 100.0;
+ let wh = f(e, "whites", cx) / 100.0;
+ let bl = f(e, "blacks", cx) / 100.0;
+ let sat = f(e, "saturation", cx) / 100.0 * f(e, "creative_sat", cx) / 100.0;
+ let vib = f(e, "vibrance", cx) / 100.0;
+ let faded = f(e, "faded_film", cx) / 100.0;
+ let st = color(e, "shadow_tint", cx);
+ let ht = color(e, "highlight_tint", cx);
+ let va = f(e, "vignette_amount", cx);
+ let vmid = f(e, "vignette_midpoint", cx) / 100.0;
+ let vround = f(e, "vignette_roundness", cx) / 100.0;
+ let vfeather = f(e, "vignette_feather", cx) / 100.0;
+ let sharpen = f(e, "sharpen", cx) / 100.0;
+ let gains = [1.0 + 0.35 * temp, 1.0 - 0.3 * tint, 1.0 - 0.35 * temp];
+ let (w, h) = (img.w as f32, img.h as f32);
+ let aspect = w / h;
+ img.map_rgb(|c, x, y| {
+ // white balance + exposure in linear light
+ let lin = [c[0] * gains[0] * exposure, c[1] * gains[1] * exposure, c[2] * gains[2] * exposure];
+ let mut v = enc(lin);
+ // whites / blacks: endpoints
+ let b0 = -bl * 0.15;
+ let w0 = 1.0 - wh * 0.15;
+ v = v.map(|q| (q - b0) / (w0 - b0).max(1e-3));
+ // highlights / shadows: luma-weighted lift/compress, hue preserving
+ let l = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
+ let ws = (1.0 - l).clamp(0.0, 1.0).powi(3);
+ let whl = l.clamp(0.0, 1.0).powi(3);
+ let nl = (l + sh * 0.35 * ws + hl * 0.35 * whl).max(0.0);
+ if l > 1e-5 {
+ let k = nl / l;
+ v = v.map(|q| q * k);
+ }
+ // contrast: smooth S-curve around mid grey
+ if contrast.abs() > 1e-4 {
+ let k = 1.0 + contrast;
+ v = v.map(|q| {
+ let q = q.clamp(0.0, 1.0);
+ let s = q * q * (3.0 - 2.0 * q);
+ if k >= 1.0 { q + (s - q) * (k - 1.0) } else { 0.5 + (q - 0.5) * k }
+ });
+ }
+ // faded film: lift blacks and compress
+ if faded > 0.0 {
+ v = v.map(|q| q * (1.0 - 0.25 * faded) + 0.12 * faded);
+ }
+ // split tone
+ let l2 = (0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2]).clamp(0.0, 1.0);
+ for k in 0..3 {
+ v[k] += (st[k] - 0.5) * 0.3 * (1.0 - l2) + (ht[k] - 0.5) * 0.3 * l2;
+ }
+ // saturation & vibrance
+ let l3 = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
+ let cur_sat = v[0].max(v[1]).max(v[2]) - v[0].min(v[1]).min(v[2]);
+ let s = sat * (1.0 + vib * (1.0 - cur_sat.clamp(0.0, 1.0)));
+ v = v.map(|q| l3 + (q - l3) * s);
+ // vignette
+ if va.abs() > 1e-4 {
+ let nx = (x as f32 / w - 0.5) * 2.0 * (1.0 + vround * 0.0) * if vround < 0.0 { aspect.powf(-vround) } else { 1.0 };
+ let ny = (y as f32 / h - 0.5) * 2.0;
+ let d = (nx * nx + ny * ny).sqrt() / std::f32::consts::SQRT_2;
+ let edge = ((d - vmid * 0.9) / (vfeather.max(0.01) * 0.9)).clamp(0.0, 1.0);
+ let e2 = edge * edge * (3.0 - 2.0 * edge);
+ let k = 1.0 + va * 0.2 * e2;
+ v = v.map(|q| if va < 0.0 { q * k.max(0.0) } else { q + (1.0 - q) * (k - 1.0) });
+ }
+ dec(v)
+ });
+ if sharpen.abs() > 1e-3 {
+ unsharp(img, 1.2 * cx.px_scale.max(0.35), sharpen.max(-1.0), 0.0);
+ }
+}
+
+// ---------- blur kernels ----------
+
+/// Box radii for an n-pass box blur approximating a Gaussian of sigma (Kovesi / Wells).
+fn boxes_for_gauss(sigma: f32, n: usize) -> Vec<usize> {
+ let wideal = ((12.0 * sigma * sigma / n as f32) + 1.0).sqrt();
+ let mut wl = wideal.floor() as i32;
+ if wl % 2 == 0 {
+ wl -= 1;
+ }
+ let wu = wl + 2;
+ let mideal = (12.0 * sigma * sigma - (n as i32 * wl * wl) as f32 - 4.0 * n as f32 * wl as f32 - 3.0 * n as f32) / (-4.0 * wl as f32 - 4.0);
+ let m = mideal.round() as i32;
+ (0..n as i32).map(|i| (((if i < m { wl } else { wu }) - 1) / 2).max(0) as usize).collect()
+}
+
+fn box_rows(px: &mut [f32], w: usize, r: usize, repeat: bool) {
+ if r == 0 {
+ return;
+ }
+ px.par_chunks_mut(w * 4).for_each_init(
+ || vec![0f32; w * 4],
+ |tmp, row| {
+ tmp.copy_from_slice(row);
+ let inv = 1.0 / (2 * r + 1) as f32;
+ let fetch = |i: isize| -> usize { if repeat { i.clamp(0, w as isize - 1) as usize } else { i as usize } };
+ let mut acc = [0f32; 4];
+ for i in -(r as isize)..=(r as isize) {
+ if repeat || (i >= 0 && (i as usize) < w) {
+ let j = fetch(i);
+ for k in 0..4 {
+ acc[k] += tmp[j * 4 + k];
+ }
+ }
+ }
+ for x in 0..w {
+ for k in 0..4 {
+ row[x * 4 + k] = acc[k] * inv;
+ }
+ let out_i = x as isize - r as isize;
+ let in_i = x as isize + r as isize + 1;
+ if repeat || out_i >= 0 {
+ let j = fetch(out_i);
+ for k in 0..4 {
+ acc[k] -= tmp[j * 4 + k];
+ }
+ }
+ if repeat || (in_i as usize) < w {
+ let j = fetch(in_i);
+ for k in 0..4 {
+ acc[k] += tmp[j * 4 + k];
+ }
+ }
+ }
+ },
+ );
+}
+
+fn transpose(img: &Image) -> Image {
+ let (w, h) = (img.w, img.h);
+ let mut out = Image::new(h, w);
+ const B: usize = 32;
+ out.px.par_chunks_mut(h * 4 * B).enumerate().for_each(|(bi, chunk)| {
+ let x0 = bi * B;
+ let rows = chunk.len() / (h * 4);
+ for y in 0..h {
+ for dx in 0..rows {
+ let x = x0 + dx;
+ let s = (y * w + x) * 4;
+ let d = (dx * h + y) * 4;
+ chunk[d..d + 4].copy_from_slice(&img.px[s..s + 4]);
+ }
+ }
+ });
+ out
+}
+
+/// Gaussian blur via 3 box passes per axis (O(1) per pixel for any radius).
+pub fn gaussian(img: &mut Image, sigma_x: f32, sigma_y: f32, repeat_edge: bool) {
+ if sigma_x > 0.3 {
+ for r in boxes_for_gauss(sigma_x, 3) {
+ box_rows(&mut img.px, img.w, r, repeat_edge);
+ }
+ }
+ if sigma_y > 0.3 {
+ let mut t = transpose(img);
+ for r in boxes_for_gauss(sigma_y, 3) {
+ box_rows(&mut t.px, t.w, r, repeat_edge);
+ }
+ *img = transpose(&t);
+ }
+}
+
+fn unsharp(img: &mut Image, radius: f32, amount: f32, threshold: f32) {
+ let mut blurred = img.clone();
+ gaussian(&mut blurred, radius, radius, true);
+ img.px.par_chunks_mut(4).zip(blurred.px.par_chunks(4)).for_each(|(p, bq)| {
+ for k in 0..3 {
+ let d = p[k] - bq[k];
+ if d.abs() >= threshold * p[3] {
+ p[k] = (p[k] + d * amount).clamp(0.0, p[3].max(p[k] + d * amount).max(0.0));
+ p[k] = p[k].max(0.0);
+ }
+ }
+ });
+}
+
+fn directional_blur(img: &mut Image, len: f32, dir: f64) {
+ if len < 0.5 {
+ return;
+ }
+ let steps = (len.ceil() as usize).clamp(2, 64);
+ let (dx, dy) = ((dir.sin() as f32) * len, (-dir.cos() as f32) * len);
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let mut acc = [0f32; 4];
+ for s in 0..steps {
+ let t = s as f32 / (steps - 1) as f32 - 0.5;
+ let p = src.sample_bilinear_clamped(x as f32 + 0.5 + dx * t, y as f32 + 0.5 + dy * t);
+ for k in 0..4 {
+ acc[k] += p[k];
+ }
+ }
+ for k in 0..4 {
+ row[x * 4 + k] = acc[k] / steps as f32;
+ }
+ }
+ });
+}
+
+fn median(img: &mut Image, r: isize) {
+ let src = img.clone();
+ let w = img.w;
+ img.px.par_chunks_mut(w * 4).enumerate().for_each_init(Vec::new, |buf: &mut Vec<f32>, (y, row)| {
+ for x in 0..w {
+ for k in 0..4 {
+ buf.clear();
+ for dy in -r..=r {
+ for dx in -r..=r {
+ buf.push(src.get_clamped(x as isize + dx, y as isize + dy)[k]);
+ }
+ }
+ let mid = buf.len() / 2;
+ buf.select_nth_unstable_by(mid, |a, b| a.total_cmp(b));
+ row[x * 4 + k] = buf[mid];
+ }
+ }
+ });
+}
+
+fn mosaic(img: &mut Image, bx: usize, by: usize) {
+ let (w, h) = (img.w, img.h);
+ let bw = (w as f32 / bx as f32).max(1.0);
+ let bh = (h as f32 / by as f32).max(1.0);
+ let src = img.clone();
+ img.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ let cy = ((y as f32 / bh).floor() + 0.5) * bh;
+ for x in 0..w {
+ let cxp = ((x as f32 / bw).floor() + 0.5) * bw;
+ let p = src.sample_bilinear_clamped(cxp, cy);
+ row[x * 4..x * 4 + 4].copy_from_slice(&p);
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_project::find_effect;
+
+ fn cx() -> FxCtx<'static> {
+ FxCtx { t: Tick::ZERO, px_scale: 1.0, seconds: 0.0, timecode: "00:00:01:00", clip_name: "x" }
+ }
+
+ #[test]
+ fn every_effect_runs_and_stays_finite() {
+ for def in filmcraft_project::effect_defs() {
+ if def.kind != filmcraft_project::EffectKind::Video || def.intrinsic {
+ continue;
+ }
+ let mut img = Image::filled(24, 16, [0.2, 0.4, 0.1, 1.0]);
+ let mut e = def.instance();
+ // push params away from identity so code paths run
+ for (id, p) in e.params.iter_mut() {
+ if let ParamValue::Float(v) = &mut p.value
+ && let Some(filmcraft_project::ParamKind::Float { soft_max, .. }) = def.param(id).map(|d| &d.kind)
+ {
+ *v = (*v + soft_max * 0.3).min(*soft_max);
+ }
+ }
+ apply(&mut img, &e, &cx());
+ assert!(img.px.iter().all(|v| v.is_finite()), "{}", def.id);
+ }
+ }
+
+ #[test]
+ fn gaussian_preserves_mean_and_blurs() {
+ let mut img = Image::new(64, 64);
+ for y in 28..36 {
+ for x in 28..36 {
+ let i = (y * 64 + x) * 4;
+ img.px[i..i + 4].copy_from_slice(&[1.0, 1.0, 1.0, 1.0]);
+ }
+ }
+ let sum0: f32 = img.px.iter().sum();
+ gaussian(&mut img, 4.0, 4.0, false);
+ let sum1: f32 = img.px.iter().sum();
+ assert!((sum0 - sum1).abs() / sum0 < 0.02, "{sum0} {sum1}");
+ assert!(img.get(32, 32)[0] < 0.9 && img.get(24, 32)[0] > 0.01);
+ }
+
+ #[test]
+ fn flip_and_crop() {
+ let mut img = Image::new(4, 1);
+ img.px[0..4].copy_from_slice(&[1.0, 0.0, 0.0, 1.0]);
+ apply(&mut img, &find_effect("horizontal_flip").unwrap().instance(), &cx());
+ assert_eq!(img.get(3, 0), [1.0, 0.0, 0.0, 1.0]);
+ let mut e = find_effect("crop").unwrap().instance();
+ e.params.get_mut("right").unwrap().value = ParamValue::Float(50.0);
+ apply(&mut img, &e, &cx());
+ assert_eq!(img.get(3, 0)[3], 0.0);
+ }
+
+ #[test]
+ fn identity_lumetri_is_identity() {
+ let mut img = Image::filled(8, 8, [0.18, 0.3, 0.05, 1.0]);
+ let before = img.clone();
+ apply(&mut img, &find_effect("lumetri").unwrap().instance(), &cx());
+ for (a, b) in img.px.iter().zip(&before.px) {
+ assert!((a - b).abs() < 2e-3, "{a} {b}");
+ }
+ }
+}
diff --git a/crates/render/src/image.rs b/crates/render/src/image.rs
new file mode 100644
index 000000000..e1c185e1d
--- /dev/null
+++ b/crates/render/src/image.rs
@@ -0,0 +1,189 @@
+//! The compositor's working image: premultiplied linear-light RGBA f32, row-major.
+
+use filmcraft_geom::Affine;
+use rayon::prelude::*;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Image {
+ pub w: usize,
+ pub h: usize,
+ pub px: Vec<f32>,
+}
+
+impl Image {
+ pub fn new(w: usize, h: usize) -> Self {
+ Self { w, h, px: vec![0.0; w * h * 4] }
+ }
+ pub fn filled(w: usize, h: usize, c: [f32; 4]) -> Self {
+ let mut px = Vec::with_capacity(w * h * 4);
+ for _ in 0..w * h {
+ px.extend_from_slice(&c);
+ }
+ Self { w, h, px }
+ }
+ #[inline]
+ pub fn get(&self, x: usize, y: usize) -> [f32; 4] {
+ let i = (y * self.w + x) * 4;
+ [self.px[i], self.px[i + 1], self.px[i + 2], self.px[i + 3]]
+ }
+ /// Clamp-to-edge fetch.
+ #[inline]
+ pub fn get_clamped(&self, x: isize, y: isize) -> [f32; 4] {
+ let x = x.clamp(0, self.w as isize - 1) as usize;
+ let y = y.clamp(0, self.h as isize - 1) as usize;
+ self.get(x, y)
+ }
+ /// Transparent-border fetch.
+ #[inline]
+ pub fn get_or_clear(&self, x: isize, y: isize) -> [f32; 4] {
+ if x < 0 || y < 0 || x >= self.w as isize || y >= self.h as isize { [0.0; 4] } else { self.get(x as usize, y as usize) }
+ }
+ /// Bilinear sample at continuous pixel coords (pixel centres at +0.5), transparent outside.
+ #[inline]
+ pub fn sample_bilinear(&self, x: f32, y: f32) -> [f32; 4] {
+ let fx = x - 0.5;
+ let fy = y - 0.5;
+ let x0 = fx.floor();
+ let y0 = fy.floor();
+ let tx = fx - x0;
+ let ty = fy - y0;
+ let (x0, y0) = (x0 as isize, y0 as isize);
+ let a = self.get_or_clear(x0, y0);
+ let b = self.get_or_clear(x0 + 1, y0);
+ let c = self.get_or_clear(x0, y0 + 1);
+ let d = self.get_or_clear(x0 + 1, y0 + 1);
+ let mut o = [0.0; 4];
+ for k in 0..4 {
+ let top = a[k] + (b[k] - a[k]) * tx;
+ let bot = c[k] + (d[k] - c[k]) * tx;
+ o[k] = top + (bot - top) * ty;
+ }
+ o
+ }
+ #[inline]
+ pub fn sample_bilinear_clamped(&self, x: f32, y: f32) -> [f32; 4] {
+ let fx = (x - 0.5).clamp(0.0, self.w as f32 - 1.0);
+ let fy = (y - 0.5).clamp(0.0, self.h as f32 - 1.0);
+ let x0 = fx.floor() as usize;
+ let y0 = fy.floor() as usize;
+ let x1 = (x0 + 1).min(self.w - 1);
+ let y1 = (y0 + 1).min(self.h - 1);
+ let tx = fx - x0 as f32;
+ let ty = fy - y0 as f32;
+ let (a, b, c, d) = (self.get(x0, y0), self.get(x1, y0), self.get(x0, y1), self.get(x1, y1));
+ let mut o = [0.0; 4];
+ for k in 0..4 {
+ let top = a[k] + (b[k] - a[k]) * tx;
+ let bot = c[k] + (d[k] - c[k]) * tx;
+ o[k] = top + (bot - top) * ty;
+ }
+ o
+ }
+
+ /// Resample `self` into a `w`×`h` image through `m` (maps source pixels → destination pixels).
+ /// Uses bilinear filtering, with a box pre-filter (mip level) when minifying by more than 2×.
+ pub fn transformed(&self, w: usize, h: usize, m: &Affine) -> Image {
+ let Some(inv) = m.inverse() else { return Image::new(w, h) };
+ // minification factor
+ let sx = (m.a * m.a + m.b * m.b).sqrt();
+ let sy = (m.c * m.c + m.d * m.d).sqrt();
+ let minify = 1.0 / sx.min(sy).max(1e-6);
+ if minify >= 2.0 && self.w >= 4 && self.h >= 4 {
+ let half = self.downsample2();
+ let m2 = m.then_apply(&Affine::scale(2.0, 2.0));
+ return half.transformed(w, h, &m2);
+ }
+ let mut out = Image::new(w, h);
+ // Destination bounds of the source rect, to skip empty rows/cols.
+ let b = m.bounds(&filmcraft_geom::Rect::new(0.0, 0.0, self.w as f64, self.h as f64));
+ let y0 = (b.y.floor().max(0.0) as usize).min(h);
+ let y1 = (b.bottom().ceil().max(0.0) as usize).min(h);
+ let x0 = (b.x.floor().max(0.0) as usize).min(w);
+ let x1 = (b.right().ceil().max(0.0) as usize).min(w);
+ let axis_aligned = m.b == 0.0 && m.c == 0.0;
+ out.px.par_chunks_mut(w * 4).enumerate().skip(y0).take(y1 - y0).for_each(|(y, row)| {
+ let py = y as f64 + 0.5;
+ for x in x0..x1 {
+ let px = x as f64 + 0.5;
+ let (u, v) =
+ if axis_aligned { (inv.a * px + inv.e, inv.d * py + inv.f) } else { (inv.a * px + inv.c * py + inv.e, inv.b * px + inv.d * py + inv.f) };
+ if u < -1.0 || v < -1.0 || u > self.w as f64 + 1.0 || v > self.h as f64 + 1.0 {
+ continue;
+ }
+ let s = self.sample_bilinear(u as f32, v as f32);
+ row[x * 4..x * 4 + 4].copy_from_slice(&s);
+ }
+ });
+ out
+ }
+
+ /// Half-size box downsample.
+ pub fn downsample2(&self) -> Image {
+ let (w, h) = ((self.w / 2).max(1), (self.h / 2).max(1));
+ let mut out = Image::new(w, h);
+ out.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let a = self.get_clamped(2 * x as isize, 2 * y as isize);
+ let b = self.get_clamped(2 * x as isize + 1, 2 * y as isize);
+ let c = self.get_clamped(2 * x as isize, 2 * y as isize + 1);
+ let d = self.get_clamped(2 * x as isize + 1, 2 * y as isize + 1);
+ for k in 0..4 {
+ row[x * 4 + k] = (a[k] + b[k] + c[k] + d[k]) * 0.25;
+ }
+ }
+ });
+ out
+ }
+
+ pub fn scale_alpha(&mut self, a: f32) {
+ if (a - 1.0).abs() < 1e-6 {
+ return;
+ }
+ self.px.par_iter_mut().for_each(|v| *v *= a);
+ }
+
+ /// Straight-alpha colour of a pixel.
+ #[inline]
+ pub fn unpremul(p: [f32; 4]) -> [f32; 3] {
+ if p[3] <= 1e-6 { [0.0; 3] } else { [p[0] / p[3], p[1] / p[3], p[2] / p[3]] }
+ }
+
+ /// Apply a per-pixel function on straight-alpha colour (alpha preserved).
+ pub fn map_rgb(&mut self, f: impl Fn([f32; 3], usize, usize) -> [f32; 3] + Sync) {
+ let w = self.w;
+ self.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w {
+ let p = &mut row[x * 4..x * 4 + 4];
+ let a = p[3];
+ if a <= 1e-6 {
+ continue;
+ }
+ let c = f([p[0] / a, p[1] / a, p[2] / a], x, y);
+ p[0] = c[0] * a;
+ p[1] = c[1] * a;
+ p[2] = c[2] * a;
+ }
+ });
+ }
+
+ /// Convert to straight sRGB RGBA8.
+ pub fn to_rgba8(&self) -> Vec<u8> {
+ let mut out = vec![0u8; self.w * self.h * 4];
+ out.par_chunks_mut(self.w * 4).zip(self.px.par_chunks(self.w * 4)).for_each(|(o, s)| filmcraft_frame::linear_premul_to_srgb8(s, o));
+ out
+ }
+
+ /// Opaque version over black (for monitors).
+ pub fn over_black_rgba8(&self) -> Vec<u8> {
+ let mut out = vec![0u8; self.w * self.h * 4];
+ out.par_chunks_mut(self.w * 4).zip(self.px.par_chunks(self.w * 4)).for_each(|(o, s)| {
+ for (o, s) in o.chunks_exact_mut(4).zip(s.chunks_exact(4)) {
+ o[0] = filmcraft_color::linear_to_srgb_u8(s[0]);
+ o[1] = filmcraft_color::linear_to_srgb_u8(s[1]);
+ o[2] = filmcraft_color::linear_to_srgb_u8(s[2]);
+ o[3] = 255;
+ }
+ });
+ out
+ }
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
new file mode 100644
index 000000000..e5368f83b
--- /dev/null
+++ b/crates/render/src/lib.rs
@@ -0,0 +1,273 @@
+//! Sequence evaluation and the CPU reference compositor.
+//!
+//! [`render_sequence`] turns (project, sequence, time, scale) into a premultiplied linear-light
+//! image. Tracks composite bottom (V1) to top. Per item: fetch the source frame at the mapped media
+//! time (already reduced for low-resolution playback), run standard effects, then the fixed effects
+//! (Motion → Opacity/blend), then composite. Transitions combine outgoing/incoming layers.
+//!
+//! The same code renders monitors, thumbnails and exports, and is the oracle for the GPU path.
+
+pub mod audio;
+pub mod blend;
+pub mod effects;
+pub mod image;
+pub mod transitions;
+
+use std::sync::Arc;
+
+use filmcraft_geom::{Affine, Vec2};
+use filmcraft_media::{FrameRequest, SharedSource};
+use filmcraft_project::{ItemId, ItemKind, ParamValue, Project, Sequence, TrackItem};
+use filmcraft_time::{Tick, TimeDisplay, format_time};
+
+pub use blend::Blend;
+pub use image::Image;
+
+/// Resolves project items to media sources (the engine owns the media pool).
+pub trait SourceProvider: Sync {
+ fn source(&self, item: ItemId) -> Option<SharedSource>;
+}
+
+impl<F: Fn(ItemId) -> Option<SharedSource> + Sync> SourceProvider for F {
+ fn source(&self, item: ItemId) -> Option<SharedSource> {
+ self(item)
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct RenderOptions {
+ /// Output scale relative to the sequence frame size (1.0 = full, 0.5 = ½ resolution…).
+ pub scale: f32,
+ /// Skip standard effects (fast scrubbing / "Toggle Effects" off).
+ pub effects: bool,
+ /// Nesting depth guard.
+ pub depth: u32,
+}
+
+impl Default for RenderOptions {
+ fn default() -> Self {
+ Self { scale: 1.0, effects: true, depth: 0 }
+ }
+}
+
+/// Output size for a sequence at a scale.
+pub fn output_size(seq: &Sequence, scale: f32) -> (usize, usize) {
+ (((seq.settings.width as f32 * scale).round() as usize).max(1), ((seq.settings.height as f32 * scale).round() as usize).max(1))
+}
+
+/// Render sequence `seq_id` at timeline time `t`.
+pub fn render_sequence(project: &Project, seq_id: ItemId, t: Tick, opts: RenderOptions, sources: &dyn SourceProvider) -> Image {
+ let Some(seq) = project.sequence(seq_id) else { return Image::new(1, 1) };
+ render_seq(project, seq, t, opts, sources)
+}
+
+fn render_seq(project: &Project, seq: &Sequence, t: Tick, opts: RenderOptions, sources: &dyn SourceProvider) -> Image {
+ let (w, h) = output_size(seq, opts.scale);
+ let mut canvas = Image::new(w, h);
+ if opts.depth > 8 {
+ return canvas;
+ }
+ let tc = format_time(t, seq.settings.frame_rate, seq.settings.drop_frame, TimeDisplay::Timecode, seq.settings.sample_rate as i64);
+ for track in &seq.video_tracks {
+ if !track.enabled {
+ continue;
+ }
+ // transition covering t?
+ if let Some(tr) = track.transitions.iter().find(|tr| tr.range().contains(t)) {
+ let a = tr.from.and_then(|id| track.item(id)).filter(|i| i.enabled);
+ let b = tr.to.and_then(|id| track.item(id)).filter(|i| i.enabled);
+ let la = a
+ .and_then(|i| item_layer(project, seq, i, t, opts, sources, &tc))
+ .map(|(img, op, _)| with_opacity(img, op))
+ .unwrap_or_else(|| Image::new(w, h));
+ let lb = b
+ .and_then(|i| item_layer(project, seq, i, t, opts, sources, &tc))
+ .map(|(img, op, _)| with_opacity(img, op))
+ .unwrap_or_else(|| Image::new(w, h));
+ let mut p = tr.progress(t) as f32;
+ if tr.reverse {
+ p = 1.0 - p;
+ }
+ let mixed = transitions::apply(&tr.effect, &la, &lb, p);
+ blend::composite(&mut canvas, &mixed, 1.0, Blend::Normal);
+ continue;
+ }
+ let Some(item) = track.item_at(t) else { continue };
+ if !item.enabled {
+ continue;
+ }
+ let pi = project.item(item.item);
+ if let Some(pi) = pi
+ && matches!(pi.kind, ItemKind::AdjustmentLayer { .. })
+ {
+ if !opts.effects {
+ continue;
+ }
+ let mt = item.source_time_at(t);
+ let mut adjusted = canvas.clone();
+ let cx = effects::FxCtx { t: mt, px_scale: opts.scale, seconds: (t - item.start).seconds(), timecode: &tc, clip_name: &item.name };
+ for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic)) {
+ effects::apply(&mut adjusted, e, &cx);
+ }
+ let (op, bl) = opacity_blend(item, mt);
+ // Adjustment layer opacity mixes adjusted over original.
+ let mut out = canvas.clone();
+ let mut adj = adjusted;
+ adj.scale_alpha(op);
+ blend::composite(&mut out, &adj, 1.0, bl);
+ canvas = out;
+ continue;
+ }
+ if let Some((layer, op, bl)) = item_layer(project, seq, item, t, opts, sources, &tc) {
+ blend::composite(&mut canvas, &layer, op, bl);
+ }
+ }
+ canvas
+}
+
+fn with_opacity(mut img: Image, op: f32) -> Image {
+ img.scale_alpha(op);
+ img
+}
+
+fn opacity_blend(item: &TrackItem, mt: Tick) -> (f32, Blend) {
+ match item.effect("opacity") {
+ Some(e) if e.enabled => {
+ let op = (e.f64_at("opacity", mt) / 100.0).clamp(0.0, 1.0) as f32;
+ let bl = match e.param("blend").map(|p| &p.value) {
+ Some(ParamValue::Choice(c)) => Blend::from_index(*c),
+ _ => Blend::Normal,
+ };
+ (op, bl)
+ }
+ _ => (1.0, Blend::Normal),
+ }
+}
+
+/// Size of an item's source at full resolution.
+fn source_size(project: &Project, item: ItemId) -> Option<(u32, u32)> {
+ match &project.item(item)?.kind {
+ ItemKind::Media(m) => m.info.video.as_ref().map(|v| (v.width, v.height)),
+ ItemKind::Sequence(s) => Some((s.settings.width, s.settings.height)),
+ ItemKind::AdjustmentLayer { width, height, .. } => Some((*width, *height)),
+ ItemKind::Subclip { parent, .. } => source_size(project, *parent),
+ }
+}
+
+/// The Motion transform of an item at media time `mt`, mapping full-res source pixels to
+/// full-res sequence pixels.
+pub fn motion_matrix(seq: &Sequence, item: &TrackItem, src: (u32, u32), mt: Tick) -> Affine {
+ let (sw, sh) = (seq.settings.width as f64, seq.settings.height as f64);
+ let mut pos = Vec2::new(sw / 2.0, sh / 2.0);
+ let mut anchor = Vec2::new(src.0 as f64 / 2.0, src.1 as f64 / 2.0);
+ let mut scale = Vec2::new(1.0, 1.0);
+ let mut rot = 0.0;
+ if let Some(m) = item.effect("motion").filter(|m| m.enabled) {
+ let p = m.vec2_at("position", mt);
+ if !p.x.is_nan() && m.param("position").is_some() {
+ pos = p;
+ }
+ let a = m.vec2_at("anchor", mt);
+ if !a.x.is_nan() && m.param("anchor").is_some() {
+ anchor = a;
+ }
+ let s = m.f64_at("scale", mt) / 100.0;
+ let uniform = m.param("uniform_scale").and_then(|p| p.value.as_bool()).unwrap_or(true);
+ let swid = if uniform { s } else { m.f64_at("scale_width", mt) / 100.0 };
+ scale = Vec2::new(swid, s);
+ rot = m.f64_at("rotation", mt);
+ }
+ if item.scale_to_frame {
+ let fit = (sw / src.0 as f64).min(sh / src.1 as f64);
+ scale = scale * fit;
+ }
+ Affine::motion(pos, scale, rot, anchor)
+}
+
+/// Render one track item's layer at timeline time `t` into a canvas-sized image.
+/// Returns (layer, opacity, blend).
+fn item_layer(
+ project: &Project,
+ seq: &Sequence,
+ item: &TrackItem,
+ t: Tick,
+ opts: RenderOptions,
+ sources: &dyn SourceProvider,
+ tc: &str,
+) -> Option<(Image, f32, Blend)> {
+ let (w, h) = output_size(seq, opts.scale);
+ let mt = item.source_time_at(t);
+ let src_size = source_size(project, item.item)?;
+ let motion = motion_matrix(seq, item, src_size, mt);
+ // How many output pixels one source pixel covers → request a reduced frame when possible.
+ let lin = ((motion.a * motion.a + motion.b * motion.b).sqrt()).max((motion.c * motion.c + motion.d * motion.d).sqrt());
+ let want = (lin * opts.scale as f64).clamp(1.0 / 64.0, 1.0) as f32;
+ let pi = project.item(item.item)?;
+ let mut layer = match &pi.kind {
+ ItemKind::Media(_) | ItemKind::Subclip { .. } => {
+ let src = sources.source(item.item)?;
+ let frame = src.video_frame(FrameRequest { time: mt, scale: want }).ok()?;
+ let data = frame.to_linear_f32();
+ Image { w: frame.width as usize, h: frame.height as usize, px: data }
+ }
+ ItemKind::Sequence(nested) => {
+ let sub = RenderOptions { scale: want, effects: opts.effects, depth: opts.depth + 1 };
+ render_seq(project, nested, mt, sub, sources)
+ }
+ ItemKind::AdjustmentLayer { .. } => return None,
+ };
+ let px_scale = layer.w as f32 / src_size.0.max(1) as f32;
+ if opts.effects {
+ let cx = effects::FxCtx { t: mt, px_scale, seconds: (t - item.start).seconds(), timecode: tc, clip_name: &item.name };
+ for e in item.effects.iter().filter(|e| e.def().is_some_and(|d| !d.intrinsic)) {
+ effects::apply(&mut layer, e, &cx);
+ }
+ }
+ // layer px → source px → sequence px → output px
+ let m = Affine::scale(opts.scale as f64, opts.scale as f64).then_apply(&motion).then_apply(&Affine::scale(1.0 / px_scale as f64, 1.0 / px_scale as f64));
+ let placed = if layer.w == w
+ && layer.h == h
+ && (m.a - 1.0).abs() < 1e-9
+ && (m.d - 1.0).abs() < 1e-9
+ && m.b == 0.0
+ && m.c == 0.0
+ && m.e.abs() < 1e-9
+ && m.f.abs() < 1e-9
+ {
+ layer
+ } else {
+ layer.transformed(w, h, &m)
+ };
+ let (op, bl) = opacity_blend(item, mt);
+ Some((placed, op, bl))
+}
+
+/// Render a single project item (e.g. for the Source monitor) at media time `t`.
+pub fn render_item(project: &Project, item: ItemId, t: Tick, scale: f32, sources: &dyn SourceProvider) -> Option<Image> {
+ let pi = project.item(item)?;
+ match &pi.kind {
+ ItemKind::Sequence(s) => Some(render_seq(project, s, t, RenderOptions { scale, ..Default::default() }, sources)),
+ _ => {
+ let src = sources.source(item)?;
+ let f = src.video_frame(FrameRequest { time: t, scale }).ok()?;
+ Some(Image { w: f.width as usize, h: f.height as usize, px: f.to_linear_f32() })
+ }
+ }
+}
+
+/// A shared, clonable source map for tests and simple hosts.
+#[derive(Default, Clone)]
+pub struct SourceMap(pub std::collections::HashMap<ItemId, SharedSource>);
+
+impl SourceProvider for SourceMap {
+ fn source(&self, item: ItemId) -> Option<SharedSource> {
+ self.0.get(&item).cloned()
+ }
+}
+
+pub fn arc_source(s: impl filmcraft_media::MediaSource + 'static) -> SharedSource {
+ Arc::new(s)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs
new file mode 100644
index 000000000..b4b75210c
--- /dev/null
+++ b/crates/render/src/tests.rs
@@ -0,0 +1,169 @@
+use super::*;
+use filmcraft_media::generators::GeneratorSource;
+use filmcraft_media::{DemoScene, Generator, MediaSource};
+use filmcraft_project::{Label, MediaClip, MediaRef, SequenceSettings, TrackKind};
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, TimeRange};
+
+fn setup() -> (Project, ItemId, ItemId, ItemId, SourceMap) {
+ let mut p = Project::new("r");
+ let mut map = SourceMap::default();
+ let mut add = |p: &mut Project, g: GeneratorSource| {
+ let info = g.info().clone();
+ let generator = g.generator.clone();
+ let id = p.add_item(
+ &info.name.clone(),
+ Label::Iris,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::Generator(generator),
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ );
+ map.0.insert(id, Arc::new(g) as SharedSource);
+ id
+ };
+ let red =
+ add(&mut p, GeneratorSource::new(Generator::ColorMatte { color: [1.0, 0.0, 0.0, 1.0] }, 320, 180, FrameRate::FPS_24, Tick(10 * TICKS_PER_SECOND)));
+ let ocean = add(&mut p, GeneratorSource::demo(DemoScene::OceanSunset));
+ let seq = p.new_sequence("s", SequenceSettings { width: 320, height: 180, frame_rate: FrameRate::FPS_24, ..Default::default() }, 2, 2, None);
+ (p, red, ocean, seq, map)
+}
+
+fn place(p: &mut Project, seq: ItemId, track: usize, item: ItemId, start_f: i64, dur_f: i64) -> filmcraft_project::ClipId {
+ let r = FrameRate::FPS_24;
+ let ti = p.make_track_item(item, TrackKind::Video, r.tick_of(start_f), TimeRange::new(Tick::ZERO, r.tick_of(dur_f)), r).unwrap();
+ let id = ti.id;
+ let mut ti = ti;
+ ti.scale_to_frame = true;
+ p.sequence_mut(seq).unwrap().video_tracks[track].items.push(ti);
+ p.sequence_mut(seq).unwrap().video_tracks[track].sort();
+ id
+}
+
+#[test]
+fn composites_tracks_and_opacity() {
+ let (mut p, red, ocean, seq, map) = setup();
+ place(&mut p, seq, 0, ocean, 0, 48);
+ let top = place(&mut p, seq, 1, red, 0, 48);
+ let img = render_sequence(&p, seq, Tick(1000), RenderOptions::default(), &map);
+ assert_eq!((img.w, img.h), (320, 180));
+ let c = img.get(160, 90);
+ assert!((c[0] - 1.0).abs() < 1e-4 && c[1] < 1e-4, "red on top: {c:?}");
+ // 50% opacity shows the bottom layer through
+ let s = p.sequence_mut(seq).unwrap();
+ let (_, it) = s.find_item_mut(top).unwrap();
+ it.effect_mut("opacity").unwrap().params.get_mut("opacity").unwrap().value = ParamValue::Float(50.0);
+ let img = render_sequence(&p, seq, Tick(1000), RenderOptions::default(), &map);
+ let c = img.get(160, 20);
+ assert!(c[0] > 0.5 && c[0] < 1.0 && c[2] > 0.0, "{c:?}");
+}
+
+#[test]
+fn half_resolution_matches_full_downsampled() {
+ let (mut p, _red, ocean, seq, map) = setup();
+ place(&mut p, seq, 0, ocean, 0, 48);
+ let full = render_sequence(&p, seq, Tick(1000), RenderOptions::default(), &map);
+ let half = render_sequence(&p, seq, Tick(1000), RenderOptions { scale: 0.5, ..Default::default() }, &map);
+ assert_eq!((half.w, half.h), (160, 90));
+ let a = full.get(200, 60);
+ let b = half.get(100, 30);
+ for k in 0..3 {
+ assert!((a[k] - b[k]).abs() < 0.06, "{a:?} vs {b:?}");
+ }
+}
+
+#[test]
+fn motion_scale_and_position() {
+ let (mut p, red, _o, seq, map) = setup();
+ let id = place(&mut p, seq, 0, red, 0, 48);
+ let s = p.sequence_mut(seq).unwrap();
+ let (_, it) = s.find_item_mut(id).unwrap();
+ let m = it.effect_mut("motion").unwrap();
+ m.params.get_mut("scale").unwrap().value = ParamValue::Float(50.0);
+ m.params.get_mut("position").unwrap().value = ParamValue::Vec2(filmcraft_geom::Vec2::new(80.0, 45.0));
+ let img = render_sequence(&p, seq, Tick(0), RenderOptions::default(), &map);
+ assert!(img.get(80, 45)[3] > 0.99);
+ assert!(img.get(10, 10)[3] > 0.99, "top-left quadrant covered");
+ assert_eq!(img.get(200, 120)[3], 0.0, "rest transparent");
+}
+
+#[test]
+fn cross_dissolve_midpoint() {
+ let (mut p, red, _o, seq, map) = setup();
+ let a = place(&mut p, seq, 0, red, 0, 24);
+ let blue_src = GeneratorSource::new(Generator::ColorMatte { color: [0.0, 0.0, 1.0, 1.0] }, 320, 180, FrameRate::FPS_24, Tick(10 * TICKS_PER_SECOND));
+ let info = blue_src.info().clone();
+ let blue = p.add_item(
+ "blue",
+ Label::Iris,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::Generator(blue_src.generator.clone()),
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ );
+ let mut map = map;
+ map.0.insert(blue, Arc::new(blue_src));
+ let b = place(&mut p, seq, 0, blue, 24, 24);
+ let r = FrameRate::FPS_24;
+ let tr = filmcraft_project::Transition {
+ id: filmcraft_project::TransitionId(999),
+ effect: filmcraft_project::find_effect("cross_dissolve").unwrap().instance(),
+ start: r.tick_of(18),
+ duration: r.tick_of(12),
+ from: Some(a),
+ to: Some(b),
+ align: Default::default(),
+ reverse: false,
+ };
+ p.sequence_mut(seq).unwrap().video_tracks[0].transitions.push(tr);
+ let img = render_sequence(&p, seq, r.tick_of(24), RenderOptions::default(), &map);
+ let c = img.get(10, 10);
+ assert!((c[0] - 0.5).abs() < 0.05 && (c[2] - 0.5).abs() < 0.05, "{c:?}");
+}
+
+#[test]
+fn audio_mix_bars_tone() {
+ let mut p = Project::new("a");
+ let g = GeneratorSource::new(Generator::BarsAndTone, 64, 36, FrameRate::FPS_24, Tick(5 * TICKS_PER_SECOND));
+ let info = g.info().clone();
+ let id = p.add_item(
+ "bars",
+ Label::Iris,
+ ItemKind::Media(MediaClip {
+ media: MediaRef::Generator(Generator::BarsAndTone),
+ info,
+ interpret: Default::default(),
+ mark_in: None,
+ mark_out: None,
+ markers: vec![],
+ offline: false,
+ proxy: None,
+ }),
+ None,
+ );
+ let mut map = SourceMap::default();
+ map.0.insert(id, Arc::new(g));
+ let seq = p.new_sequence("s", SequenceSettings::default(), 1, 1, None);
+ let r = FrameRate::FPS_23_976;
+ let mut ti = p.make_track_item(id, TrackKind::Audio, Tick::ZERO, TimeRange::new(Tick::ZERO, Tick(TICKS_PER_SECOND)), r).unwrap();
+ ti.effect_mut("volume").unwrap().params.get_mut("level").unwrap().value = ParamValue::Float(-6.0);
+ p.sequence_mut(seq).unwrap().audio_tracks[0].items.push(ti);
+ let s = p.sequence(seq).unwrap();
+ let buf = audio::mix_sequence(&p, s, 0, 4800, &map);
+ let peak = buf.peaks()[0];
+ let expect = 10f32.powf(-26.0 / 20.0);
+ assert!((peak - expect).abs() < 0.01, "{peak} vs {expect}");
+}
diff --git a/crates/render/src/transitions.rs b/crates/render/src/transitions.rs
new file mode 100644
index 000000000..914b561c4
--- /dev/null
+++ b/crates/render/src/transitions.rs
@@ -0,0 +1,261 @@
+//! Video transitions: combine the outgoing (A) and incoming (B) layers at progress `p` ∈ [0,1].
+
+use filmcraft_geom::Affine;
+use filmcraft_project::{EffectInstance, ParamValue};
+use rayon::prelude::*;
+
+use crate::image::Image;
+
+fn dir(e: &EffectInstance) -> u32 {
+ match e.param("direction").map(|p| &p.value) {
+ Some(ParamValue::Choice(c)) => *c,
+ _ => 3,
+ }
+}
+
+/// Mask-based mix: out = A·(1-m) + B·m with m = f(x, y) ∈ [0,1].
+fn masked(a: &Image, b: &Image, m: impl Fn(f32, f32) -> f32 + Sync) -> Image {
+ let (w, h) = (a.w, a.h);
+ let mut out = Image::new(w, h);
+ out.px.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| {
+ let v = (y as f32 + 0.5) / h as f32;
+ for x in 0..w {
+ let u = (x as f32 + 0.5) / w as f32;
+ let k = m(u, v).clamp(0.0, 1.0);
+ let i = (y * w + x) * 4;
+ for c in 0..4 {
+ row[x * 4 + c] = a.px[i + c] * (1.0 - k) + b.px[i + c] * k;
+ }
+ }
+ });
+ out
+}
+
+fn over(dst: &mut Image, src: &Image) {
+ crate::blend::composite(dst, src, 1.0, crate::blend::Blend::Normal);
+}
+
+fn shifted(img: &Image, dx: f64, dy: f64) -> Image {
+ img.transformed(img.w, img.h, &Affine::translate(dx, dy))
+}
+
+/// Soft edge width in uv units.
+const EDGE: f32 = 0.004;
+
+fn step(edge: f32, x: f32) -> f32 {
+ ((x - edge) / EDGE + 0.5).clamp(0.0, 1.0)
+}
+
+pub fn apply(e: &EffectInstance, a: &Image, b: &Image, p: f32) -> Image {
+ let (w, h) = (a.w as f64, a.h as f64);
+ let aspect = (a.w as f32) / (a.h as f32).max(1.0);
+ let pd = p as f64;
+ match e.effect.as_str() {
+ "cross_dissolve" | "non_additive_dissolve" | "morph_cut" => masked(a, b, |_, _| p),
+ "film_dissolve" => {
+ // blend in a gamma-2.2-like space for a filmic, less-dippy dissolve
+ let mut out = Image::new(a.w, a.h);
+ out.px.par_iter_mut().zip(a.px.par_iter().zip(b.px.par_iter())).for_each(|(o, (x, y))| {
+ let g = 1.0 / 2.2;
+ let v = x.max(0.0).powf(g) * (1.0 - p) + y.max(0.0).powf(g) * p;
+ *o = v.powf(2.2);
+ });
+ out
+ }
+ "additive_dissolve" => {
+ let (ka, kb) = ((2.0 * (1.0 - p)).min(1.0), (2.0 * p).min(1.0));
+ let mut out = Image::new(a.w, a.h);
+ out.px.par_iter_mut().zip(a.px.par_iter().zip(b.px.par_iter())).for_each(|(o, (x, y))| *o = (x * ka + y * kb).min(1.0));
+ out
+ }
+ "dip_to_black" | "dip_to_white" => {
+ let col = if e.effect == "dip_to_black" { [0.0, 0.0, 0.0, 1.0] } else { [1.0, 1.0, 1.0, 1.0] };
+ let mut out = Image::filled(a.w, a.h, col);
+ let (src, k) = if p < 0.5 { (a, 1.0 - p * 2.0) } else { (b, (p - 0.5) * 2.0) };
+ let mut s = src.clone();
+ s.scale_alpha(k);
+ over(&mut out, &s);
+ out
+ }
+ "wipe" => {
+ let d = dir(e);
+ masked(a, b, move |u, v| match d {
+ 0 => 1.0 - step(p, v), // from north: B grows from top
+ 1 => step(1.0 - p, u),
+ 2 => step(1.0 - p, v),
+ _ => 1.0 - step(p, u),
+ })
+ }
+ "barn_doors" => masked(a, b, |u, _| 1.0 - step(p * 0.5, (u - 0.5).abs())),
+ "clock_wipe" | "radial_wipe" => masked(a, b, |u, v| {
+ let ang = ((u - 0.5) * aspect).atan2(-(v - 0.5)) / std::f32::consts::TAU;
+ let ang = ang.rem_euclid(1.0);
+ 1.0 - step(p, ang)
+ }),
+ "iris_round" => {
+ let r = p * 0.8;
+ masked(a, b, move |u, v| 1.0 - step(r, (((u - 0.5) * aspect).powi(2) + (v - 0.5).powi(2)).sqrt()))
+ }
+ "iris_box" => masked(a, b, |u, v| 1.0 - step(p * 0.5, (u - 0.5).abs().max((v - 0.5).abs()))),
+ "iris_diamond" => masked(a, b, |u, v| 1.0 - step(p, (u - 0.5).abs() + (v - 0.5).abs())),
+ "iris_cross" => masked(a, b, |u, v| 1.0 - step(p * 0.5, (u - 0.5).abs().min((v - 0.5).abs()) * 2.0 - p * 0.0).min(1.0)),
+ "venetian_blinds" => masked(a, b, |_, v| 1.0 - step(p, (v * 10.0).fract())),
+ "checker_wipe" => masked(a, b, |u, v| {
+ let cxv = (u * 8.0).floor() as i32 + (v * 8.0).floor() as i32;
+ let off = if cxv % 2 == 0 { 0.0 } else { 0.5 };
+ 1.0 - step((p * 2.0 - off).clamp(0.0, 1.0), (u * 8.0).fract())
+ }),
+ "gradient_wipe" => {
+ let soft = e.f64_at("softness", filmcraft_time::Tick::ZERO) as f32 / 100.0 + 0.02;
+ masked(a, b, move |u, v| {
+ let g = (u * 0.7 + v * 0.3).clamp(0.0, 1.0);
+ ((p * (1.0 + soft) - g) / soft).clamp(0.0, 1.0)
+ })
+ }
+ "inset" => masked(a, b, |u, v| if u < p && v < p { 1.0 } else { 0.0 }),
+ "center_split" => {
+ let mut out = b.clone();
+ let off_x = w * 0.5 * pd;
+ let off_y = h * 0.5 * pd;
+ let quads = [(-off_x, -off_y, 0.0, 0.0), (off_x, -off_y, 0.5, 0.0), (-off_x, off_y, 0.0, 0.5), (off_x, off_y, 0.5, 0.5)];
+ for (dx, dy, qx, qy) in quads {
+ let mut q = masked(a, &Image::new(a.w, a.h), move |u, v| if u >= qx && u < qx + 0.5 && v >= qy && v < qy + 0.5 { 0.0 } else { 1.0 });
+ q = shifted(&q, dx, dy);
+ over(&mut out, &q);
+ }
+ out
+ }
+ "split" => {
+ let mut out = b.clone();
+ let left = masked(a, &Image::new(a.w, a.h), |u, _| if u < 0.5 { 0.0 } else { 1.0 });
+ let right = masked(a, &Image::new(a.w, a.h), |u, _| if u >= 0.5 { 0.0 } else { 1.0 });
+ over(&mut out, &shifted(&left, -w * 0.5 * pd, 0.0));
+ over(&mut out, &shifted(&right, w * 0.5 * pd, 0.0));
+ out
+ }
+ "band_slide" => {
+ let mut out = a.clone();
+ let bands = 6;
+ let bb = masked(&Image::new(a.w, a.h), b, |_, _| 1.0);
+ for i in 0..bands {
+ let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
+ let band = masked(&Image::new(a.w, a.h), &bb, move |_, v| if (v * bands as f32).floor() as i32 == i { 1.0 } else { 0.0 });
+ over(&mut out, &shifted(&band, sign * w * (1.0 - pd), 0.0));
+ }
+ out
+ }
+ "push" | "whip" => {
+ let (dx, dy) = match dir(e) {
+ 0 => (0.0, h),
+ 1 => (-w, 0.0),
+ 2 => (0.0, -h),
+ _ => (w, 0.0),
+ };
+ let ease = if e.effect == "whip" { ease_in_out(pd) } else { pd };
+ let mut out = shifted(a, dx * ease, dy * ease);
+ over(&mut out, &shifted(b, dx * (ease - 1.0), dy * (ease - 1.0)));
+ if e.effect == "whip" {
+ let s = (1.0 - (2.0 * pd - 1.0).abs()) as f32 * 40.0 * (a.w as f32 / 1920.0);
+ if s > 0.5 {
+ crate::effects::gaussian(&mut out, s, 0.0, true);
+ }
+ }
+ out
+ }
+ "slide" => {
+ let (dx, dy) = match dir(e) {
+ 0 => (0.0, -h),
+ 1 => (w, 0.0),
+ 2 => (0.0, h),
+ _ => (-w, 0.0),
+ };
+ let mut out = a.clone();
+ over(&mut out, &shifted(b, dx * (1.0 - pd), dy * (1.0 - pd)));
+ out
+ }
+ "cross_zoom" => {
+ let z = 1.0 + 3.0 * (if pd < 0.5 { pd * 2.0 } else { (1.0 - pd) * 2.0 });
+ let src = if pd < 0.5 { a } else { b };
+ let m = Affine::translate(w / 2.0, h / 2.0).then_apply(&Affine::scale(z, z)).then_apply(&Affine::translate(-w / 2.0, -h / 2.0));
+ let mut out = src.transformed(a.w, a.h, &m);
+ let blur = (z as f32 - 1.0) * 6.0 * (a.w as f32 / 1920.0);
+ if blur > 0.3 {
+ crate::effects::gaussian(&mut out, blur, blur, true);
+ }
+ out
+ }
+ "flip_over" | "cube_spin" => {
+ // Horizontal squeeze approximating a 3D rotation (A shrinks, then B grows).
+ let (src, k) = if pd < 0.5 { (a, 1.0 - pd * 2.0) } else { (b, (pd - 0.5) * 2.0) };
+ let k = k.max(0.001);
+ let cxp = if e.effect == "cube_spin" { if pd < 0.5 { 0.0 } else { w } } else { w / 2.0 };
+ let m = Affine::translate(cxp, 0.0).then_apply(&Affine::scale(k, 1.0)).then_apply(&Affine::translate(-cxp, 0.0));
+ if e.effect == "cube_spin" {
+ let ma = Affine::scale(1.0 - pd, 1.0);
+ let mb = Affine::translate(w * (1.0 - pd), 0.0).then_apply(&Affine::scale(pd.max(0.001), 1.0));
+ let mut out = a.transformed(a.w, a.h, &ma);
+ over(&mut out, &b.transformed(a.w, a.h, &mb));
+ return out;
+ }
+ src.transformed(a.w, a.h, &m)
+ }
+ "page_peel" | "page_turn" => {
+ // Diagonal fold line sweeping from the bottom-right corner, with a shaded curl band.
+ let mut out = masked(a, b, |u, v| step(1.0 - p * 1.1, 1.0 - (u + v) * 0.5 + 0.0) * 0.0 + if (u + v) * 0.5 > 1.0 - p { 1.0 } else { 0.0 });
+ let w_ = a.w;
+ out.px.par_chunks_mut(w_ * 4).enumerate().for_each(|(y, row)| {
+ for x in 0..w_ {
+ let u = x as f32 / a.w as f32;
+ let v = y as f32 / a.h as f32;
+ let d = (u + v) * 0.5 - (1.0 - p);
+ if d < 0.0 && d > -0.06 {
+ let shade = 0.75 + 0.25 * (-d / 0.06);
+ for c in 0..3 {
+ row[x * 4 + c] *= shade;
+ }
+ }
+ }
+ });
+ out
+ }
+ _ => masked(a, b, |_, _| p),
+ }
+}
+
+fn ease_in_out(t: f64) -> f64 {
+ if t < 0.5 { 4.0 * t * t * t } else { 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 }
+}
+
+/// Audio crossfade gains (out, in) for progress p.
+pub fn audio_gains(kind: &str, p: f32) -> (f32, f32) {
+ match kind {
+ "constant_gain" => (1.0 - p, p),
+ "exponential_fade" => ((1.0 - p).powi(3), 1.0 - (1.0 - p).powi(3)),
+ _ => ((p * std::f32::consts::FRAC_PI_2).cos(), (p * std::f32::consts::FRAC_PI_2).sin()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn endpoints() {
+ let a = Image::filled(16, 8, [1.0, 0.0, 0.0, 1.0]);
+ let b = Image::filled(16, 8, [0.0, 0.0, 1.0, 1.0]);
+ for def in filmcraft_project::effect_defs().iter().filter(|d| d.kind == filmcraft_project::EffectKind::VideoTransition) {
+ let e = def.instance();
+ let end = apply(&e, &a, &b, 1.0);
+ let c = end.get(8, 4);
+ assert!(c.iter().all(|v| v.is_finite()), "{}", def.id);
+ if !matches!(
+ def.id,
+ "center_split" | "band_slide" | "page_peel" | "page_turn" | "cube_spin" | "iris_cross" | "inset" | "checker_wipe" | "venetian_blinds"
+ ) {
+ assert!(c[2] > 0.9 && c[0] < 0.1, "{} at p=1 shows B: {c:?}", def.id);
+ }
+ let start = apply(&e, &a, &b, 0.0);
+ assert!(start.px.iter().all(|v| v.is_finite()));
+ }
+ }
+}