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
A filter layer is applied where the stack is drawn, on the GPU
Jareer90c6bcc4a976
diff --git a/engine/crates/concat-export/src/lib.rs b/engine/crates/concat-export/src/lib.rsindex 3d108c62..6f51980c 100644--- a/engine/crates/concat-export/src/lib.rs+++ b/engine/crates/concat-export/src/lib.rs@@ -37,7 +37,7 @@ use concat_effects::Catalogue;use concat_media::audio::{self, AudioClip};use concat_media::{DecodeOptions, Decoder, EncodeOptions, Encoder, FrameSink, FrameSource};use concat_project::model::{AppliedFilter, Cutout};-use concat_render::{Compositor, CpuCompositor, Layer, Placement, plan_frame};+use concat_render::{Compositor, CpuCompositor, Layer, Placement, Treatment as GpuTreatment, plan_frame};use concat_vision::{Mapping, MaskStore};use serde::Deserialize;@@ -1101,6 +1101,25 @@ fn composite_treated(}live.sort_by_key(|treatment| treatment.track);+ // A compositor that runs passes applies every treatment without a+ // pixel leaving the GPU, so long as none of them needs FFmpeg for+ // a package that has no shader.+ if live.iter().all(|treatment| treatment.chain.is_empty()) {+ let gpu: Vec<GpuTreatment<'_>> = live+ .iter()+ .map(|treatment| GpuTreatment {+ track: treatment.track,+ passes: &treatment.passes,+ strength: treatment.strength_at(time),+ })+ .collect();+ if let Some(frame) =+ compositor.composite_treated(width, height, time.as_f64() as f32, sources, &gpu)+ {+ return frame;+ }+ }+let mut ground: Option<Frame> = None;let mut next = 0;for treatment in live {@@ -1480,10 +1499,11 @@ impl PreviewSources {.any(|treatment| treatment.covers(self.time))}- /// The frame, treatments included, drawn with `compositor`.- pub fn composite(&self, compositor: &mut dyn Compositor) -> Frame {- let placed: Vec<(Layer<'_>, usize)> = self- .sources+ /// The layers as [`PreviewSources::layers`] gives them, each with the+ /// track it came from, for a compositor applying treatments itself.+ pub fn placed(&self) -> Vec<(Layer<'_>, usize)> {+ let seconds = self.seconds();+ self.sources.iter().map(|source| {(@@ -1496,11 +1516,46 @@ impl PreviewSources {).with_blend(source.blend).with_passes(&source.passes)- .at_time(self.time.as_f64() as f32),+ .at_time(seconds),source.track,)})+ .collect()+ }++ /// The treatments live at this instant, in ascending track order, as+ /// a GPU compositor takes them - or None when one of them needs FFmpeg+ /// for a package with no shader, and only [`PreviewSources::composite`]+ /// can draw the frame.+ pub fn live_treatments(&self) -> Option<Vec<GpuTreatment<'_>>> {+ let mut live: Vec<&Treatment> = self+ .treatments+ .iter()+ .filter(|treatment| treatment.covers(self.time)).collect();+ if live.iter().any(|treatment| !treatment.chain.is_empty()) {+ return None;+ }+ live.sort_by_key(|treatment| treatment.track);+ Some(+ live.iter()+ .map(|treatment| GpuTreatment {+ track: treatment.track,+ passes: &treatment.passes,+ strength: treatment.strength_at(self.time),+ })+ .collect(),+ )+ }++ /// The instant, in seconds, for passes that move.+ pub fn seconds(&self) -> f32 {+ self.time.as_f64() as f32+ }++ /// The frame, treatments included, drawn with `compositor`.+ pub fn composite(&self, compositor: &mut dyn Compositor) -> Frame {+ let placed = self.placed();composite_treated(compositor,self.width,diff --git a/engine/crates/concat-host/src/preview.rs b/engine/crates/concat-host/src/preview.rsindex e64c6a21..7f74371f 100644--- a/engine/crates/concat-host/src/preview.rs+++ b/engine/crates/concat-host/src/preview.rs@@ -105,8 +105,21 @@ impl Monitor {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- // and uploaded whole; only instants under a layer pay for it.+ // A layer whose look is a shader is applied where the stack is+ // drawn, on the GPU; only a layer that needs FFmpeg for a+ // package with no shader takes the frame through the CPU.+ if let Some(treatments) = sources.live_treatments() {+ let layers = sources.placed();+ return gpu+ .composite_texture_treated(+ spec.width,+ spec.height,+ sources.seconds(),+ &layers,+ &treatments,+ )+ .ok_or_else(|| "the GPU device was lost".to_owned());+ }let frame = sources.composite(&mut *gpu);let layers = [concat_render::Layer::new(&frame)];return gpudiff --git a/engine/crates/concat-render/src/compositor.rs b/engine/crates/concat-render/src/compositor.rsindex d6cedb90..3729261b 100644--- a/engine/crates/concat-render/src/compositor.rs+++ b/engine/crates/concat-render/src/compositor.rs@@ -133,6 +133,19 @@ impl<'a> Layer<'a> {}}+/// A layer clip at one instant, for a compositor that can apply it over+/// the stack beneath its track without leaving the GPU: its passes, and how+/// hard the result is blended back over the untreated stack.+#[derive(Clone, Copy, Debug)]+pub struct Treatment<'a> {+ /// The track the layer sits on; every layer on a lower track is under it.+ pub track: usize,+ /// The passes to run over the stack beneath, in order.+ pub passes: &'a [ShaderPass],+ /// How much of the treated stack to keep over the untreated, `0..=1`.+ pub strength: f32,+}+/// Blends layers into a single output frame.pub trait Compositor {/// Draws `layers` bottom-most first over an opaque black background.@@ -141,6 +154,22 @@ pub trait Compositor {/// The result is always fully opaque - it is what goes to screen or to an/// encoder, and neither has anything to show through.fn composite(&mut self, width: u32, height: u32, layers: &[Layer<'_>]) -> Frame;++ /// Draws `layers` - each with the track it came from, bottom-most first+ /// - with every treatment applied over the stack beneath its track, the+ /// treatments in ascending track order. `None` from a compositor that+ /// cannot run passes, which the CPU reference cannot: the caller then+ /// applies the treatments its own way.+ fn composite_treated(+ &mut self,+ _width: u32,+ _height: u32,+ _time: f32,+ _layers: &[(Layer<'_>, usize)],+ _treatments: &[Treatment<'_>],+ ) -> Option<Frame> {+ None+ }}/// A straightforward CPU compositor.diff --git a/engine/crates/concat-render/src/gpu.rs b/engine/crates/concat-render/src/gpu.rsindex 1af8c50e..03584c11 100644--- a/engine/crates/concat-render/src/gpu.rs+++ b/engine/crates/concat-render/src/gpu.rs@@ -32,7 +32,7 @@ use concat_core::frame::Frame;use concat_core::shader::{Lut, ShaderPass};use concat_core::timeline::Blend;-use crate::compositor::{Compositor, CpuCompositor, Layer};+use crate::compositor::{Compositor, CpuCompositor, Layer, Treatment};/// Bytes per row must be a multiple of this for a texture-to-buffer copy.const ROW_ALIGN: usize = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;@@ -433,32 +433,76 @@ impl WgpuCompositor {layers: &[Layer<'_>],) -> Vec<(u32, u32, usize, Blend)> {self.used.values_mut().for_each(|used| *used = 0);-let mut draws: Vec<(u32, u32, usize, Blend)> = Vec::with_capacity(layers.len());let mut vertices: Vec<Vertex> = Vec::with_capacity(layers.len() * 6);for layer in layers {- if layer.opacity <= 0.0 {- continue;- }- 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((+ self.push_layer(&mut draws, &mut vertices, width, height, layer);+ }+ self.write_vertices(&vertices);+ draws+ }++ /// One layer's draw: its pixels uploaded, its passes run, its quad+ /// placed in an output `width` by `height`.+ fn push_layer(+ &mut self,+ draws: &mut Vec<(u32, u32, usize, Blend)>,+ vertices: &mut Vec<Vertex>,+ width: u32,+ height: u32,+ layer: &Layer<'_>,+ ) {+ if layer.opacity <= 0.0 {+ return;+ }+ let mut index = self.upload(layer.frame);+ if !layer.passes.is_empty() {+ index = self.run_passes(layer.frame.width(),layer.frame.height(),index,- layer.blend,- ));- vertices.extend_from_slice(&Self::quad(layer, width, height));+ layer.passes,+ layer.time,+ );}+ draws.push((+ layer.frame.width(),+ layer.frame.height(),+ index,+ layer.blend,+ ));+ vertices.extend_from_slice(&Self::quad(layer, width, height));+ }+ /// A draw of a pooled texture the size of the output, over the whole+ /// of it: how a stack already drawn is used as the ground for more.+ fn push_pooled(+ draws: &mut Vec<(u32, u32, usize, Blend)>,+ vertices: &mut Vec<Vertex>,+ width: u32,+ height: u32,+ index: usize,+ opacity: f32,+ ) {+ draws.push((width, height, index, Blend::Normal));+ let corner = |x: f32, y: f32, u: f32, v: f32| Vertex {+ position: [x, y],+ uv: [u, v],+ opacity: opacity.clamp(0.0, 1.0),+ };+ vertices.extend_from_slice(&[+ corner(-1.0, 1.0, 0.0, 0.0),+ corner(1.0, 1.0, 1.0, 0.0),+ corner(-1.0, -1.0, 0.0, 1.0),+ corner(1.0, 1.0, 1.0, 0.0),+ corner(1.0, -1.0, 1.0, 1.0),+ corner(-1.0, -1.0, 0.0, 1.0),+ ]);+ }++ /// Writes the quads for the next render, growing the buffer when a+ /// frame has more layers than any before it.+ fn write_vertices(&mut self, vertices: &[Vertex]) {if vertices.len() > self.vertex_capacity {self.vertex_capacity = vertices.len().next_power_of_two();self.vertices = self.device.create_buffer(&wgpu::BufferDescriptor {@@ -470,9 +514,106 @@ impl WgpuCompositor {}if !vertices.is_empty() {self.queue- .write_buffer(&self.vertices, 0, as_bytes(&vertices));+ .write_buffer(&self.vertices, 0, as_bytes(vertices));}- draws+ }++ /// Renders `draws` into a fresh pooled texture of the output size and+ /// returns its index: a stack drawn so far, kept on the GPU as the+ /// ground for a treatment or for the layers above it.+ fn render_pooled(+ &mut self,+ width: u32,+ height: u32,+ draws: &[(u32, u32, usize, Blend)],+ vertices: &[Vertex],+ ) -> usize {+ let target = self.claim(width, height);+ self.write_vertices(vertices);+ let view = self.pool[&(width, height)][target]+ .texture+ .create_view(&wgpu::TextureViewDescriptor::default());+ let encoder = self.encode(&view, draws);+ self.queue.submit([encoder.finish()]);+ target+ }++ /// The draws of a treated frame, every treatment applied over the+ /// stack beneath its track without a pixel leaving the GPU: the stack+ /// below is drawn into a pooled texture, the passes run over that, and+ /// the result - blended back over the untreated stack by the strength+ /// - becomes the ground the rest is drawn on. What comes back are the+ /// draws for the final render, into whichever target the caller wants.+ fn prepare_treated(+ &mut self,+ width: u32,+ height: u32,+ time: f32,+ layers: &[(Layer<'_>, usize)],+ treatments: &[Treatment<'_>],+ ) -> (Vec<(u32, u32, usize, Blend)>, Vec<Vertex>) {+ self.used.values_mut().for_each(|used| *used = 0);+ let mut ground: Option<usize> = None;+ let mut next = 0;+ for treatment in treatments {+ let mut draws = Vec::new();+ let mut vertices = Vec::new();+ if let Some(index) = ground {+ Self::push_pooled(&mut draws, &mut vertices, width, height, index, 1.0);+ }+ while next < layers.len() && layers[next].1 < treatment.track {+ self.push_layer(&mut draws, &mut vertices, width, height, &layers[next].0);+ next += 1;+ }+ let below = self.render_pooled(width, height, &draws, &vertices);+ let strength = treatment.strength.clamp(0.0, 1.0);+ if strength <= 0.0 || treatment.passes.is_empty() {+ ground = Some(below);+ continue;+ }+ let treated = self.run_passes(width, height, below, treatment.passes, time);+ ground = Some(if strength >= 1.0 {+ treated+ } else {+ let mut draws = Vec::new();+ let mut vertices = Vec::new();+ Self::push_pooled(&mut draws, &mut vertices, width, height, below, 1.0);+ Self::push_pooled(&mut draws, &mut vertices, width, height, treated, strength);+ self.render_pooled(width, height, &draws, &vertices)+ });+ }+ let mut draws = Vec::new();+ let mut vertices = Vec::new();+ if let Some(index) = ground {+ Self::push_pooled(&mut draws, &mut vertices, width, height, index, 1.0);+ }+ for (layer, _) in &layers[next..] {+ self.push_layer(&mut draws, &mut vertices, width, height, layer);+ }+ (draws, vertices)+ }++ /// [`WgpuCompositor::composite_texture`] with treatments; see+ /// [`Treatment`] and `prepare_treated`.+ pub fn composite_texture_treated(+ &mut self,+ width: u32,+ height: u32,+ time: f32,+ layers: &[(Layer<'_>, usize)],+ treatments: &[Treatment<'_>],+ ) -> Option<wgpu::Texture> {+ if self.dead {+ return None;+ }+ let (draws, vertices) = self.prepare_treated(width, height, time, layers, treatments);+ self.write_vertices(&vertices);+ let texture = self.presentable(width, height);+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let encoder = self.encode(&view, &draws);+ self.queue.submit([encoder.finish()]);+ self.retire();+ Some(texture)}/// The render pass: every draw over black into `view`. Returns the@@ -776,14 +917,8 @@ impl WgpuCompositor {/// seen, and the identity's for a pass without one. Returns the id the/// group is filed under.fn lut_group(&mut self, lut: Option<&Lut>) -> u64 {- let identity;- let lut = match lut {- Some(lut) => lut,- None => {- identity = Lut::identity(2);- &identity- }- };+ static IDENTITY: std::sync::OnceLock<Lut> = std::sync::OnceLock::new();+ let lut = lut.unwrap_or_else(|| IDENTITY.get_or_init(|| Lut::identity(2)));if self.luts.contains_key(&lut.id) {return lut.id;}@@ -1009,12 +1144,51 @@ impl Compositor for WgpuCompositor {}let draws = self.prepare(width, height, layers);+ match self.render_and_read(width, height, &draws) {+ Some(frame) => frame,+ None => {+ self.dead = true;+ CpuCompositor.composite(width, height, layers)+ }+ }+ }++ fn composite_treated(+ &mut self,+ width: u32,+ height: u32,+ time: f32,+ layers: &[(Layer<'_>, usize)],+ treatments: &[Treatment<'_>],+ ) -> Option<Frame> {+ if self.dead {+ return None;+ }+ let (draws, vertices) = self.prepare_treated(width, height, time, layers, treatments);+ self.write_vertices(&vertices);+ let frame = self.render_and_read(width, height, &draws);+ if frame.is_none() {+ self.dead = true;+ }+ frame+ }+}++impl WgpuCompositor {+ /// Draws into the readback target and copies it out: one submit, one+ /// wait. `None` when the device did not deliver the pixels.+ fn render_and_read(+ &mut self,+ width: u32,+ height: u32,+ draws: &[(u32, u32, usize, Blend)],+ ) -> Option<Frame> {self.target(width, height);let target = self.target.as_ref().expect("just ensured");let view = target.texture.create_view(&wgpu::TextureViewDescriptor::default());- let mut encoder = self.encode(&view, &draws);+ let mut encoder = self.encode(&view, draws);encoder.copy_texture_to_buffer(wgpu::TexelCopyTextureInfo {texture: &target.texture,@@ -1038,14 +1212,7 @@ impl Compositor for WgpuCompositor {);self.queue.submit([encoder.finish()]);self.retire();-- match self.read_back() {- Some(frame) => frame,- None => {- self.dead = true;- CpuCompositor.composite(width, height, layers)- }- }+ self.read_back()}}@@ -1113,6 +1280,42 @@ mod tests {assert_eq!(&out.pixels()[..3], &[255, 0, 0]);}+ /// A treatment runs its passes over the stack beneath its track and+ /// nothing above it, blended back by its strength, without the frame+ /// leaving the GPU: an invert over a red ground under a blue quarter+ /// turns the ground cyan and leaves the blue alone.+ #[test]+ fn a_treatment_treats_the_stack_beneath_its_track_only() {+ let Some(mut gpu) = gpu() else { return };+ let manifest = concat_effects::Manifest::parse(+ "[effect]\nid = \"test.invert2\"\nname = \"Invert\"\nkind = \"effect\"\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 passes = [shader.pass(&Default::default(), &[], 1.0, None)];+ let red = solid(8, 8, [255, 0, 0, 255]);+ let blue = solid(4, 4, [0, 0, 255, 255]);+ let layers = [(Layer::new(&red), 0), (Layer::new(&blue), 2)];+ let full = [Treatment { track: 1, passes: &passes, strength: 1.0 }];+ let out = gpu+ .composite_treated(8, 8, 0.0, &layers, &full)+ .expect("drawn");+ // Top-left is under the blue quarter; bottom-right is treated ground.+ assert_eq!(&out.pixels()[..3], &[0, 0, 255]);+ let last = out.pixels().len() - 4;+ assert_eq!(&out.pixels()[last..last + 3], &[0, 255, 255]);+ let half = [Treatment { track: 1, passes: &passes, strength: 0.5 }];+ let out = gpu+ .composite_treated(8, 8, 0.0, &layers, &half)+ .expect("drawn");+ let p = &out.pixels()[last..last + 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-render/src/lib.rs b/engine/crates/concat-render/src/lib.rsindex e7da632c..ba75dc96 100644--- a/engine/crates/concat-render/src/lib.rs+++ b/engine/crates/concat-render/src/lib.rs@@ -18,7 +18,7 @@ pub mod compositor;pub mod gpu;pub mod plan;-pub use compositor::{Compositor, CpuCompositor, Layer, Placement};+pub use compositor::{Compositor, CpuCompositor, Layer, Placement, Treatment};#[cfg(feature = "gpu")]pub use gpu::WgpuCompositor;pub use plan::{FramePlan, PlannedLayer, plan_frame};