Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: apply color grades in the composite and background passes

Richie McIlroy50a3cdb0e958
diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rs
index 8a56e705f..559eef503 100644
--- a/crates/rendering/src/composite_frame.rs
+++ b/crates/rendering/src/composite_frame.rs
@@ -92,6 +92,14 @@ pub struct CompositeVideoFrameUniforms {
/// squares its top corners against decorative frame chrome with
/// `[0, 0, 1, 1]`.
pub corner_radii: [f32; 4],
+ /// Color grade: (exposure in stops, contrast, saturation, temperature).
+ pub color_adjust_a: [f32; 4],
+ /// Color grade: (tint, fade, split_tone, vignette).
+ pub color_adjust_b: [f32; 4],
+ /// (grain amount, per-frame grain seed, grade-active flag, full-frame
+ /// vignette flag). The active flag lets the shader skip the whole color
+ /// pass in one uniform branch when the layer has no grade.
+ pub grain_params: [f32; 4],
}
impl Default for CompositeVideoFrameUniforms {
@@ -119,6 +127,85 @@ impl Default for CompositeVideoFrameUniforms {
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
corner_radii: [1.0; 4],
+ color_adjust_a: [0.0; 4],
+ color_adjust_b: [0.0; 4],
+ grain_params: [0.0; 4],
+ }
+ }
+}
+
+/// The three uniform vec4s that drive the shader's color pass, derived from a
+/// layer's [`cap_project::ColorCorrection`]. Intensity scaling happens here so
+/// the shader never needs to know about it, and every field is clamped so a
+/// hand-edited config can't push the shader outside its designed ranges.
+#[derive(Debug, Clone, Copy)]
+pub struct ColorGradeUniformParams {
+ pub color_adjust_a: [f32; 4],
+ pub color_adjust_b: [f32; 4],
+ pub grain_params: [f32; 4],
+}
+
+impl ColorGradeUniformParams {
+ pub const IDENTITY: Self = Self {
+ color_adjust_a: [0.0; 4],
+ color_adjust_b: [0.0; 4],
+ grain_params: [0.0; 4],
+ };
+
+ /// Mirrors the shader's own gate: `grain_params.z` is the active flag
+ /// `from_config` sets when any adjustment survives clamping and intensity
+ /// scaling.
+ pub fn is_active(&self) -> bool {
+ self.grain_params[2] > 0.5
+ }
+
+ /// `full_frame_vignette` selects the vignette's coordinate space:
+ /// the screen uses the full output frame (so the display card and the
+ /// graded background share one continuous vignette field), while the
+ /// camera vignettes within its own card.
+ pub fn from_config(
+ config: &cap_project::ColorCorrection,
+ frame_number: u32,
+ full_frame_vignette: bool,
+ ) -> Self {
+ let intensity = config.intensity.clamp(0.0, 1.0);
+ let exposure_stops = config.exposure.clamp(-1.0, 1.0) * 1.5 * intensity;
+ let contrast = config.contrast.clamp(-1.0, 1.0) * intensity;
+ let saturation = config.saturation.clamp(-1.0, 1.0) * intensity;
+ let temperature = config.temperature.clamp(-1.0, 1.0) * intensity;
+ let tint = config.tint.clamp(-1.0, 1.0) * intensity;
+ let fade = config.fade.clamp(0.0, 1.0) * intensity;
+ let split_tone = config.split_tone.clamp(-1.0, 1.0) * intensity;
+ let vignette = config.vignette.clamp(0.0, 1.0) * intensity;
+ let grain = config.grain.clamp(0.0, 1.0);
+
+ let active = [
+ exposure_stops,
+ contrast,
+ saturation,
+ temperature,
+ tint,
+ fade,
+ split_tone,
+ vignette,
+ grain,
+ ]
+ .iter()
+ .any(|v| v.abs() > 1e-4);
+
+ // Cycling seed keeps grain animated while staying deterministic per
+ // frame number, so preview and export always match.
+ let grain_seed = (frame_number % 600) as f32;
+
+ Self {
+ color_adjust_a: [exposure_stops, contrast, saturation, temperature],
+ color_adjust_b: [tint, fade, split_tone, vignette],
+ grain_params: [
+ grain,
+ grain_seed,
+ if active { 1.0 } else { 0.0 },
+ if full_frame_vignette { 1.0 } else { 0.0 },
+ ],
}
}
}
diff --git a/crates/rendering/src/layers/color_grade.rs b/crates/rendering/src/layers/color_grade.rs
new file mode 100644
index 000000000..f23bb69b7
--- /dev/null
+++ b/crates/rendering/src/layers/color_grade.rs
@@ -0,0 +1,188 @@
+use bytemuck::{Pod, Zeroable};
+use wgpu::util::DeviceExt;
+
+use crate::ProjectUniforms;
+
+/// Full-frame pass that applies the screen's color grade (including grain)
+/// to the background canvas, so the backdrop and the display card read as one
+/// graded scene. Runs between the background (+ its blur) and the display
+/// layer, and only when the screen grade is active — an ungraded project
+/// skips the pass entirely.
+pub struct ColorGradeLayer {
+ active: bool,
+ uniforms_buffer: wgpu::Buffer,
+ pipeline: ColorGradePipeline,
+}
+
+impl ColorGradeLayer {
+ pub fn new(device: &wgpu::Device) -> Self {
+ Self {
+ active: false,
+ uniforms_buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("ColorGrade Uniform Buffer"),
+ contents: bytemuck::cast_slice(&[ColorGradeUniforms::default()]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ }),
+ pipeline: ColorGradePipeline::new(device),
+ }
+ }
+
+ pub fn is_active(&self) -> bool {
+ self.active
+ }
+
+ pub fn prepare(&mut self, queue: &wgpu::Queue, uniforms: &ProjectUniforms) {
+ // Reuses the exact params the display card was given: grain and
+ // vignette only stay continuous across the card edge if both passes
+ // grade with identical values.
+ let params = uniforms.screen_color_grade;
+ self.active = params.is_active();
+ if !self.active {
+ return;
+ }
+
+ queue.write_buffer(
+ &self.uniforms_buffer,
+ 0,
+ bytemuck::cast_slice(&[ColorGradeUniforms {
+ color_adjust_a: params.color_adjust_a,
+ color_adjust_b: params.color_adjust_b,
+ grain_params: params.grain_params,
+ }]),
+ );
+ }
+
+ pub fn render(
+ &self,
+ pass: &mut wgpu::RenderPass<'_>,
+ device: &wgpu::Device,
+ source_texture: &wgpu::TextureView,
+ ) {
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(
+ 0,
+ &self
+ .pipeline
+ .bind_group(device, &self.uniforms_buffer, source_texture),
+ &[],
+ );
+ pass.draw(0..3, 0..1);
+ }
+}
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
+struct ColorGradeUniforms {
+ color_adjust_a: [f32; 4],
+ color_adjust_b: [f32; 4],
+ grain_params: [f32; 4],
+}
+
+struct ColorGradePipeline {
+ bind_group_layout: wgpu::BindGroupLayout,
+ render_pipeline: wgpu::RenderPipeline,
+}
+
+impl ColorGradePipeline {
+ fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("color-grade Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ ],
+ });
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Color Grade Shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/color-grade.wgsl").into()),
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Color Grade Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Color Grade Pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ polygon_mode: wgpu::PolygonMode::Fill,
+ unclipped_depth: false,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+ Self {
+ bind_group_layout,
+ render_pipeline,
+ }
+ }
+
+ fn bind_group(
+ &self,
+ device: &wgpu::Device,
+ uniform_buffer: &wgpu::Buffer,
+ texture_view: &wgpu::TextureView,
+ ) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ColorGrade Bind Group"),
+ layout: &self.bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(texture_view),
+ },
+ ],
+ })
+ }
+}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index cb96d8b4d..6237813d1 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -3,6 +3,7 @@ mod blur;
mod camera;
mod camera3d;
mod captions;
+mod color_grade;
mod cursor;
mod display;
mod frame;
@@ -67,6 +68,7 @@ pub use blur::*;
pub use camera::*;
pub use camera3d::*;
pub use captions::*;
+pub use color_grade::*;
pub use cursor::*;
pub use display::*;
pub use frame::*;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index c3167f012..eb625d23a 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -5,7 +5,7 @@ use cap_project::{
FrameStyle, ProjectConfiguration, RecordingMeta, SceneMode, StudioRecordingMeta,
TimelineFrameMapping, TimelineSource, XY,
};
-use composite_frame::CompositeVideoFrameUniforms;
+use composite_frame::{ColorGradeUniformParams, CompositeVideoFrameUniforms};
use core::f64;
use cursor_interpolation::{
InterpolatedCursorPosition, interpolate_cursor, interpolate_cursor_with_click_spring,
@@ -18,8 +18,8 @@ use frame_pipeline::{
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, Camera3DBlurKind, Camera3DLayer, CameraLayer,
- CaptionsLayer, CursorLayer, DisplayLayer, FrameLayer, KeyboardLayer, MaskLayer, NotchLayer,
- NotchUniforms, TextLayer,
+ CaptionsLayer, ColorGradeLayer, CursorLayer, DisplayLayer, FrameLayer, KeyboardLayer,
+ MaskLayer, NotchLayer, NotchUniforms, TextLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -2251,6 +2251,10 @@ pub struct ProjectUniforms {
/// The recording device's physical notch, redrawn over the capture;
/// `None` when the overlay is off or the recording has no notch.
pub notch: Option<layers::NotchUniforms>,
+ /// The screen grade's uniform params, shared verbatim by the display card
+ /// and the background grade pass so grain and vignette stay continuous
+ /// across the card edge.
+ screen_color_grade: ColorGradeUniformParams,
/// Final placement of the outer display card (chrome included) in output
/// px. Equals `display.target_bounds` when no frame is active.
display_outer_bounds: [f32; 4],
@@ -3286,6 +3290,17 @@ impl ProjectUniforms {
let current_recording_time = segment_frames.recording_time;
let prev_recording_time = (segment_frames.recording_time - 1.0 / fps_f32).max(0.0);
+ let screen_color_grade = ColorGradeUniformParams::from_config(
+ &project.color_correction.screen,
+ frame_number,
+ true,
+ );
+ let camera_color_grade = ColorGradeUniformParams::from_config(
+ &project.color_correction.camera,
+ frame_number,
+ false,
+ );
+
let cursor_stop_time = project
.cursor
.stop_movement_in_last_seconds
@@ -3719,6 +3734,10 @@ impl ProjectUniforms {
_padding1: [0.0; 3],
border_color,
corner_radii: [1.0; 4],
+ // Chrome is decoration, not video: never graded.
+ color_adjust_a: [0.0; 4],
+ color_adjust_b: [0.0; 4],
+ grain_params: [0.0; 4],
},
style: frame.style,
theme: frame.theme,
@@ -3781,6 +3800,11 @@ impl ProjectUniforms {
border_color: [0.0; 4],
frame_size: [1.0, 1.0],
crop_bounds: [0.0, 0.0, 1.0, 1.0],
+ // The notch redraw is hardware, not video: never
+ // graded.
+ color_adjust_a: [0.0; 4],
+ color_adjust_b: [0.0; 4],
+ grain_params: [0.0; 4],
},
raster_size: [unzoomed.full_size[0] as f64, unzoomed.full_size[1] as f64],
source_crop: placement.source_crop,
@@ -3836,6 +3860,9 @@ impl ProjectUniforms {
_padding1: [0.0; 3],
border_color,
corner_radii: display_corner_radii,
+ color_adjust_a: screen_color_grade.color_adjust_a,
+ color_adjust_b: screen_color_grade.color_adjust_b,
+ grain_params: screen_color_grade.grain_params,
},
display_parent_motion_px,
frame_chrome,
@@ -4038,6 +4065,9 @@ impl ProjectUniforms {
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
corner_radii: [1.0; 4],
+ color_adjust_a: camera_color_grade.color_adjust_a,
+ color_adjust_b: camera_color_grade.color_adjust_b,
+ grain_params: camera_color_grade.grain_params,
}
});
@@ -4135,6 +4165,9 @@ impl ProjectUniforms {
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
corner_radii: [1.0; 4],
+ color_adjust_a: camera_color_grade.color_adjust_a,
+ color_adjust_b: camera_color_grade.color_adjust_b,
+ grain_params: camera_color_grade.grain_params,
}
});
@@ -4189,6 +4222,7 @@ impl ProjectUniforms {
texts,
camera3d,
camera3d_zoom,
+ screen_color_grade,
}
}
}
@@ -5248,6 +5282,7 @@ impl<'a> FrameRenderer<'a> {
pub struct RendererLayers {
background: BackgroundLayer,
background_blur: BlurLayer,
+ background_color_grade: ColorGradeLayer,
frame: FrameLayer,
display: DisplayLayer,
notch: NotchLayer,
@@ -5280,6 +5315,7 @@ impl RendererLayers {
Self {
background: BackgroundLayer::new(device),
background_blur: BlurLayer::new(device),
+ background_color_grade: ColorGradeLayer::new(device),
frame: FrameLayer::new(device, shared_composite_pipeline.clone()),
notch: NotchLayer::new(device, shared_composite_pipeline.clone()),
display: DisplayLayer::new_with_all_shared_pipelines(
@@ -5444,6 +5480,9 @@ impl RendererLayers {
self.background_blur.prepare(&constants.queue, uniforms);
}
+ self.background_color_grade
+ .prepare(&constants.queue, uniforms);
+
if render_display {
self.frame.prepare(constants, uniforms);
self.notch
@@ -5585,6 +5624,8 @@ impl RendererLayers {
if uniforms.project.background.blur > 0.0 {
self.background_blur.prepare(&constants.queue, uniforms);
}
+ self.background_color_grade
+ .prepare(&constants.queue, uniforms);
timings.background_blur_prepare_duration = start.elapsed();
let start = Instant::now();
@@ -5761,6 +5802,22 @@ impl RendererLayers {
session.swap_textures();
}
+ // Grade the backdrop before any content layers draw, so the screen's
+ // color grade covers the whole scene (padding, wallpaper, blur) and
+ // not just the display card. Content layers apply their own grades.
+ // The pass overwrites every pixel (fullscreen triangle, no blending),
+ // so the target's old contents never need loading.
+ if self.background_color_grade.is_active() {
+ let mut pass = render_pass!(
+ session.other_texture_view(),
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ );
+ self.background_color_grade
+ .render(&mut pass, device, session.current_texture_view());
+
+ session.swap_textures();
+ }
+
let should_render_screen = render_display
&& uniforms.scene.should_render_screen()
&& self.display.has_valid_frame();
diff --git a/crates/rendering/src/shaders/color-grade.wgsl b/crates/rendering/src/shaders/color-grade.wgsl
new file mode 100644
index 000000000..5e95150d0
--- /dev/null
+++ b/crates/rendering/src/shaders/color-grade.wgsl
@@ -0,0 +1,105 @@
+// Full-frame color grade for the background canvas. Runs between the
+// background (+ its blur) and the display layer so the backdrop wears the
+// same grade as the screen and the padded scene reads as one frame.
+//
+// The grade math MUST stay in sync with apply_color_grade in
+// composite-video-frame.wgsl: the display card applies the same grade in its
+// own shader, and grain + vignette are computed in the same output-pixel
+// space so the two layers meet seamlessly at the card edge.
+
+struct Uniforms {
+ // (exposure stops, contrast, saturation, temperature).
+ color_adjust_a: vec4<f32>,
+ // (tint, fade, split_tone, vignette).
+ color_adjust_b: vec4<f32>,
+ // (grain amount, per-frame grain seed, grade-active flag, unused).
+ grain_params: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: Uniforms;
+@group(0) @binding(1) var frame_texture: texture_2d<f32>;
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4<f32> {
+ var positions = array<vec2<f32>, 3>(
+ vec2<f32>(-1.0, -1.0),
+ vec2<f32>(3.0, -1.0),
+ vec2<f32>(-1.0, 3.0)
+ );
+ return vec4<f32>(positions[vertex_index], 0.0, 1.0);
+}
+
+fn grain_hash(p: vec2<f32>) -> f32 {
+ var p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+@fragment
+fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
+ let color = textureLoad(frame_texture, vec2<i32>(frag_coord.xy), 0);
+
+ let exposure = uniforms.color_adjust_a.x;
+ let contrast = uniforms.color_adjust_a.y;
+ let saturation = uniforms.color_adjust_a.z;
+ let temperature = uniforms.color_adjust_a.w;
+ let tint = uniforms.color_adjust_b.x;
+ let fade = uniforms.color_adjust_b.y;
+ let split_tone = uniforms.color_adjust_b.z;
+ let vignette = uniforms.color_adjust_b.w;
+ let grain = uniforms.grain_params.x;
+
+ // Exposure in stops.
+ var rgb = color.rgb * exp2(exposure);
+
+ // White balance: temperature trades red against blue, tint trades green
+ // against magenta. Multiplicative so black stays black.
+ rgb = rgb * vec3<f32>(
+ 1.0 + 0.10 * temperature + 0.04 * tint,
+ 1.0 - 0.07 * tint,
+ 1.0 - 0.10 * temperature + 0.04 * tint,
+ );
+
+ // Contrast around mid gray.
+ rgb = (rgb - vec3<f32>(0.5)) * (1.0 + contrast) + vec3<f32>(0.5);
+
+ // Saturation via luma mix (-1 = grayscale).
+ let luma = dot(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(0.2126, 0.7152, 0.0722));
+ rgb = mix(vec3<f32>(luma), rgb, 1.0 + saturation);
+
+ // Split toning: teal into shadows, orange into highlights (reversed when
+ // the amount is negative), weighted by luma bands.
+ let shadow_w = 1.0 - smoothstep(0.2, 0.65, luma);
+ let highlight_w = smoothstep(0.35, 0.8, luma);
+ rgb += split_tone * (
+ shadow_w * vec3<f32>(-0.06, 0.02, 0.08) +
+ highlight_w * vec3<f32>(0.08, 0.02, -0.06)
+ );
+
+ // Film fade: raised blacks, gently dulled highlights.
+ rgb = rgb * (1.0 - 0.18 * fade) + vec3<f32>(0.09 * fade);
+
+ // Full-frame vignette (the display card computes its vignette in the
+ // same output space, so the field is continuous across the card edge).
+ if vignette > 0.0 {
+ let dims = vec2<f32>(textureDimensions(frame_texture));
+ let r = length((frag_coord.xy / dims - vec2<f32>(0.5)) * 2.0);
+ rgb = rgb * (1.0 - vignette * 0.65 * smoothstep(0.5, 1.5, r));
+ }
+
+ // Animated monochrome grain, peaked in the midtones like scanned film.
+ // Same hash, coordinates, and seed as the display layer so the noise
+ // field is continuous across the card boundary.
+ if grain > 0.0 {
+ let seed = uniforms.grain_params.y;
+ let noise = grain_hash(frag_coord.xy + vec2<f32>(seed * 17.0, seed * 29.0));
+ let graded_luma = dot(
+ clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)),
+ vec3<f32>(0.2126, 0.7152, 0.0722)
+ );
+ let response = 0.25 + 0.75 * (1.0 - abs(2.0 * graded_luma - 1.0));
+ rgb += (noise - 0.5) * grain * 0.35 * response;
+ }
+
+ return vec4<f32>(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), color.a);
+}
diff --git a/crates/rendering/src/shaders/composite-video-frame.wgsl b/crates/rendering/src/shaders/composite-video-frame.wgsl
index b7b43776f..f68d02c61 100644
--- a/crates/rendering/src/shaders/composite-video-frame.wgsl
+++ b/crates/rendering/src/shaders/composite-video-frame.wgsl
@@ -26,6 +26,13 @@ struct Uniforms {
// the uniform rounding; the display squares its top corners against
// decorative frame chrome with (0, 0, 1, 1).
corner_radii: vec4<f32>,
+ // Color grade: (exposure stops, contrast, saturation, temperature).
+ color_adjust_a: vec4<f32>,
+ // Color grade: (tint, fade, split_tone, vignette).
+ color_adjust_b: vec4<f32>,
+ // (grain amount, per-frame grain seed, grade-active flag, full-frame
+ // vignette flag).
+ grain_params: vec4<f32>,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@@ -131,6 +138,91 @@ fn rounded_rect_coverage(p: vec2<f32>, b: vec2<f32>, r: f32, rounding_type: f32)
return coverage * 0.25;
}
+// One-value hash with good distribution (same family as the background
+// layer's gradient noise); sin-free so it stays stable across GPU drivers.
+fn grain_hash(p: vec2<f32>) -> f32 {
+ var p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+// Applies the layer's color grade + film grain to a resolved video color.
+// Runs once per output pixel (after any motion-blur resolve), so its cost is
+// independent of blur tap counts, and ungraded layers skip everything in a
+// single coherent uniform branch.
+fn apply_color_grade(color: vec4<f32>, target_uv: vec2<f32>, frag_pos: vec2<f32>) -> vec4<f32> {
+ if uniforms.grain_params.z < 0.5 {
+ return color;
+ }
+
+ let exposure = uniforms.color_adjust_a.x;
+ let contrast = uniforms.color_adjust_a.y;
+ let saturation = uniforms.color_adjust_a.z;
+ let temperature = uniforms.color_adjust_a.w;
+ let tint = uniforms.color_adjust_b.x;
+ let fade = uniforms.color_adjust_b.y;
+ let split_tone = uniforms.color_adjust_b.z;
+ let vignette = uniforms.color_adjust_b.w;
+ let grain = uniforms.grain_params.x;
+
+ // Exposure in stops.
+ var rgb = color.rgb * exp2(exposure);
+
+ // White balance: temperature trades red against blue, tint trades green
+ // against magenta. Multiplicative so black stays black.
+ rgb = rgb * vec3<f32>(
+ 1.0 + 0.10 * temperature + 0.04 * tint,
+ 1.0 - 0.07 * tint,
+ 1.0 - 0.10 * temperature + 0.04 * tint,
+ );
+
+ // Contrast around mid gray.
+ rgb = (rgb - vec3<f32>(0.5)) * (1.0 + contrast) + vec3<f32>(0.5);
+
+ // Saturation via luma mix (-1 = grayscale).
+ let luma = dot(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), vec3<f32>(0.2126, 0.7152, 0.0722));
+ rgb = mix(vec3<f32>(luma), rgb, 1.0 + saturation);
+
+ // Split toning: teal into shadows, orange into highlights (reversed when
+ // the amount is negative), weighted by luma bands.
+ let shadow_w = 1.0 - smoothstep(0.2, 0.65, luma);
+ let highlight_w = smoothstep(0.35, 0.8, luma);
+ rgb += split_tone * (
+ shadow_w * vec3<f32>(-0.06, 0.02, 0.08) +
+ highlight_w * vec3<f32>(0.08, 0.02, -0.06)
+ );
+
+ // Film fade: raised blacks, gently dulled highlights.
+ rgb = rgb * (1.0 - 0.18 * fade) + vec3<f32>(0.09 * fade);
+
+ // Vignette. The screen computes it over the full output frame so the
+ // card and the graded background share one continuous field; the camera
+ // vignettes within its own card.
+ if vignette > 0.0 {
+ var vig_uv = target_uv;
+ if uniforms.grain_params.w > 0.5 {
+ vig_uv = frag_pos / uniforms.output_size;
+ }
+ let r = length((vig_uv - vec2<f32>(0.5)) * 2.0);
+ rgb = rgb * (1.0 - vignette * 0.65 * smoothstep(0.5, 1.5, r));
+ }
+
+ // Animated monochrome grain, peaked in the midtones like scanned film.
+ // The per-frame seed decorrelates the hash every frame.
+ if grain > 0.0 {
+ let seed = uniforms.grain_params.y;
+ let noise = grain_hash(frag_pos + vec2<f32>(seed * 17.0, seed * 29.0));
+ let graded_luma = dot(
+ clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)),
+ vec3<f32>(0.2126, 0.7152, 0.0722)
+ );
+ let response = 0.25 + 0.75 * (1.0 - abs(2.0 * graded_luma - 1.0));
+ rgb += (noise - 0.5) * grain * 0.35 * response;
+ }
+
+ return vec4<f32>(clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)), color.a);
+}
+
fn composite_source_over(foreground: vec4<f32>, background: vec4<f32>) -> vec4<f32> {
let alpha = foreground.a + background.a * (1.0 - foreground.a);
@@ -256,7 +348,7 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let zoom_amount = uniforms.motion_blur_params.z;
if !blur_active {
- return composite_source_over(base_color, shadow_color);
+ return composite_source_over(apply_color_grade(base_color, target_uv, p), shadow_color);
}
// Screen Studio semantics: the user amount is baked into the LENGTH of
@@ -270,7 +362,7 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
if blur_mode < 1.5 {
let velocity_uv = uniforms.motion_blur_vector;
if length(velocity_uv) < 1e-5 {
- return composite_source_over(base_color, shadow_color);
+ return composite_source_over(apply_color_grade(base_color, target_uv, p), shadow_color);
}
// 21-tap box along [0, +v]: matches the reference directional filter
@@ -291,14 +383,17 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
if out_alpha <= 0.0001 || alpha_sum <= 0.0001 {
return shadow_color;
}
- return composite_source_over(vec4(accum / alpha_sum, out_alpha), shadow_color);
+ return composite_source_over(
+ apply_color_grade(vec4(accum / alpha_sum, out_alpha), target_uv, p),
+ shadow_color
+ );
}
let zoom_center = uniforms.motion_blur_zoom_center;
let dir = zoom_center - target_uv;
let center_dist = length(dir);
if center_dist < 1e-4 || zoom_amount < 1e-4 {
- return composite_source_over(base_color, shadow_color);
+ return composite_source_over(apply_color_grade(base_color, target_uv, p), shadow_color);
}
// Radial blur toward the scale origin: ray length grows with distance
@@ -332,7 +427,10 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
if out_alpha <= 0.0001 {
return shadow_color;
}
- return composite_source_over(vec4(accum / alpha_sum, out_alpha), shadow_color);
+ return composite_source_over(
+ apply_color_grade(vec4(accum / alpha_sum, out_alpha), target_uv, p),
+ shadow_color
+ );
}
fn sample_texture(uv: vec2<f32>, crop_bounds_uv: vec4<f32>) -> vec4<f32> {