The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
Effects as shaders: a WGSL backend in the wgpu compositor
Jareerdd822d9d17e5
diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex eb38d830..2f70557f 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -1130,7 +1130,9 @@ version = "0.2.0"name = "concat-effects"version = "0.2.0"dependencies = [+ "concat-core","concat-project",+ "naga","serde","thiserror 2.0.20","toml",@@ -1189,6 +1191,7 @@ name = "concat-render"version = "0.2.0"dependencies = ["concat-core",+ "concat-effects","pollster","wgpu",]diff --git a/engine/crates/concat-core/src/lib.rs b/engine/crates/concat-core/src/lib.rsindex 4eb86ffb..6346010d 100644--- a/engine/crates/concat-core/src/lib.rs+++ b/engine/crates/concat-core/src/lib.rs@@ -20,10 +20,12 @@ pub mod animate;pub mod arena;pub mod frame;pub mod retime;+pub mod shader;pub mod time;pub mod timeline;pub use frame::Frame;pub use retime::SpeedCurve;+pub use shader::ShaderPass;pub use time::{FrameRate, Rational, TimeRange};pub use timeline::{Blend, Clip, ClipId, Project, Timeline, Track, TrackId, TrackKind};diff --git a/engine/crates/concat-core/src/shader.rs b/engine/crates/concat-core/src/shader.rsnew file mode 100644index 00000000..47a6d509--- /dev/null+++ b/engine/crates/concat-core/src/shader.rs@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! A shader pass, as the compositor runs it.+//!+//! An effect on the GPU is a fragment shader over a layer's pixels: the+//! layer goes in as a texture, the pass draws it out again changed, and the+//! result is what gets composited. This is the whole description of one+//! such pass, resolved from a package and a clip's settings by the effect+//! catalogue and carried to the renderer as data - the renderer compiles+//! and caches the pipeline by `key`, and pours `params` into the shader's+//! uniform buffer as it is, because the catalogue already laid the bytes+//! out the way the shader's `Params` struct wants them.+//!+//! It lives here, in the crate every other one can see, so the catalogue+//! that builds it and the compositor that runs it need not know each other.++use std::sync::Arc;++/// One fragment pass over a layer.+#[derive(Clone, Debug, PartialEq)]+pub struct ShaderPass {+ /// What to cache the compiled pipeline under: the package's id and+ /// version, so a package that changes its shader gets a new pipeline+ /// and one that only changes its knobs keeps the old.+ pub key: String,+ /// The complete WGSL module: the host's prelude with the package's body,+ /// declaring `fn effect(uv: vec2<f32>) -> vec4<f32>`.+ pub source: Arc<str>,+ /// The `Params` uniform, laid out to the struct's offsets. Sixteen bytes+ /// at least, so an empty struct still has a buffer.+ pub params: Vec<u8>,+ /// How much of the result to keep over the untouched layer, `0..=1`. A+ /// look at half strength is half the look; an effect is always one.+ pub intensity: f32,+}++impl ShaderPass {+ /// The uniform buffer's minimum size: a struct with nothing in it still+ /// needs a binding.+ pub const MIN_PARAMS: usize = 16;+}diff --git a/engine/crates/concat-effects/Cargo.toml b/engine/crates/concat-effects/Cargo.tomlindex 4ea4f4c1..5810869a 100644--- a/engine/crates/concat-effects/Cargo.toml+++ b/engine/crates/concat-effects/Cargo.toml@@ -8,7 +8,11 @@ description = "Effect packages: the catalogue of video effects, audio filters, t[dependencies]concat-project.workspace = true+concat-core.workspace = trueserde = { version = "1", features = ["derive"] }+# Shaders are parsed and checked at load, and their `Params` struct read+# for its layout, with the same front end the renderer's wgpu uses.+naga = { version = "29", features = ["wgsl-in"] }thiserror.workspace = true# Manifests are TOML: the format people hand-write. Project files stay JSON.toml = "1.1"diff --git a/engine/crates/concat-effects/build.rs b/engine/crates/concat-effects/build.rsindex c32648b3..b5851912 100644--- a/engine/crates/concat-effects/build.rs+++ b/engine/crates/concat-effects/build.rs@@ -25,9 +25,9 @@ fn main() {ids.sort();let mut table = String::from(- "/// Every built-in package: its folder name, its manifest, and its \- fixtures if it has any.\n\- pub(crate) static BUILTIN_SOURCES: &[(&str, &str, Option<&str>)] = &[\n",+ "/// Every built-in package: its folder name, its manifest, its \+ fixtures if it has any, and its shader if it has one.\n\+ pub(crate) static BUILTIN_SOURCES: &[(&str, &str, Option<&str>, Option<&str>)] = &[\n",);for id in &ids {let dir = packages.join(id);@@ -40,9 +40,16 @@ fn main() {} else {"None".to_owned()};+ let shader = dir.join("effect.wgsl");+ println!("cargo:rerun-if-changed={}", shader.display());+ let shader = if shader.is_file() {+ format!("Some(include_str!({:?}))", shader.display().to_string())+ } else {+ "None".to_owned()+ };writeln!(table,- " ({id:?}, include_str!({:?}), {fixtures}),",+ " ({id:?}, include_str!({:?}), {fixtures}, {shader}),",manifest.display().to_string()).expect("write");diff --git a/engine/crates/concat-effects/packages/concat.adjust/effect.toml b/engine/crates/concat-effects/packages/concat.adjust/effect.tomlindex f74507a6..eec4154f 100644--- a/engine/crates/concat-effects/packages/concat.adjust/effect.toml+++ b/engine/crates/concat-effects/packages/concat.adjust/effect.toml@@ -118,3 +118,6 @@ let = ["high = clamp(0.75 + highlights / 100 * 0.18, 0.55, 0.95)",]chain = "exposure=exposure={fixed(exposure, 2)},eq=brightness={fixed(brightness / 100 * 0.5, 3)}:contrast={fixed(1 + contrast / 100, 3)}:saturation={fixed(1 + saturation / 100 * 2, 3)},colortemperature=temperature={round(temperature)},colorbalance=gm={fixed(0 - tint / 100 * 0.5, 3)},curves=all='0/{fixed(lift, 3)} 0.25/{fixed(low, 3)} 0.75/{fixed(high, 3)} 1/1',unsharp=5:5:{fixed(sharpen / 100 * 2, 2)},vignette=a={fixed(vignette / 100 * 1.2, 3)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.adjust/effect.wgsl b/engine/crates/concat-effects/packages/concat.adjust/effect.wgslnew file mode 100644index 00000000..1da3b98c--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.adjust/effect.wgsl@@ -0,0 +1,83 @@+struct Params {+ exposure: f32,+ brightness: f32,+ contrast: f32,+ saturation: f32,+ temperature: f32,+ tint: f32,+ shadows: f32,+ highlights: f32,+ sharpen: f32,+ vignette: f32,+ fade: f32,+}++fn kelvin(k: f32) -> vec3<f32> {+ let t = clamp(k, 1000.0, 40000.0) / 100.0;+ var r: f32;+ var g: f32;+ var b: f32;+ if (t <= 66.0) {+ r = 1.0;+ g = clamp((99.4708 * log(t) - 161.1196) / 255.0, 0.0, 1.0);+ if (t <= 19.0) {+ b = 0.0;+ } else {+ b = clamp((138.5177 * log(t - 10.0) - 305.0448) / 255.0, 0.0, 1.0);+ }+ } else {+ r = clamp(329.6987 * pow(t - 60.0, -0.1332) / 255.0, 0.0, 1.0);+ g = clamp(288.1222 * pow(t - 60.0, -0.0755) / 255.0, 0.0, 1.0);+ b = 1.0;+ }+ return vec3<f32>(r, g, b);+}++// The manual colour panel, in the order a colourist works: exposure and+// balance, then tone, then the edge and the frame.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let src = sample(uv);+ var c = src.rgb;++ // Exposure in stops, then brightness as an offset.+ c = c * exp2(params.exposure) + vec3<f32>(params.brightness / 100.0 * 0.5);++ // White balance about daylight, and green to magenta.+ c = c * (kelvin(params.temperature) / kelvin(6500.0));+ c.g = c.g - params.tint / 100.0 * 0.25;++ // Contrast about middle grey, saturation about luminance.+ c = (c - vec3<f32>(0.5)) * (1.0 + params.contrast / 100.0) + vec3<f32>(0.5);+ c = mix(vec3<f32>(luma(c)), c, 1.0 + params.saturation / 100.0 * 2.0);++ // Shadows and highlights lift or crush their end; fade lifts the black.+ let l = luma(clamp(c, vec3<f32>(0.0), vec3<f32>(1.0)));+ let low = (1.0 - smoothstep(0.0, 0.5, l)) * params.shadows / 100.0 * 0.18;+ let high = smoothstep(0.5, 1.0, l) * params.highlights / 100.0 * 0.18;+ c = c + vec3<f32>(low + high);+ let lift = params.fade / 100.0 * 0.25;+ c = c * (1.0 - lift) + vec3<f32>(lift);++ // Sharpen: the difference from a small blur, scaled.+ if (params.sharpen > 0.0) {+ var blur = vec3<f32>(0.0);+ for (var y: i32 = -1; y <= 1; y++) {+ for (var x: i32 = -1; x <= 1; x++) {+ blur += sample(uv + vec2<f32>(f32(x), f32(y)) * t).rgb;+ }+ }+ blur /= 9.0;+ c = c + (src.rgb - blur) * params.sharpen / 100.0 * 2.0;+ }++ // Vignette: darker towards the corners.+ if (params.vignette > 0.0) {+ let d = length((uv - vec2<f32>(0.5)) * vec2<f32>(2.0));+ let v = params.vignette / 100.0;+ let fall = smoothstep(1.4 - v * 0.9, 1.6 - v * 0.3, d);+ c = c * (1.0 - fall * (0.4 + 0.6 * v));+ }++ return vec4<f32>(clamp(c, vec3<f32>(0.0), vec3<f32>(1.0)), src.a);+}diff --git a/engine/crates/concat-effects/packages/concat.black-white/effect.toml b/engine/crates/concat-effects/packages/concat.black-white/effect.tomlindex e790c9c3..8f4bffcd 100644--- a/engine/crates/concat-effects/packages/concat.black-white/effect.toml+++ b/engine/crates/concat-effects/packages/concat.black-white/effect.toml@@ -9,3 +9,6 @@ description = "Drops every colour to grey."[ffmpeg]chain = "hue=s=0"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.black-white/effect.wgsl b/engine/crates/concat-effects/packages/concat.black-white/effect.wgslnew file mode 100644index 00000000..b76064e5--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.black-white/effect.wgsl@@ -0,0 +1,5 @@+// Every channel takes the luminance.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ return vec4<f32>(vec3<f32>(luma(c.rgb)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.blue-screen/effect.toml b/engine/crates/concat-effects/packages/concat.blue-screen/effect.tomlindex ef472049..22860e45 100644--- a/engine/crates/concat-effects/packages/concat.blue-screen/effect.toml+++ b/engine/crates/concat-effects/packages/concat.blue-screen/effect.toml@@ -27,3 +27,6 @@ unit = "%"[ffmpeg]chain = "chromakey=color=0x0000FFty={fixed(similarity / 100, 3)}:blend={fixed(softness / 100, 3)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.blue-screen/effect.wgsl b/engine/crates/concat-effects/packages/concat.blue-screen/effect.wgslnew file mode 100644index 00000000..642b73bf--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.blue-screen/effect.wgsl@@ -0,0 +1,19 @@+struct Params { similarity: f32, softness: f32 }++// Keys by chroma distance in YCbCr, the way the FFmpeg chain does, so the+// same similarity and softness mean the same edge on either path.+fn chroma(rgb: vec3<f32>) -> vec2<f32> {+ let cb = -0.1146 * rgb.r - 0.3854 * rgb.g + 0.5 * rgb.b;+ let cr = 0.5 * rgb.r - 0.4542 * rgb.g - 0.0458 * rgb.b;+ return vec2<f32>(cb, cr);+}++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let key = vec3<f32>(0.0, 0.0, 1.0);+ let d = distance(chroma(c.rgb), chroma(key)) / 0.7071;+ let similarity = params.similarity / 100.0;+ let softness = params.softness / 100.0;+ let keep = smoothstep(similarity, similarity + max(softness, 0.001), d);+ return vec4<f32>(c.rgb, c.a * keep);+}diff --git a/engine/crates/concat-effects/packages/concat.box-blur/effect.toml b/engine/crates/concat-effects/packages/concat.box-blur/effect.tomlindex 5b4f217a..370851a8 100644--- a/engine/crates/concat-effects/packages/concat.box-blur/effect.toml+++ b/engine/crates/concat-effects/packages/concat.box-blur/effect.toml@@ -20,3 +20,6 @@ unit = "px"[ffmpeg]chain = "boxblur={round(radius)}:1"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.box-blur/effect.wgsl b/engine/crates/concat-effects/packages/concat.box-blur/effect.wgslnew file mode 100644index 00000000..05ab323f--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.box-blur/effect.wgsl@@ -0,0 +1,14 @@+struct Params { radius: f32 }++// A box of `radius` pixels either side, sampled on a 9×9 grid.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let step = max(params.radius / 4.0, 0.5);+ var sum = vec4<f32>(0.0);+ for (var y: i32 = -4; y <= 4; y++) {+ for (var x: i32 = -4; x <= 4; x++) {+ sum += sample(uv + vec2<f32>(f32(x), f32(y)) * step * t);+ }+ }+ return sum / 81.0;+}diff --git a/engine/crates/concat-effects/packages/concat.contrast-pop/effect.toml b/engine/crates/concat-effects/packages/concat.contrast-pop/effect.tomlindex e14a02e1..7f0b8664 100644--- a/engine/crates/concat-effects/packages/concat.contrast-pop/effect.toml+++ b/engine/crates/concat-effects/packages/concat.contrast-pop/effect.toml@@ -18,3 +18,6 @@ step = 0.05[ffmpeg]chain = "eq=contrast={fixed(contrast, 2)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.contrast-pop/effect.wgsl b/engine/crates/concat-effects/packages/concat.contrast-pop/effect.wgslnew file mode 100644index 00000000..35210fc9--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.contrast-pop/effect.wgsl@@ -0,0 +1,7 @@+struct Params { contrast: f32 }++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let out = (c.rgb - vec3<f32>(0.5)) * params.contrast + vec3<f32>(0.5);+ return vec4<f32>(clamp(out, vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.cool/effect.toml b/engine/crates/concat-effects/packages/concat.cool/effect.tomlindex 7e23b7e4..ee6aca35 100644--- a/engine/crates/concat-effects/packages/concat.cool/effect.toml+++ b/engine/crates/concat-effects/packages/concat.cool/effect.toml@@ -19,3 +19,6 @@ unit = "K"[ffmpeg]chain = "colortemperature=temperature={round(temperature)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.cool/effect.wgsl b/engine/crates/concat-effects/packages/concat.cool/effect.wgslnew file mode 100644index 00000000..b0834a89--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.cool/effect.wgsl@@ -0,0 +1,30 @@+struct Params { temperature: f32 }++// Colour temperature as a white balance shift: the picture as if it were+// lit at `temperature` kelvin while the camera was set for daylight.+fn kelvin(k: f32) -> vec3<f32> {+ let t = clamp(k, 1000.0, 40000.0) / 100.0;+ var r: f32;+ var g: f32;+ var b: f32;+ if (t <= 66.0) {+ r = 1.0;+ g = clamp((99.4708 * log(t) - 161.1196) / 255.0, 0.0, 1.0);+ if (t <= 19.0) {+ b = 0.0;+ } else {+ b = clamp((138.5177 * log(t - 10.0) - 305.0448) / 255.0, 0.0, 1.0);+ }+ } else {+ r = clamp(329.6987 * pow(t - 60.0, -0.1332) / 255.0, 0.0, 1.0);+ g = clamp(288.1222 * pow(t - 60.0, -0.0755) / 255.0, 0.0, 1.0);+ b = 1.0;+ }+ return vec3<f32>(r, g, b);+}++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let tint = kelvin(params.temperature) / kelvin(6500.0);+ return vec4<f32>(clamp(c.rgb * tint, vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.film-grain/effect.toml b/engine/crates/concat-effects/packages/concat.film-grain/effect.tomlindex 4b06bad8..7aeccaa6 100644--- a/engine/crates/concat-effects/packages/concat.film-grain/effect.toml+++ b/engine/crates/concat-effects/packages/concat.film-grain/effect.toml@@ -19,3 +19,6 @@ step = 1[ffmpeg]chain = "noise=alls={round(amount)}:allf=t+u"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.film-grain/effect.wgsl b/engine/crates/concat-effects/packages/concat.film-grain/effect.wgslnew file mode 100644index 00000000..1ade46d0--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.film-grain/effect.wgsl@@ -0,0 +1,9 @@+struct Params { amount: f32 }++// Per-pixel noise that changes every frame, scaled by the amount.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let n = hash(uv * frame.size, fract(frame.time * 7.31)) - 0.5;+ let grain = n * params.amount / 100.0;+ return vec4<f32>(clamp(c.rgb + vec3<f32>(grain), vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.fisheye/effect.toml b/engine/crates/concat-effects/packages/concat.fisheye/effect.tomlindex d6c1348f..358df7aa 100644--- a/engine/crates/concat-effects/packages/concat.fisheye/effect.toml+++ b/engine/crates/concat-effects/packages/concat.fisheye/effect.toml@@ -22,3 +22,6 @@ let = ["k = strength / 100",]chain = "lenscorrection=k1={fixed(-0.55 * k, 3)}:k2={fixed(-0.2 * k, 3)}:i=bilinear"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.fisheye/effect.wgsl b/engine/crates/concat-effects/packages/concat.fisheye/effect.wgslnew file mode 100644index 00000000..dea7f53c--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.fisheye/effect.wgsl@@ -0,0 +1,15 @@+struct Params { strength: f32 }++// Barrel distortion about the centre, stronger towards the edge.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let k = params.strength / 100.0 * 0.6;+ let aspect = frame.size.x / frame.size.y;+ var p = (uv - vec2<f32>(0.5)) * vec2<f32>(2.0 * aspect, 2.0);+ let r2 = dot(p, p);+ p = p * (1.0 - k * r2) / (1.0 - k * (aspect * aspect + 1.0) * 0.5);+ let q = p / vec2<f32>(2.0 * aspect, 2.0) + vec2<f32>(0.5);+ if (q.x < 0.0 || q.x > 1.0 || q.y < 0.0 || q.y > 1.0) {+ return vec4<f32>(0.0, 0.0, 0.0, 0.0);+ }+ return sample(q);+}diff --git a/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.toml b/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.tomlindex 5ee89015..c131746e 100644--- a/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.toml+++ b/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.toml@@ -19,3 +19,6 @@ unit = "px"[ffmpeg]chain = "gblur=sigma={fixed(radius, 1)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.wgsl b/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.wgslnew file mode 100644index 00000000..45c64b38--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.gaussian-blur/effect.wgsl@@ -0,0 +1,20 @@+struct Params { radius: f32 }++// A Gaussian of sigma `radius` pixels, sampled on a 9×9 grid whose spacing+// grows with the sigma; bilinear filtering fills the gaps at large radii.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let sigma = max(params.radius, 0.5);+ let step = max(sigma / 2.5, 1.0);+ var sum = vec4<f32>(0.0);+ var weight = 0.0;+ for (var y: i32 = -4; y <= 4; y++) {+ for (var x: i32 = -4; x <= 4; x++) {+ let d = vec2<f32>(f32(x), f32(y)) * step;+ let w = exp(-dot(d, d) / (2.0 * sigma * sigma));+ sum += sample(uv + d * t) * w;+ weight += w;+ }+ }+ return sum / weight;+}diff --git a/engine/crates/concat-effects/packages/concat.glow/effect.toml b/engine/crates/concat-effects/packages/concat.glow/effect.tomlindex 54765bc6..64c3c381 100644--- a/engine/crates/concat-effects/packages/concat.glow/effect.toml+++ b/engine/crates/concat-effects/packages/concat.glow/effect.toml@@ -19,3 +19,6 @@ unit = "%"[ffmpeg]chain = "split[glowa{index}][glowb{index}];[glowb{index}]gblur=sigma=18[glowg{index}];[glowa{index}][glowg{index}]blend=all_mode=screen:all_opacity={fixed(amount / 100, 2)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.glow/effect.wgsl b/engine/crates/concat-effects/packages/concat.glow/effect.wgslnew file mode 100644index 00000000..91e9f6e2--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.glow/effect.wgsl@@ -0,0 +1,21 @@+struct Params { amount: f32 }++// A wide soft blur, screened over the picture by the amount.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let c = sample(uv);+ let step = 6.0;+ var blur = vec3<f32>(0.0);+ var weight = 0.0;+ for (var y: i32 = -3; y <= 3; y++) {+ for (var x: i32 = -3; x <= 3; x++) {+ let d = vec2<f32>(f32(x), f32(y));+ let w = exp(-dot(d, d) / 8.0);+ blur += sample(uv + d * step * t).rgb * w;+ weight += w;+ }+ }+ blur /= weight;+ let screen = vec3<f32>(1.0) - (vec3<f32>(1.0) - c.rgb) * (vec3<f32>(1.0) - blur);+ return vec4<f32>(mix(c.rgb, screen, params.amount / 100.0), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.green-screen/effect.toml b/engine/crates/concat-effects/packages/concat.green-screen/effect.tomlindex 77526729..ccb066f7 100644--- a/engine/crates/concat-effects/packages/concat.green-screen/effect.toml+++ b/engine/crates/concat-effects/packages/concat.green-screen/effect.toml@@ -27,3 +27,6 @@ unit = "%"[ffmpeg]chain = "chromakey=color=0x00FF00ty={fixed(similarity / 100, 3)}:blend={fixed(softness / 100, 3)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.green-screen/effect.wgsl b/engine/crates/concat-effects/packages/concat.green-screen/effect.wgslnew file mode 100644index 00000000..1efc7668--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.green-screen/effect.wgsl@@ -0,0 +1,19 @@+struct Params { similarity: f32, softness: f32 }++// Keys by chroma distance in YCbCr, the way the FFmpeg chain does, so the+// same similarity and softness mean the same edge on either path.+fn chroma(rgb: vec3<f32>) -> vec2<f32> {+ let cb = -0.1146 * rgb.r - 0.3854 * rgb.g + 0.5 * rgb.b;+ let cr = 0.5 * rgb.r - 0.4542 * rgb.g - 0.0458 * rgb.b;+ return vec2<f32>(cb, cr);+}++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let key = vec3<f32>(0.0, 1.0, 0.0);+ let d = distance(chroma(c.rgb), chroma(key)) / 0.7071;+ let similarity = params.similarity / 100.0;+ let softness = params.softness / 100.0;+ let keep = smoothstep(similarity, similarity + max(softness, 0.001), d);+ return vec4<f32>(c.rgb, c.a * keep);+}diff --git a/engine/crates/concat-effects/packages/concat.invert/effect.toml b/engine/crates/concat-effects/packages/concat.invert/effect.tomlindex e228c60d..3165d578 100644--- a/engine/crates/concat-effects/packages/concat.invert/effect.toml+++ b/engine/crates/concat-effects/packages/concat.invert/effect.toml@@ -9,3 +9,6 @@ description = "Every colour becomes its opposite."[ffmpeg]chain = "negate"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.invert/effect.wgsl b/engine/crates/concat-effects/packages/concat.invert/effect.wgslnew file mode 100644index 00000000..050109eb--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.invert/effect.wgsl@@ -0,0 +1,4 @@+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ return vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.mask-circle/effect.toml b/engine/crates/concat-effects/packages/concat.mask-circle/effect.tomlindex 0ab66b5f..3f0dbce2 100644--- a/engine/crates/concat-effects/packages/concat.mask-circle/effect.toml+++ b/engine/crates/concat-effects/packages/concat.mask-circle/effect.toml@@ -59,3 +59,6 @@ let = ["py = y / 100",]chain = "format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='alpha(X,Y)*abs({round(invert)}-clip(({fixed(radius, 4)}*min(W,H)+{fixed(soft, 4)}*min(W,H)/2-hypot(X-W*{fixed(px, 4)},Y-H*{fixed(py, 4)}))/({fixed(soft, 4)}*min(W,H)+0.5),0,1))'"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.mask-circle/effect.wgsl b/engine/crates/concat-effects/packages/concat.mask-circle/effect.wgslnew file mode 100644index 00000000..7a7461d9--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.mask-circle/effect.wgsl@@ -0,0 +1,15 @@+struct Params { size: f32, feather: f32, x: f32, y: f32, invert: f32 }++// A soft-edged disc keeps the picture; outside it, nothing.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let px = uv * frame.size;+ let short = min(frame.size.x, frame.size.y);+ let radius = params.size / 200.0 * short;+ let soft = params.feather / 200.0 * short + 0.5;+ let centre = vec2<f32>(params.x, params.y) / 100.0 * frame.size;+ let d = distance(px, centre);+ var keep = clamp((radius + soft * 0.5 - d) / soft, 0.0, 1.0);+ keep = abs(params.invert - keep);+ return vec4<f32>(c.rgb, c.a * keep);+}diff --git a/engine/crates/concat-effects/packages/concat.mask-linear/effect.toml b/engine/crates/concat-effects/packages/concat.mask-linear/effect.tomlindex 9a2866ef..972bb97c 100644--- a/engine/crates/concat-effects/packages/concat.mask-linear/effect.toml+++ b/engine/crates/concat-effects/packages/concat.mask-linear/effect.toml@@ -39,3 +39,6 @@ let = ["soft = feather / 100",]chain = "format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='alpha(X,Y)*abs({round(invert)}-clip((W*{fixed(edge, 4)}+W*{fixed(soft, 4)}/2-X)/(W*{fixed(soft, 4)}+0.5),0,1))'"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.mask-linear/effect.wgsl b/engine/crates/concat-effects/packages/concat.mask-linear/effect.wgslnew file mode 100644index 00000000..b1728f16--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.mask-linear/effect.wgsl@@ -0,0 +1,10 @@+struct Params { position: f32, feather: f32, invert: f32 }++// Keeps the picture left of a soft vertical edge.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let edge = params.position / 100.0;+ let soft = params.feather / 100.0 + 0.0005;+ let keep = abs(params.invert - clamp((edge + soft * 0.5 - uv.x) / soft, 0.0, 1.0));+ return vec4<f32>(c.rgb, c.a * keep);+}diff --git a/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.toml b/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.tomlindex 849d57fd..b8083fdb 100644--- a/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.toml+++ b/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.toml@@ -69,3 +69,6 @@ let = ["py = y / 100",]chain = "format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='alpha(X,Y)*abs({round(invert)}-clip(({fixed(hw, 4)}*W+{fixed(soft, 4)}*min(W,H)/2-abs(X-W*{fixed(px, 4)}))/({fixed(soft, 4)}*min(W,H)+0.5),0,1)*clip(({fixed(hh, 4)}*H+{fixed(soft, 4)}*min(W,H)/2-abs(Y-H*{fixed(py, 4)}))/({fixed(soft, 4)}*min(W,H)+0.5),0,1))'"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.wgsl b/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.wgslnew file mode 100644index 00000000..5e21ded6--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.mask-rectangle/effect.wgsl@@ -0,0 +1,15 @@+struct Params { width: f32, height: f32, feather: f32, x: f32, y: f32, invert: f32 }++// A soft-edged rectangle keeps the picture; outside it, nothing.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let px = uv * frame.size;+ let short = min(frame.size.x, frame.size.y);+ let soft = params.feather / 200.0 * short + 0.5;+ let centre = vec2<f32>(params.x, params.y) / 100.0 * frame.size;+ let half = vec2<f32>(params.width / 200.0 * frame.size.x, params.height / 200.0 * frame.size.y);+ let ax = clamp((half.x + soft * 0.5 - abs(px.x - centre.x)) / soft, 0.0, 1.0);+ let ay = clamp((half.y + soft * 0.5 - abs(px.y - centre.y)) / soft, 0.0, 1.0);+ let keep = abs(params.invert - ax * ay);+ return vec4<f32>(c.rgb, c.a * keep);+}diff --git a/engine/crates/concat-effects/packages/concat.mirror/effect.toml b/engine/crates/concat-effects/packages/concat.mirror/effect.tomlindex 61af66f0..c8b20dc6 100644--- a/engine/crates/concat-effects/packages/concat.mirror/effect.toml+++ b/engine/crates/concat-effects/packages/concat.mirror/effect.toml@@ -9,3 +9,6 @@ description = "The left half, reflected onto the right."[ffmpeg]chain = "crop=iw/2:ih:0:0,split[mirl{index}][mirr{index}];[mirr{index}]hflip[mirf{index}];[mirl{index}][mirf{index}]hstack"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.mirror/effect.wgsl b/engine/crates/concat-effects/packages/concat.mirror/effect.wgslnew file mode 100644index 00000000..b2b48f48--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.mirror/effect.wgsl@@ -0,0 +1,5 @@+// The left half, and its reflection on the right.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let x = select(1.0 - uv.x, uv.x, uv.x < 0.5);+ return sample(vec2<f32>(x, uv.y));+}diff --git a/engine/crates/concat-effects/packages/concat.motion-blur/effect.toml b/engine/crates/concat-effects/packages/concat.motion-blur/effect.tomlindex 0a620e75..8fd22931 100644--- a/engine/crates/concat-effects/packages/concat.motion-blur/effect.toml+++ b/engine/crates/concat-effects/packages/concat.motion-blur/effect.toml@@ -19,3 +19,6 @@ unit = "px"[ffmpeg]chain = "gblur=sigma={fixed(length, 1)}:sigmaV=0.1"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.motion-blur/effect.wgsl b/engine/crates/concat-effects/packages/concat.motion-blur/effect.wgslnew file mode 100644index 00000000..407a11dd--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.motion-blur/effect.wgsl@@ -0,0 +1,18 @@+struct Params { length: f32 }++// A horizontal streak of `length` pixels: taps along a line, Gaussian+// weighted so the ends fade.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let sigma = max(params.length, 0.5);+ let step = max(sigma / 6.0, 1.0);+ var sum = vec4<f32>(0.0);+ var weight = 0.0;+ for (var i: i32 = -12; i <= 12; i++) {+ let d = f32(i) * step;+ let w = exp(-(d * d) / (2.0 * sigma * sigma));+ sum += sample(uv + vec2<f32>(d, 0.0) * t) * w;+ weight += w;+ }+ return sum / weight;+}diff --git a/engine/crates/concat-effects/packages/concat.pixelate/effect.toml b/engine/crates/concat-effects/packages/concat.pixelate/effect.tomlindex df407ff3..5e9f26da 100644--- a/engine/crates/concat-effects/packages/concat.pixelate/effect.toml+++ b/engine/crates/concat-effects/packages/concat.pixelate/effect.toml@@ -20,3 +20,6 @@ unit = "px"[ffmpeg]chain = "pixelize=width={round(size)}:height={round(size)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.pixelate/effect.wgsl b/engine/crates/concat-effects/packages/concat.pixelate/effect.wgslnew file mode 100644index 00000000..ba982b45--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.pixelate/effect.wgsl@@ -0,0 +1,8 @@+struct Params { size: f32 }++// Every pixel takes the colour at the centre of its `size`-pixel block.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let block = max(round(params.size), 1.0);+ let p = floor(uv * frame.size / block) * block + vec2<f32>(block * 0.5);+ return sample(p / frame.size);+}diff --git a/engine/crates/concat-effects/packages/concat.posterize/effect.toml b/engine/crates/concat-effects/packages/concat.posterize/effect.tomlindex f6d6c24a..36843b74 100644--- a/engine/crates/concat-effects/packages/concat.posterize/effect.toml+++ b/engine/crates/concat-effects/packages/concat.posterize/effect.toml@@ -22,3 +22,6 @@ let = ["size = round(256 / max(round(levels), 2))",]chain = "lutrgb=r=trunc(val/{size})*{size}:g=trunc(val/{size})*{size}:b=trunc(val/{size})*{size}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.posterize/effect.wgsl b/engine/crates/concat-effects/packages/concat.posterize/effect.wgslnew file mode 100644index 00000000..2d7d6831--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.posterize/effect.wgsl@@ -0,0 +1,7 @@+struct Params { levels: f32 }++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let n = max(round(params.levels), 2.0);+ return vec4<f32>(floor(c.rgb * n) / (n - 1.0) * ((n - 1.0) / n) + vec3<f32>(0.0), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.sepia/effect.toml b/engine/crates/concat-effects/packages/concat.sepia/effect.tomlindex 0776038d..9fce303d 100644--- a/engine/crates/concat-effects/packages/concat.sepia/effect.toml+++ b/engine/crates/concat-effects/packages/concat.sepia/effect.toml@@ -9,3 +9,6 @@ description = "The warm brown of an old photograph."[ffmpeg]chain = "colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.sepia/effect.wgsl b/engine/crates/concat-effects/packages/concat.sepia/effect.wgslnew file mode 100644index 00000000..87c54c9f--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.sepia/effect.wgsl@@ -0,0 +1,8 @@+// The classic sepia matrix, the same numbers the FFmpeg chain uses.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let r = dot(c.rgb, vec3<f32>(0.393, 0.769, 0.189));+ let g = dot(c.rgb, vec3<f32>(0.349, 0.686, 0.168));+ let b = dot(c.rgb, vec3<f32>(0.272, 0.534, 0.131));+ return vec4<f32>(clamp(vec3<f32>(r, g, b), vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.shake/effect.toml b/engine/crates/concat-effects/packages/concat.shake/effect.tomlindex fa65c60d..61bb4174 100644--- a/engine/crates/concat-effects/packages/concat.shake/effect.toml+++ b/engine/crates/concat-effects/packages/concat.shake/effect.toml@@ -33,3 +33,6 @@ let = ["f2 = round(f * 1.3)",]chain = "crop=iw-{2 * a}:ih-{2 * a}:{a}+{a}*sin(t*{f}):{a}+{a}*cos(t*{f2})"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.shake/effect.wgsl b/engine/crates/concat-effects/packages/concat.shake/effect.wgslnew file mode 100644index 00000000..2c4fe2c8--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.shake/effect.wgsl@@ -0,0 +1,13 @@+struct Params { amount: f32, speed: f32 }++// The picture shifted by a wandering offset of up to `amount` pixels.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = frame.time;+ let dx = sin(t * params.speed) * params.amount;+ let dy = cos(t * params.speed * 1.3) * params.amount;+ let q = uv + vec2<f32>(dx, dy) / frame.size;+ if (q.x < 0.0 || q.x > 1.0 || q.y < 0.0 || q.y > 1.0) {+ return vec4<f32>(0.0, 0.0, 0.0, 0.0);+ }+ return sample(q);+}diff --git a/engine/crates/concat-effects/packages/concat.sharpen/effect.toml b/engine/crates/concat-effects/packages/concat.sharpen/effect.tomlindex 59a2775f..6adb8331 100644--- a/engine/crates/concat-effects/packages/concat.sharpen/effect.toml+++ b/engine/crates/concat-effects/packages/concat.sharpen/effect.toml@@ -18,3 +18,6 @@ step = 0.05[ffmpeg]chain = "unsharp=5:5:{fixed(amount, 2)}:5:5:0"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.sharpen/effect.wgsl b/engine/crates/concat-effects/packages/concat.sharpen/effect.wgslnew file mode 100644index 00000000..6feff244--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.sharpen/effect.wgsl@@ -0,0 +1,16 @@+struct Params { amount: f32 }++// Unsharp mask: the picture plus its difference from a small blur.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let t = texel();+ let c = sample(uv);+ var blur = vec3<f32>(0.0);+ for (var y: i32 = -2; y <= 2; y++) {+ for (var x: i32 = -2; x <= 2; x++) {+ blur += sample(uv + vec2<f32>(f32(x), f32(y)) * t).rgb;+ }+ }+ blur /= 25.0;+ let sharp = c.rgb + (c.rgb - blur) * params.amount;+ return vec4<f32>(clamp(sharp, vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.vibrance/effect.toml b/engine/crates/concat-effects/packages/concat.vibrance/effect.tomlindex 13c626f5..255a8eaa 100644--- a/engine/crates/concat-effects/packages/concat.vibrance/effect.toml+++ b/engine/crates/concat-effects/packages/concat.vibrance/effect.toml@@ -18,3 +18,6 @@ step = 0.05[ffmpeg]chain = "vibrance=intensity={fixed(intensity, 2)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.vibrance/effect.wgsl b/engine/crates/concat-effects/packages/concat.vibrance/effect.wgslnew file mode 100644index 00000000..fb0611d4--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.vibrance/effect.wgsl@@ -0,0 +1,12 @@+struct Params { intensity: f32 }++// Saturates the dull colours more than the vivid ones.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let l = luma(c.rgb);+ let mx = max(max(c.r, c.g), c.b);+ let mn = min(min(c.r, c.g), c.b);+ let sat = mx - mn;+ let boost = params.intensity * (1.0 - sat);+ return vec4<f32>(clamp(mix(vec3<f32>(l), c.rgb, 1.0 + boost), vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.vignette/effect.toml b/engine/crates/concat-effects/packages/concat.vignette/effect.tomlindex 2645116d..88f67294 100644--- a/engine/crates/concat-effects/packages/concat.vignette/effect.toml+++ b/engine/crates/concat-effects/packages/concat.vignette/effect.toml@@ -19,3 +19,6 @@ unit = "%"[ffmpeg]chain = "vignette=angle={fixed(0.25 + (strength / 100) * 1.05, 3)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.vignette/effect.wgsl b/engine/crates/concat-effects/packages/concat.vignette/effect.wgslnew file mode 100644index 00000000..61e1b8a6--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.vignette/effect.wgsl@@ -0,0 +1,10 @@+struct Params { strength: f32 }++// Darkens towards the corners: a smooth fall-off from the centre.+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let d = length((uv - vec2<f32>(0.5)) * vec2<f32>(2.0));+ let s = params.strength / 100.0;+ let fall = smoothstep(1.4 - s * 0.9, 1.4 + 0.2 - s * 0.3, d);+ return vec4<f32>(c.rgb * (1.0 - fall * (0.4 + 0.6 * s)), c.a);+}diff --git a/engine/crates/concat-effects/packages/concat.warm/effect.toml b/engine/crates/concat-effects/packages/concat.warm/effect.tomlindex 9d269189..4167ebe7 100644--- a/engine/crates/concat-effects/packages/concat.warm/effect.toml+++ b/engine/crates/concat-effects/packages/concat.warm/effect.toml@@ -19,3 +19,6 @@ unit = "K"[ffmpeg]chain = "colortemperature=temperature={round(temperature)}"++[wgsl]+entry = "effect.wgsl"diff --git a/engine/crates/concat-effects/packages/concat.warm/effect.wgsl b/engine/crates/concat-effects/packages/concat.warm/effect.wgslnew file mode 100644index 00000000..b0834a89--- /dev/null+++ b/engine/crates/concat-effects/packages/concat.warm/effect.wgsl@@ -0,0 +1,30 @@+struct Params { temperature: f32 }++// Colour temperature as a white balance shift: the picture as if it were+// lit at `temperature` kelvin while the camera was set for daylight.+fn kelvin(k: f32) -> vec3<f32> {+ let t = clamp(k, 1000.0, 40000.0) / 100.0;+ var r: f32;+ var g: f32;+ var b: f32;+ if (t <= 66.0) {+ r = 1.0;+ g = clamp((99.4708 * log(t) - 161.1196) / 255.0, 0.0, 1.0);+ if (t <= 19.0) {+ b = 0.0;+ } else {+ b = clamp((138.5177 * log(t - 10.0) - 305.0448) / 255.0, 0.0, 1.0);+ }+ } else {+ r = clamp(329.6987 * pow(t - 60.0, -0.1332) / 255.0, 0.0, 1.0);+ g = clamp(288.1222 * pow(t - 60.0, -0.0755) / 255.0, 0.0, 1.0);+ b = 1.0;+ }+ return vec3<f32>(r, g, b);+}++fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ let tint = kelvin(params.temperature) / kelvin(6500.0);+ return vec4<f32>(clamp(c.rgb * tint, vec3<f32>(0.0), vec3<f32>(1.0)), c.a);+}diff --git a/engine/crates/concat-effects/src/catalogue.rs b/engine/crates/concat-effects/src/catalogue.rsindex a3966d23..be39f4d2 100644--- a/engine/crates/concat-effects/src/catalogue.rs+++ b/engine/crates/concat-effects/src/catalogue.rs@@ -17,7 +17,10 @@ use serde::Deserialize;use crate::Error;use crate::expr::{Expr, Value};+use concat_core::ShaderPass;+use crate::manifest::{Kind, Manifest};+use crate::shader::Shader;use crate::template::Template;/// A compiled FFmpeg backend.@@ -67,6 +70,9 @@ pub struct Package {/// What the package declares.pub manifest: Manifest,chain: Option<Chain>,+ /// The shader, when the package has one: the GPU renders it, and the+ /// chain - if the package has that too - is the CPU's fallback.+ shader: Option<Shader>,/// The pinned outputs shipped with the package.pub fixtures: Vec<Fixture>,}@@ -114,14 +120,44 @@ struct FixtureFile {impl Package {/// Compiles a package from the text of its manifest and, if it ships- /// one, its fixtures file.- pub fn from_sources(manifest: &str, fixtures: Option<&str>) -> Result<Package, Error> {+ /// them, its fixtures file and its shader.+ pub fn from_sources(+ manifest: &str,+ fixtures: Option<&str>,+ shader: Option<&str>,+ ) -> Result<Package, Error> {let manifest = Manifest::parse(manifest)?;let invalid = |message: String| Error::Invalid {id: manifest.effect.id.clone(),message,};+ // A `[wgsl]` table without the file, or the file without the table,+ // is a package that does not know what it is.+ let shader = match (&manifest.wgsl, shader) {+ (Some(_), Some(body)) => Some(+ Shader::compile(&manifest, body)+ .map_err(|message| invalid(format!("shader: {message}")))?,+ ),+ (Some(wgsl), None) => {+ return Err(invalid(format!(+ "[wgsl] names `{}` but no shader was given",+ wgsl.entry+ )));+ }+ (None, Some(_)) => {+ return Err(invalid(+ "a shader was given but the manifest has no [wgsl] table".to_owned(),+ ));+ }+ (None, None) => None,+ };+ if shader.is_none() && manifest.ffmpeg.is_none() && manifest.effect.kind != Kind::Audio {+ return Err(invalid(+ "the package has neither a shader nor a chain".to_owned(),+ ));+ }+let chain = match &manifest.ffmpeg {None => None,Some(ffmpeg) => {@@ -174,6 +210,7 @@ impl Package {let package = Package {manifest,chain,+ shader,fixtures,};// Render at every bound now, so a type error in an expression is a@@ -201,6 +238,11 @@ impl Package {self.manifest.effect.kind}+ /// The shader, when the package renders on the GPU.+ pub fn shader(&self) -> Option<&Shader> {+ self.shader.as_ref()+ }+/// Whether `id` is this package's id or one of its aliases.pub fn answers_to(&self, id: &str) -> bool {self.id() == id || self.manifest.effect.aliases.iter().any(|alias| alias == id)@@ -327,8 +369,8 @@ impl Catalogue {static BUILTIN: OnceLock<Catalogue> = OnceLock::new();BUILTIN.get_or_init(|| {let mut catalogue = Catalogue::new();- for (folder, manifest, fixtures) in crate::builtins::BUILTIN_SOURCES {- let package = Package::from_sources(manifest, *fixtures)+ for (folder, manifest, fixtures, shader) in crate::builtins::BUILTIN_SOURCES {+ let package = Package::from_sources(manifest, *fixtures, *shader).unwrap_or_else(|error| panic!("built-in package {folder}: {error}"));assert_eq!(package.id(),@@ -396,7 +438,10 @@ impl Catalogue {}};let fixtures = read("fixtures.toml").ok();- match Package::from_sources(&manifest, fixtures.as_deref()).and_then(|p| self.add(p)) {+ let shader = read("effect.wgsl").ok();+ match Package::from_sources(&manifest, fixtures.as_deref(), shader.as_deref())+ .and_then(|p| self.add(p))+ {Ok(()) => {}Err(error) => errors.push(error),}@@ -446,14 +491,42 @@ impl Catalogue {/// empty string if it has none. Effects apply in the order they were/// added.pub fn video_chain(&self, effects: &[AppliedFilter]) -> String {- self.compose(&[Kind::Effect, Kind::Filter], effects)+ self.compose(&[Kind::Effect, Kind::Filter], effects, false)+ }++ /// The video chain for a renderer that runs shaders: every package with+ /// one is left out, because [`Catalogue::shader_passes`] carries it.+ pub fn video_chain_gpu(&self, effects: &[AppliedFilter]) -> String {+ self.compose(&[Kind::Effect, Kind::Filter], effects, true)+ }++ /// The shader passes of a clip's chain, in applied order: one per enabled+ /// entry whose package has a shader. A filter's intensity rides along;+ /// an effect is always whole.+ pub fn shader_passes(&self, effects: &[AppliedFilter]) -> Vec<ShaderPass> {+ effects+ .iter()+ .filter(|applied| applied.enabled)+ .filter_map(|applied| {+ let package = self.get(&applied.id)?;+ let shader = package.shader()?;+ let intensity = if package.kind() == Kind::Filter {+ (applied.params.get(INTENSITY).copied().unwrap_or(100.0) / 100.0)+ .clamp(0.0, 1.0) as f32+ } else {+ 1.0+ };+ let values = package.resolve(&applied.params);+ Some(shader.pass(&values, &package.manifest.params, intensity))+ })+ .collect()}/// The complete FFmpeg audio filter string for a clip's filters, or the/// empty string if it has none. Filters apply in the order they were/// added: EQ before a limiter is a different sound from the reverse.pub fn audio_chain(&self, filters: &[AppliedFilter]) -> String {- self.compose(&[Kind::Audio], filters)+ self.compose(&[Kind::Audio], filters, false)}/// Enabled entries of these `kinds` in applied order, comma-joined. Bypassed@@ -461,7 +534,7 @@ impl Catalogue {/// an FFmpeg backend contribute nothing. The index each fragment is/// rendered at is its *emitted* position, so labels stay stable when a/// bypassed entry sits earlier in the list.- fn compose(&self, kinds: &[Kind], applied: &[AppliedFilter]) -> String {+ fn compose(&self, kinds: &[Kind], applied: &[AppliedFilter], skip_shaders: bool) -> String {let mut fragments: Vec<String> = Vec::new();for applied in applied.iter().filter(|applied| applied.enabled) {let Some(package) = self.get(&applied.id) else {@@ -470,6 +543,9 @@ impl Catalogue {if !kinds.contains(&package.kind()) {continue;}+ if skip_shaders && package.shader().is_some() {+ continue;+ }match package.ffmpeg_fragment(&applied.params, fragments.len()) {Ok(Some(fragment)) => {let index = fragments.len();diff --git a/engine/crates/concat-effects/src/lib.rs b/engine/crates/concat-effects/src/lib.rsindex 02ccc8a6..dfcc3bc2 100644--- a/engine/crates/concat-effects/src/lib.rs+++ b/engine/crates/concat-effects/src/lib.rs@@ -21,6 +21,7 @@pub mod catalogue;pub mod expr;pub mod manifest;+pub mod shader;pub mod template;mod builtins {@@ -29,6 +30,7 @@ mod builtins {pub use catalogue::{At, Catalogue, Fixture, Package};pub use manifest::{Kind, Manifest, Param, ParamType};+pub use shader::Shader;/// Why a package could not be loaded.#[derive(thiserror::Error, Debug)]@@ -269,6 +271,7 @@ mod tests {Package::from_sources("[effect]\nid = \"a.b\"\nname = \"B\"\nkind = \"effect\"\n[ffmpeg]\nchain = \"negate\"\n",None,+ None,).expect("loads")};diff --git a/engine/crates/concat-effects/src/manifest.rs b/engine/crates/concat-effects/src/manifest.rsindex 69093729..ea94b2f0 100644--- a/engine/crates/concat-effects/src/manifest.rs+++ b/engine/crates/concat-effects/src/manifest.rs@@ -294,14 +294,10 @@ impl Manifest {"intensity names `{intensity}`, which is not a parameter")));}- match (&self.ffmpeg, &self.wgsl) {- (None, None) => {- return Err(self.invalid("no backend: add an [ffmpeg] or a [wgsl] table"));- }- (Some(_), Some(_)) => {- return Err(self.invalid("two backends: keep one of [ffmpeg] and [wgsl]"));- }- _ => {}+ // Both backends may be present: the shader renders wherever there+ // is a GPU, and the chain is what a machine without one gets.+ if self.ffmpeg.is_none() && self.wgsl.is_none() {+ return Err(self.invalid("no backend: add an [ffmpeg] or a [wgsl] table"));}if self.ffmpeg.is_some() && matches!(self.effect.kind, Kind::Transition | Kind::Generator) {return Err(self.invalid("an [ffmpeg] package must be an effect, a filter or audio"));diff --git a/engine/crates/concat-effects/src/shader.rs b/engine/crates/concat-effects/src/shader.rsnew file mode 100644index 00000000..89529265--- /dev/null+++ b/engine/crates/concat-effects/src/shader.rs@@ -0,0 +1,382 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! A package's shader: what it declares, checked and laid out at load.+//!+//! A WGSL package writes two things and nothing else: a `Params` struct+//! whose fields are its knobs, and `fn effect(uv: vec2<f32>) -> vec4<f32>`,+//! the colour it wants at a point of the layer. Everything around that -+//! the bindings, the frame's size and time, the vertex stage, the mixing of+//! the result back over the untouched layer by intensity - is the host's,+//! and is stitched on here so every package shares one contract and no+//! package can bind things differently.+//!+//! The stitched module is parsed and validated when the package loads, the+//! same way a chain template is, so a broken shader is a load error and not+//! a black frame. Its `Params` struct is read back through naga for the+//! offset of every field, which is how a clip's settings become the bytes+//! of a uniform buffer without a package having to say anything about+//! layout.++use std::collections::BTreeMap;+use std::sync::Arc;++use concat_core::ShaderPass;++use crate::manifest::{Manifest, Param, ParamType};++/// What every package's shader can see. Group 0 is the layer, group 1 the+/// host's frame block and the package's own parameters.+pub const PRELUDE: &str = r#"// ── the host's half of the contract; see concat-effects/src/shader.rs ──+struct Frame {+ /// The layer's size in pixels.+ size: vec2<f32>,+ /// Seconds into the timeline.+ time: f32,+ /// How much of the effect to keep over the untouched layer.+ intensity: f32,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var source_sampler: sampler;+@group(1) @binding(0) var<uniform> frame: Frame;+@group(1) @binding(1) var<uniform> params: Params;++/// The layer's colour at `uv`, straight alpha.+fn sample(uv: vec2<f32>) -> vec4<f32> {+ return textureSample(source, source_sampler, uv);+}++/// One pixel, as a fraction of the layer.+fn texel() -> vec2<f32> {+ return vec2<f32>(1.0, 1.0) / frame.size;+}++/// Luminance, Rec. 709.+fn luma(rgb: vec3<f32>) -> f32 {+ return dot(rgb, vec3<f32>(0.2126, 0.7152, 0.0722));+}++/// A hash in 0..1 from a point and a seed, for grain and dither.+fn hash(p: vec2<f32>, seed: f32) -> f32 {+ let q = vec3<f32>(p, seed);+ return fract(sin(dot(q, vec3<f32>(12.9898, 78.233, 37.719))) * 43758.5453);+}+"#;++/// The stages the host draws with: a full-screen triangle, and a fragment+/// that mixes the package's colour over the untouched layer by intensity.+pub const POSTLUDE: &str = r#"+struct VsOut {+ @builtin(position) position: vec4<f32>,+ @location(0) uv: vec2<f32>,+}++@vertex+fn vs_main(@builtin(vertex_index) index: u32) -> VsOut {+ // One triangle over the whole target; the clip trims it to the square.+ let x = f32(i32(index & 1u) * 4 - 1);+ let y = f32(i32(index >> 1u) * 4 - 1);+ var out: VsOut;+ out.position = vec4<f32>(x, y, 0.0, 1.0);+ out.uv = vec2<f32>((x + 1.0) * 0.5, 1.0 - (y + 1.0) * 0.5);+ return out;+}++@fragment+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {+ let base = sample(in.uv);+ let treated = effect(in.uv);+ return mix(base, treated, clamp(frame.intensity, 0.0, 1.0));+}+"#;++/// Where one parameter lands in the uniform buffer.+#[derive(Clone, Debug, PartialEq)]+struct Slot {+ key: String,+ offset: usize,+ kind: ParamType,+}++/// A package's shader, stitched, checked and laid out.+#[derive(Clone, Debug)]+pub struct Shader {+ key: String,+ source: Arc<str>,+ slots: Vec<Slot>,+ span: usize,+}++impl Shader {+ /// Stitches `body` into the host's contract, checks it, and reads the+ /// `Params` struct for where each of the manifest's parameters lands.+ /// Every declared parameter must be a field of the struct; a field the+ /// manifest does not declare is allowed and stays zero.+ pub fn compile(manifest: &Manifest, body: &str) -> Result<Shader, String> {+ let declares_params = body+ .split("struct")+ .skip(1)+ .any(|rest| rest.trim_start().starts_with("Params"));+ if !body.contains("fn effect") {+ return Err(+ "the shader declares no `fn effect(uv: vec2<f32>) -> vec4<f32>`".to_owned(),+ );+ }+ let mut source = String::with_capacity(PRELUDE.len() + body.len() + POSTLUDE.len() + 64);+ if !declares_params {+ // A package with no knobs still has to bind something.+ source.push_str("struct Params { _unused: f32 }\n");+ }+ source.push_str(body);+ source.push('\n');+ source.push_str(PRELUDE);+ source.push_str(POSTLUDE);++ let module =+ naga::front::wgsl::parse_str(&source).map_err(|error| error.emit_to_string(&source))?;+ let mut validator = naga::valid::Validator::new(+ naga::valid::ValidationFlags::all(),+ naga::valid::Capabilities::all(),+ );+ validator+ .validate(&module)+ .map_err(|error| error.emit_to_string(&source))?;+ if !module+ .functions+ .iter()+ .any(|(_, function)| function.name.as_deref() == Some("effect"))+ {+ return Err(+ "the shader declares no `fn effect(uv: vec2<f32>) -> vec4<f32>`".to_owned(),+ );+ }++ let (members, span) = module+ .types+ .iter()+ .find_map(|(_, ty)| match (&ty.name, &ty.inner) {+ (Some(name), naga::TypeInner::Struct { members, span }) if name == "Params" => {+ Some((members.clone(), *span as usize))+ }+ _ => None,+ })+ .ok_or_else(|| "the shader declares no `struct Params`".to_owned())?;++ let mut slots = Vec::new();+ for param in &manifest.params {+ let member = members+ .iter()+ .find(|member| member.name.as_deref() == Some(param.key.as_str()))+ .ok_or_else(|| format!("`Params` has no field `{}`", param.key))?;+ let inner = &module.types[member.ty].inner;+ let wanted = match param.kind {+ ParamType::Point => 2,+ ParamType::Color => 4,+ _ => 1,+ };+ let width = match inner {+ naga::TypeInner::Scalar(scalar) if is_f32(scalar) => 1,+ naga::TypeInner::Vector { size, scalar } if is_f32(scalar) => *size as usize,+ _ => 0,+ };+ if width != wanted {+ return Err(format!(+ "`Params.{}` must be {}",+ param.key,+ match wanted {+ 2 => "a vec2<f32>",+ 4 => "a vec4<f32>",+ _ => "an f32",+ }+ ));+ }+ slots.push(Slot {+ key: param.key.clone(),+ offset: member.offset as usize,+ kind: param.kind,+ });+ }++ Ok(Shader {+ key: format!("{}@{}", manifest.effect.id, manifest.effect.version),+ source: Arc::from(source),+ slots,+ span: span.max(ShaderPass::MIN_PARAMS).div_ceil(16) * 16,+ })+ }++ /// The stitched module.+ pub fn source(&self) -> &str {+ &self.source+ }++ /// The `Params` buffer for these resolved values, laid out to the+ /// struct. Every declared parameter is present in `values` by the time+ /// the catalogue calls this; anything missing reads as zero.+ pub fn params_bytes(&self, values: &BTreeMap<String, f64>, params: &[Param]) -> Vec<u8> {+ let mut bytes = vec![0u8; self.span];+ let mut put = |offset: usize, value: f64| {+ let at = offset..offset + 4;+ if at.end <= bytes.len() {+ bytes[at].copy_from_slice(&(value as f32).to_le_bytes());+ }+ };+ for slot in &self.slots {+ match slot.kind {+ ParamType::Point => {+ put(+ slot.offset,+ values+ .get(&format!("{}.x", slot.key))+ .copied()+ .unwrap_or(0.5),+ );+ put(+ slot.offset + 4,+ values+ .get(&format!("{}.y", slot.key))+ .copied()+ .unwrap_or(0.5),+ );+ }+ ParamType::Color => {+ // Packed RGBA in one number, as the document stores it.+ let packed = values.get(&slot.key).copied().unwrap_or(0.0).max(0.0) as u32;+ for (index, shift) in [24u32, 16, 8, 0].into_iter().enumerate() {+ put(+ slot.offset + index * 4,+ f64::from((packed >> shift) & 0xff) / 255.0,+ );+ }+ }+ _ => {+ let fallback = params+ .iter()+ .find(|param| param.key == slot.key)+ .map(|param| param.default)+ .unwrap_or(0.0);+ put(+ slot.offset,+ values.get(&slot.key).copied().unwrap_or(fallback),+ );+ }+ }+ }+ bytes+ }++ /// A pass over a layer with these values.+ pub fn pass(+ &self,+ values: &BTreeMap<String, f64>,+ params: &[Param],+ intensity: f32,+ ) -> ShaderPass {+ ShaderPass {+ key: self.key.clone(),+ source: Arc::clone(&self.source),+ params: self.params_bytes(values, params),+ intensity,+ }+ }+}++fn is_f32(scalar: &naga::Scalar) -> bool {+ scalar.kind == naga::ScalarKind::Float && scalar.width == 4+}++#[cfg(test)]+mod tests {+ use super::*;++ fn manifest(params: &str) -> Manifest {+ Manifest::parse(&format!(+ r#"+[effect]+id = "test.thing"+name = "Thing"+kind = "effect"+{params}+[wgsl]+entry = "effect.wgsl"+"#+ ))+ .expect("a valid manifest")+ }++ #[test]+ fn a_body_is_stitched_checked_and_laid_out() {+ let manifest = manifest(+ r#"+[[param]]+key = "amount"+label = "Amount"+min = 0+max = 1+default = 0.25++[[param]]+key = "radius"+label = "Radius"+min = 0+max = 10+default = 2+"#,+ );+ let shader = Shader::compile(+ &manifest,+ r#"+struct Params { radius: f32, amount: f32 }+fn effect(uv: vec2<f32>) -> vec4<f32> {+ let c = sample(uv);+ return vec4<f32>(c.rgb * params.amount + params.radius * 0.0, c.a);+}+"#,+ )+ .expect("compiles");+ assert_eq!(shader.key, "test.thing@1");+ assert!(shader.source().contains("fn fs_main"));+ // radius first at 0, amount at 4; the buffer padded to sixteen.+ let mut values = BTreeMap::new();+ values.insert("amount".to_owned(), 0.5);+ let bytes = shader.params_bytes(&values, &manifest.params);+ assert_eq!(bytes.len(), 16);+ assert_eq!(f32::from_le_bytes(bytes[0..4].try_into().unwrap()), 2.0);+ assert_eq!(f32::from_le_bytes(bytes[4..8].try_into().unwrap()), 0.5);+ }++ #[test]+ fn a_package_with_no_knobs_still_binds() {+ let manifest = manifest("");+ let shader = Shader::compile(+ &manifest,+ "fn effect(uv: vec2<f32>) -> vec4<f32> { return sample(uv); }",+ )+ .expect("compiles");+ assert_eq!(shader.params_bytes(&BTreeMap::new(), &[]).len(), 16);+ }++ #[test]+ fn a_missing_field_or_a_broken_body_is_refused() {+ let manifest = manifest(+ r#"+[[param]]+key = "amount"+label = "Amount"+"#,+ );+ let missing = Shader::compile(+ &manifest,+ "struct Params { other: f32 }\nfn effect(uv: vec2<f32>) -> vec4<f32> { return sample(uv); }",+ );+ assert!(missing.unwrap_err().contains("no field `amount`"));+ let broken = Shader::compile(+ &manifest,+ "struct Params { amount: f32 }\nfn effect(uv: vec2<f32>) -> vec4<f32> { return nonsense; }",+ );+ assert!(broken.is_err());+ let no_effect = Shader::compile(&manifest, "struct Params { amount: f32 }");+ assert!(no_effect.unwrap_err().contains("fn effect"));+ }+}diff --git a/engine/crates/concat-export/src/flatten.rs b/engine/crates/concat-export/src/flatten.rsindex f80ea6b5..cc251019 100644--- a/engine/crates/concat-export/src/flatten.rs+++ b/engine/crates/concat-export/src/flatten.rs@@ -65,6 +65,8 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Expflip_v: false,blend: String::new(),crop: None,+ effects: clip.video_effects.clone(),+ transition_chain: String::new(),scale: 1.0,offset_x: 0.0,offset_y: 0.0,@@ -119,6 +121,8 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Exp.crop.filter(|crop| !crop.is_none()).map(|crop| [crop.left, crop.top, crop.right, crop.bottom]),+ effects: clip.video_effects.clone(),+ transition_chain: String::new(),scale: clip.scale,offset_x: clip.offset_x,offset_y: clip.offset_y,diff --git a/engine/crates/concat-export/src/lib.rs b/engine/crates/concat-export/src/lib.rsindex ed2464af..55f60f89 100644--- a/engine/crates/concat-export/src/lib.rs+++ b/engine/crates/concat-export/src/lib.rs@@ -30,10 +30,13 @@ use std::sync::atomic::{AtomicBool, Ordering};use concat_core::SpeedCurve;use concat_core::animate::Animation;use concat_core::frame::Frame;+use concat_core::shader::ShaderPass;use concat_core::time::{FrameRate, Rational};use concat_core::timeline::{Clip, ClipId, MediaRef, Timeline, Track, TrackKind, Transform};+use concat_effects::Catalogue;use concat_media::audio::{self, AudioClip};use concat_media::{DecodeOptions, Decoder, EncodeOptions, Encoder, FrameSink, FrameSource};+use concat_project::model::AppliedFilter;use concat_render::{Compositor, CpuCompositor, Layer, Placement, plan_frame};use serde::Deserialize;@@ -123,6 +126,16 @@ pub struct ExportClip {/// is fitted; absent for none.#[serde(default)]pub crop: Option<[f64; 4]>,+ /// The clip's applied effects, as the document holds them. When present+ /// they take precedence over `video_filter_chain`: the renderer builds+ /// the chain for its own backend from them, and runs the ones with+ /// shaders on the GPU.+ #[serde(default)]+ pub effects: Vec<AppliedFilter>,+ /// The fades transition resolution bakes in, kept apart from the effects+ /// so either can be rebuilt without the other.+ #[serde(skip)]+ pub transition_chain: String,/// Multiplier over the fitted size. 1 fills the frame, preserving aspect.#[serde(default = "unity")]pub scale: f64,@@ -345,7 +358,7 @@ fn resolve_transitions(clips: &mut [ExportClip], rate: FrameRate, bake_fades: bolet frames = ((half.min(a.duration) * fps).round() as i64).max(1);let total = (a.duration * fps).round() as i64;append_filter(- &mut a.video_filter_chain,+ &mut a.transition_chain,&format!("fade=t=out:start_frame={}:nb_frames={frames}{colour}",(total - frames).max(0)@@ -356,7 +369,7 @@ fn resolve_transitions(clips: &mut [ExportClip], rate: FrameRate, bake_fades: bolet b = &mut clips[cut.incoming];let frames = ((half.min(b.duration) * fps).round() as i64).max(1);append_filter(- &mut b.video_filter_chain,+ &mut b.transition_chain,&format!("fade=t=in:start_frame=0:nb_frames={frames}{colour}"),);}@@ -546,6 +559,18 @@ pub fn audio_pieces(clip: &ExportClip) -> Vec<AudioClip> {.collect()}+/// One decoded picture on its way to the compositor, with everything the+/// layer it becomes needs. Generic over how the frame is held: owned in the+/// export, shared out of the reader pool in the monitor.+struct Source<F> {+ frame: F,+ opacity: f32,+ transform: Transform,+ track: usize,+ blend: concat_core::timeline::Blend,+ passes: Vec<ShaderPass>,+}+/// The fraction-to-pixel placement of one composited layer: fitted and/// centred is the base, the clip's transform moves it from there. The one/// definition the exporter and the preview share - these two paths must@@ -579,12 +604,12 @@ fn place_layer<'a>(/// The best compositor this machine offers: the GPU when the `gpu` feature is/// on and the machine has one, the CPU reference otherwise. Never an error -/// a machine with no adapter renders slower, not not-at-all.-fn best_compositor() -> Box<dyn Compositor> {+fn best_compositor() -> (Box<dyn Compositor>, bool) {#[cfg(feature = "gpu")]if let Some(gpu) = concat_render::WgpuCompositor::new() {- return Box::new(gpu);+ return (Box::new(gpu), true);}- Box::new(CpuCompositor)+ (Box::new(CpuCompositor), false)}/// Composites every frame of the timeline into a soundless video file.@@ -596,6 +621,7 @@ fn render_picture(destination: &Path,reporter: &mut Reporter<'_>,) -> Result<(), String> {+ let (mut compositor, gpu) = best_compositor();let BuiltTimeline {timeline,stills,@@ -604,7 +630,8 @@ fn render_picture(tracks,treatments,pre_chains,- } = build_timeline(request, rate, visible);+ passes,+ } = build_timeline(request, rate, visible, gpu);let mut encoder = Encoder::create(destination,@@ -619,8 +646,6 @@ fn render_picture().map_err(|error| error.to_string())?;- let mut compositor = best_compositor();-// One decoder per clip, opened at its in-point the first time the clip is// needed and dropped the moment it leaves the playhead. Every decoder is// opened at `output rate / clip speed`, so pulling exactly one frame per@@ -638,8 +663,7 @@ fn render_picture(let time = rate.time_of_frame(index);let plan = plan_frame(&timeline, time);- let mut sources: Vec<(Frame, f32, Transform, usize, concat_core::timeline::Blend)> =- Vec::with_capacity(plan.layers.len());+ let mut sources: Vec<Source<Frame>> = Vec::with_capacity(plan.layers.len());for layer in &plan.layers {if !layer.paced {let (decode_width, decode_height) = decode_sizes@@ -657,14 +681,14 @@ fn render_picture(chain,pre,) {- let track = tracks.get(&layer.clip).copied().unwrap_or(0);- sources.push((- frame.as_ref().clone(),- layer.opacity,- layer.transform,- track,- layer.blend,- ));+ sources.push(Source {+ frame: frame.as_ref().clone(),+ opacity: layer.opacity,+ transform: layer.transform,+ track: tracks.get(&layer.clip).copied().unwrap_or(0),+ blend: layer.blend,+ passes: passes.get(&layer.clip).cloned().unwrap_or_default(),+ });}continue;}@@ -721,18 +745,33 @@ fn render_picture(// aborting the export - a clip trimmed past its media's end is a// mistake in the edit, not a failure of the renderer.if let Some(frame) = decoder.next_frame().map_err(|error| error.to_string())? {- let track = tracks.get(&layer.clip).copied().unwrap_or(0);- sources.push((frame, layer.opacity, layer.transform, track, layer.blend));+ sources.push(Source {+ frame,+ opacity: layer.opacity,+ transform: layer.transform,+ track: tracks.get(&layer.clip).copied().unwrap_or(0),+ blend: layer.blend,+ passes: passes.get(&layer.clip).cloned().unwrap_or_default(),+ });}}+ let seconds = time.as_f64() as f32;let layers: Vec<(Layer<'_>, usize)> = sources.iter()- .map(|(frame, opacity, transform, track, blend)| {+ .map(|source| {(- place_layer(frame, *opacity, transform, request.width, request.height)- .with_blend(*blend),- *track,+ place_layer(+ &source.frame,+ source.opacity,+ &source.transform,+ request.width,+ request.height,+ )+ .with_blend(source.blend)+ .with_passes(&source.passes)+ .at_time(seconds),+ source.track,)}).collect();@@ -776,6 +815,8 @@ struct BuiltTimeline {tracks: HashMap<ClipId, usize>,/// The clip's pre-fit chain - its crop - where it has one.pre_chains: HashMap<ClipId, String>,+ /// The clip's shader passes, on a GPU renderer.+ passes: HashMap<ClipId, Vec<ShaderPass>>,/// The layers: treatments over the stack, by span.treatments: Vec<Treatment>,}@@ -788,6 +829,9 @@ struct Treatment {end: Rational,track: usize,chain: String,+ /// The layer's shader passes, when the renderer runs them; the chain is+ /// then whatever the GPU cannot.+ passes: Vec<ShaderPass>,strength: f32,ramp_in: f64,ramp_out: f64,@@ -863,7 +907,22 @@ fn composite_treated(let treated = if strength <= 0.0 {below} else {- match concat_media::treat(&below, &treatment.chain) {+ // Shader passes run through the compositor over the ground as a+ // layer of its own; whatever is left for FFmpeg runs after.+ let shaded = if treatment.passes.is_empty() {+ below.clone()+ } else {+ let ground = [Layer::new(&below)+ .with_passes(&treatment.passes)+ .at_time(time.as_f64() as f32)];+ compositor.composite(width, height, &ground)+ };+ let result = if treatment.chain.is_empty() {+ Ok(shaded)+ } else {+ concat_media::treat(&shaded, &treatment.chain)+ };+ match result {Ok(treated) if strength >= 1.0 => treated,Ok(treated) => mix(&below, &treated, strength),// A chain FFmpeg refuses leaves the picture as it was@@ -884,6 +943,7 @@ fn build_timeline(request: &ExportRequest,rate: FrameRate,visible: &[&ExportClip],+ gpu: bool,) -> BuiltTimeline {let mut timeline = Timeline::new(request.width, request.height, rate);let mut stills = std::collections::HashSet::new();@@ -892,6 +952,7 @@ fn build_timeline(let mut tracks_of: HashMap<ClipId, usize> = HashMap::new();let mut treatments: Vec<Treatment> = Vec::new();let mut pre_chains: HashMap<ClipId, String> = HashMap::new();+ let mut passes: HashMap<ClipId, Vec<ShaderPass>> = HashMap::new();let lanes = visible.iter().map(|clip| clip.track).max().unwrap_or(0) + 1;let tracks: Vec<_> = (0..lanes)@@ -911,12 +972,15 @@ fn build_timeline(// A layer has no pixels to decode: it is a treatment over the// stack, kept beside the timeline rather than in it.if clip.kind == ClipKind::Layer {- if !clip.video_filter_chain.is_empty() {+ let chain = full_chain(clip, gpu);+ let layer_passes = if gpu { shader_passes(clip) } else { Vec::new() };+ if !chain.is_empty() || !layer_passes.is_empty() {treatments.push(Treatment {start,end: start + duration,track: clip.track,- chain: clip.video_filter_chain.clone(),+ chain,+ passes: layer_passes,strength: clip.opacity.clamp(0.0, 1.0) as f32,ramp_in: clip.fade_in.max(0.0),ramp_out: clip.fade_out.max(0.0),@@ -956,7 +1020,7 @@ fn build_timeline(if let Some(size) = fitted_size(request, clip) {decode_sizes.insert(id, size);}- let chain = full_chain(clip);+ let chain = full_chain(clip, gpu);if !chain.is_empty() {filter_chains.insert(id, chain);}@@ -964,6 +1028,12 @@ fn build_timeline(if !pre.is_empty() {pre_chains.insert(id, pre);}+ if gpu {+ let clip_passes = shader_passes(clip);+ if !clip_passes.is_empty() {+ passes.insert(id, clip_passes);+ }+ }}}@@ -975,6 +1045,7 @@ fn build_timeline(tracks: tracks_of,treatments,pre_chains,+ passes,}}@@ -995,23 +1066,40 @@ fn pre_chain(clip: &ExportClip) -> String {}}-/// The clip's effect chain with its flips in front: a flip is a treatment-/// of the picture like any other, and comes first so the effects see the-/// picture the viewer will.-fn full_chain(clip: &ExportClip) -> String {- let mut parts: Vec<&str> = Vec::new();+/// The clip's FFmpeg chain for one backend: flips first - a flip is a+/// treatment of the picture like any other, and comes first so the effects+/// see the picture the viewer will - then the effects this backend runs as+/// chains, then the transition fades. On the GPU every effect with a shader+/// is left out here and carried by [`shader_passes`] instead.+fn full_chain(clip: &ExportClip, gpu: bool) -> String {+ let mut parts: Vec<String> = Vec::new();if clip.flip_h {- parts.push("hflip");+ parts.push("hflip".to_owned());}if clip.flip_v {- parts.push("vflip");+ parts.push("vflip".to_owned());+ }+ let effects = if clip.effects.is_empty() {+ clip.video_filter_chain.clone()+ } else if gpu {+ Catalogue::builtin().video_chain_gpu(&clip.effects)+ } else {+ Catalogue::builtin().video_chain(&clip.effects)+ };+ if !effects.is_empty() {+ parts.push(effects);}- if !clip.video_filter_chain.is_empty() {- parts.push(&clip.video_filter_chain);+ if !clip.transition_chain.is_empty() {+ parts.push(clip.transition_chain.clone());}parts.join(",")}+/// The clip's shader passes, for a renderer that runs them.+fn shader_passes(clip: &ExportClip) -> Vec<ShaderPass> {+ Catalogue::builtin().shader_passes(&clip.effects)+}+/// The engine's keys for a flattened clip's animation, or None for none.fn animation_of(keys: &[ExportKey]) -> Option<Animation> {use concat_core::animate::{Ease, Key, Track};@@ -1112,7 +1200,7 @@ pub fn preview_frame(pool: &concat_media::ReaderPool,request: &PreviewFrameRequest,) -> Result<Vec<u8>, String> {- let sources = preview_sources(pool, request)?;+ let sources = preview_sources(pool, request, false)?;// CPU on purpose: one frame at preview size is milliseconds, and holding// a GPU context alive for occasional scrubs is not worth its memory. The// window composites on its own device through `preview_sources`.@@ -1123,13 +1211,7 @@ pub fn preview_frame(/// compositor needs to draw the paused monitor's frame, decoded but not yet/// drawn, so a caller with a GPU can draw them where they are shown.pub struct PreviewSources {- sources: Vec<(- std::sync::Arc<Frame>,- f32,- Transform,- usize,- concat_core::timeline::Blend,- )>,+ sources: Vec<Source<std::sync::Arc<Frame>>>,width: u32,height: u32,time: Rational,@@ -1141,11 +1223,20 @@ impl PreviewSources {/// caller drawing these itself is skipping the treatments, so check/// [`PreviewSources::has_treatments`] first.pub fn layers(&self) -> Vec<Layer<'_>> {+ let seconds = self.time.as_f64() as f32;self.sources.iter()- .map(|(frame, opacity, transform, _, blend)| {- place_layer(frame.as_ref(), *opacity, transform, self.width, self.height)- .with_blend(*blend)+ .map(|source| {+ place_layer(+ source.frame.as_ref(),+ source.opacity,+ &source.transform,+ self.width,+ self.height,+ )+ .with_blend(source.blend)+ .with_passes(&source.passes)+ .at_time(seconds)}).collect()}@@ -1163,11 +1254,19 @@ impl PreviewSources {let placed: Vec<(Layer<'_>, usize)> = self.sources.iter()- .map(|(frame, opacity, transform, track, blend)| {+ .map(|source| {(- place_layer(frame.as_ref(), *opacity, transform, self.width, self.height)- .with_blend(*blend),- *track,+ place_layer(+ source.frame.as_ref(),+ source.opacity,+ &source.transform,+ self.width,+ self.height,+ )+ .with_blend(source.blend)+ .with_passes(&source.passes)+ .at_time(self.time.as_f64() as f32),+ source.track,)}).collect();@@ -1198,6 +1297,7 @@ impl PreviewSources {pub fn preview_sources(pool: &concat_media::ReaderPool,request: &PreviewFrameRequest,+ gpu: bool,) -> Result<PreviewSources, String> {let rate = FrameRate::new(Rational::new(request.rate_num, request.rate_den));let BuiltTimeline {@@ -1208,17 +1308,12 @@ pub fn preview_sources(tracks,treatments,pre_chains,- } = preview_timeline(request, rate);+ passes,+ } = preview_timeline(request, rate, gpu);let time = quantise(request.time, rate);let plan = plan_frame(&timeline, time);- let mut sources: Vec<(- std::sync::Arc<Frame>,- f32,- Transform,- usize,- concat_core::timeline::Blend,- )> = Vec::with_capacity(plan.layers.len());+ let mut sources: Vec<Source<std::sync::Arc<Frame>>> = Vec::with_capacity(plan.layers.len());let mut failures: Vec<String> = Vec::new();for layer in &plan.layers {let (decode_width, decode_height) = decode_sizes@@ -1238,13 +1333,14 @@ pub fn preview_sources(chain,pre,) {- Ok(frame) => sources.push((+ Ok(frame) => sources.push(Source {frame,- layer.opacity,- layer.transform,- tracks.get(&layer.clip).copied().unwrap_or(0),- layer.blend,- )),+ opacity: layer.opacity,+ transform: layer.transform,+ track: tracks.get(&layer.clip).copied().unwrap_or(0),+ blend: layer.blend,+ passes: passes.get(&layer.clip).cloned().unwrap_or_default(),+ }),Err(error) => failures.push(format!("{}: {error}", layer.media.display())),}}@@ -1270,7 +1366,7 @@ pub fn preview_sources(}/// The preview's timeline, built the exporter's way.-fn preview_timeline(request: &PreviewFrameRequest, rate: FrameRate) -> BuiltTimeline {+fn preview_timeline(request: &PreviewFrameRequest, rate: FrameRate, gpu: bool) -> BuiltTimeline {let mut resolved = request.clips.clone();resolve_transitions(&mut resolved, rate, false);let visible: Vec<&ExportClip> = resolved@@ -1290,7 +1386,7 @@ fn preview_timeline(request: &PreviewFrameRequest, rate: FrameRate) -> BuiltTimepreset: String::new(),clips: Vec::new(),};- build_timeline(&shim, rate, &visible)+ build_timeline(&shim, rate, &visible, gpu)}/// Warms the reader pool for the frames about to be presented.@@ -1308,6 +1404,7 @@ pub fn preview_prefetch(pool: &concat_media::ReaderPool,request: &PreviewFrameRequest,frames: u32,+ gpu: bool,) {let rate = FrameRate::new(Rational::new(request.rate_num, request.rate_den));let BuiltTimeline {@@ -1317,7 +1414,7 @@ pub fn preview_prefetch(filter_chains,pre_chains,..- } = preview_timeline(request, rate);+ } = preview_timeline(request, rate, gpu);let fps = rate.fps().as_f64();for ahead in 0..frames {@@ -1366,6 +1463,7 @@ mod tests {end: Rational::from_int(10),track: 1,chain: "negate".to_owned(),+ passes: Vec::new(),strength: 1.0,ramp_in: 0.0,ramp_out: 0.0,@@ -1447,6 +1545,8 @@ mod tests {flip_v: false,blend: String::new(),crop: None,+ effects: Vec::new(),+ transition_chain: String::new(),scale: 1.0,offset_x: 0.0,offset_y: 0.0,@@ -1621,11 +1721,11 @@ mod tests {// Half a second each side at 30fps is 15 frames.assert_eq!(- clips[0].video_filter_chain,+ clips[0].transition_chain,"fade=t=out:start_frame=105:nb_frames=15");assert_eq!(- clips[1].video_filter_chain,+ clips[1].transition_chain,"fade=t=in:start_frame=0:nb_frames=15");assert_eq!(clips[1].start, 4.0, "nothing moves for an edge fade");@@ -1639,8 +1739,8 @@ mod tests {];clips[1].transition = spec("fade-white", 0.5);resolve_transitions(&mut clips, FrameRate::THIRTY, true);- assert!(clips[0].video_filter_chain.ends_with(":color=white"));- assert!(clips[1].video_filter_chain.contains("t=in"));+ assert!(clips[0].transition_chain.ends_with(":color=white"));+ assert!(clips[1].transition_chain.contains("t=in"));}#[test]@@ -1652,11 +1752,10 @@ mod tests {clips[1].video_filter_chain = "hue=s=0".to_owned();clips[1].transition = spec("fade-black", 0.5);resolve_transitions(&mut clips, FrameRate::THIRTY, true);- assert!(- clips[1].video_filter_chain.starts_with("hue=s=0,fade=t=in"),- "was: {}",- clips[1].video_filter_chain- );+ // The fade lives beside the effects and joins after them when the+ // decoder's chain is built.+ let chain = full_chain(&clips[1], false);+ assert!(chain.starts_with("hue=s=0,fade=t=in"), "was: {chain}");}#[test]diff --git a/engine/crates/concat-host/src/preview.rs b/engine/crates/concat-host/src/preview.rsindex 98817579..e64c6a21 100644--- a/engine/crates/concat-host/src/preview.rs+++ b/engine/crates/concat-host/src/preview.rs@@ -102,7 +102,7 @@ impl Monitor {.as_ref().ok_or_else(|| "the monitor has no GPU device".to_owned())?;let request = Self::request(clips, settings, spec);- let sources = concat_export::preview_sources(&self.pool, &request)?;+ let sources = concat_export::preview_sources(&self.pool, &request, true)?;let mut gpu = gpu.lock().map_err(|_| "compositor poisoned".to_owned())?;if sources.has_treatments() {// A layer's chain runs on the CPU, so the frame is drawn there@@ -157,7 +157,7 @@ impl Monitor {frames: u32,) {let request = Self::request(clips, settings, spec);- concat_export::preview_prefetch(&self.pool, &request, frames.min(8));+ concat_export::preview_prefetch(&self.pool, &request, frames.min(8), self.has_gpu());}/// Forgets every cached frame and reader, for when the project closes.diff --git a/engine/crates/concat-host/src/titles.rs b/engine/crates/concat-host/src/titles.rsindex fc9305a2..1651a267 100644--- a/engine/crates/concat-host/src/titles.rs+++ b/engine/crates/concat-host/src/titles.rs@@ -117,6 +117,8 @@ impl Titles {flip_v: clip.flip_v,blend: clip.blend.clone(),crop: None,+ effects: clip.video_effects.clone(),+ transition_chain: String::new(),scale: clip.scale,offset_x: clip.offset_x,offset_y: clip.offset_y,diff --git a/engine/crates/concat-render/Cargo.toml b/engine/crates/concat-render/Cargo.tomlindex b6aff3a1..6e821385 100644--- a/engine/crates/concat-render/Cargo.toml+++ b/engine/crates/concat-render/Cargo.toml@@ -16,5 +16,10 @@ concat-core.workspace = truewgpu = { workspace = true, optional = true }pollster = { workspace = true, optional = true }+[dev-dependencies]+# The pass test compiles a real package shader through the catalogue's+# stitching, so what the test runs is what a package would run.+concat-effects.workspace = true+[lints]workspace = truediff --git a/engine/crates/concat-render/src/compositor.rs b/engine/crates/concat-render/src/compositor.rsindex ddd197c8..a7c2406b 100644--- a/engine/crates/concat-render/src/compositor.rs+++ b/engine/crates/concat-render/src/compositor.rs@@ -9,6 +9,7 @@//! `wgpu` will slot into.use concat_core::frame::{BYTES_PER_PIXEL, Frame};+use concat_core::shader::ShaderPass;use concat_core::timeline::Blend;/// A layer's placement beyond its base position, in output pixels.@@ -65,6 +66,12 @@ pub struct Layer<'a> {pub placement: Placement,/// How the layer's colour meets the ground.pub blend: Blend,+ /// Shader passes to run over the layer's pixels before it is placed, in+ /// order. The GPU compositor runs them; the CPU reference cannot, and+ /// draws the layer untreated.+ pub passes: &'a [ShaderPass],+ /// Seconds into the timeline, for passes that move.+ pub time: f32,}impl<'a> Layer<'a> {@@ -77,9 +84,23 @@ impl<'a> Layer<'a> {y: 0,placement: Placement::IDENTITY,blend: Blend::Normal,+ passes: &[],+ time: 0.0,}}+ /// Sets the shader passes to run over the layer first.+ pub fn with_passes(mut self, passes: &'a [ShaderPass]) -> Self {+ self.passes = passes;+ self+ }++ /// Sets the timeline instant the passes see.+ pub fn at_time(mut self, time: f32) -> Self {+ self.time = time;+ self+ }+/// Sets the blend mode.pub fn with_blend(mut self, blend: Blend) -> Self {self.blend = blend;diff --git a/engine/crates/concat-render/src/gpu.rs b/engine/crates/concat-render/src/gpu.rsindex 9af25773..bda3a721 100644--- a/engine/crates/concat-render/src/gpu.rs+++ b/engine/crates/concat-render/src/gpu.rs@@ -29,6 +29,7 @@use std::collections::HashMap;use concat_core::frame::Frame;+use concat_core::shader::ShaderPass;use concat_core::timeline::Blend;use crate::compositor::{Compositor, CpuCompositor, Layer};@@ -94,6 +95,15 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {}"#;+/// One package's shader, compiled once and kept: its pipeline, and the two+/// uniform buffers every pass through it rewrites.+struct CompiledShader {+ pipeline: wgpu::RenderPipeline,+ frame: wgpu::Buffer,+ params: wgpu::Buffer,+ bind_group: wgpu::BindGroup,+}+/// A cached layer texture and its bind group, reusable for any layer of the/// same size.struct PooledTexture {@@ -130,6 +140,10 @@ pub struct WgpuCompositor {/// One pipeline per blend mode, indexed as `Blend::ALL` is.pipelines: Vec<wgpu::RenderPipeline>,bind_layout: wgpu::BindGroupLayout,+ /// Group 1 of a shader pass: the frame block and the package's params.+ uniform_layout: wgpu::BindGroupLayout,+ /// Compiled passes by their key; see `ShaderPass::key`.+ shaders: HashMap<String, CompiledShader>,sampler: wgpu::Sampler,vertices: wgpu::Buffer,vertex_capacity: usize,@@ -193,6 +207,22 @@ impl WgpuCompositor {],});+ // What a shader pass binds at group 1: the host's frame block and+ // the package's own `Params`, both uniforms.+ let uniform_entry = |binding: u32| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ };+ let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("concat pass uniforms"),+ entries: &[uniform_entry(0), uniform_entry(1)],+ });let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {label: Some("concat compositor"),bind_group_layouts: &[Some(&bind_layout)],@@ -301,6 +331,8 @@ impl WgpuCompositor {queue,pipelines,bind_layout,+ uniform_layout,+ shaders: HashMap::new(),sampler,vertices,vertex_capacity: 6 * 8,@@ -374,7 +406,16 @@ impl WgpuCompositor {if layer.opacity <= 0.0 {continue;}- let index = self.upload(layer.frame);+ let mut index = self.upload(layer.frame);+ if !layer.passes.is_empty() {+ index = self.run_passes(+ layer.frame.width(),+ layer.frame.height(),+ index,+ layer.passes,+ layer.time,+ );+ }draws.push((layer.frame.width(),layer.frame.height(),@@ -531,7 +572,33 @@ impl WgpuCompositor {/// Claims a pooled texture of the layer's size, uploading its pixels.fn upload(&mut self, frame: &Frame) -> usize {- let key = (frame.width(), frame.height());+ let index = self.claim(frame.width(), frame.height());+ let texture = &self.pool[&(frame.width(), frame.height())][index].texture;+ self.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ frame.pixels(),+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(frame.width() * 4),+ rows_per_image: Some(frame.height()),+ },+ wgpu::Extent3d {+ width: frame.width(),+ height: frame.height(),+ depth_or_array_layers: 1,+ },+ );+ index+ }++ /// Claims a pooled texture of this size, blank, for a pass to draw into.+ fn claim(&mut self, width: u32, height: u32) -> usize {+ let key = (width, height);let used = self.used.entry(key).or_insert(0);let pool = self.pool.entry(key).or_default();@@ -539,15 +606,19 @@ impl WgpuCompositor {let texture = self.device.create_texture(&wgpu::TextureDescriptor {label: Some("concat layer"),size: wgpu::Extent3d {- width: frame.width(),- height: frame.height(),+ width,+ height,depth_or_array_layers: 1,},mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,format: wgpu::TextureFormat::Rgba8Unorm,- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ // A render attachment too: a shader pass draws one pooled+ // texture into another of the same size.+ usage: wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::RENDER_ATTACHMENT,view_formats: &[],});let view = texture.create_view(&wgpu::TextureViewDescriptor::default());@@ -573,28 +644,155 @@ impl WgpuCompositor {let index = *used;*used += 1;+ index+ }- self.queue.write_texture(- wgpu::TexelCopyTextureInfo {- texture: &pool[index].texture,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- frame.pixels(),- wgpu::TexelCopyBufferLayout {- offset: 0,- bytes_per_row: Some(frame.width() * 4),- rows_per_image: Some(frame.height()),- },- wgpu::Extent3d {- width: frame.width(),- height: frame.height(),- depth_or_array_layers: 1,+ /// The compiled pipeline for a pass, built the first time its key is+ /// seen. The catalogue validated the module at load, so a failure here+ /// is a driver disagreement; wgpu reports it through its error scope and+ /// the pass draws nothing rather than the frame being lost.+ fn shader(&mut self, pass: &ShaderPass) {+ if self.shaders.contains_key(&pass.key) {+ return;+ }+ let module = self+ .device+ .create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some(&pass.key),+ source: wgpu::ShaderSource::Wgsl(pass.source.as_ref().into()),+ });+ let layout = self+ .device+ .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some(&pass.key),+ bind_group_layouts: &[Some(&self.bind_layout), Some(&self.uniform_layout)],+ immediate_size: 0,+ });+ let pipeline = self+ .device+ .create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(&pass.key),+ layout: Some(&layout),+ vertex: wgpu::VertexState {+ module: &module,+ entry_point: Some("vs_main"),+ compilation_options: Default::default(),+ buffers: &[],+ },+ fragment: Some(wgpu::FragmentState {+ module: &module,+ entry_point: Some("fs_main"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8Unorm,+ // A pass replaces: mixing by intensity is the+ // shader's own last line.+ blend: None,+ write_mask: wgpu::ColorWrites::ALL,+ })],+ }),+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });+ let frame = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("concat pass frame"),+ size: 16,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let params = self.device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("concat pass params"),+ size: pass.params.len().max(ShaderPass::MIN_PARAMS) as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("concat pass uniforms"),+ layout: &self.uniform_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: frame.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: params.as_entire_binding(),+ },+ ],+ });+ self.shaders.insert(+ pass.key.clone(),+ CompiledShader {+ pipeline,+ frame,+ params,+ bind_group,},);+ }- index+ /// Runs `passes` over the pooled texture `source` of `width` × `height`,+ /// each drawing into a fresh pooled texture of the same size, and+ /// returns the index of the last one drawn. Each pass is its own+ /// submission so the uniforms it wrote are the ones it reads.+ fn run_passes(+ &mut self,+ width: u32,+ height: u32,+ source: usize,+ passes: &[ShaderPass],+ time: f32,+ ) -> usize {+ let mut current = source;+ for pass in passes {+ let target = self.claim(width, height);+ self.shader(pass);+ let shader = &self.shaders[&pass.key];+ let frame_block: [f32; 4] = [width as f32, height as f32, time, pass.intensity];+ let frame_bytes: Vec<u8> = frame_block.iter().flat_map(|v| v.to_le_bytes()).collect();+ self.queue.write_buffer(&shader.frame, 0, &frame_bytes);+ let mut params = pass.params.clone();+ params.resize(shader.params.size() as usize, 0);+ self.queue.write_buffer(&shader.params, 0, ¶ms);++ let pool = &self.pool[&(width, height)];+ let view = pool[target]+ .texture+ .create_view(&wgpu::TextureViewDescriptor::default());+ let mut encoder = self+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("concat pass"),+ });+ {+ let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("concat pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ render.set_pipeline(&shader.pipeline);+ render.set_bind_group(0, &pool[current].bind_group, &[]);+ render.set_bind_group(1, &shader.bind_group, &[]);+ render.draw(0..3, 0..1);+ }+ self.queue.submit([encoder.finish()]);+ current = target;+ }+ current}/// The six vertices of one layer's quad, transformed the same way the CPU@@ -730,6 +928,39 @@ mod tests {use crate::CpuCompositor;use crate::compositor::Placement;+ /// A pass runs over the layer before it is placed: an invert shader+ /// over a red frame composites cyan, and at half intensity the mix.+ #[test]+ fn a_pass_treats_the_layer_before_it_is_placed() {+ let Some(mut gpu) = gpu() else { return };+ let manifest = concat_effects::Manifest::parse(+ "[effect]\nid = \"test.invert\"\nname = \"Invert\"\nkind = \"filter\"\n[wgsl]\nentry = \"effect.wgsl\"\n",+ )+ .expect("a manifest");+ let shader = concat_effects::Shader::compile(+ &manifest,+ "fn effect(uv: vec2<f32>) -> vec4<f32> { let c = sample(uv); return vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a); }",+ )+ .expect("compiles");+ let red = {+ let mut frame = Frame::black(4, 4);+ for pixel in frame.pixels_mut().chunks_exact_mut(4) {+ pixel.copy_from_slice(&[255, 0, 0, 255]);+ }+ frame+ };+ let full = [shader.pass(&Default::default(), &[], 1.0)];+ let out = gpu.composite(4, 4, &[Layer::new(&red).with_passes(&full)]);+ assert_eq!(&out.pixels()[..3], &[0, 255, 255]);+ let half = [shader.pass(&Default::default(), &[], 0.5)];+ let out = gpu.composite(4, 4, &[Layer::new(&red).with_passes(&half)]);+ let p = &out.pixels()[..3];+ assert!(+ p[0] > 120 && p[0] < 136 && p[1] > 120 && p[1] < 136,+ "{p:?}"+ );+ }+fn gpu() -> Option<WgpuCompositor> {let compositor = WgpuCompositor::new();if compositor.is_none() {diff --git a/engine/crates/concat/ui/workspace/config-pane.slint b/engine/crates/concat/ui/workspace/config-pane.slintindex 6a8bafd5..68c60608 100644--- a/engine/crates/concat/ui/workspace/config-pane.slint+++ b/engine/crates/concat/ui/workspace/config-pane.slint@@ -434,8 +434,9 @@ export component ConfigPane inherits Rectangle {}}- // The tab's sections, as a dropdown under the strip. One section- // needs no dropdown: the strip already says where you are.+ // The tab's sections, as a second strip under the first, in the+ // same segmented style. One section needs no strip: the tab already+ // says where you are.if root.has-selection && root.sections.length > 1: Rectangle {height: 40px;background: Theme.panel;@@ -449,23 +450,11 @@ export component ConfigPane inherits Rectangle {}HorizontalLayout {- padding-left: Theme.pad;- padding-right: Theme.pad;- spacing: 8px;-- Text {- text: "Section";- color: Theme.fg-muted;- font-size: Theme.fs;- vertical-alignment: center;- }-- Rectangle { horizontal-stretch: 1; }-+ padding-left: 8px;+ padding-right: 8px;VerticalLayout {alignment: center;- Select {- width: 168px;+ SegmentedControl {options: root.sections;current: Math.max(0, Math.min(root.section, root.sections.length - 1));changed(index) => { root.pick-section(index); }