Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(rendering): avoid linear cursor scans during raw playback

Akshar Pateld5a563ab2376
diff --git a/crates/rendering/src/cursor_interpolation.rs b/crates/rendering/src/cursor_interpolation.rs
index b8ffdc597..afe5c8098 100644
--- a/crates/rendering/src/cursor_interpolation.rs
+++ b/crates/rendering/src/cursor_interpolation.rs
@@ -272,13 +272,14 @@ pub fn interpolate_cursor_with_click_spring(
);
interpolate_timeline(&timeline, time_ms)
} else {
- interpolate_raw_cursor(cursor, time_ms)
+ interpolate_raw_cursor(cursor, time_ms, false)
}
}
fn interpolate_raw_cursor(
cursor: &CursorEvents,
time_ms: f64,
+ moves_are_ordered: bool,
) -> Option<InterpolatedCursorPosition> {
if cursor.moves.is_empty() {
return None;
@@ -309,21 +310,26 @@ fn interpolate_raw_cursor(
});
}
- cursor.moves.windows(2).find_map(|chunk| {
- if time_ms >= chunk[0].time_ms && time_ms < chunk[1].time_ms {
- let c = &chunk[0];
- let next = &chunk[1];
- let delta_ms = (next.time_ms - c.time_ms) as f32;
- let dt = (delta_ms / 1000.0).max(0.000_1);
- let velocity = XY::new(((next.x - c.x) as f32) / dt, ((next.y - c.y) as f32) / dt);
- Some(InterpolatedCursorPosition {
- position: Coord::new(XY { x: c.x, y: c.y }),
- velocity,
- cursor_id: c.cursor_id.clone(),
- })
- } else {
- None
- }
+ let chunk = if moves_are_ordered {
+ let end = cursor
+ .moves
+ .partition_point(|event| event.time_ms <= time_ms);
+ cursor.moves.get(end.checked_sub(1)?..=end)?
+ } else {
+ cursor
+ .moves
+ .windows(2)
+ .find(|chunk| time_ms >= chunk[0].time_ms && time_ms < chunk[1].time_ms)?
+ };
+ let c = &chunk[0];
+ let next = &chunk[1];
+ let delta_ms = (next.time_ms - c.time_ms) as f32;
+ let dt = (delta_ms / 1000.0).max(0.000_1);
+ let velocity = XY::new(((next.x - c.x) as f32) / dt, ((next.y - c.y) as f32) / dt);
+ Some(InterpolatedCursorPosition {
+ position: Coord::new(XY { x: c.x, y: c.y }),
+ velocity,
+ cursor_id: c.cursor_id.clone(),
})
}
@@ -337,6 +343,7 @@ struct CursorTimelineVariant {
pub struct PrecomputedCursorTimeline {
timeline: Vec<SmoothedCursorEvent>,
raw_cursor: CursorEvents,
+ raw_moves_are_ordered: bool,
has_smoothing: bool,
variants: Mutex<Vec<CursorTimelineVariant>>,
}
@@ -347,10 +354,12 @@ impl PrecomputedCursorTimeline {
smoothing: Option<SpringMassDamperSimulationConfig>,
click_spring: Option<ClickSpringConfig>,
) -> Self {
+ let raw_moves_are_ordered = cursor.moves.is_sorted_by(|a, b| a.time_ms <= b.time_ms);
if cursor.moves.is_empty() || smoothing.is_none() {
return Self {
timeline: vec![],
raw_cursor: cursor.clone(),
+ raw_moves_are_ordered,
has_smoothing: false,
variants: Mutex::new(Vec::new()),
};
@@ -369,6 +378,7 @@ impl PrecomputedCursorTimeline {
Self {
timeline,
raw_cursor: CursorEvents::default(),
+ raw_moves_are_ordered,
has_smoothing: true,
variants: Mutex::new(Vec::new()),
}
@@ -412,9 +422,22 @@ impl PrecomputedCursorTimeline {
if self.has_smoothing {
interpolate_timeline(&self.timeline, time_ms)
} else {
- interpolate_raw_cursor(&self.raw_cursor, time_ms)
+ interpolate_raw_cursor(&self.raw_cursor, time_ms, self.raw_moves_are_ordered)
}
}
+
+ // Style overrides use the same source events as this timeline's constructor.
+ pub(crate) fn interpolate_raw(
+ &self,
+ cursor: &CursorEvents,
+ time_secs: f32,
+ ) -> Option<InterpolatedCursorPosition> {
+ interpolate_raw_cursor(
+ cursor,
+ (time_secs * 1000.0) as f64,
+ self.raw_moves_are_ordered,
+ )
+ }
}
fn build_smoothed_timeline(
@@ -1367,6 +1390,154 @@ mod tests {
assert!(timeline.interpolate(0.1).is_none());
}
+ #[test]
+ fn raw_timeline_lookup_matches_linear_reference() {
+ let cases = [
+ vec![],
+ vec![0.0],
+ vec![f64::NAN],
+ vec![0.0, 0.0, 10.0, 10.0, 20.0, 100.0, 100.0],
+ vec![-0.0, 0.0, 0.0, 10.0, 100.0],
+ vec![0.0, 20.0, 10.0, 50.0, 100.0],
+ vec![0.0, 10.0, f64::NAN, 30.0, 100.0],
+ vec![f64::NAN, 10.0, 30.0, 100.0],
+ vec![0.0, 10.0, f64::NAN],
+ vec![f64::NEG_INFINITY, 0.0, 10.0, f64::INFINITY],
+ vec![0.0, f64::INFINITY, 10.0, 100.0],
+ ];
+ for times in cases {
+ let cursor = CursorEvents {
+ moves: times
+ .iter()
+ .enumerate()
+ .map(|(index, &time)| {
+ let mut event =
+ cursor_move(time, index as f64 * 0.13, index as f64 * -0.07);
+ event.cursor_id = index.to_string();
+ event
+ })
+ .collect(),
+ clicks: Vec::new(),
+ };
+ let timeline = PrecomputedCursorTimeline::new(&cursor, None, None);
+ let queries = [
+ -1.0, -0.0, 0.0, 0.001, 0.009, 0.01, 0.019, 0.02, 0.05, 0.1, 1.0,
+ ]
+ .into_iter()
+ .chain([f32::NAN, f32::NEG_INFINITY, f32::INFINITY])
+ .chain(times.iter().flat_map(|&time| {
+ let time = (time / 1000.0) as f32;
+ [time.next_down(), time, time.next_up()]
+ }));
+ for time in queries {
+ assert_position_bits(
+ interpolate_cursor(&cursor, time, None),
+ timeline.interpolate(time),
+ );
+ assert_position_bits(
+ interpolate_cursor(&cursor, time, None),
+ timeline.interpolate_raw(&cursor, time),
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn raw_style_lookup_reuses_smoothed_source_order_without_retaining_events() {
+ let cursor = dense_cursor(2);
+ let timeline = PrecomputedCursorTimeline::new(&cursor, Some(DEFAULT_CLICK_SPRING), None);
+ assert!(timeline.raw_cursor.moves.is_empty());
+ assert!(timeline.raw_cursor.clicks.is_empty());
+ for time in [1.7, 0.4, 2.0, 0.0, -1.0, 0.017, 1.7] {
+ assert_position_bits(
+ interpolate_cursor(&cursor, time, None),
+ timeline.interpolate_raw(&cursor, time),
+ );
+ }
+ }
+
+ #[test]
+ #[ignore]
+ fn benchmark_raw_cursor_frame_lookup() {
+ use std::{hint::black_box, time::Instant};
+
+ for duration_secs in [60, 600, 3600] {
+ let cursor = CursorEvents {
+ moves: (0..=duration_secs * 60)
+ .map(|index| {
+ let mut event = cursor_move(
+ index as f64 * 1000.0 / 60.0,
+ (index % 479) as f64 / 479.0,
+ (index % 283) as f64 / 283.0,
+ );
+ event.cursor_id = (index / 31 % 3).to_string();
+ event
+ })
+ .collect(),
+ clicks: Vec::new(),
+ };
+ let started = Instant::now();
+ let timeline = PrecomputedCursorTimeline::new(&cursor, None, None);
+ println!(
+ "raw_cursor_setup duration_secs={duration_secs} moves={} setup_ms={:.3}",
+ cursor.moves.len(),
+ started.elapsed().as_secs_f64() * 1000.0,
+ );
+
+ for workload in ["start", "middle", "end", "random_seek"] {
+ let mut baseline = Vec::new();
+ let mut optimized = Vec::new();
+ for frame in 0..544 {
+ let time = match workload {
+ "start" => 1.0 + (frame % 120) as f32 / 60.0,
+ "middle" => duration_secs as f32 * 0.5 + (frame % 120) as f32 / 60.0,
+ "end" => duration_secs as f32 - 3.0 + (frame % 120) as f32 / 60.0,
+ _ => (frame * 104729 % 1009) as f32 / 1009.0 * duration_secs as f32,
+ };
+ let queries = [time, (time - 1.0 / 60.0).max(0.0), (time - 0.4).max(0.0)];
+ for query in queries {
+ assert_position_bits(
+ interpolate_cursor(&cursor, query, None),
+ timeline.interpolate_raw(&cursor, query),
+ );
+ }
+ let measure =
+ |interpolate: &dyn Fn(f32) -> Option<InterpolatedCursorPosition>| {
+ let started = Instant::now();
+ let positions = queries.map(|time| interpolate(black_box(time)));
+ let elapsed = started.elapsed().as_secs_f64() * 1e6;
+ drop(black_box(positions));
+ elapsed
+ };
+ let old = |time| interpolate_cursor(black_box(&cursor), time, None);
+ let new = |time| black_box(&timeline).interpolate_raw(black_box(&cursor), time);
+ let (old_us, new_us) = if frame % 2 == 0 {
+ (measure(&old), measure(&new))
+ } else {
+ let new_us = measure(&new);
+ (measure(&old), new_us)
+ };
+ if frame >= 32 {
+ baseline.push(old_us);
+ optimized.push(new_us);
+ }
+ }
+ baseline.sort_by(f64::total_cmp);
+ optimized.sort_by(f64::total_cmp);
+ let p50 = baseline.len() / 2;
+ let p95 = baseline.len() * 95 / 100;
+ println!(
+ "raw_cursor_frame duration_secs={duration_secs} workload={workload} frames={} queries_per_frame=3 baseline_p50_us={:.3} baseline_p95_us={:.3} optimized_p50_us={:.3} optimized_p95_us={:.3}",
+ baseline.len(),
+ baseline[p50],
+ baseline[p95],
+ optimized[p50],
+ optimized[p95],
+ );
+ }
+ }
+ }
+
#[test]
fn cursor_position_lookup_matches_linear_reference() {
let cases = [
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 05758d1d9..c1a0e2ff6 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -3700,7 +3700,7 @@ impl ProjectUniforms {
};
let cursor_interp_fn = |time: f32| -> Option<InterpolatedCursorPosition> {
if cursor.raw {
- interpolate_cursor(cursor_events, time, None)
+ precomputed_cursor.interpolate_raw(cursor_events, time)
} else {
variant
.as_deref()
@@ -8427,6 +8427,224 @@ mod project_uniforms_tests {
.unwrap()
}
+ #[tokio::test]
+ async fn raw_precomputed_cursor_preserves_rendered_pixels() {
+ let mut constants = cursor_test_constants().await;
+ let size = XY::new(320, 180);
+ constants.options.screen_size = size;
+ let events = CursorEvents {
+ moves: vec![
+ cursor_move(0.0, 0.1, 0.5),
+ cursor_move(0.0, 0.2, 0.5),
+ cursor_move(250.0, 0.3, 0.4),
+ cursor_move(800.0, 0.8, 0.6),
+ cursor_move(1500.0, 0.4, 0.3),
+ cursor_move(1800.0, 0.6, 0.5),
+ ],
+ clicks: vec![cap_project::CursorClickEvent {
+ active_modifiers: Vec::new(),
+ cursor_num: 0,
+ cursor_id: "primary".to_string(),
+ time_ms: 300.0,
+ down: true,
+ }],
+ };
+ let source = DecodedFrame::new(vec![160; 320 * 180 * 4], size.x, size.y);
+ for base_raw in [true, false] {
+ let mut project = ProjectConfiguration::default();
+ project.cursor.raw = base_raw;
+ project.cursor.set_cursor_type(CursorType::Circle);
+ project.cursor.motion_blur = 0.6;
+ project.cursor.rotation_amount = 1.0;
+ project.cursor.stop_movement_in_last_seconds = Some(0.5);
+ project.cursor.ripple.enabled = true;
+ project.timeline = Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [{ "start": 0.0, "end": 2.0, "timescale": 1.0 }],
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ );
+ if !base_raw {
+ let mut style_cursor = project.cursor.clone();
+ style_cursor.raw = true;
+ project.timeline = Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [{ "start": 0.0, "end": 2.0, "timescale": 1.0 }],
+ "zoomSegments": [],
+ "styleSegments": [{
+ "start": 0.0, "end": 2.0,
+ "overrides": { "cursor": style_cursor }
+ }]
+ }))
+ .unwrap(),
+ );
+ }
+ let cursor = PrecomputedCursorTimeline::new(
+ &events,
+ (!base_raw).then_some(SpringMassDamperSimulationConfig {
+ tension: project.cursor.tension,
+ mass: project.cursor.mass,
+ friction: project.cursor.friction,
+ }),
+ Some(project.cursor.click_spring_config()),
+ );
+ let zoom = ZoomTransformTimeline::from_project(&project, &events, 2.0, size);
+ let mut legacy_renderer = FrameRenderer::new(&constants);
+ let mut indexed_renderer = FrameRenderer::new(&constants);
+ let mut hidden_renderer = FrameRenderer::new(&constants);
+ let mut legacy_layers = RendererLayers::new(&constants.device, &constants.queue);
+ let mut indexed_layers = RendererLayers::new(&constants.device, &constants.queue);
+ let mut hidden_layers = RendererLayers::new(&constants.device, &constants.queue);
+ for frame_number in [0, 24, 36, 75, 105] {
+ let time = frame_number as f32 / 60.0;
+ let frames = DecodedSegmentFrames {
+ screen_size: size,
+ screen_frame: Some(source.clone()),
+ camera_frame: None,
+ segment_time: time,
+ recording_time: time,
+ segment_has_camera: false,
+ };
+ let legacy = ProjectUniforms::new(
+ &constants,
+ &project,
+ frame_number,
+ 60,
+ size,
+ &events,
+ &frames,
+ 2.0,
+ &zoom,
+ );
+ let indexed = ProjectUniforms::new_with_precomputed_cursor(
+ &constants,
+ &project,
+ frame_number,
+ 60,
+ size,
+ &events,
+ &frames,
+ 2.0,
+ &zoom,
+ &cursor,
+ );
+ let legacy = legacy_renderer
+ .render_immediate(frames.clone(), legacy, &events, true, &mut legacy_layers)
+ .await
+ .unwrap();
+ let indexed = indexed_renderer
+ .render_immediate(frames.clone(), indexed, &events, true, &mut indexed_layers)
+ .await
+ .unwrap();
+ assert!(
+ legacy.data == indexed.data,
+ "raw={base_raw} frame={frame_number}: rendered cursor pixels changed"
+ );
+ if frame_number == 24 {
+ let mut hidden = ProjectUniforms::new(
+ &constants,
+ &project,
+ frame_number,
+ 60,
+ size,
+ &events,
+ &frames,
+ 2.0,
+ &zoom,
+ );
+ hidden.project.cursor.hide = true;
+ let hidden = hidden_renderer
+ .render_immediate(frames, hidden, &events, true, &mut hidden_layers)
+ .await
+ .unwrap();
+ assert!(
+ legacy.data != hidden.data,
+ "raw={base_raw}: the fixture must draw a cursor"
+ );
+ }
+ }
+ }
+ }
+
+ #[tokio::test]
+ #[ignore]
+ async fn benchmark_raw_cursor_uniform_preparation() {
+ use std::hint::black_box;
+
+ let mut constants = cursor_test_constants().await;
+ let size = XY::new(320, 180);
+ constants.options.screen_size = size;
+ println!("raw_uniforms adapter={}", constants.adapter_name());
+ let source = DecodedFrame::new(vec![160; 320 * 180 * 4], size.x, size.y);
+ for duration_secs in [60, 600, 3600] {
+ let mut project = ProjectConfiguration::default();
+ project.cursor.raw = true;
+ project.timeline = Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [{ "start": 0.0, "end": duration_secs, "timescale": 1.0 }],
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ );
+ let project = Arc::new(project);
+ let events = CursorEvents {
+ moves: (0..=duration_secs * 60)
+ .map(|index| {
+ cursor_move(
+ index as f64 * 1000.0 / 60.0,
+ (index % 479) as f64 / 479.0,
+ (index % 283) as f64 / 283.0,
+ )
+ })
+ .collect(),
+ clicks: Vec::new(),
+ };
+ let cursor = PrecomputedCursorTimeline::new(&events, None, None);
+ let zoom =
+ ZoomTransformTimeline::from_project(&project, &events, duration_secs as f64, size);
+ let mut samples = Vec::new();
+ for index in 0..544 {
+ let frame_number = (duration_secs - 3) * 60 + index % 120;
+ let time = frame_number as f32 / 60.0;
+ let frames = DecodedSegmentFrames {
+ screen_size: size,
+ screen_frame: Some(source.clone()),
+ camera_frame: None,
+ segment_time: time,
+ recording_time: time,
+ segment_has_camera: false,
+ };
+ let started = Instant::now();
+ let uniforms = ProjectUniforms::new_with_precomputed_cursor(
+ black_box(&constants),
+ black_box(&project),
+ black_box(frame_number),
+ 60,
+ size,
+ black_box(&events),
+ black_box(&frames),
+ duration_secs as f64,
+ black_box(&zoom),
+ black_box(&cursor),
+ );
+ let elapsed = started.elapsed().as_secs_f64() * 1e6;
+ drop(black_box(uniforms));
+ if index >= 32 {
+ samples.push(elapsed);
+ }
+ }
+ samples.sort_by(f64::total_cmp);
+ println!(
+ "raw_uniforms duration_secs={duration_secs} moves={} frames={} p50_us={:.3} p95_us={:.3}",
+ events.moves.len(),
+ samples.len(),
+ samples[samples.len() / 2],
+ samples[samples.len() * 95 / 100],
+ );
+ }
+ }
+
#[tokio::test]
async fn cursor_tracks_each_clips_display_aspect_ratio() {
let constants = cursor_test_constants().await;