Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add keyboard overlay rendering layer with fade and character buildup

Cursor Agent5b121ee86837
diff --git a/crates/rendering/src/layers/keyboard.rs b/crates/rendering/src/layers/keyboard.rs
new file mode 100644
index 000000000..8e1e38517
--- /dev/null
+++ b/crates/rendering/src/layers/keyboard.rs
@@ -0,0 +1,595 @@
+use bytemuck::{Pod, Zeroable};
+use cap_project::XY;
+use glyphon::{
+ Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, SwashCache,
+ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Weight,
+};
+use log::warn;
+use wgpu::{Device, Queue, include_wgsl, util::DeviceExt};
+
+use crate::{DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, parse_color_component};
+
+#[repr(C)]
+#[derive(Copy, Clone, Pod, Zeroable, Debug)]
+struct KeyboardBackgroundUniforms {
+ rect: [f32; 4],
+ color: [f32; 4],
+ radius: f32,
+ _padding: [f32; 3],
+ _padding2: [f32; 4],
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum KeyboardPosition {
+ AboveCaptions,
+ TopLeft,
+ TopCenter,
+ TopRight,
+ BottomLeft,
+ BottomCenter,
+ BottomRight,
+}
+
+impl KeyboardPosition {
+ fn from_str(s: &str) -> Self {
+ match s {
+ "top-left" => Self::TopLeft,
+ "top-center" | "top" => Self::TopCenter,
+ "top-right" => Self::TopRight,
+ "bottom-left" => Self::BottomLeft,
+ "bottom-right" => Self::BottomRight,
+ "bottom-center" | "bottom" => Self::BottomCenter,
+ _ => Self::AboveCaptions,
+ }
+ }
+
+ fn y_factor(&self) -> f32 {
+ match self {
+ Self::TopLeft | Self::TopCenter | Self::TopRight => 0.08,
+ Self::AboveCaptions => 0.75,
+ Self::BottomLeft | Self::BottomCenter | Self::BottomRight => 0.85,
+ }
+ }
+}
+
+const BOUNCE_OFFSET_PIXELS: f32 = 6.0;
+
+pub struct KeyboardLayer {
+ font_system: FontSystem,
+ swash_cache: SwashCache,
+ text_atlas: TextAtlas,
+ text_renderer: TextRenderer,
+ text_buffer: Buffer,
+ viewport: Viewport,
+ background_pipeline: wgpu::RenderPipeline,
+ background_bind_group: wgpu::BindGroup,
+ background_uniform_buffer: wgpu::Buffer,
+ background_scissor: Option<[u32; 4]>,
+ output_size: (u32, u32),
+ has_content: bool,
+}
+
+impl KeyboardLayer {
+ pub fn new(device: &Device, queue: &Queue) -> Self {
+ let font_system = FontSystem::new();
+ let swash_cache = SwashCache::new();
+ let cache = Cache::new(device);
+ let viewport = Viewport::new(device, &cache);
+ let mut text_atlas = TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8Unorm);
+ let text_renderer = TextRenderer::new(
+ &mut text_atlas,
+ device,
+ wgpu::MultisampleState::default(),
+ None,
+ );
+
+ let metrics = Metrics::new(28.0, 28.0 * 1.2);
+ let text_buffer = Buffer::new_empty(metrics);
+
+ let background_uniforms = KeyboardBackgroundUniforms {
+ rect: [0.0; 4],
+ color: [0.0; 4],
+ radius: 0.0,
+ _padding: [0.0; 3],
+ _padding2: [0.0; 4],
+ };
+
+ let background_uniform_buffer =
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Keyboard Background Uniform Buffer"),
+ contents: bytemuck::bytes_of(&background_uniforms),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+
+ let background_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Keyboard Background Bind Group Layout"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+
+ let background_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Keyboard Background Bind Group"),
+ layout: &background_bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: background_uniform_buffer.as_entire_binding(),
+ }],
+ });
+
+ let background_shader =
+ device.create_shader_module(include_wgsl!("../shaders/caption_bg.wgsl"));
+
+ let background_pipeline_layout =
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Keyboard Background Pipeline Layout"),
+ bind_group_layouts: &[&background_bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let background_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Keyboard Background Pipeline"),
+ layout: Some(&background_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &background_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &background_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
+ Self {
+ font_system,
+ swash_cache,
+ text_atlas,
+ text_renderer,
+ text_buffer,
+ viewport,
+ background_pipeline,
+ background_bind_group,
+ background_uniform_buffer,
+ background_scissor: None,
+ output_size: (0, 0),
+ has_content: false,
+ }
+ }
+
+ pub fn prepare(
+ &mut self,
+ uniforms: &ProjectUniforms,
+ _segment_frames: &DecodedSegmentFrames,
+ output_size: XY<u32>,
+ constants: &RenderVideoConstants,
+ ) {
+ self.has_content = false;
+ self.background_scissor = None;
+ self.output_size = (output_size.x, output_size.y);
+
+ let Some(keyboard_data) = &uniforms.project.keyboard else {
+ return;
+ };
+
+ if !keyboard_data.settings.enabled {
+ return;
+ }
+
+ let timeline = match &uniforms.project.timeline {
+ Some(t) => t,
+ None => return,
+ };
+
+ if timeline.keyboard_segments.is_empty() {
+ return;
+ }
+
+ let current_time = uniforms.frame_number as f64 / uniforms.frame_rate as f64;
+ let settings = &keyboard_data.settings;
+ let fade_duration = settings.fade_duration as f64;
+ let linger_duration = settings.linger_duration as f64;
+
+ let active_segment = find_active_keyboard_segment(
+ current_time,
+ &timeline.keyboard_segments,
+ linger_duration,
+ fade_duration,
+ );
+
+ let Some(active) = active_segment else {
+ return;
+ };
+
+ let visible_text = build_visible_text(
+ &active.segment,
+ current_time,
+ );
+
+ if visible_text.is_empty() {
+ return;
+ }
+
+ let fade_opacity = calculate_fade(
+ current_time,
+ active.segment.start,
+ active.segment.end,
+ fade_duration,
+ linger_duration,
+ );
+
+ if fade_opacity <= 0.0 {
+ return;
+ }
+
+ let bounce_offset = calculate_keyboard_bounce(
+ current_time,
+ active.segment.start,
+ active.segment.end,
+ fade_duration,
+ );
+
+ let (width, height) = (output_size.x, output_size.y);
+ let device = &constants.device;
+ let queue = &constants.queue;
+
+ let position = active
+ .segment
+ .position_override
+ .as_deref()
+ .map(KeyboardPosition::from_str)
+ .unwrap_or_else(|| KeyboardPosition::from_str(&settings.position));
+
+ let margin = width as f32 * 0.05;
+
+ let color_hex = active
+ .segment
+ .color_override
+ .as_deref()
+ .unwrap_or(&settings.color);
+ let text_color = [
+ parse_color_component(color_hex, 0),
+ parse_color_component(color_hex, 1),
+ parse_color_component(color_hex, 2),
+ ];
+
+ let bg_color_hex = active
+ .segment
+ .background_color_override
+ .as_deref()
+ .unwrap_or(&settings.background_color);
+ let background_color_rgb = [
+ parse_color_component(bg_color_hex, 0),
+ parse_color_component(bg_color_hex, 1),
+ parse_color_component(bg_color_hex, 2),
+ ];
+
+ let background_alpha = ((settings.background_opacity as f32 / 100.0) * fade_opacity as f32)
+ .clamp(0.0, 1.0);
+
+ let font_size_base = active
+ .segment
+ .font_size_override
+ .unwrap_or(settings.size) as f32;
+ let font_size = font_size_base * (height as f32 / 1080.0);
+ let metrics = Metrics::new(font_size, font_size * 1.2);
+
+ let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);
+ let wrap_width = (width as f32 - margin * 2.0).max(font_size);
+ updated_buffer.set_size(&mut self.font_system, Some(wrap_width), None);
+
+ let font_family = match settings.font.as_str() {
+ "System Serif" => Family::Serif,
+ "System Monospace" => Family::Monospace,
+ _ => Family::SansSerif,
+ };
+
+ let weight = if settings.font_weight >= 700 {
+ Weight::BOLD
+ } else if settings.font_weight >= 500 {
+ Weight::MEDIUM
+ } else {
+ Weight::NORMAL
+ };
+
+ let text_alpha = (fade_opacity as f32).clamp(0.0, 1.0);
+ let color = Color::rgba(
+ (text_color[0] * 255.0) as u8,
+ (text_color[1] * 255.0) as u8,
+ (text_color[2] * 255.0) as u8,
+ (text_alpha * 255.0) as u8,
+ );
+
+ let attrs = Attrs::new().family(font_family).weight(weight).color(color);
+ updated_buffer.set_text(
+ &mut self.font_system,
+ &visible_text,
+ &attrs,
+ Shaping::Advanced,
+ );
+
+ let mut layout_width: f32 = 0.0;
+ let mut layout_height: f32 = 0.0;
+ for run in glyphon::cosmic_text::LayoutRunIter::new(&updated_buffer) {
+ layout_width = layout_width.max(run.line_w);
+ layout_height = layout_height.max(run.line_top + run.line_height);
+ }
+
+ if layout_height == 0.0 {
+ layout_height = font_size * 1.2;
+ layout_width = layout_width.max(font_size);
+ }
+
+ let available_width = (width as f32 - margin * 2.0).max(1.0);
+ let padding = font_size * 0.45;
+ let corner_radius = font_size * 0.5;
+ let text_width = layout_width.min(available_width);
+ let text_height = layout_height;
+ let box_width = (text_width + padding * 2.0).min(available_width).max(1.0);
+ let box_height = (text_height + padding * 2.0).min(height as f32).max(1.0);
+
+ let background_left = ((width as f32 - box_width) / 2.0).max(0.0);
+
+ let center_y = height as f32 * position.y_factor();
+ let base_background_top =
+ (center_y - box_height / 2.0).clamp(0.0, (height as f32 - box_height).max(0.0));
+ let background_top = (base_background_top + bounce_offset as f32)
+ .clamp(0.0, (height as f32 - box_height).max(0.0));
+
+ let text_left = background_left + padding;
+ let text_top = background_top + padding;
+
+ let bounds = TextBounds {
+ left: (text_left - 2.0).floor() as i32,
+ top: (text_top - 2.0).floor() as i32,
+ right: (text_left + text_width + 2.0).ceil() as i32,
+ bottom: (text_top + text_height + 2.0).ceil() as i32,
+ };
+
+ self.text_buffer = updated_buffer;
+ self.viewport.update(queue, Resolution { width, height });
+
+ let text_areas = vec![TextArea {
+ buffer: &self.text_buffer,
+ left: text_left,
+ top: text_top,
+ scale: 1.0,
+ bounds,
+ default_color: color,
+ custom_glyphs: &[],
+ }];
+
+ match self.text_renderer.prepare(
+ device,
+ queue,
+ &mut self.font_system,
+ &mut self.text_atlas,
+ &self.viewport,
+ text_areas,
+ &mut self.swash_cache,
+ ) {
+ Ok(_) => {}
+ Err(e) => warn!("Error preparing keyboard text: {e:?}"),
+ }
+
+ let rect = KeyboardBackgroundUniforms {
+ rect: [
+ background_left.max(0.0),
+ background_top.max(0.0),
+ box_width,
+ box_height,
+ ],
+ color: [
+ background_color_rgb[0],
+ background_color_rgb[1],
+ background_color_rgb[2],
+ background_alpha,
+ ],
+ radius: corner_radius.min(box_width / 2.0).min(box_height / 2.0),
+ _padding: [0.0; 3],
+ _padding2: [0.0; 4],
+ };
+
+ queue.write_buffer(
+ &self.background_uniform_buffer,
+ 0,
+ bytemuck::bytes_of(&rect),
+ );
+
+ let scissor_padding = 4.0;
+ let scissor_x = (background_left - scissor_padding).max(0.0).floor() as u32;
+ let scissor_y = (background_top - scissor_padding).max(0.0).floor() as u32;
+ let max_width = width.saturating_sub(scissor_x);
+ let max_height = height.saturating_sub(scissor_y);
+
+ if max_width == 0 || max_height == 0 {
+ self.has_content = false;
+ return;
+ }
+
+ let scissor_width = (box_width + scissor_padding * 2.0)
+ .ceil()
+ .max(1.0)
+ .min(max_width as f32) as u32;
+ let scissor_height = (box_height + scissor_padding * 2.0)
+ .ceil()
+ .max(1.0)
+ .min(max_height as f32) as u32;
+
+ if scissor_width == 0 || scissor_height == 0 {
+ self.has_content = false;
+ return;
+ }
+
+ self.background_scissor = Some([scissor_x, scissor_y, scissor_width, scissor_height]);
+ self.has_content = true;
+ }
+
+ pub fn has_content(&self) -> bool {
+ self.has_content
+ }
+
+ pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
+ if !self.has_content {
+ return;
+ }
+
+ if let Some([x, y, width, height]) = self.background_scissor {
+ pass.set_scissor_rect(x, y, width, height);
+ pass.set_pipeline(&self.background_pipeline);
+ pass.set_bind_group(0, &self.background_bind_group, &[]);
+ pass.draw(0..6, 0..1);
+ pass.set_scissor_rect(x, y, width, height);
+ } else if self.output_size.0 > 0 && self.output_size.1 > 0 {
+ pass.set_scissor_rect(0, 0, self.output_size.0, self.output_size.1);
+ }
+
+ match self
+ .text_renderer
+ .render(&self.text_atlas, &self.viewport, pass)
+ {
+ Ok(_) => {}
+ Err(e) => warn!("Error rendering keyboard text: {e:?}"),
+ }
+
+ if self.output_size.0 > 0 && self.output_size.1 > 0 {
+ pass.set_scissor_rect(0, 0, self.output_size.0, self.output_size.1);
+ }
+ }
+}
+
+struct ActiveKeyboardSegment<'a> {
+ segment: &'a cap_project::KeyboardTrackSegment,
+}
+
+fn find_active_keyboard_segment<'a>(
+ time: f64,
+ segments: &'a [cap_project::KeyboardTrackSegment],
+ linger_duration: f64,
+ fade_duration: f64,
+) -> Option<ActiveKeyboardSegment<'a>> {
+ let extended_end = linger_duration + fade_duration;
+
+ for segment in segments {
+ if time >= segment.start && time < segment.end {
+ return Some(ActiveKeyboardSegment { segment });
+ }
+ }
+
+ for segment in segments {
+ if time >= segment.end && time < segment.end + extended_end {
+ return Some(ActiveKeyboardSegment { segment });
+ }
+ }
+
+ None
+}
+
+fn build_visible_text(
+ segment: &cap_project::KeyboardTrackSegment,
+ current_time: f64,
+) -> String {
+ if segment.keys.is_empty() {
+ return segment.display_text.clone();
+ }
+
+ let time_offset_from_start = (current_time - segment.start) * 1000.0;
+
+ let mut visible = String::new();
+ let chars: Vec<char> = segment.display_text.chars().collect();
+
+ for (i, key) in segment.keys.iter().enumerate() {
+ if time_offset_from_start >= key.time_offset {
+ if i < chars.len() {
+ visible.push(chars[i]);
+ }
+ }
+ }
+
+ if visible.is_empty() && !segment.display_text.is_empty() {
+ visible.push(chars[0]);
+ }
+
+ visible
+}
+
+fn calculate_fade(
+ current_time: f64,
+ start: f64,
+ end: f64,
+ fade_duration: f64,
+ linger_duration: f64,
+) -> f32 {
+ if fade_duration <= 0.0 {
+ if current_time >= start && current_time < end + linger_duration {
+ return 1.0;
+ }
+ return 0.0;
+ }
+
+ let time_from_start = current_time - start;
+ let time_to_end = end - current_time;
+
+ let fade_in = (time_from_start / fade_duration).min(1.0) as f32;
+
+ let effective_time_to_end = time_to_end + linger_duration;
+ let fade_out = if effective_time_to_end > linger_duration {
+ 1.0
+ } else if effective_time_to_end > 0.0 {
+ (effective_time_to_end / fade_duration).min(1.0) as f32
+ } else {
+ 0.0
+ };
+
+ fade_in.min(fade_out).max(0.0)
+}
+
+fn calculate_keyboard_bounce(
+ current_time: f64,
+ start: f64,
+ end: f64,
+ fade_duration: f64,
+) -> f64 {
+ if fade_duration <= 0.0 {
+ return 0.0;
+ }
+
+ let time_from_start = current_time - start;
+ let time_to_end = end - current_time;
+
+ let fade_in_progress = (time_from_start / fade_duration).clamp(0.0, 1.0);
+ let fade_out_progress = (time_to_end / fade_duration).clamp(0.0, 1.0);
+
+ if fade_in_progress < 1.0 {
+ let ease = 1.0 - fade_in_progress;
+ -(ease * ease) * BOUNCE_OFFSET_PIXELS as f64
+ } else if fade_out_progress < 1.0 {
+ let ease = 1.0 - fade_out_progress;
+ (ease * ease) * BOUNCE_OFFSET_PIXELS as f64
+ } else {
+ 0.0
+ }
+}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index 536fbb3bf..7e727b27d 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -4,6 +4,7 @@ mod camera;
mod captions;
mod cursor;
mod display;
+mod keyboard;
mod mask;
mod text;
@@ -13,5 +14,6 @@ pub use camera::*;
pub use captions::*;
pub use cursor::*;
pub use display::*;
+pub use keyboard::*;
pub use mask::*;
pub use text::*;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index c74753409..2a72587cd 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -12,7 +12,7 @@ use futures::FutureExt;
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
- MaskLayer, TextLayer,
+ KeyboardLayer, MaskLayer, TextLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -2414,6 +2414,7 @@ pub struct RendererLayers {
mask: MaskLayer,
text: TextLayer,
captions: CaptionsLayer,
+ keyboard: KeyboardLayer,
}
impl RendererLayers {
@@ -2436,6 +2437,7 @@ impl RendererLayers {
mask: MaskLayer::new(device),
text: TextLayer::new(device, queue),
captions: CaptionsLayer::new(device, queue),
+ keyboard: KeyboardLayer::new(device, queue),
}
}
@@ -2537,6 +2539,13 @@ impl RendererLayers {
constants,
);
+ self.keyboard.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
+ );
+
Ok(())
}
@@ -2618,6 +2627,13 @@ impl RendererLayers {
constants,
);
+ self.keyboard.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
+ );
+
Ok(())
}
@@ -2705,6 +2721,11 @@ impl RendererLayers {
self.text.render(&mut pass);
}
+ if self.keyboard.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ self.keyboard.render(&mut pass);
+ }
+
if self.captions.has_content() {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.captions.render(&mut pass);