From 916d918defb29a78e65c736b1bf59e11a55d6fff Mon Sep 17 00:00:00 2001 From: qflen Date: Tue, 13 Oct 2026 11:20:38 +0200 Subject: [PATCH 1/2] perf(editor): reuse the zoom timeline across paused scrub frames The paused preview renderer rebuilt ZoomTransformTimeline for every scrub frame. The timeline clusters cursor events for each auto zoom and precomputes its springs from t=0 in 8 ms steps, so every scrub frame cost O(playhead): about 18 ms late in a 30-minute recording with 60 auto zooms, more than a 60 Hz frame on its own. Keep one timeline per recording clip (and per outgoing transition clip) across scrub frames and drop them whenever the project changes, the way playback already rebuilds its timelines on project_config changes. Extending a timeline incrementally is bit-identical to precomputing it in one go (sequential_and_seek_precompute_are_identical), so rendered frames are unchanged. Paused ruler drag through EditorInstance (BGRA surface output, 1248x702 preview, two tokio workers), Apple M5, release, 6 processes each: 30 min / 60 auto zooms: median frame latency 14.0 -> 4.0 ms (-72%), p95 22.4 -> 7.5 ms, CPU while dragging 2.34 -> 0.75 s. 10 min / 20 auto zooms: median 7.0 -> 4.0 ms (-43%). Adds a scrub-benchmark example to the GPUI app. --- apps/desktop-gpui/examples/scrub-benchmark.rs | 163 ++++++++++++++++++ crates/editor/src/editor_instance.rs | 64 ++++--- 2 files changed, 205 insertions(+), 22 deletions(-) create mode 100644 apps/desktop-gpui/examples/scrub-benchmark.rs diff --git a/apps/desktop-gpui/examples/scrub-benchmark.rs b/apps/desktop-gpui/examples/scrub-benchmark.rs new file mode 100644 index 00000000000..b9bf6e719b1 --- /dev/null +++ b/apps/desktop-gpui/examples/scrub-benchmark.rs @@ -0,0 +1,163 @@ +//! Paused-scrub benchmark: drags the playhead through an `EditorInstance` the +//! way the editor's ruler drag does (`preview_tx` pushes at the 60 fps preview +//! clock and the default Half preview size), on the app's two-worker runtime, +//! and reports per-frame request-to-frame latency at several depths into the +//! recording plus the process CPU time spent dragging. +//! +//! The editor can write `project-config.json` back into the project, so point +//! it at a copy rather than a recording in the library. +//! +//! Run: cargo run --release --example scrub-benchmark -- [STEPS] [STEP_FRAMES] + +use std::{path::PathBuf, sync::Arc, time::Duration, time::Instant}; + +use cap_editor::{AudioOutput, EditorFrameFormat, EditorFrameOutput, EditorInstance}; +use cap_project::XY; + +const PREVIEW_FPS: u32 = 60; +const PREVIEW_RESOLUTION: XY = XY { x: 1248, y: 702 }; +const REGION_FRACTIONS: [f64; 5] = [0.02, 0.17, 0.5, 0.83, 0.98]; + +fn cpu_secs() -> f64 { + let mut usage = std::mem::MaybeUninit::::zeroed(); + unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) }; + let usage = unsafe { usage.assume_init() }; + let secs = |time: libc::timeval| time.tv_sec as f64 + time.tv_usec as f64 / 1_000_000.0; + secs(usage.ru_utime) + secs(usage.ru_stime) +} + +fn percentile(sorted: &[f64], fraction: f64) -> f64 { + sorted[((sorted.len() - 1) as f64 * fraction).round() as usize] +} + +fn frame_number(output: &EditorFrameOutput) -> u32 { + match output { + EditorFrameOutput::Rgba(frame) => frame.frame_number, + EditorFrameOutput::Nv12(frame) => frame.frame_number, + #[cfg(target_os = "macos")] + EditorFrameOutput::Surface(frame) => frame.frame_number, + } +} + +async fn render( + instance: &EditorInstance, + frames: &flume::Receiver, + frame: u32, +) -> anyhow::Result { + while frames.try_recv().is_ok() {} + let requested = Instant::now(); + instance + .preview_tx + .send_modify(|value| *value = Some((frame, PREVIEW_FPS, PREVIEW_RESOLUTION))); + loop { + let rendered = tokio::time::timeout(Duration::from_secs(30), frames.recv_async()) + .await + .map_err(|_| anyhow::anyhow!("timed out waiting for frame {frame}"))??; + if rendered == frame { + return Ok(requested.elapsed().as_secs_f64() * 1000.0); + } + } +} + +async fn run(project_path: PathBuf, steps: u32, step_frames: u32) -> anyhow::Result<()> { + #[cfg(target_os = "macos")] + let format = EditorFrameFormat::BgraSurface; + #[cfg(not(target_os = "macos"))] + let format = EditorFrameFormat::Rgba; + + let (frame_tx, frame_rx) = flume::unbounded::(); + let audio_output = Arc::new(AudioOutput::new_headless(Box::new(|_samples, _at| {}))); + let instance = EditorInstance::new_with_audio_output_and_frame_format( + project_path.clone(), + |_state| {}, + Box::new(move |output, _layout| { + let _ = frame_tx.send(frame_number(&output)); + }), + None, + format, + audio_output, + ) + .await + .map_err(anyhow::Error::msg)?; + + let duration = instance + .project_config + .1 + .borrow() + .timeline + .as_ref() + .map_or(0.0, |timeline| timeline.duration()); + let last_frame = (duration * PREVIEW_FPS as f64) as u32; + render(&instance, &frame_rx, 0).await?; + + let mut regions = Vec::new(); + let mut drag = Vec::new(); + let mut drag_cpu_secs = 0.0; + for fraction in REGION_FRACTIONS { + let start = ((last_frame as f64 * fraction) as u32) + .min(last_frame.saturating_sub(steps * step_frames)); + let seek_ms = render(&instance, &frame_rx, start).await?; + let cpu_started = cpu_secs(); + let mut latencies = Vec::with_capacity(steps as usize); + for step in 1..=steps { + latencies.push(render(&instance, &frame_rx, start + step * step_frames).await?); + } + drag_cpu_secs += cpu_secs() - cpu_started; + drag.extend_from_slice(&latencies); + latencies.sort_by(f64::total_cmp); + regions.push(serde_json::json!({ + "atSecs": start as f64 / PREVIEW_FPS as f64, + "seekMs": seek_ms, + "dragMedianMs": percentile(&latencies, 0.5), + "dragP95Ms": percentile(&latencies, 0.95), + })); + } + drag.sort_by(f64::total_cmp); + println!( + "{}", + serde_json::json!({ + "project": project_path, + "durationSecs": duration, + "steps": steps, + "stepFrames": step_frames, + "regions": regions, + "dragMedianMs": percentile(&drag, 0.5), + "dragP95Ms": percentile(&drag, 0.95), + "dragCpuSecs": drag_cpu_secs, + }) + ); + instance.dispose().await; + Ok(()) +} + +fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into()), + ) + .with_writer(std::io::stderr) + .init(); + + let mut arguments = std::env::args().skip(1); + let project_path = arguments + .next() + .map(PathBuf::from) + .ok_or_else(|| anyhow::anyhow!("Pass a studio .cap project path"))?; + let steps = arguments + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(30u32) + .max(1); + let step_frames = arguments + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(4u32) + .max(1); + + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_stack_size(16 * 1024 * 1024) + .enable_all() + .build()? + .block_on(run(project_path, steps, step_frames)) +} diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs index f670c27a4fb..ea0569daa9a 100644 --- a/crates/editor/src/editor_instance.rs +++ b/crates/editor/src/editor_instance.rs @@ -12,6 +12,7 @@ use cap_rendering::{ get_duration, spring_mass_damper::SpringMassDamperSimulationConfig, }; use std::{ + collections::HashMap, path::{Path, PathBuf}, sync::{ Arc, @@ -983,6 +984,9 @@ impl EditorInstance { tokio::spawn(async move { let mut prefetch_cancel_token: Option = None; let mut cursor_cache = PreviewCursorCache::default(); + let mut project_rx = self.project_config.1.clone(); + let mut zoom_timelines = HashMap::::new(); + let mut outgoing_zoom_timelines = HashMap::::new(); loop { preview_rx.changed().await.unwrap(); @@ -1007,7 +1011,14 @@ impl EditorInstance { break; } - let project = self.project_config.1.borrow().clone(); + let project = { + let project = project_rx.borrow_and_update(); + if project.has_changed() { + zoom_timelines.clear(); + outgoing_zoom_timelines.clear(); + } + project.clone() + }; let frame_time = frame_number as f64 / fps as f64; let transition_mapping = project.timeline.as_ref().and_then(|timeline| { if timeline.transitions.is_empty() { @@ -1073,15 +1084,21 @@ impl EditorInstance { // Scrub renders sample the same precomputed spring // timeline playback and export use (the old focus // interpolator was never precomputed here and fell - // back to a divergent direct interpolation). - let mut zoom_timeline = - ZoomTransformTimeline::from_project_for_clip( - &project, - &segment_medias.cursor, - total_duration, - self.render_constants.options.screen_size, - segment.recording_clip, - ); + // back to a divergent direct interpolation). The + // timeline is kept until the project changes: it + // precomputes from t=0, so rebuilding it per frame + // made each scrub frame cost O(playhead). + let zoom_timeline = zoom_timelines + .entry(segment.recording_clip) + .or_insert_with(|| { + ZoomTransformTimeline::from_project_for_clip( + &project, + &segment_medias.cursor, + total_duration, + self.render_constants.options.screen_size, + segment.recording_clip, + ) + }); zoom_timeline .ensure_precomputed_until((frame_number as f32 + 1.0) / fps as f32); @@ -1109,14 +1126,17 @@ impl EditorInstance { ) => frames, }; if let Some(outgoing_frames) = outgoing_frames { - let mut outgoing_zoom = - ZoomTransformTimeline::from_project_for_outgoing_clip( - &project, - &outgoing_media.cursor, - total_duration, - self.render_constants.options.screen_size, - outgoing.segment.recording_clip, - ); + let outgoing_zoom = outgoing_zoom_timelines + .entry(outgoing.segment.recording_clip) + .or_insert_with(|| { + ZoomTransformTimeline::from_project_for_outgoing_clip( + &project, + &outgoing_media.cursor, + total_duration, + self.render_constants.options.screen_size, + outgoing.segment.recording_clip, + ) + }); outgoing_zoom.ensure_precomputed_until( (frame_number as f32 + 1.0) / fps as f32, ); @@ -1140,7 +1160,7 @@ impl EditorInstance { &outgoing_media.cursor, &outgoing_frames, total_duration, - &outgoing_zoom, + outgoing_zoom, cursor_timeline, ) } else { @@ -1153,7 +1173,7 @@ impl EditorInstance { &outgoing_media.cursor, &outgoing_frames, total_duration, - &outgoing_zoom, + outgoing_zoom, ) }; Some(( @@ -1201,7 +1221,7 @@ impl EditorInstance { &segment_medias.cursor, &segment_frames, total_duration, - &zoom_timeline, + zoom_timeline, cursor_timeline, ) } else { @@ -1214,7 +1234,7 @@ impl EditorInstance { &segment_medias.cursor, &segment_frames, total_duration, - &zoom_timeline, + zoom_timeline, ) }; From 09abc9055f048f53e520f23bd4274ba6d2eb47bf Mon Sep 17 00:00:00 2001 From: qflen Date: Tue, 13 Oct 2026 11:34:43 +0200 Subject: [PATCH 2/2] fix(desktop-gpui): build the scrub benchmark on Windows and keep drags inside the project Read process CPU time with GetProcessTimes on Windows, where libc is not a dependency, and stop the drag one frame before the project ends so the last request is a frame the preview can render. A drag that does not fit now fails up front instead of timing out. --- apps/desktop-gpui/examples/scrub-benchmark.rs | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/apps/desktop-gpui/examples/scrub-benchmark.rs b/apps/desktop-gpui/examples/scrub-benchmark.rs index b9bf6e719b1..1f3f32c1d6c 100644 --- a/apps/desktop-gpui/examples/scrub-benchmark.rs +++ b/apps/desktop-gpui/examples/scrub-benchmark.rs @@ -18,6 +18,7 @@ const PREVIEW_FPS: u32 = 60; const PREVIEW_RESOLUTION: XY = XY { x: 1248, y: 702 }; const REGION_FRACTIONS: [f64; 5] = [0.02, 0.17, 0.5, 0.83, 0.98]; +#[cfg(unix)] fn cpu_secs() -> f64 { let mut usage = std::mem::MaybeUninit::::zeroed(); unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) }; @@ -26,6 +27,34 @@ fn cpu_secs() -> f64 { secs(usage.ru_utime) + secs(usage.ru_stime) } +#[cfg(windows)] +fn cpu_secs() -> f64 { + use windows_sys::Win32::{ + Foundation::FILETIME, + System::Threading::{GetCurrentProcess, GetProcessTimes}, + }; + + let empty = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let (mut creation, mut exit, mut kernel, mut user) = (empty, empty, empty, empty); + unsafe { + GetProcessTimes( + GetCurrentProcess(), + &mut creation, + &mut exit, + &mut kernel, + &mut user, + ) + }; + let secs = |time: FILETIME| { + ((u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime)) as f64 + / 10_000_000.0 + }; + secs(kernel) + secs(user) +} + fn percentile(sorted: &[f64], fraction: f64) -> f64 { sorted[((sorted.len() - 1) as f64 * fraction).round() as usize] } @@ -87,15 +116,19 @@ async fn run(project_path: PathBuf, steps: u32, step_frames: u32) -> anyhow::Res .timeline .as_ref() .map_or(0.0, |timeline| timeline.duration()); - let last_frame = (duration * PREVIEW_FPS as f64) as u32; + let last_frame = ((duration * PREVIEW_FPS as f64) as u32).saturating_sub(1); + let drag_frames = steps.saturating_mul(step_frames); + anyhow::ensure!( + drag_frames <= last_frame, + "a {drag_frames}-frame drag does not fit in this {duration:.1}s project; pass fewer STEPS or STEP_FRAMES" + ); render(&instance, &frame_rx, 0).await?; let mut regions = Vec::new(); let mut drag = Vec::new(); let mut drag_cpu_secs = 0.0; for fraction in REGION_FRACTIONS { - let start = ((last_frame as f64 * fraction) as u32) - .min(last_frame.saturating_sub(steps * step_frames)); + let start = ((last_frame as f64 * fraction) as u32).min(last_frame - drag_frames); let seek_ms = render(&instance, &frame_rx, start).await?; let cpu_started = cpu_secs(); let mut latencies = Vec::with_capacity(steps as usize);