Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: align cursor overlays with per-clip display geometry
Richie McIlroy9841043552c3
diff --git a/apps/desktop-gpui/src/screenshot_editor.rs b/apps/desktop-gpui/src/screenshot_editor.rsindex 3504b6059..0b8f6db08 100644--- a/apps/desktop-gpui/src/screenshot_editor.rs+++ b/apps/desktop-gpui/src/screenshot_editor.rs@@ -291,6 +291,7 @@ async fn render_still(resolution_base: Option<cap_project::XY<u32>>,) -> Result<RenderedFrame, String> {let segment_frames = DecodedSegmentFrames {+ screen_size: cap_project::XY::new(source.width(), source.height()),screen_frame: Some(source.clone()),camera_frame: None,segment_time: 0.0,diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 8b5886e82..aa5c89efa 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -1575,7 +1575,7 @@ async fn generate_export_preview_inner(.decoders.get_frames(segment_time as f32,- !project_config.camera.hide,+ !project_config.camera.hide && render_segment.render_display,render_segment.render_display,clip_config.map(|v| v.offsets).unwrap_or_default(),)@@ -1629,7 +1629,7 @@ async fn generate_export_preview_inner(.decoders.get_frames(outgoing.source_time as f32,- !project_config.camera.hide,+ !project_config.camera.hide && outgoing_segment.render_display,outgoing_segment.render_display,outgoing_offsets,)@@ -1933,7 +1933,7 @@ async fn generate_export_preview_fast_inner(.decoders.get_frames(segment_time as f32,- !project_config.camera.hide,+ !project_config.camera.hide && !settings.cursor_only,!settings.cursor_only,clip_config.map(|v| v.offsets).unwrap_or_default(),)@@ -1987,7 +1987,7 @@ async fn generate_export_preview_fast_inner(.decoders.get_frames(outgoing.source_time as f32,- !project_config.camera.hide,+ !project_config.camera.hide && !settings.cursor_only,!settings.cursor_only,outgoing_offsets,)diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rsindex fbecc7a14..c2760a8fb 100644--- a/apps/desktop/src-tauri/src/screenshot_editor.rs+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs@@ -407,6 +407,10 @@ impl ScreenshotEditorInstances {break;}let segment_frames = DecodedSegmentFrames {+ screen_size: cap_project::XY::new(+ decoded_frame.width(),+ decoded_frame.height(),+ ),screen_frame: Some(DecodedFrame::new(decoded_frame.data().to_vec(),decoded_frame.width(),@@ -876,6 +880,7 @@ pub async fn prewarm_screenshot_renderer() {);let segment_frames = DecodedSegmentFrames {+ screen_size: cap_project::XY::new(width, height),screen_frame: Some(DecodedFrame::new(vec![255u8; (width * height * 4) as usize],width,@@ -1681,6 +1686,7 @@ pub async fn render_screenshot_png(instance: &ScreenshotEditorInstance) -> Resul);let decoded_frame = DecodedFrame::new(data, width, height);let segment_frames = DecodedSegmentFrames {+ screen_size: cap_project::XY::new(width, height),screen_frame: Some(DecodedFrame::new(decoded_frame.data().to_vec(),decoded_frame.width(),diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rsindex 9ed8a42df..33a042bf7 100644--- a/crates/editor/src/playback.rs+++ b/crates/editor/src/playback.rs@@ -1767,6 +1767,7 @@ mod tests {fn decoded_frames(bytes: usize) -> DecodedSegmentFrames {DecodedSegmentFrames {+ screen_size: XY::new(1, 1),screen_frame: Some(DecodedFrame::new(vec![0; bytes], 1, 1)),camera_frame: None,segment_time: 0.0,diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex b4857ff2a..e6ec17d38 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -190,20 +190,17 @@ pub fn make_cursor_only_project(mut project_config: ProjectConfiguration) -> Proproject_config.background.shadow = 0.0;project_config.background.advanced_shadow = None;project_config.background.border = None;- project_config.camera.hide = true;project_config.captions = None;project_config.keyboard = None;if let Some(timeline) = project_config.timeline.as_mut() {timeline.mask_segments.clear();// Fullscreen text segments pause the recording clock (holds), which- // shapes the frame count and cursor motion; dropping them would- // desync this overlay pass from the main render. Keep them as- // invisible placeholders (empty content draws nothing) and only- // remove overlay-layout texts.+ // shapes the frame count and cursor motion. Split titles also move+ // the cursor with the display, so both need invisible placeholders.timeline.text_segments- .retain(|text| text.layout == cap_project::TextLayout::Fullscreen);+ .retain(|text| text.layout != cap_project::TextLayout::Overlay);for text in &mut timeline.text_segments {text.content.clear();}@@ -246,3 +243,58 @@ impl ExporterBase {}}}++#[cfg(test)]+mod cursor_only_tests {+ use super::*;+ use cap_project::TextLayout;++ #[test]+ fn cursor_only_preserves_layout_and_recording_time_without_title_pixels() {+ for hide_camera in [false, true] {+ let mut project = ProjectConfiguration::default();+ project.camera.hide = hide_camera;+ project.timeline = Some(+ serde_json::from_value(serde_json::json!({+ "segments": [{ "start": 0.0, "end": 8.0, "timescale": 1.0 }],+ "zoomSegments": [],+ "sceneSegments": [{ "start": 1.0, "end": 3.0, "mode": "splitScreen" }],+ "textSegments": [+ { "start": 0.0, "end": 1.0, "layout": "overlay" },+ { "start": 1.0, "end": 2.0, "layout": "fullscreen" },+ { "start": 2.0, "end": 3.0, "layout": "splitLeft" },+ { "start": 3.0, "end": 4.0, "layout": "splitRight" }+ ]+ }))+ .unwrap(),+ );+ let duration = project.timeline.as_ref().unwrap().duration();+ let cursor_only = make_cursor_only_project(project);+ let timeline = cursor_only.timeline.unwrap();+ assert_eq!(cursor_only.camera.hide, hide_camera);+ assert_eq!(timeline.duration(), duration);+ assert_eq!(+ timeline+ .text_segments+ .iter()+ .map(|text| text.layout)+ .collect::<Vec<_>>(),+ [+ TextLayout::Fullscreen,+ TextLayout::SplitLeft,+ TextLayout::SplitRight+ ],+ );+ assert!(+ timeline+ .text_segments+ .iter()+ .all(|text| text.content.is_empty())+ );+ assert!(matches!(+ timeline.scene_segments[0].mode,+ cap_project::SceneMode::SplitScreen+ ));+ }+ }+}diff --git a/crates/export/src/preview.rs b/crates/export/src/preview.rsindex ade1845d7..682ea44be 100644--- a/crates/export/src/preview.rs+++ b/crates/export/src/preview.rs@@ -104,7 +104,7 @@ async fn render_preview_with_base(.decoders.get_frames(segment_time as f32,- !exporter_base.project_config.camera.hide,+ !exporter_base.project_config.camera.hide && !settings.cursor_only,!settings.cursor_only,clip_config.map(|v| v.offsets).unwrap_or_default(),)@@ -165,7 +165,7 @@ async fn render_preview_with_base(.decoders.get_frames(outgoing.source_time as f32,- !exporter_base.project_config.camera.hide,+ !exporter_base.project_config.camera.hide && !settings.cursor_only,!settings.cursor_only,outgoing_offsets,)diff --git a/crates/rendering/examples/background-benchmark.rs b/crates/rendering/examples/background-benchmark.rsindex c0b2bc554..c14db8d22 100644--- a/crates/rendering/examples/background-benchmark.rs+++ b/crates/rendering/examples/background-benchmark.rs@@ -90,6 +90,7 @@ fn default_cases() -> Vec<Case> {fn segment(source: &DecodedFrame, frame: u32) -> DecodedSegmentFrames {DecodedSegmentFrames {+ screen_size: XY::new(source.width(), source.height()),screen_frame: Some(source.clone()),camera_frame: None,segment_time: frame as f32 / 60.0,diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rsindex c6510b784..ebe9063cf 100644--- a/crates/rendering/src/composite_frame.rs+++ b/crates/rendering/src/composite_frame.rs@@ -1,4 +1,5 @@use bytemuck::{Pod, Zeroable};+use cap_project::XY;use wgpu::{include_wgsl, util::DeviceExt};pub struct CompositeVideoFramePipeline {@@ -206,6 +207,60 @@ impl ColorGradeUniformParams {}impl CompositeVideoFrameUniforms {+ pub(crate) fn for_source_frame(mut self, source_size: XY<u32>) -> Self {+ let scale_x = source_size.x as f32 / self.frame_size[0].max(1.0);+ let scale_y = source_size.y as f32 / self.frame_size[1].max(1.0);++ self.crop_bounds = [+ self.crop_bounds[0] * scale_x,+ self.crop_bounds[1] * scale_y,+ self.crop_bounds[2] * scale_x,+ self.crop_bounds[3] * scale_y,+ ];+ self.frame_size = [source_size.x as f32, source_size.y as f32];++ let crop_w = self.crop_bounds[2] - self.crop_bounds[0];+ let crop_h = self.crop_bounds[3] - self.crop_bounds[1];+ let target_w = self.target_bounds[2] - self.target_bounds[0];+ let target_h = self.target_bounds[3] - self.target_bounds[1];++ if crop_w > 0.0 && crop_h > 0.0 && target_w > 0.0 && target_h > 0.0 {+ let source_aspect = crop_w / crop_h;+ let target_aspect = target_w / target_h;++ if (source_aspect - target_aspect).abs() > 0.001 {+ let scale = (target_w / crop_w).min(target_h / crop_h);+ let fitted_w = crop_w * scale;+ let fitted_h = crop_h * scale;+ let new_x0 = self.target_bounds[0] + (target_w - fitted_w) * 0.5;+ let new_y0 = self.target_bounds[1] + (target_h - fitted_h) * 0.5;++ self.target_bounds = [new_x0, new_y0, new_x0 + fitted_w, new_y0 + fitted_h];+ self.target_size = [fitted_w, fitted_h];+ }+ }++ self+ }++ pub(crate) fn source_uv_to_target(&self, position: XY<f64>) -> XY<f64> {+ let crop_size = XY::new(+ (self.crop_bounds[2] - self.crop_bounds[0]).max(f32::EPSILON) as f64,+ (self.crop_bounds[3] - self.crop_bounds[1]).max(f32::EPSILON) as f64,+ );+ let source_position =+ position * XY::new(self.frame_size[0] as f64, self.frame_size[1] as f64);+ let mut position_in_crop = (source_position+ - XY::new(self.crop_bounds[0] as f64, self.crop_bounds[1] as f64))+ / crop_size;+ if self.mirror_x != 0.0 {+ position_in_crop.x = 1.0 - position_in_crop.x;+ }++ XY::new(self.target_bounds[0] as f64, self.target_bounds[1] as f64)+ + position_in_crop * XY::new(self.target_size[0] as f64, self.target_size[1] as f64)+ }+pub fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {device.create_buffer_init(&(wgpu::util::BufferInitDescriptor {diff --git a/crates/rendering/src/layers/animated_gradient.rs b/crates/rendering/src/layers/animated_gradient.rsindex 49a0a7ccc..5890f99f9 100644--- a/crates/rendering/src/layers/animated_gradient.rs+++ b/crates/rendering/src/layers/animated_gradient.rs@@ -401,6 +401,7 @@ mod tests {let project = ProjectConfiguration::default();let cursor = CursorEvents::default();let frames = DecodedSegmentFrames {+ screen_size: constants.options.screen_size,screen_frame: None,camera_frame: None,segment_time: frame as f32 / 30.0,diff --git a/crates/rendering/src/layers/click_ripple.rs b/crates/rendering/src/layers/click_ripple.rsindex d7e03c7ca..895ff0606 100644--- a/crates/rendering/src/layers/click_ripple.rs+++ b/crates/rendering/src/layers/click_ripple.rs@@ -3,7 +3,7 @@ use cap_project::XY;use wgpu::{include_wgsl, util::DeviceExt};use super::cursor::{CursorPlacement, cursor_height_px};-use crate::{Coord, FrameSpace, ProjectUniforms, RenderVideoConstants, zoom::InterpolatedZoom};+use crate::{Coord, FrameSpace, ProjectUniforms, RenderVideoConstants};/// Ripples older than this are dropped rather than queued, so a burst of/// clicks can never grow the uniform buffer.@@ -145,13 +145,7 @@ impl ClickRippleLayer {}}- pub fn prepare(- &mut self,- uniforms: &ProjectUniforms,- resolution_base: XY<u32>,- zoom: &InterpolatedZoom,- constants: &RenderVideoConstants,- ) {+ pub fn prepare(&mut self, uniforms: &ProjectUniforms, constants: &RenderVideoConstants) {self.instance_count = 0;if uniforms.click_ripples.is_empty() {@@ -166,13 +160,11 @@ impl ClickRippleLayer {ripple.strength_clamped(),];- let crop = ProjectUniforms::get_crop(&constants.options, &uniforms.project);- let display_size =- ProjectUniforms::display_size(&constants.options, &uniforms.project, resolution_base);+ let display = &uniforms.display;let radius = cursor_height_px(- constants.options.screen_size.y as f32,- crop.size.y as f32,- display_size.y as f32,+ display.frame_size[1],+ display.crop_bounds[3] - display.crop_bounds[1],+ display.target_size[1],uniforms.cursor_size,1.0,) * RIPPLE_RADIUS_SCALE@@ -185,12 +177,7 @@ impl ClickRippleLayer {let quad_side = (radius * 2.0 * RIPPLE_QUAD_EXTENT) as f64;let size = Coord::<FrameSpace>::new(XY::new(quad_side, quad_side));let hotspot = XY::new(0.5, 0.5);- let placement = CursorPlacement {- constants,- uniforms,- resolution_base,- zoom,- };+ let placement = CursorPlacement { uniforms };let mut slots = [0u8; MAX_CLICK_RIPPLES * SLOT_SIZE as usize];let mut count = 0usize;diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rsindex 21dcb3d24..9e8e4b63f 100644--- a/crates/rendering/src/layers/cursor.rs+++ b/crates/rendering/src/layers/cursor.rs@@ -7,9 +7,8 @@ use tracing::error;use wgpu::{BindGroup, FilterMode, include_wgsl, util::DeviceExt};use crate::{- Coord, DecodedSegmentFrames, FrameSpace, ProjectUniforms, RawDisplayUVSpace,- RenderVideoConstants, STANDARD_CURSOR_HEIGHT, composite_frame::ColorGradeUniformParams,- zoom::InterpolatedZoom,+ Coord, DecodedSegmentFrames, FrameSpace, ProjectUniforms, RenderVideoConstants,+ STANDARD_CURSOR_HEIGHT, composite_frame::ColorGradeUniformParams,};const CURSOR_CLICK_DURATION: f64 = 0.13;@@ -378,9 +377,7 @@ impl CursorLayer {pub fn prepare(&mut self,segment_frames: &DecodedSegmentFrames,- resolution_base: XY<u32>,cursor: &CursorEvents,- zoom: &InterpolatedZoom,uniforms: &ProjectUniforms,constants: &RenderVideoConstants,) {@@ -407,7 +404,6 @@ impl CursorLayer {}let fps = uniforms.frame_rate.max(1) as f32;- let screen_size = constants.options.screen_size;let fps_scale = fps / CURSOR_BASELINE_FPS;let cursor_strength = (uniforms.motion_blur_amount * CURSOR_MULTIPLIER * fps_scale).clamp(0.0, CURSOR_MAX_STRENGTH);@@ -416,14 +412,11 @@ impl CursorLayer {.as_ref().filter(|prev| prev.cursor_id == interpolated_cursor.cursor_id).map(|prev| {- let delta_uv = XY::new(- (interpolated_cursor.position.coord.x - prev.position.coord.x) as f32,- (interpolated_cursor.position.coord.y - prev.position.coord.y) as f32,- );- XY::new(- delta_uv.x * screen_size.x as f32,- delta_uv.y * screen_size.y as f32,- )+ let current = uniforms+ .display+ .source_uv_to_target(interpolated_cursor.position.coord);+ let previous = uniforms.display.source_uv_to_target(prev.position.coord);+ (current - previous).map(|value| value as f32)}).unwrap_or_else(|| XY::new(0.0, 0.0));@@ -512,16 +505,11 @@ impl CursorLayer {let size = {let click_t = get_click_t(&cursor.clicks, (time_s as f64) * 1000.0);let click_scale_factor = click_t * 1.0 + (1.0 - click_t) * CLICK_SHRINK_SIZE;- let crop = ProjectUniforms::get_crop(&constants.options, &uniforms.project);- let display_size = ProjectUniforms::display_size(- &constants.options,- &uniforms.project,- resolution_base,- );+ let display = &uniforms.display;let size = cursor_height_px(- constants.options.screen_size.y as f32,- crop.size.y as f32,- display_size.y as f32,+ display.frame_size[1],+ display.crop_bounds[3] - display.crop_bounds[1],+ display.target_size[1],uniforms.cursor_size,click_scale_factor,);@@ -542,13 +530,7 @@ impl CursorLayer {})};- let (position_size, cursor_opacity) = CursorPlacement {- constants,- uniforms,- resolution_base,- zoom,- }- .map(+ let (position_size, cursor_opacity) = CursorPlacement { uniforms }.map(interpolated_cursor.position.coord,size,cursor_texture.hotspot,@@ -614,15 +596,8 @@ impl CursorLayer {}}-/// The cursor sprite's output-rect chain: frame space minus hotspot -> zoomed-/// frame space -> split-screen pane remap -> text-takeover affine. The click-/// ripple has to land in exactly the same place as the sprite it sits under,-/// so both go through here.pub(crate) struct CursorPlacement<'a> {- pub constants: &'a RenderVideoConstants,pub uniforms: &'a ProjectUniforms,- pub resolution_base: XY<u32>,- pub zoom: &'a InterpolatedZoom,}impl CursorPlacement<'_> {@@ -633,115 +608,17 @@ impl CursorPlacement<'_> {hotspot_frac: XY<f64>,opacity: f32,) -> ([f32; 4], f32) {- let hotspot = Coord::<FrameSpace>::new(size.coord * hotspot_frac);-- let position = Coord::<RawDisplayUVSpace>::new(position_uv).to_frame_space(- &self.constants.options,- &self.uniforms.project,- self.resolution_base,- ) - hotspot;-- // Transform to zoomed space- let zoomed_position = position.to_zoomed_frame_space(- &self.constants.options,- &self.uniforms.project,- self.resolution_base,- self.zoom,- );-- let zoomed_size = (position + size).to_zoomed_frame_space(- &self.constants.options,- &self.uniforms.project,- self.resolution_base,- self.zoom,- ) - zoomed_position;-- // In split-screen the screen only occupies a half-rect, so remap the- // cursor from its raw source UV into that pane (matching the display- // layer's split crop -> half-rect mapping) and scale the sprite by the- // same factor. The cursor shader's screen_bounds clip already follows- // uniforms.display.target_bounds (the morphing half), so a cursor that- // lands outside the visible crop is confined automatically.- let position_size = match &self.uniforms.split {- Some(split) if split.factor > 0.001 => {- let screen_size = self.constants.options.screen_size;- let crop =- ProjectUniforms::get_crop(&self.constants.options, &self.uniforms.project);- let display_size = ProjectUniforms::display_size(- &self.constants.options,- &self.uniforms.project,- self.resolution_base,- );-- let scrop = split.screen.crop;- let starget = split.screen.target;- let crop_w = (scrop[2] - scrop[0]).max(f32::EPSILON);- let crop_h = (scrop[3] - scrop[1]).max(f32::EPSILON);- let target_w = starget[2] - starget[0];- let target_h = starget[3] - starget[1];-- let cursor_px = [- position_uv.x as f32 * screen_size.x as f32,- position_uv.y as f32 * screen_size.y as f32,- ];- let tip = [- starget[0] + (cursor_px[0] - scrop[0]) / crop_w * target_w,- starget[1] + (cursor_px[1] - scrop[1]) / crop_h * target_h,- ];-- // Source->pane scale (uniform; the split crop matches the pane- // aspect) relative to the normal source->frame scale.- let normal_scale = display_size.x as f32 / (crop.size.x as f32).max(f32::EPSILON);- let size_factor = (target_w / crop_w) / normal_scale.max(f32::EPSILON);-- let split_pos = [- tip[0] - hotspot.x as f32 * size_factor,- tip[1] - hotspot.y as f32 * size_factor,- ];- let split_size = [size.x as f32 * size_factor, size.y as f32 * size_factor];-- let t = split.factor as f32;- [- crate::lerp_f32(zoomed_position.x as f32, split_pos[0], t),- crate::lerp_f32(zoomed_position.y as f32, split_pos[1], t),- crate::lerp_f32(zoomed_size.x as f32, split_size[0], t),- crate::lerp_f32(zoomed_size.y as f32, split_size[1], t),- ]- }- _ => [- zoomed_position.x as f32,- zoomed_position.y as f32,- zoomed_size.x as f32,- zoomed_size.y as f32,- ],- };-- // A text takeover relocates the display card by a uniform scale +- // translate (the takeover target preserves the card's aspect), so the- // cursor follows with the same affine map — and fades with the card- // when a Fullscreen takeover hides it.- let (position_size, opacity) = match &self.uniforms.takeover {- Some(takeover) if takeover.t > 0.001 => {- let from_w = (takeover.from[2] - takeover.from[0]).max(f32::EPSILON);- let scale = (takeover.to[2] - takeover.to[0]) / from_w;- let mapped = [- takeover.to[0] + (position_size[0] - takeover.from[0]) * scale,- takeover.to[1] + (position_size[1] - takeover.from[1]) * scale,- position_size[2] * scale,- position_size[3] * scale,- ];- let t = takeover.t;- (- [- crate::lerp_f32(position_size[0], mapped[0], t),- crate::lerp_f32(position_size[1], mapped[1], t),- crate::lerp_f32(position_size[2], mapped[2], t),- crate::lerp_f32(position_size[3], mapped[3], t),- ],- opacity * takeover.overlay_fade,- )- }- _ => (position_size, opacity),+ let hotspot = size.coord * hotspot_frac;+ let position = self.uniforms.display.source_uv_to_target(position_uv) - hotspot;+ let position_size = [+ position.x as f32,+ position.y as f32,+ size.x as f32,+ size.y as f32,+ ];+ let opacity = match &self.uniforms.takeover {+ Some(takeover) if takeover.t > 0.001 => opacity * takeover.overlay_fade,+ _ => opacity,};(position_size, opacity)}@@ -1267,32 +1144,11 @@ mod tests {}#[test]- fn cursor_height_is_zoomed_once_by_frame_transform() {- let options = crate::RenderOptions {- camera_size: None,- screen_size: XY::new(1080, 1080),- preserve_screen_alpha: false,- };- let mut project = ProjectConfiguration::default();- project.background.padding = 0.0;- let resolution_base = XY::new(1080, 1080);- let zoom = InterpolatedZoom {- t: 1.0,- bounds: crate::zoom::SegmentBounds::new(XY::new(0.0, 0.0), XY::new(2.0, 2.0)),- };- let position = Coord::<FrameSpace>::new(XY::new(0.0, 0.0));- let size = Coord::<FrameSpace>::new(XY::new(- 0.0,- cursor_height_px(1080.0, 1080.0, 1080.0, 100.0, 1.0) as f64,- ));-- let zoomed_position =- position.to_zoomed_frame_space(&options, &project, resolution_base, &zoom);- let zoomed_size =- (position + size).to_zoomed_frame_space(&options, &project, resolution_base, &zoom)- - zoomed_position;-- assert!((zoomed_size.y as f32 - STANDARD_CURSOR_HEIGHT * 2.0).abs() < 0.001);+ fn cursor_height_uses_the_fitted_zoomed_display_once() {+ for source_height in [540.0, 1080.0, 2160.0] {+ let height = cursor_height_px(source_height, source_height, 2160.0, 100.0, 1.0);+ assert!((height - STANDARD_CURSOR_HEIGHT * 2.0).abs() < 0.001);+ }}#[test]diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rsindex d4de70fa3..595585eeb 100644--- a/crates/rendering/src/layers/display.rs+++ b/crates/rendering/src/layers/display.rs@@ -15,52 +15,6 @@ struct PendingTextureCopy {dst_texture_index: usize,}-fn uniforms_for_source_frame(- mut uniforms: CompositeVideoFrameUniforms,- base_size: XY<u32>,- source_size: XY<u32>,-) -> CompositeVideoFrameUniforms {- let scale_x = source_size.x as f32 / base_size.x.max(1) as f32;- let scale_y = source_size.y as f32 / base_size.y.max(1) as f32;-- uniforms.crop_bounds = [- uniforms.crop_bounds[0] * scale_x,- uniforms.crop_bounds[1] * scale_y,- uniforms.crop_bounds[2] * scale_x,- uniforms.crop_bounds[3] * scale_y,- ];- uniforms.frame_size = [source_size.x as f32, source_size.y as f32];-- // The shader stretches the cropped source across the whole target rect. When a- // clip's aspect differs from the target rect (e.g. an imported clip recorded at- // a different resolution than the project's first clip), shrink the target rect- // to the clip's aspect and centre it ("contain") so the clip is never stretched;- // the leftover margins stay transparent and the project background shows through.- // Same-sized clips keep an identical aspect, so this is a no-op for them.- let crop_w = uniforms.crop_bounds[2] - uniforms.crop_bounds[0];- let crop_h = uniforms.crop_bounds[3] - uniforms.crop_bounds[1];- let target_w = uniforms.target_bounds[2] - uniforms.target_bounds[0];- let target_h = uniforms.target_bounds[3] - uniforms.target_bounds[1];-- if crop_w > 0.0 && crop_h > 0.0 && target_w > 0.0 && target_h > 0.0 {- let source_aspect = crop_w / crop_h;- let target_aspect = target_w / target_h;-- if (source_aspect - target_aspect).abs() > 0.001 {- let scale = (target_w / crop_w).min(target_h / crop_h);- let fitted_w = crop_w * scale;- let fitted_h = crop_h * scale;- let new_x0 = uniforms.target_bounds[0] + (target_w - fitted_w) * 0.5;- let new_y0 = uniforms.target_bounds[1] + (target_h - fitted_h) * 0.5;-- uniforms.target_bounds = [new_x0, new_y0, new_x0 + fitted_w, new_y0 + fitted_h];- uniforms.target_size = [fitted_w, fitted_h];- }- }-- uniforms-}-pub struct DisplayLayer {frame_textures: [wgpu::Texture; 2],frame_texture_views: [wgpu::TextureView; 2],@@ -200,7 +154,6 @@ impl DisplayLayer {let actual_width = screen_frame.width();let actual_height = screen_frame.height();let source_size = XY::new(actual_width, actual_height);- let uniforms = uniforms_for_source_frame(uniforms, frame_size, source_size);let format = screen_frame.format();let current_recording_time = segment_frames.recording_time;let frame_storage = screen_frame.storage_identity();@@ -573,7 +526,6 @@ impl DisplayLayer {device: &wgpu::Device,queue: &wgpu::Queue,segment_frames: &DecodedSegmentFrames,- frame_size: XY<u32>,uniforms: CompositeVideoFrameUniforms,encoder: &mut wgpu::CommandEncoder,) -> bool {@@ -590,7 +542,6 @@ impl DisplayLayer {let actual_width = screen_frame.width();let actual_height = screen_frame.height();let source_size = XY::new(actual_width, actual_height);- let uniforms = uniforms_for_source_frame(uniforms, frame_size, source_size);let format = screen_frame.format();let current_recording_time = segment_frames.recording_time;let frame_storage = screen_frame.storage_identity();diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 4593c6355..da28e5b9b 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -451,6 +451,8 @@ impl RecordingSegmentDecoders {offsets: ClipOffsets,) -> Option<DecodedSegmentFrames> {let camera_request_time = segment_time + offsets.camera;+ let (screen_width, screen_height) = self.screen_video_dimensions();+ let screen_size = XY::new(screen_width, screen_height);if needs_display {let (screen, camera) = tokio::join!(@@ -472,6 +474,7 @@ impl RecordingSegmentDecoders {}Some(DecodedSegmentFrames {+ screen_size,screen_frame: Some(screen?),camera_frame,segment_time,@@ -497,6 +500,7 @@ impl RecordingSegmentDecoders {);Some(DecodedSegmentFrames {+ screen_size,screen_frame: None,camera_frame,segment_time,@@ -514,6 +518,8 @@ impl RecordingSegmentDecoders {offsets: ClipOffsets,) -> Option<DecodedSegmentFrames> {let camera_request_time = segment_time + offsets.camera;+ let (screen_width, screen_height) = self.screen_video_dimensions();+ let screen_size = XY::new(screen_width, screen_height);if needs_display {let (screen, camera) = tokio::join!(@@ -531,6 +537,7 @@ impl RecordingSegmentDecoders {let camera_frame = camera.flatten();Some(DecodedSegmentFrames {+ screen_size,screen_frame: Some(screen?),camera_frame,segment_time,@@ -556,6 +563,7 @@ impl RecordingSegmentDecoders {);Some(DecodedSegmentFrames {+ screen_size,screen_frame: None,camera_frame,segment_time,@@ -772,7 +780,7 @@ pub async fn render_video_to_channel(decode_segment_frames_with_retry(&render_segment.decoders,segment_time,- needs_camera,+ needs_camera && render_segment.render_display,render_segment.render_display,clip_config.map(|v| v.offsets).unwrap_or_default(),current_frame_number,@@ -785,7 +793,7 @@ pub async fn render_video_to_channel(decode_segment_frames_with_retry(&render_segment.decoders,segment_time,- needs_camera,+ needs_camera && render_segment.render_display,render_segment.render_display,clip_config.map(|v| v.offsets).unwrap_or_default(),current_frame_number,@@ -849,7 +857,7 @@ pub async fn render_video_to_channel(Some(decode_segment_frames_with_retry(&next_render_segment.decoders,next_seg_time,- needs_camera,+ needs_camera && next_render_segment.render_display,next_render_segment.render_display,next_clip_config.map(|v| v.offsets).unwrap_or_default(),next_frame_number,@@ -1246,7 +1254,7 @@ pub async fn render_video_to_channel_nv12(decode_segment_frames_with_retry(&render_segment.decoders,segment_time,- needs_camera,+ needs_camera && render_segment.render_display,render_segment.render_display,clip_config.map(|v| v.offsets).unwrap_or_default(),current_frame_number,@@ -1259,7 +1267,7 @@ pub async fn render_video_to_channel_nv12(decode_segment_frames_with_retry(&render_segment.decoders,segment_time,- needs_camera,+ needs_camera && render_segment.render_display,render_segment.render_display,clip_config.map(|v| v.offsets).unwrap_or_default(),current_frame_number,@@ -1324,7 +1332,7 @@ pub async fn render_video_to_channel_nv12(Some(decode_segment_frames_with_retry(&next_render_segment.decoders,next_seg_time,- needs_camera,+ needs_camera && next_render_segment.render_display,next_render_segment.render_display,next_clip_config.map(|v| v.offsets).unwrap_or_default(),next_frame_number,@@ -1696,7 +1704,7 @@ async fn decode_timeline_source_frames(decode_segment_frames_with_retry(&render_segment.decoders,source.source_time,- needs_camera,+ needs_camera && render_segment.render_display,render_segment.render_display,clip_config.map(|clip| clip.offsets).unwrap_or_default(),current_frame_number,@@ -4126,6 +4134,19 @@ impl ProjectUniforms {)};+ let source_size = segment_frames+ .screen_frame+ .as_ref()+ .map_or(segment_frames.screen_size, |frame| {+ XY::new(frame.width(), frame.height())+ });+ let display = display.for_source_frame(source_size);+ let display_outer_bounds = if frame_chrome.is_none() {+ display.target_bounds+ } else {+ display_outer_bounds+ };+let camera = options.camera_size.filter(|_| !project.camera.hide && scene.should_render_camera())@@ -5020,6 +5041,7 @@ mod tests {#[derive(Clone)]pub struct DecodedSegmentFrames {+ pub screen_size: XY<u32>,pub screen_frame: Option<DecodedFrame>,pub camera_frame: Option<DecodedFrame>,pub segment_time: f32,@@ -5109,6 +5131,7 @@ mod nv12_flush_tests {moves: vec![],};let frames = DecodedSegmentFrames {+ screen_size: XY::new(4, 4),screen_frame: None,camera_frame: None,segment_time: 0.0,@@ -6225,21 +6248,10 @@ impl RendererLayers {);}- self.click_ripple.prepare(- uniforms,- uniforms.resolution_base,- &uniforms.zoom,- constants,- );+ self.click_ripple.prepare(uniforms, constants);- self.cursor.prepare(- segment_frames,- uniforms.resolution_base,- cursor,- &uniforms.zoom,- uniforms,- constants,- );+ self.cursor+ .prepare(segment_frames, cursor, uniforms, constants);let camera_frame_data = if segment_frames.segment_has_camera {constants.options.camera_size.and_then(|_| {@@ -6263,7 +6275,7 @@ impl RendererLayers {self.camera.prepare(&constants.device,&constants.queue,- if segment_frames.segment_has_camera {+ if render_display && segment_frames.segment_has_camera {uniforms.camera} else {None@@ -6274,7 +6286,7 @@ impl RendererLayers {self.camera_only.prepare(&constants.device,&constants.queue,- if segment_frames.segment_has_camera {+ if render_display && segment_frames.segment_has_camera {uniforms.camera_only} else {None@@ -6373,7 +6385,6 @@ impl RendererLayers {&constants.device,&constants.queue,segment_frames,- constants.options.screen_size,uniforms.display,encoder,);@@ -6387,20 +6398,9 @@ impl RendererLayers {timings.display_prepare_duration = start.elapsed();let start = Instant::now();- self.click_ripple.prepare(- uniforms,- uniforms.resolution_base,- &uniforms.zoom,- constants,- );- self.cursor.prepare(- segment_frames,- uniforms.resolution_base,- cursor,- &uniforms.zoom,- uniforms,- constants,- );+ self.click_ripple.prepare(uniforms, constants);+ self.cursor+ .prepare(segment_frames, cursor, uniforms, constants);timings.cursor_prepare_duration = start.elapsed();let camera_frame_data = if segment_frames.segment_has_camera {@@ -6426,7 +6426,7 @@ impl RendererLayers {self.camera.prepare_with_encoder(&constants.device,&constants.queue,- if segment_frames.segment_has_camera {+ if render_display && segment_frames.segment_has_camera {uniforms.camera} else {None@@ -6440,7 +6440,7 @@ impl RendererLayers {self.camera_only.prepare_with_encoder(&constants.device,&constants.queue,- if segment_frames.segment_has_camera {+ if render_display && segment_frames.segment_has_camera {uniforms.camera_only} else {None@@ -7088,7 +7088,374 @@ mod notch_bounds_tests {#[cfg(test)]mod project_uniforms_tests {use super::*;- use cap_project::CursorMoveEvent;+ use cap_project::{BackgroundSource, CursorMoveEvent};++ async fn cursor_test_constants() -> RenderVideoConstants {+ let recording_meta: RecordingMeta = serde_json::from_value(serde_json::json!({+ "pretty_name": "mixed-aspect-cursor",+ "display": { "path": "display.mp4", "fps": 30 },+ "camera": null,+ "audio": null,+ "cursor": null+ }))+ .unwrap();+ let meta = recording_meta.studio_meta().unwrap().clone();+ let screen_size = XY::new(1600, 900);+ RenderVideoConstants::new_with_options(+ RenderOptions {+ screen_size,+ camera_size: None,+ preserve_screen_alpha: false,+ },+ recording_meta,+ meta,+ )+ .await+ .unwrap()+ }++ #[tokio::test]+ async fn cursor_tracks_each_clips_display_aspect_ratio() {+ let constants = cursor_test_constants().await;+ let screen_size = constants.options.screen_size;+ let mut project = ProjectConfiguration::default();+ project.background.padding = 0.0;+ let events = CursorEvents::default();+ let zoom_timeline =+ ZoomTransformTimeline::from_project(&project, &events, 1.0, screen_size);++ for (source_size, bounds) in [+ (XY::new(1600, 900), [0.0, 0.0, 1600.0, 900.0]),+ (XY::new(1600, 776), [0.0, 62.0, 1600.0, 838.0]),+ (XY::new(900, 1600), [546.875, 0.0, 1053.125, 900.0]),+ (XY::new(800, 450), [0.0, 0.0, 1600.0, 900.0]),+ ] {+ let mut frames = DecodedSegmentFrames {+ screen_size: source_size,+ screen_frame: Some(DecodedFrame::new(Vec::new(), source_size.x, source_size.y)),+ camera_frame: None,+ segment_time: 0.0,+ recording_time: 0.0,+ segment_has_camera: false,+ };+ for decode_display in [true, false] {+ frames.screen_size = if decode_display {+ screen_size+ } else {+ source_size+ };+ if !decode_display {+ frames.screen_frame = None;+ }+ let uniforms = ProjectUniforms::new(+ &constants,+ &project,+ 0,+ 30,+ screen_size,+ &events,+ &frames,+ 1.0,+ &zoom_timeline,+ );+ for (actual, expected) in uniforms.frame_layout().display.iter().zip(bounds) {+ assert!((*actual - expected).abs() < 0.001);+ }+ let placement = layers::CursorPlacement {+ uniforms: &uniforms,+ };++ for position in [+ XY::new(0.1, 0.1),+ XY::new(0.5, 0.5),+ XY::new(0.9, 0.9),+ XY::new(-0.1, 1.1),+ ] {+ let (rect, _) = placement.map(+ position,+ Coord::new(XY::new(24.0, 36.0)),+ XY::new(0.25, 0.75),+ 1.0,+ );+ let expected = [+ bounds[0] + position.x as f32 * (bounds[2] - bounds[0]),+ bounds[1] + position.y as f32 * (bounds[3] - bounds[1]),+ ];+ let tip = [rect[0] + 6.0, rect[1] + 27.0];+ for (axis, (actual, expected)) in tip.iter().zip(expected).enumerate() {+ assert!(+ (*actual - expected).abs() < 0.001,+ "source {source_size:?}, position {position:?}, axis {axis}: {actual} != {expected}",+ );+ }+ assert_eq!(rect[2..], [24.0, 36.0]);+ }+ }+ }+ }++ fn pixel_center(+ frame: &RenderedFrame,+ selected: impl Fn(&[u8], usize, usize) -> bool,+ ) -> XY<f64> {+ let mut sum = XY::new(0.0, 0.0);+ let mut count = 0;+ for (y, row) in frame+ .data+ .chunks_exact(frame.padded_bytes_per_row as usize)+ .take(frame.height as usize)+ .enumerate()+ {+ for (x, pixel) in row.chunks_exact(4).take(frame.width as usize).enumerate() {+ if selected(pixel, x, y) {+ sum = sum + XY::new(x as f64 + 0.5, y as f64 + 0.5);+ count += 1;+ }+ }+ }+ assert!(count > 0, "expected visible pixels");+ sum / count as f64+ }++ #[tokio::test]+ async fn cursor_and_ripple_pixels_follow_the_display_through_layout_changes() {+ let mut constants = cursor_test_constants().await;+ constants.options.camera_size = Some(XY::new(1280, 720));+ let mut project = ProjectConfiguration::default();+ project.background.source = BackgroundSource::Color {+ value: [255, 255, 255],+ alpha: 255,+ };+ project.background.shadow = 0.0;+ project.screen_motion_blur = 0.0;+ project.cursor.motion_blur = 0.0;+ project.cursor.raw = true;+ project.cursor.set_cursor_type(CursorType::Circle);+ project.cursor.ripple.enabled = true;+ project.cursor.ripple.color = [0, 255, 0];+ project.cursor.ripple.strength = 1.0;+ project.timeline = Some(+ serde_json::from_value(serde_json::json!({+ "segments": [{ "start": 0.0, "end": 4.0, "timescale": 1.0 }],+ "zoomSegments": []+ }))+ .unwrap(),+ );+ let short = XY::new(1600, 776);+ let mut cases = vec![+ ("original", project.clone(), XY::new(1600, 900), 120),+ ("shorter", project.clone(), short, 120),+ ("portrait", project.clone(), XY::new(900, 1600), 120),+ (+ "same-aspect-low-resolution",+ project.clone(),+ XY::new(800, 450),+ 120,+ ),+ ];++ let mut cropped = project.clone();+ cropped.background.crop = Some(Crop {+ position: XY::new(160, 90),+ size: XY::new(1280, 630),+ });+ cropped.background.padding = 20.0;+ cropped.background.display_position = Some(XY::new(0.55, 0.45));+ cases.push(("crop-padding-position", cropped, short, 120));++ let mut framed = project.clone();+ framed.background.frame = Some(FrameConfiguration {+ style: FrameStyle::Browser,+ ..Default::default()+ });+ cases.push(("decorative-frame", framed, short, 120));++ let mut zoomed = project.clone();+ zoomed.timeline.as_mut().unwrap().zoom_segments = vec![+ serde_json::from_value(serde_json::json!({+ "start": 0.0, "end": 4.0, "amount": 2.0,+ "mode": { "manual": { "x": 0.6, "y": 0.4 } },+ "instantAnimation": true+ }))+ .unwrap(),+ ];+ cases.push(("zoom", zoomed, short, 120));++ for (name, mode, frame_number) in [+ ("split-morph", SceneMode::SplitScreen, 105),+ ("split", SceneMode::SplitScreen, 150),+ ("floating", SceneMode::Floating, 150),+ ] {+ let mut split = project.clone();+ split.timeline.as_mut().unwrap().scene_segments = vec![cap_project::SceneSegment {+ start: 2.0,+ end: 4.0,+ mode,+ split_layout: None,+ transition_in: 0.5,+ transition_out: 0.5,+ }];+ cases.push((name, split, short, frame_number));+ }++ for layout in ["fullscreen", "splitLeft", "splitRight"] {+ let mut takeover = project.clone();+ takeover.timeline.as_mut().unwrap().text_segments = vec![+ serde_json::from_value(serde_json::json!({+ "start": 0.0, "end": 4.0, "content": "",+ "layout": layout, "layoutTransition": 0.5+ }))+ .unwrap(),+ ];+ cases.push((layout, takeover, short, 15));+ }++ let mut renderer = FrameRenderer::new(&constants);+ let mut layers = RendererLayers::new(&constants.device, &constants.queue);+ for (index, (name, project, source_size, frame_number)) in cases.into_iter().enumerate() {+ let marker = XY::new(+ source_size.x * (55 + index as u32 % 3) / 100,+ source_size.y * (30 + index as u32 % 4) / 100,+ );+ let position = XY::new(+ (marker.x as f64 + 0.5) / source_size.x as f64,+ (marker.y as f64 + 0.5) / source_size.y as f64,+ );+ let mut pixels = vec![255; (source_size.x * source_size.y * 4) as usize];+ for y in marker.y - 5..=marker.y + 5 {+ for x in marker.x - 5..=marker.x + 5 {+ let offset = ((y * source_size.x + x) * 4) as usize;+ pixels[offset..offset + 4].copy_from_slice(&[0, 0, 255, 255]);+ }+ }+ let frames = DecodedSegmentFrames {+ screen_size: source_size,+ screen_frame: Some(DecodedFrame::new(pixels, source_size.x, source_size.y)),+ camera_frame: Some(DecodedFrame::new(vec![255; 1280 * 720 * 4], 1280, 720)),+ segment_time: index as f32 * 0.125,+ recording_time: index as f32 * 0.125,+ segment_has_camera: true,+ };+ let events = CursorEvents {+ moves: vec![cursor_move(0.0, position.x, position.y)],+ clicks: vec![],+ };+ let zoom_timeline = ZoomTransformTimeline::from_project(+ &project,+ &events,+ 4.0,+ constants.options.screen_size,+ );+ let uniforms = ProjectUniforms::new(+ &constants,+ &project,+ frame_number,+ 60,+ XY::new(800, 450),+ &events,+ &frames,+ 4.0,+ &zoom_timeline,+ );+ if let Some(chrome) = &uniforms.frame_chrome {+ assert_eq!(+ uniforms.frame_layout().display,+ chrome.composite.target_bounds+ );+ }+ if matches!(name, "fullscreen" | "splitLeft" | "splitRight") {+ let (_, opacity) = layers::CursorPlacement {+ uniforms: &uniforms,+ }+ .map(+ position,+ Coord::new(XY::new(24.0, 36.0)),+ XY::new(0.25, 0.75),+ 0.8,+ );+ let expected = if name == "fullscreen" { 0.4 } else { 0.8 };+ assert!((opacity - expected).abs() < 0.001);+ }+ let mut display_uniforms = uniforms.clone();+ display_uniforms.project.cursor.hide = true;+ let display = renderer+ .render_immediate(frames.clone(), display_uniforms, &events, true, &mut layers)+ .await+ .unwrap();+ let marker_center = pixel_center(&display, |pixel, _, _| {+ pixel[2] > pixel[0].saturating_add(50) && pixel[2] > pixel[1].saturating_add(50)+ });++ for ripple_only in [false, true] {+ let mut overlay_uniforms = uniforms.clone();+ if ripple_only {+ overlay_uniforms.project.cursor.hide = true;+ overlay_uniforms.click_ripples = vec![ClickRipple {+ position: Coord::new(position),+ progress: 0.35,+ }];+ }+ let overlay = renderer+ .render_immediate(frames.clone(), overlay_uniforms, &events, true, &mut layers)+ .await+ .unwrap();+ let overlay_center = pixel_center(&overlay, |pixel, x, y| {+ let offset = y * display.padded_bytes_per_row as usize + x * 4;+ pixel[..3]+ .iter()+ .zip(&display.data[offset..offset + 3])+ .any(|(actual, base)| actual.abs_diff(*base) > 12)+ });+ assert!(+ (marker_center.x - overlay_center.x).abs() < 1.5+ && (marker_center.y - overlay_center.y).abs() < 1.5,+ "{name}, ripple={ripple_only}: marker {marker_center:?}, overlay {overlay_center:?}",+ );++ let mut cursor_only_frames = frames.clone();+ cursor_only_frames.screen_frame = None;+ cursor_only_frames.camera_frame = None;+ let mut cursor_only_uniforms = ProjectUniforms::new(+ &constants,+ &project,+ frame_number,+ 60,+ XY::new(800, 450),+ &events,+ &cursor_only_frames,+ 4.0,+ &zoom_timeline,+ );+ cursor_only_uniforms.project.background.source = BackgroundSource::Color {+ value: [0, 0, 0],+ alpha: 0,+ };+ if ripple_only {+ cursor_only_uniforms.project.cursor.hide = true;+ cursor_only_uniforms.click_ripples = vec![ClickRipple {+ position: Coord::new(position),+ progress: 0.35,+ }];+ }+ let cursor_only = renderer+ .render_immediate(+ cursor_only_frames,+ cursor_only_uniforms,+ &events,+ false,+ &mut layers,+ )+ .await+ .unwrap();+ let cursor_only_center = pixel_center(&cursor_only, |pixel, _, _| pixel[3] > 12);+ assert!(+ (marker_center.x - cursor_only_center.x).abs() < 1.5+ && (marker_center.y - cursor_only_center.y).abs() < 1.5,+ "{name}, ripple={ripple_only}: marker {marker_center:?}, cursor-only {cursor_only_center:?}",+ );+ }+ }+ }fn cursor_move(time_ms: f64, x: f64, y: f64) -> CursorMoveEvent {CursorMoveEvent {