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
feat(render): the compositor blends in linear light, in an extended linear Rec. 709 working space
Jareer9a36ef373937
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex d36a5e91..4f1a6a76 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -101,14 +101,23 @@ flowchart LRdecoded picture, the effects resolved for that instant, and the treatmentslive over the stack, and hands the whole thing to a compositor, which takesa `FramePlan` and nothing else.+- **The working space** is linear light on Rec. 709 primaries, extended (a+ value may be negative, a colour outside Rec. 709, or above one, a+ highlight), half floats, with 1.0 the white of an SDR picture: the layout+ Windows calls scRGB and Apple extended linear sRGB. A frame is converted+ into it on the GPU as it is uploaded and out of it once, at the resolve+ (`concat-render/src/gpu.rs`, `COPY_SHADER`); blending, opacity and fades+ happen in light, as in Resolve and Final Cut. Effect packages written for+ gamma-encoded `0..1` see that through the prelude's `legacy_in` and+ `legacy_out` (`concat-effects/src/shader.rs`) until the GPU-only effects+ replace them.- **One compositor.** The GPU one draws every frame, the monitor's and theexport's; a machine without a GPU runs it on the platform's softwareadapter (WARP on Windows, lavapipe on Linux), and a machine with neitheris told so. The CPU compositor that was the reference is kept in the testsalone (`concat-render/src/reference.rs`), the oracle the parity suite(`concat-render/src/gpu/tests.rs`) holds the GPU to at a structural- similarity above 0.99 while both draw 8-bit pictures; it goes when the- working space goes float. Geometry (crop, fit, centre, scale, turn) and+ similarity above 0.99, blending in light as the GPU does. Geometry (crop, fit, centre, scale, turn) andweighing (fades folded into a scale and offset, wipes into edges, mask,opacity) are computed once in the plan.diff --git a/src/crates/concat-effects/src/shader.rs b/src/crates/concat-effects/src/shader.rsindex fc372595..62127215 100644--- a/src/crates/concat-effects/src/shader.rs+++ b/src/crates/concat-effects/src/shader.rs@@ -55,9 +55,10 @@ struct Frame {@group(3) @binding(0) var reveal_texture: texture_2d<f32>;@group(3) @binding(1) var reveal_sampler: sampler;-/// The layer's colour at `uv`, straight alpha.+/// The layer's colour at `uv`, straight alpha, in the gamma-encoded Rec. 709+/// `0..1` today's packages were written for (see `legacy_in`).fn sample(uv: vec2<f32>) -> vec4<f32> {- return textureSample(source, source_sampler, uv);+ return legacy_in(textureSample(source, source_sampler, uv));}/// One pixel, as a fraction of the layer.@@ -95,6 +96,22 @@ fn reveal_order(uv: vec2<f32>) -> f32 {}// ── the grading library ──++/// The compositor's working space - linear light on Rec. 709 primaries,+/// extended past `0..1`, with 1.0 the white of an SDR picture - brought into+/// the gamma-encoded `0..1` a package written before it was made for:+/// clipped to the range, then BT.1886's 2.4 gamma. The host samples through+/// this, so such a package sees the picture it always saw.+fn legacy_in(colour: vec4<f32>) -> vec4<f32> {+ let clipped = clamp(colour.rgb, vec3<f32>(0.0), vec3<f32>(1.0));+ return vec4<f32>(pow(clipped, vec3<f32>(1.0 / 2.4)), colour.a);+}++/// A legacy package's result taken back into the working space: the 2.4+/// gamma undone.+fn legacy_out(colour: vec4<f32>) -> vec4<f32> {+ return vec4<f32>(pow(max(colour.rgb, vec3<f32>(0.0)), vec3<f32>(2.4)), colour.a);+}//// Every look is a few of these in different amounts, so they live here,// once, rather than in each package. Each has an FFmpeg twin a manifest's@@ -383,7 +400,7 @@ fn vs_main(@builtin(vertex_index) index: u32) -> VsOut {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));+ return legacy_out(mix(base, treated, clamp(frame.intensity, 0.0, 1.0)));}"#;@@ -847,14 +864,15 @@ struct Frame {@group(2) @binding(0) var lut_texture: texture_3d<f32>;@group(2) @binding(1) var lut_sampler: sampler;-/// The outgoing picture's colour at `uv`, straight alpha.+/// The outgoing picture's colour at `uv`, straight alpha, gamma-encoded+/// Rec. 709 as the packages were written for (see `legacy_in`).fn from_at(uv: vec2<f32>) -> vec4<f32> {- return textureSample(from_texture, from_sampler, uv);+ return legacy_in(textureSample(from_texture, from_sampler, uv));}-/// The incoming picture's colour at `uv`, straight alpha.+/// The incoming picture's colour at `uv`, likewise.fn to_at(uv: vec2<f32>) -> vec4<f32> {- return textureSample(to_texture, to_sampler, uv);+ return legacy_in(textureSample(to_texture, to_sampler, uv));}/// What the shared grading helpers read: the outgoing picture, so `soften`@@ -910,7 +928,7 @@ fn vs_main(@builtin(vertex_index) index: u32) -> VsOut {@fragmentfn fs_main(in: VsOut) -> @location(0) vec4<f32> {- return transition(in.uv, frame.progress);+ return legacy_out(transition(in.uv, frame.progress));}"#;diff --git a/src/crates/concat-render/src/gpu.rs b/src/crates/concat-render/src/gpu.rsindex 79a7b0bd..65c9a721 100644--- a/src/crates/concat-render/src/gpu.rs+++ b/src/crates/concat-render/src/gpu.rs@@ -171,11 +171,24 @@ const WORK: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;/// What a texture in the pool costs a pixel.const WORK_BYTES: u64 = 8;-/// A picture copied texel for texel into a target of the same size: an-/// uploaded frame into the working format, and a finished frame out of it-/// into the eight bits a screen and an encoder take. A triangle that covers-/// the target, and a load at each fragment's own texel, so nothing is-/// filtered on the way.+/// A picture copied texel for texel into a target of the same size, through+/// the colour conversion at each end of the working space: an uploaded+/// frame into it (`fs_upload`), and a finished frame out of it into the+/// eight bits a screen and an encoder take (`fs_resolve`). A triangle that+/// covers the target, and a load at each fragment's own texel, so nothing+/// is filtered on the way.+///+/// The working space is linear light on Rec. 709 primaries, extended: a+/// value may be negative (a colour outside Rec. 709, as a Rec. 2020 source+/// has) or above one (a highlight), with 1.0 the white of an SDR picture+/// (203 nits, ITU-R BT.2408) - the layout Windows calls scRGB and Apple's+/// EDR extended linear sRGB. Blending and every fade then behave as light+/// does. Rec. 709 primaries rather than Rec. 2020's because the store is+/// half floats: in a basis the picture is not in, a primary leaks a few+/// ten-thousandths into its neighbours, and the output's 1/2.4 power makes+/// that a visible tint in the shadows. An eight-bit frame is gamma-encoded+/// Rec. 709, taken as BT.1886's 2.4 gamma; the resolve undoes exactly what+/// the upload did, so a picture with nothing on it comes out as it went in.const COPY_SHADER: &str = r#"@group(0) @binding(0) var picture: texture_2d<f32>;@group(0) @binding(1) var picture_sampler: sampler;@@ -187,8 +200,16 @@ fn vs_full(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {}@fragment-fn fs_copy(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {- return textureLoad(picture, vec2<i32>(at.xy), 0);+fn fs_upload(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {+ let colour = textureLoad(picture, vec2<i32>(at.xy), 0);+ return vec4<f32>(pow(max(colour.rgb, vec3<f32>(0.0)), vec3<f32>(2.4)), colour.a);+}++@fragment+fn fs_resolve(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {+ let colour = textureLoad(picture, vec2<i32>(at.xy), 0);+ let clipped = clamp(colour.rgb, vec3<f32>(0.0), vec3<f32>(1.0));+ return vec4<f32>(pow(clipped, vec3<f32>(1.0 / 2.4)), colour.a);}"#;@@ -640,9 +661,9 @@ impl WgpuCompositor {bind_group_layouts: &[Some(&bind_layout)],immediate_size: 0,});- let copy_into = |format: wgpu::TextureFormat, label: &str| {+ let copy_into = |format: wgpu::TextureFormat, entry: &str| {device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some(label),+ label: Some(entry),layout: Some(©_layout),vertex: wgpu::VertexState {module: ©_shader,@@ -652,7 +673,7 @@ impl WgpuCompositor {},fragment: Some(wgpu::FragmentState {module: ©_shader,- entry_point: Some("fs_copy"),+ entry_point: Some(entry),compilation_options: Default::default(),targets: &[Some(wgpu::ColorTargetState {format,@@ -667,8 +688,8 @@ impl WgpuCompositor {cache: None,})};- let upload_pipeline = copy_into(WORK, "concat upload");- let resolve_pipeline = copy_into(wgpu::TextureFormat::Rgba8Unorm, "concat resolve");+ let upload_pipeline = copy_into(WORK, "fs_upload");+ let resolve_pipeline = copy_into(wgpu::TextureFormat::Rgba8Unorm, "fs_resolve");let sampler = device.create_sampler(&wgpu::SamplerDescriptor {label: Some("concat layer"),@@ -1958,46 +1979,6 @@ impl WgpuCompositor {stages}- /// A texture holding a whole frame's pixels, for a transition input. Made- /// fresh each combine rather than pooled: a transition is a short window,- /// and its two inputs are full-frame, so the pool would only churn.- fn input_texture(&self, frame: &Frame) -> wgpu::Texture {- let texture = self.device.create_texture(&wgpu::TextureDescriptor {- label: Some("concat transition input"),- size: wgpu::Extent3d {- width: frame.width(),- height: frame.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,- view_formats: &[],- });- self.queue.write_texture(- wgpu::TexelCopyTextureInfo {- texture: &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,- },- );- texture- }-/// The bind group for a pass's table, uploaded the first time its id is/// seen, and the identity's for a pass without one. Returns the id the/// group is filed under.@@ -2359,13 +2340,18 @@ impl Compositor for WgpuCompositor {if self.dead {return None;}- // The two pictures, uploaded.- let from_texture = self.input_texture(from);- let to_texture = self.input_texture(to);- let from_view = from_texture.create_view(&wgpu::TextureViewDescriptor::default());- let to_view = to_texture.create_view(&wgpu::TextureViewDescriptor::default());-+ // The two pictures, uploaded into the working space as any frame+ // is, so the shader reads what the device-kept path hands it.self.used.values_mut().for_each(|used| *used = 0);+ let view_of = |gpu: &Self, frame: &Frame, index: usize| {+ gpu.pool[&(frame.width(), frame.height())][index]+ .texture+ .create_view(&wgpu::TextureViewDescriptor::default())+ };+ let from_index = self.upload(from);+ let to_index = self.upload(to);+ let from_view = view_of(self, from, from_index);+ let to_view = view_of(self, to, to_index);let (canvas, _, canvas_view) = self.canvas(width, height);self.target(width, height);let target_texture = self.target.as_ref().expect("just ensured").texture.clone();diff --git a/src/crates/concat-render/src/gpu/tests.rs b/src/crates/concat-render/src/gpu/tests.rsindex 8b6ebe39..c90ef238 100644--- a/src/crates/concat-render/src/gpu/tests.rs+++ b/src/crates/concat-render/src/gpu/tests.rs@@ -210,10 +210,12 @@ fn a_treatment_treats_the_stack_beneath_its_track_only() {assert_eq!(&out.pixels()[..3], &[0, 0, 255]);let last = out.pixels().len() - 4;assert_eq!(&out.pixels()[last..last + 3], &[0, 255, 255]);+ // At half strength the ground is halfway between red and cyan in light:+ // a half of each channel, which BT.1886's 2.4 gamma stores at 191.let out = gpu.render(&treated(0.5));let p = &out.pixels()[last..last + 3];assert!(- p[0] > 120 && p[0] < 136 && p[1] > 120 && p[1] < 136,+ p.iter().all(|channel| (189..=193).contains(channel)),"{p:?}");// The CPU reference agrees on the whole picture.@@ -492,7 +494,18 @@ fn a_transition_combines_its_two_inputs_by_progress() {};assert_eq!(&at(0.0).pixels()[..3], &[255, 0, 0], "all outgoing at 0");assert_eq!(&at(1.0).pixels()[..3], &[0, 0, 255], "all incoming at 1");- assert_eq!(&at(0.5).pixels()[..3], &[128, 0, 128], "the exact half mix");+ // The package mixes in the gamma it was written for (the legacy+ // wrapper), so its half is the half of the stored levels, give or take+ // the level the round trip through linear light can round to.+ let half = at(0.5);+ assert!(+ half.pixels()[..3]+ .iter()+ .zip([128u8, 0, 128])+ .all(|(got, want)| got.abs_diff(want) <= 1),+ "the half mix: {:?}",+ &half.pixels()[..3]+ );}/// Every packaged effect and filter with a shader actually renders ondiff --git a/src/crates/concat-render/src/reference.rs b/src/crates/concat-render/src/reference.rsindex d5d5b9fa..bc2376f5 100644--- a/src/crates/concat-render/src/reference.rs+++ b/src/crates/concat-render/src/reference.rs@@ -65,7 +65,7 @@ impl Compositor for CpuCompositor {ground = if strength >= 1.0 {treated} else {- mix_frames(&ground, &treated, strength)+ mix_light(&ground, &treated, strength)};}for layer in &plan.layers[next..] {@@ -97,6 +97,30 @@ pub(crate) fn run_effects(picture: &Frame, effects: &[ShaderPass], seconds: f32)}/// `a` towards `b` by `amount`, per channel.+/// `a` towards `b` by `amount`, in linear light: a treatment's strength,+/// which the GPU weighs over the working space.+pub(crate) fn mix_light(a: &Frame, b: &Frame, amount: f32) -> Frame {+ let amount = amount.clamp(0.0, 1.0);+ let mut out = a.clone();+ for (index, (pixel, over)) in out+ .pixels_mut()+ .iter_mut()+ .zip(b.pixels().iter())+ .enumerate()+ {+ if index % 4 == 3 {+ let base = f32::from(*pixel);+ *pixel = (base + (f32::from(*over) - base) * amount).round() as u8;+ continue;+ }+ let base = linear(f32::from(*pixel));+ *pixel = encoded(base + (linear(f32::from(*over)) - base) * amount).round() as u8;+ }+ out+}++/// `a` towards `b` by `amount` in their stored gamma: the old transition+/// shapes, which the GPU also runs in gamma through its legacy wrapper.pub(crate) fn mix_frames(a: &Frame, b: &Frame, amount: f32) -> Frame {let amount = amount.clamp(0.0, 1.0);let mut out = a.clone();@@ -201,10 +225,12 @@ impl Weighing<'_> {if alpha <= 0.0 {return;}+ // In linear light, as the GPU blends: the layer's colour and the+ // ground decoded from their stored gamma, weighed, and encoded back.for channel in 0..3 {- let colour = self.shading.colour(channel, sample[channel] / 255.0) * 255.0;- let ground = f32::from(under[channel]);- under[channel] = mix(self.blend, colour, ground, alpha)+ let colour = self.shading.colour(channel, linear(sample[channel]));+ let ground = linear(f32::from(under[channel]));+ under[channel] = encoded(mix(self.blend, colour, ground, alpha)).round().clamp(0.0, 255.0) as u8;}@@ -212,8 +238,20 @@ impl Weighing<'_> {}}+/// A stored eight-bit level, `0..=255`, as linear light `0..1`: BT.1886's+/// 2.4 gamma, the GPU's upload.+fn linear(level: f32) -> f32 {+ (level / 255.0).max(0.0).powf(2.4)+}++/// Linear light back to an eight-bit level, clipped: the GPU's resolve.+fn encoded(light: f32) -> f32 {+ light.clamp(0.0, 1.0).powf(1.0 / 2.4) * 255.0+}+/// One channel of `blend`: `colour` is the layer's straight colour, `under`-/// the ground, both in `0..=255`, `alpha` how much of the layer is there.+/// the ground, both linear light `0..1`, `alpha` how much of the layer is+/// there./// Normal, Multiply, Screen and Add are the GPU's fixed-function blends/// over premultiplied colour, spelled the same way so the two paths agree./// Lighten and Darken weigh the lighter (darker) of the two in by the@@ -226,8 +264,8 @@ fn mix(blend: Blend, colour: f32, under: f32, alpha: f32) -> f32 {let over = colour * alpha;match blend {Blend::Normal => over + under * (1.0 - alpha),- Blend::Multiply => over * under / 255.0 + under * (1.0 - alpha),- Blend::Screen => over * (1.0 - under / 255.0) + under,+ Blend::Multiply => over * under + under * (1.0 - alpha),+ Blend::Screen => over * (1.0 - under) + under,Blend::Add => over + under,Blend::Lighten => colour.max(under) * alpha + under * (1.0 - alpha),Blend::Darken => colour.min(under) * alpha + under * (1.0 - alpha),@@ -453,7 +491,9 @@ mod tests {}/// Multiply by white and screen with black both leave the ground as it- /// was; add brightens it, darken cannot, lighten takes the brighter.+ /// was; add brightens it - in light: 100 and 50 are 0.106 and 0.020 of+ /// white, and their sum is stored at 107 - darken cannot, lighten takes+ /// the brighter.#[test]fn the_blend_modes_do_what_their_names_say() {let over = |rgba: [u8; 4], blend: Blend| {@@ -465,7 +505,7 @@ mod tests {assert_eq!(over([255, 255, 255, 255], Blend::Multiply), 100);assert_eq!(over([0, 0, 0, 255], Blend::Screen), 100);assert_eq!(over([255, 255, 255, 255], Blend::Screen), 255);- assert_eq!(over([50, 50, 50, 255], Blend::Add), 150);+ assert_eq!(over([50, 50, 50, 255], Blend::Add), 107);assert_eq!(over([255, 255, 255, 255], Blend::Darken), 100);assert_eq!(over([30, 30, 30, 255], Blend::Lighten), 100);assert_eq!(over([200, 200, 200, 255], Blend::Lighten), 200);@@ -484,12 +524,14 @@ mod tests {assert_eq!(frame.pixel(1, 1), Some([255, 0, 0, 255]));}+ /// Half a white layer over black is half the light of white, which a+ /// 2.4 gamma stores at 191, not at the level halfway up.#[test]- fn half_opacity_lands_halfway() {+ fn half_opacity_lands_halfway_in_light() {let mut white = layer(solid(1, 1, [255, 255, 255, 255]));white.opacity = 0.5;let frame = render(1, 1, vec![white]);- assert_eq!(frame.pixel(0, 0), Some([128, 128, 128, 255]));+ assert_eq!(frame.pixel(0, 0), Some([191, 191, 191, 255]));}#[test]@@ -497,8 +539,8 @@ mod tests {let mut half = layer(solid(1, 1, [255, 255, 255, 128]));half.opacity = 0.5;let frame = render(1, 1, vec![half]);- // 128/255 * 0.5 ~= 0.251- assert_eq!(frame.pixel(0, 0), Some([64, 64, 64, 255]));+ // 128/255 * 0.5 ~= 0.251 of white's light, stored at 143.+ assert_eq!(frame.pixel(0, 0), Some([143, 143, 143, 255]));}#[test]@@ -676,7 +718,8 @@ mod tests {amount: 0.5,}];let frame = render(4, 4, vec![faded]);- assert_eq!(frame.pixel(0, 0), Some([255, 128, 128, 255]));+ // Half way to white in light: green and blue at half of white's.+ assert_eq!(frame.pixel(0, 0), Some([255, 191, 191, 255]));let mut wiped = layer(red);wiped.transitions = vec![Transition::Wipe {