From c2bfe409cc3b74d306190f3a8fc75e6377f0c2d5 Mon Sep 17 00:00:00 2001 From: Kyzer Phneh Date: Mon, 23 Nov 2026 17:10:51 +0000 Subject: [PATCH 1/3] perf(desktop): compare Half and Full editor preview Add one command that measures playback frame rate and frame latency at two preview qualities on the same project. It does not write the saved quality and does not change the platform default. --- apps/desktop-gpui/src/editor_latency.rs | 197 +++- apps/desktop-gpui/src/editor_latency_bench.rs | 847 +++++++++++++++++- apps/desktop-gpui/src/editor_window.rs | 58 ++ apps/desktop-gpui/src/main.rs | 1 + 4 files changed, 1068 insertions(+), 35 deletions(-) diff --git a/apps/desktop-gpui/src/editor_latency.rs b/apps/desktop-gpui/src/editor_latency.rs index 10446a7a4b1..e8dba3bd201 100644 --- a/apps/desktop-gpui/src/editor_latency.rs +++ b/apps/desktop-gpui/src/editor_latency.rs @@ -1,7 +1,8 @@ //! Timestamps every preview frame through the editor's pipeline, from the //! frame demand to the canvas paint that hands it to the compositor. Only -//! `CAP_GPUI_AUTO_LATENCY_BENCH=1` turns it on, and that bench drains the marks -//! after every scenario. Off, each mark is one `OnceLock` read. +//! `CAP_GPUI_AUTO_LATENCY_BENCH=1` or `CAP_GPUI_AUTO_PREVIEW_COMPARE=1` turns +//! it on, and that bench drains the marks after every scenario. Off, each +//! mark is one `OnceLock` read. //! //! Stages, in pipeline order: //! * `Input` -- the harness's synthetic pointer or edit, just before it runs. @@ -36,16 +37,22 @@ struct Probe { sizes: Mutex>, } +pub(crate) fn probe_enabled() -> bool { + env_flag("CAP_GPUI_AUTO_LATENCY_BENCH") || env_flag("CAP_GPUI_AUTO_PREVIEW_COMPARE") +} + +fn env_flag(name: &str) -> bool { + std::env::var(name).is_ok_and(|value| value == "1") +} + fn probe() -> Option<&'static Probe> { static PROBE: OnceLock> = OnceLock::new(); PROBE .get_or_init(|| { - std::env::var("CAP_GPUI_AUTO_LATENCY_BENCH") - .is_ok_and(|value| value == "1") - .then(|| Probe { - marks: Mutex::new(Vec::with_capacity(1 << 16)), - sizes: Mutex::new(Vec::with_capacity(1 << 16)), - }) + probe_enabled().then(|| Probe { + marks: Mutex::new(Vec::with_capacity(1 << 16)), + sizes: Mutex::new(Vec::with_capacity(1 << 16)), + }) }) .as_ref() } @@ -292,6 +299,106 @@ pub(crate) fn percentiles(samples: &mut [f64]) -> Option<[f64; 4]> { Some([at(0.5), at(0.95), at(0.99), samples[samples.len() - 1]]) } +pub(crate) struct PlaybackStats { + pub frames: usize, + pub skipped: u32, + pub fps: f64, + pub present_p95_ms: Option, + pub rendered_to_painted_p95_ms: Option, + pub size: Option<[u32; 2]>, + pub steady: Vec, +} + +pub(crate) fn playback_stats( + marks: &[Mark], + sizes: &[(u64, [u32; 2])], + from: Instant, + until: Instant, +) -> PlaybackStats { + let (shown, _) = presentations(marks); + let steady: Vec = shown + .into_iter() + .filter(|presentation| presentation.painted >= from && presentation.painted <= until) + .collect(); + let window_secs = until.saturating_duration_since(from).as_secs_f64(); + let frames = steady.len(); + let fps = if window_secs > 0.0 { + frames as f64 / window_secs + } else { + 0.0 + }; + let skipped: u32 = steady + .windows(2) + .map(|pair| { + pair[1] + .frame + .saturating_sub(pair[0].frame) + .saturating_sub(1) + }) + .sum(); + let mut intervals: Vec = steady + .windows(2) + .map(|pair| millis(pair[0].painted, pair[1].painted)) + .collect(); + let mut rendered_to_painted: Vec = steady + .iter() + .filter_map(|presentation| { + presentation + .rendered + .map(|rendered| millis(rendered, presentation.painted)) + }) + .collect(); + PlaybackStats { + frames, + skipped, + fps, + present_p95_ms: percentiles(&mut intervals).map(|percentile| percentile[1]), + rendered_to_painted_p95_ms: percentiles(&mut rendered_to_painted) + .map(|percentile| percentile[1]), + size: modal_painted_size(marks, sizes, from, until), + steady, + } +} + +fn modal_painted_size( + marks: &[Mark], + sizes: &[(u64, [u32; 2])], + from: Instant, + until: Instant, +) -> Option<[u32; 2]> { + let by_sequence: std::collections::HashMap = sizes.iter().copied().collect(); + let mut seen = std::collections::HashSet::new(); + let mut counts: Vec<([u32; 2], usize)> = Vec::new(); + for mark in marks { + if mark.stage != Stage::Painted || mark.at < from || mark.at > until { + continue; + } + if !seen.insert(mark.sequence) { + continue; + } + let Some(size) = by_sequence.get(&mark.sequence).copied() else { + continue; + }; + if let Some((_, count)) = counts.iter_mut().find(|(known, _)| *known == size) { + *count += 1; + } else { + counts.push((size, 1)); + } + } + counts + .into_iter() + .max_by(|left, right| { + left.1 + .cmp(&right.1) + .then_with(|| { + (u64::from(left.0[0]) * u64::from(left.0[1])) + .cmp(&(u64::from(right.0[0]) * u64::from(right.0[1]))) + }) + .then_with(|| left.0[0].cmp(&right.0[0])) + }) + .map(|(size, _)| size) +} + #[cfg(test)] mod tests { use std::time::Duration; @@ -478,4 +585,78 @@ mod tests { assert_eq!(percentiles(&mut samples), Some([51.0, 95.0, 99.0, 100.0])); assert_eq!(percentiles(&mut []), None); } + + fn steady_playback(frame_numbers: &[u32], size: [u32; 2]) -> PlaybackStats { + let base = Instant::now(); + let from = at(base, 1_000); + let until = at(base, 2_000); + let mut marks = Vec::new(); + let mut sizes = Vec::new(); + for (index, frame) in frame_numbers.iter().copied().enumerate() { + let painted = from + Duration::from_millis(u64::try_from(index).unwrap() * 100); + let sequence = u64::try_from(index + 1).unwrap(); + marks.push(mark( + Stage::Rendered, + frame, + 0, + painted - Duration::from_millis(8), + )); + marks.push(mark( + Stage::Arrived, + frame, + sequence, + painted - Duration::from_millis(2), + )); + marks.push(mark(Stage::Painted, frame, sequence, painted)); + sizes.push((sequence, size)); + } + playback_stats(&marks, &sizes, from, until) + } + + #[test] + fn steady_playback_reports_fps_latency_and_size() { + let stats = steady_playback(&(0..10).collect::>(), [1248, 702]); + assert_eq!(stats.frames, 10); + assert_eq!(stats.skipped, 0); + assert!((stats.fps - 10.0).abs() < 1e-9); + assert_eq!(stats.present_p95_ms, Some(100.0)); + assert_eq!(stats.rendered_to_painted_p95_ms, Some(8.0)); + assert_eq!(stats.size, Some([1248, 702])); + } + + #[test] + fn a_gap_in_frame_numbers_counts_as_skipped_source_frames() { + let stats = steady_playback(&[0, 1, 3, 4, 5, 6, 7, 8, 9, 10], [1920, 1080]); + assert_eq!(stats.skipped, 1); + assert_eq!(stats.size, Some([1920, 1080])); + } + + #[test] + fn no_painted_frame_is_not_a_playback_measurement() { + let base = Instant::now(); + let stats = playback_stats(&[], &[], at(base, 0), at(base, 1_000)); + assert_eq!(stats.frames, 0); + assert_eq!(stats.fps, 0.0); + assert_eq!(stats.present_p95_ms, None); + assert_eq!(stats.rendered_to_painted_p95_ms, None); + assert_eq!(stats.size, None); + } + + #[test] + fn the_painted_size_is_the_one_that_appears_most() { + let base = Instant::now(); + let from = at(base, 0); + let until = at(base, 1_000); + let marks = [ + mark(Stage::Painted, 1, 1, at(base, 10)), + mark(Stage::Painted, 2, 2, at(base, 20)), + mark(Stage::Painted, 3, 3, at(base, 30)), + mark(Stage::Painted, 3, 3, at(base, 40)), + ]; + let sizes = [(1, [10, 10]), (2, [1920, 1080]), (3, [1920, 1080])]; + assert_eq!( + playback_stats(&marks, &sizes, from, until).size, + Some([1920, 1080]) + ); + } } diff --git a/apps/desktop-gpui/src/editor_latency_bench.rs b/apps/desktop-gpui/src/editor_latency_bench.rs index 2c835154e10..bce3898579a 100644 --- a/apps/desktop-gpui/src/editor_latency_bench.rs +++ b/apps/desktop-gpui/src/editor_latency_bench.rs @@ -9,6 +9,20 @@ //! CAP_GPUI_AUTO_EDITOR= CAP_GPUI_AUTO_LATENCY_BENCH=1 \ //! CAP_GPUI_NO_MENUS=1 CAP_GPUI_NO_TRAY=1 CAP_GPUI_MUTE_AUDIO=1 \ //! cargo run --release +//! +//! Half against Full, same project and scenarios, from `apps/desktop-gpui`: +//! cargo run --release -- --preview-compare +//! +//! That runs `playback,pause` at `half` then `full`, five times, and swaps +//! which quality goes first on each repeat. It prints the adapter, playback +//! frames per second, and `playback_frame_latency_p95_ms` (render callback to +//! paint over the steady window). `pause_frame_latency_p95_ms` is the pause +//! to a canvas-sized frame. `--preview-compare-repeats`, +//! `--preview-compare-scenarios`, and `--preview-compare-qualities` override +//! those. The `build=` line is `release` or `dev`. A `dev` build leaves this +//! crate unoptimized, so its frame rate is not the shipping cost. The command +//! does not write the saved preview quality, and it does not change +//! [`crate::store::EditorPreviewQuality::for_this_machine`]. use std::time::{Duration, Instant}; @@ -20,6 +34,7 @@ use crate::{ editor_sidebar::{BgSlider, SliderKey}, editor_timeline::{self, TrackKind}, editor_window::EditorWindow, + store::SettingsEnum, }; const DISPLAY_INTERVAL_MS: f64 = 1000.0 / 60.0; @@ -38,11 +53,16 @@ const PAUSE_SETTLE: Duration = Duration::from_secs(2); type Handle = WindowHandle; pub(crate) async fn run(handle: Handle, cx: &mut AsyncApp) { - if !std::env::var("CAP_GPUI_AUTO_LATENCY_BENCH").is_ok_and(|value| value == "1") { + if !editor_latency::probe_enabled() { return; } + let compare = std::env::var("CAP_GPUI_AUTO_PREVIEW_COMPARE").is_ok_and(|value| value == "1"); let scenarios = std::env::var("CAP_GPUI_AUTO_LATENCY_SCENARIOS").unwrap_or_else(|_| { - "playback,scrub-fast,scrub-fine,zoom-drag,preset,slider,resize,pause".into() + if compare { + "playback,pause".into() + } else { + "playback,scrub-fast,scrub-fine,zoom-drag,preset,slider,resize,pause".into() + } }); let started = Instant::now(); @@ -86,16 +106,25 @@ pub(crate) async fn run(handle: Handle, cx: &mut AsyncApp) { println!("{header}"); memory_report("start"); + if compare { + let failed = run_compare(handle, cx, &scenarios).await; + std::process::exit(if failed { 1 } else { 0 }); + } + for scenario in scenarios.split(',').map(str::trim) { match scenario { - "playback" => playback(handle, cx).await, + "playback" => { + playback(handle, cx).await; + } "scrub-fast" => scrub(handle, cx, "scrub-fast", 0.1, 0.6).await, "scrub-fine" => scrub(handle, cx, "scrub-fine", 0.3, 0.302).await, "zoom-drag" => zoom_drag(handle, cx).await, "preset" => preset(handle, cx).await, "slider" => slider(handle, cx).await, "resize" => resize(handle, cx).await, - "pause" => pause(handle, cx).await, + "pause" => { + pause(handle, cx).await; + } other => eprintln!("latency-bench: unknown scenario {other}"), } memory_report(scenario); @@ -163,9 +192,10 @@ async fn paced_inputs( } } -async fn playback(handle: Handle, cx: &mut AsyncApp) { +async fn playback(handle: Handle, cx: &mut AsyncApp) -> editor_latency::PlaybackStats { pause_at(handle, cx, 0.1).await; editor_latency::take(); + editor_latency::take_sizes(); let before = update(handle, cx, |view, _, _| view.bench_pump_snapshot()); let pressed = Instant::now(); update(handle, cx, |view, window, cx| view.toggle_play(window, cx)); @@ -176,45 +206,40 @@ async fn playback(handle: Handle, cx: &mut AsyncApp) { .map(|(after, before)| after.since(before)); wait(cx, SETTLE).await; let marks = editor_latency::take(); + let sizes = editor_latency::take_sizes(); let (shown, replaced) = editor_latency::presentations(&marks); let first = shown .first() .map(|presentation| editor_latency::millis(pressed, presentation.painted)); - let steady: Vec = shown - .iter() - .copied() - .filter(|presentation| presentation.painted >= pressed + PLAYBACK_WARMUP) - .filter(|presentation| presentation.painted <= pressed + PLAYBACK) - .collect(); + let stats = editor_latency::playback_stats( + &marks, + &sizes, + pressed + PLAYBACK_WARMUP, + pressed + PLAYBACK, + ); let window_secs = PLAYBACK.saturating_sub(PLAYBACK_WARMUP).as_secs_f64(); - let skipped: u32 = steady - .windows(2) - .map(|pair| { - pair[1] - .frame - .saturating_sub(pair[0].frame) - .saturating_sub(1) - }) - .sum(); - let repeats = steady + let repeats = stats + .steady .windows(2) .filter(|pair| pair[1].frame <= pair[0].frame) .count(); - let mut intervals = intervals(&steady); + let mut intervals = intervals(&stats.steady); let late = intervals .iter() .filter(|interval| **interval > DISPLAY_INTERVAL_MS * 1.5) .count(); println!( "latency-bench: playback first-frame {} ms, {:.1} fps presented over {window_secs:.0}s, \ - {skipped} source frames skipped, {repeats} out of order, {late} intervals over 25 ms, \ + {} source frames skipped, {repeats} out of order, {late} intervals over 25 ms, \ {replaced} replaced before paint, pump dropped {}", first.map_or("-".into(), |ms| format!("{ms:.1}")), - steady.len() as f64 / window_secs, + stats.fps, + stats.skipped, pump.map_or(0, |pump| pump.dropped), ); report("playback", "present interval", &mut intervals); - stage_report("playback", &steady); + stage_report("playback", &stats.steady); + stats } async fn scrub(handle: Handle, cx: &mut AsyncApp, label: &str, from: f64, to: f64) { @@ -402,7 +427,7 @@ async fn resize(handle: Handle, cx: &mut AsyncApp) { /// Play, pause, and time how long the paused frame takes to be drawn at the /// canvas's own device-pixel size. A build that never re-renders on pause /// reports the size it settles at instead. -async fn pause(handle: Handle, cx: &mut AsyncApp) { +async fn pause(handle: Handle, cx: &mut AsyncApp) -> PauseMeasure { let mut to_sharp = Vec::with_capacity(PAUSE_ROUNDS); for round in 0..PAUSE_ROUNDS { pause_at(handle, cx, 0.2 + 0.12 * round as f64).await; @@ -420,7 +445,7 @@ async fn pause(handle: Handle, cx: &mut AsyncApp) { view.bench_preview_canvas(window) }) else { println!("latency-bench: pause skipped, the preview has no canvas"); - return; + return PauseMeasure::NoCanvas; }; let mut seen = std::collections::HashSet::new(); let painted: Vec<(Instant, [u32; 2])> = marks @@ -457,7 +482,9 @@ async fn pause(handle: Handle, cx: &mut AsyncApp) { save_frame(handle, cx); } } + let latency = editor_latency::percentiles(&mut to_sharp.clone()).map(|rank| rank[1]); report("pause", "pause->canvas-size frame", &mut to_sharp); + PauseMeasure::Latency(latency) } /// `CAP_GPUI_AUTO_LATENCY_SHOT=`: capture the screen with the settled @@ -702,3 +729,769 @@ fn report(label: &str, stage: &str, samples: &mut [f64]) { None => println!("latency-bench: {label} {stage} n=0"), } } + +enum PauseMeasure { + NoCanvas, + Latency(Option), +} + +struct MeasuredPass { + quality: crate::store::EditorPreviewQuality, + repeat: u32, + fps: Option, + frame_latency_p95_ms: Option, + present_interval_p95_ms: Option, + pause_frame_latency_p95_ms: Option, + size: Option<[u32; 2]>, + errors: u32, +} + +struct QualitySummary { + quality: crate::store::EditorPreviewQuality, + samples: usize, + fps: Vec, + latency: Vec, + present: Vec, + pause: Vec, + size: Option<[u32; 2]>, + errors: u32, +} + +struct CompareReport { + text: String, + failed: bool, +} + +struct PreviewCompareLaunch { + project: String, + repeats: Option, + scenarios: Option, + qualities: Option, +} + +pub(crate) fn apply_preview_compare_args() { + let args: Vec = std::env::args().skip(1).collect(); + let launch = match preview_compare_launch(args.iter().map(String::as_str)) { + Ok(Some(launch)) => launch, + Ok(None) => return, + Err(error) => { + eprintln!("preview-compare: {error}"); + std::process::exit(1); + } + }; + if !std::path::Path::new(&launch.project).is_dir() { + eprintln!( + "preview-compare: {} is not a .cap project directory", + launch.project + ); + std::process::exit(1); + } + unsafe { + std::env::set_var("CAP_GPUI_AUTO_EDITOR", &launch.project); + std::env::set_var("CAP_GPUI_AUTO_PREVIEW_COMPARE", "1"); + std::env::set_var("CAP_GPUI_NO_MENUS", "1"); + std::env::set_var("CAP_GPUI_NO_TRAY", "1"); + std::env::set_var("CAP_GPUI_MUTE_AUDIO", "1"); + if let Some(repeats) = &launch.repeats { + std::env::set_var("CAP_GPUI_AUTO_PREVIEW_COMPARE_REPEATS", repeats); + } + if let Some(scenarios) = &launch.scenarios { + std::env::set_var("CAP_GPUI_AUTO_LATENCY_SCENARIOS", scenarios); + } + if let Some(qualities) = &launch.qualities { + std::env::set_var("CAP_GPUI_AUTO_PREVIEW_QUALITIES", qualities); + } + } +} + +fn preview_compare_launch<'a>( + args: impl IntoIterator, +) -> Result, String> { + let args: Vec<&str> = args.into_iter().collect(); + let mut project = None; + let mut repeats = None; + let mut scenarios = None; + let mut qualities = None; + let mut index = 0; + while index < args.len() { + let arg = args[index]; + match arg { + "--preview-compare" => { + project = Some(flag_value(&args, index, arg)?.to_string()); + index += 2; + } + "--preview-compare-repeats" => { + let text = flag_value(&args, index, arg)?; + parse_repeats(text)?; + repeats = Some(text.to_string()); + index += 2; + } + "--preview-compare-scenarios" => { + scenarios = Some(flag_value(&args, index, arg)?.to_string()); + index += 2; + } + "--preview-compare-qualities" => { + let text = flag_value(&args, index, arg)?; + parse_qualities(text)?; + qualities = Some(text.to_string()); + index += 2; + } + other if other.starts_with("--preview-compare") => { + return Err(format!("unknown argument {other}")); + } + _ => index += 1, + } + } + let extra = repeats.is_some() || scenarios.is_some() || qualities.is_some(); + match project { + Some(project) => Ok(Some(PreviewCompareLaunch { + project, + repeats, + scenarios, + qualities, + })), + None if extra => Err("missing --preview-compare ".into()), + None => Ok(None), + } +} + +fn flag_value<'a>(args: &[&'a str], index: usize, flag: &str) -> Result<&'a str, String> { + args.get(index + 1) + .copied() + .filter(|value| !value.starts_with("--")) + .ok_or_else(|| format!("{flag} needs a value")) +} + +fn parse_qualities(text: &str) -> Result, String> { + let mut qualities = Vec::new(); + for part in text.split(',') { + let part = part.trim(); + if part.is_empty() { + return Err("preview quality list has an empty entry".into()); + } + let Some(quality) = crate::store::EditorPreviewQuality::from_json(part) else { + return Err(format!("unknown preview quality '{part}'")); + }; + qualities.push(quality); + } + if qualities.len() < 2 { + return Err("preview compare needs at least two qualities".into()); + } + Ok(qualities) +} + +fn parse_repeats(text: &str) -> Result { + let repeats = text + .parse::() + .map_err(|_| format!("repeats '{text}' is not a number"))?; + if repeats == 0 { + return Err("repeats must be at least 1".into()); + } + Ok(repeats) +} + +fn ordered_qualities( + qualities: &[crate::store::EditorPreviewQuality], + repeat_index: u32, +) -> Vec { + let mut order = qualities.to_vec(); + if repeat_index % 2 == 1 { + order.reverse(); + } + order +} + +async fn run_compare(handle: Handle, cx: &mut AsyncApp, scenarios: &str) -> bool { + let qualities = match parse_qualities( + &std::env::var("CAP_GPUI_AUTO_PREVIEW_QUALITIES").unwrap_or_else(|_| "half,full".into()), + ) { + Ok(qualities) => qualities, + Err(error) => { + println!("preview-compare: {error}"); + return true; + } + }; + let repeats = match parse_repeats( + &std::env::var("CAP_GPUI_AUTO_PREVIEW_COMPARE_REPEATS").unwrap_or_else(|_| "5".into()), + ) { + Ok(repeats) => repeats, + Err(error) => { + println!("preview-compare: {error}"); + return true; + } + }; + let adapter = match adapter_line().await { + Ok(line) => line, + Err(line) => { + println!("{line}"); + return true; + } + }; + println!("{adapter}"); + println!( + "preview-compare: build={}", + if cfg!(debug_assertions) { + "dev" + } else { + "release" + } + ); + println!( + "preview-compare: qualities={} repeats={repeats} scenarios={scenarios}", + qualities + .iter() + .map(|quality| quality.as_json()) + .collect::>() + .join(",") + ); + let saved_choice = preview_choice_record(); + let mut passes = Vec::new(); + for index in 0..repeats { + for quality in ordered_qualities(&qualities, index) { + passes.push(run_pass(handle, cx, quality, index + 1, scenarios).await); + } + } + let report = compare_report(&passes, preview_choice_record() == saved_choice); + println!("{}", report.text); + report.failed +} + +async fn adapter_line() -> Result { + let Some(device) = crate::app_windows::shared_wgpu_device().await else { + return Err(format_adapter("unavailable", "none", "none", true)); + }; + let info = device.adapter.get_info(); + Ok(format_adapter( + &info.name, + &format!("{:?}", info.backend), + &format!("{:?}", info.device_type), + device.is_software_adapter, + )) +} + +fn format_adapter(name: &str, backend: &str, device_type: &str, software: bool) -> String { + let label = if software { + "software-adapter" + } else { + "hardware-adapter" + }; + let name = name.replace('"', "'"); + format!( + "preview-compare: adapter label={label} name=\"{name}\" backend={backend} device_type={device_type} software={software}" + ) +} + +async fn run_pass( + handle: Handle, + cx: &mut AsyncApp, + quality: crate::store::EditorPreviewQuality, + repeat: u32, + scenarios: &str, +) -> MeasuredPass { + update(handle, cx, |view, _, cx| { + view.set_preview_quality_for_measurement(quality, cx); + }); + let mut errors = 0u32; + let mut playback_stats = None; + let mut pause_latency = None; + let mut saw_playback = false; + for scenario in scenarios + .split(',') + .map(str::trim) + .filter(|scenario| !scenario.is_empty()) + { + match scenario { + "playback" => { + saw_playback = true; + playback_stats = Some(playback(handle, cx).await); + } + "pause" => match pause(handle, cx).await { + PauseMeasure::NoCanvas => errors += 1, + PauseMeasure::Latency(latency) => pause_latency = latency, + }, + "scrub-fast" => scrub(handle, cx, "scrub-fast", 0.1, 0.6).await, + "scrub-fine" => scrub(handle, cx, "scrub-fine", 0.3, 0.302).await, + "zoom-drag" => zoom_drag(handle, cx).await, + "preset" => preset(handle, cx).await, + "slider" => slider(handle, cx).await, + "resize" => resize(handle, cx).await, + other => { + eprintln!("latency-bench: unknown scenario {other}"); + errors += 1; + } + } + memory_report(scenario); + } + let frames = playback_stats.as_ref().map_or(0, |stats| stats.frames); + let size = playback_stats.as_ref().and_then(|stats| stats.size); + if !saw_playback || frames == 0 || size.is_none() { + errors += 1; + } + let measured = playback_stats.as_ref().filter(|stats| stats.frames > 0); + MeasuredPass { + quality, + repeat, + fps: measured.map(|stats| stats.fps), + frame_latency_p95_ms: measured.and_then(|stats| stats.rendered_to_painted_p95_ms), + present_interval_p95_ms: measured.and_then(|stats| stats.present_p95_ms), + pause_frame_latency_p95_ms: pause_latency, + size: measured.and_then(|stats| stats.size), + errors, + } +} + +fn compare_report(passes: &[MeasuredPass], default_unchanged: bool) -> CompareReport { + let summaries = summarize(passes); + let resolution = resolution_changed(&summaries); + let mut failed = + !default_unchanged || passes.iter().any(|pass| pass.errors > 0) || resolution != Some(true); + if summaries.iter().any(|summary| summary.samples == 0) { + failed = true; + } + let mut lines: Vec = passes.iter().map(format_pass).collect(); + lines.extend(summaries.iter().map(format_summary)); + lines.push(format_verdict(&summaries, resolution, default_unchanged)); + CompareReport { + text: lines.join("\n"), + failed, + } +} + +fn summarize(passes: &[MeasuredPass]) -> Vec { + let mut order = Vec::new(); + for pass in passes { + if !order.contains(&pass.quality) { + order.push(pass.quality); + } + } + order + .into_iter() + .map(|quality| { + let group: Vec<&MeasuredPass> = passes + .iter() + .filter(|pass| pass.quality == quality) + .collect(); + let mut errors = group.iter().map(|pass| pass.errors).sum(); + let sizes: Vec<[u32; 2]> = group.iter().filter_map(|pass| pass.size).collect(); + let size = if sizes.is_empty() { + None + } else if sizes.iter().all(|size| *size == sizes[0]) { + Some(sizes[0]) + } else { + errors += 1; + None + }; + QualitySummary { + quality, + samples: group.iter().filter(|pass| pass.fps.is_some()).count(), + fps: group.iter().filter_map(|pass| pass.fps).collect(), + latency: group + .iter() + .filter_map(|pass| pass.frame_latency_p95_ms) + .collect(), + present: group + .iter() + .filter_map(|pass| pass.present_interval_p95_ms) + .collect(), + pause: group + .iter() + .filter_map(|pass| pass.pause_frame_latency_p95_ms) + .collect(), + size, + errors, + } + }) + .collect() +} + +fn resolution_changed(summaries: &[QualitySummary]) -> Option { + let sizes: Vec<[u32; 2]> = summaries + .iter() + .filter_map(|summary| summary.size) + .collect(); + if sizes.len() < 2 || sizes.len() != summaries.len() { + return None; + } + Some(sizes.iter().any(|size| *size != sizes[0])) +} + +fn format_pass(pass: &MeasuredPass) -> String { + format!( + "preview-compare: quality={} repeat={} playback_fps={} playback_frame_latency_p95_ms={} present_interval_p95_ms={} pause_frame_latency_p95_ms={} size={} errors={}", + pass.quality.as_json(), + pass.repeat, + fmt_fps(pass.fps), + fmt_ms(pass.frame_latency_p95_ms), + fmt_ms(pass.present_interval_p95_ms), + fmt_ms(pass.pause_frame_latency_p95_ms), + fmt_size(pass.size), + pass.errors, + ) +} + +fn format_summary(summary: &QualitySummary) -> String { + format!( + "preview-compare: quality={} samples={} playback_fps_median={} playback_frame_latency_p95_ms_median={} present_interval_p95_ms_median={} pause_frame_latency_p95_ms_median={} size={} errors={}", + summary.quality.as_json(), + summary.samples, + fmt_spread(&summary.fps, true), + fmt_spread(&summary.latency, false), + fmt_spread(&summary.present, false), + fmt_spread(&summary.pause, false), + fmt_size(summary.size), + summary.errors, + ) +} + +fn format_verdict( + summaries: &[QualitySummary], + resolution: Option, + default_unchanged: bool, +) -> String { + let resolution = match resolution { + Some(true) => "true", + Some(false) => "false", + None => "unknown", + }; + format!( + "preview-compare: playback_fps_ranges_overlap={} playback_frame_latency_ranges_overlap={} resolution_changed={resolution} default_unchanged={default_unchanged}", + metric_overlap(summaries, |summary| &summary.fps), + metric_overlap(summaries, |summary| &summary.latency), + ) +} + +fn preview_choice_record() -> String { + let path = crate::store::tauri_store_path(); + let Ok(text) = std::fs::read_to_string(&path) else { + return "missing".to_string(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return "unreadable".to_string(); + }; + let general = value.get("general_settings"); + let quality = general + .and_then(|item| item.get("editorPreviewQuality")) + .and_then(|item| item.as_str()) + .unwrap_or("-"); + let chosen = general + .and_then(|item| item.get(crate::store::EDITOR_PREVIEW_QUALITY_CHOSEN_KEY)) + .map(|item| item.to_string()) + .unwrap_or_else(|| "-".to_string()); + format!("{quality}/{chosen}") +} + +fn metric_overlap( + summaries: &[QualitySummary], + metric: impl Fn(&QualitySummary) -> &[f64], +) -> &'static str { + if summaries.len() < 2 { + return "inconclusive"; + } + let mut saw_overlap = false; + for pair in summaries.windows(2) { + match ranges_overlap(metric(&pair[0]), metric(&pair[1])) { + "inconclusive" => return "inconclusive", + "true" => saw_overlap = true, + _ => {} + } + } + if saw_overlap { "true" } else { "false" } +} + +fn ranges_overlap(left: &[f64], right: &[f64]) -> &'static str { + if left.len() < 5 || right.len() < 5 { + return "inconclusive"; + } + let Some((_, left_min, left_max)) = spread(left) else { + return "inconclusive"; + }; + let Some((_, right_min, right_max)) = spread(right) else { + return "inconclusive"; + }; + if left_min <= right_max && right_min <= left_max { + "true" + } else { + "false" + } +} + +fn spread(values: &[f64]) -> Option<(f64, f64, f64)> { + if values.is_empty() { + return None; + } + let mut sorted = values.to_vec(); + let median = editor_latency::percentiles(&mut sorted)?[0]; + let min = sorted[0]; + let max = *sorted.last()?; + Some((median, min, max)) +} + +fn fmt_fps(value: Option) -> String { + value.map_or_else(|| "-".to_string(), |value| format!("{value:.1}")) +} + +fn fmt_ms(value: Option) -> String { + value.map_or_else(|| "-".to_string(), |value| format!("{value:.2}")) +} + +fn fmt_size(size: Option<[u32; 2]>) -> String { + size.map_or_else( + || "-".to_string(), + |size| format!("{}x{}", size[0], size[1]), + ) +} + +fn fmt_spread(values: &[f64], fps: bool) -> String { + let Some((median, min, max)) = spread(values) else { + return "-".to_string(); + }; + if fps { + format!("{median:.1} range={min:.1}..{max:.1}") + } else { + format!("{median:.2} range={min:.2}..{max:.2}") + } +} + +#[cfg(test)] +mod compare_tests { + use super::*; + use crate::store::SettingsEnum; + + fn pass( + quality: crate::store::EditorPreviewQuality, + repeat: u32, + fps: f64, + latency: f64, + size: [u32; 2], + ) -> MeasuredPass { + MeasuredPass { + quality, + repeat, + fps: Some(fps), + frame_latency_p95_ms: Some(latency), + present_interval_p95_ms: Some(16.7), + pause_frame_latency_p95_ms: Some(12.0), + size: Some(size), + errors: 0, + } + } + + #[test] + fn one_repeat_does_not_claim_the_ranges_separated() { + let report = compare_report( + &[ + pass( + crate::store::EditorPreviewQuality::Half, + 1, + 30.0, + 8.0, + [1248, 702], + ), + pass( + crate::store::EditorPreviewQuality::Full, + 1, + 28.0, + 9.0, + [1920, 1080], + ), + ], + true, + ); + assert!(!report.failed); + assert!( + report + .text + .contains("playback_fps_ranges_overlap=inconclusive") + ); + assert!( + report + .text + .contains("playback_frame_latency_ranges_overlap=inconclusive") + ); + assert!(report.text.contains("resolution_changed=true")); + assert!(report.text.contains("default_unchanged=true")); + assert!(report.text.contains("size=1248x702")); + assert!(report.text.contains("size=1920x1080")); + assert!(report.text.contains("playback_fps=30.0")); + assert!(report.text.contains("playback_frame_latency_p95_ms=8.00")); + } + + #[test] + fn a_changed_saved_preview_choice_fails() { + let report = compare_report( + &[ + pass( + crate::store::EditorPreviewQuality::Half, + 1, + 30.0, + 8.0, + [1248, 702], + ), + pass( + crate::store::EditorPreviewQuality::Full, + 1, + 28.0, + 9.0, + [1920, 1080], + ), + ], + false, + ); + assert!(report.failed); + assert!(report.text.contains("default_unchanged=false")); + } + + #[test] + fn five_separated_runs_report_medians_and_no_overlap() { + let half = [58.0, 59.0, 60.0, 61.0, 62.0]; + let full = [40.0, 41.0, 42.0, 43.0, 44.0]; + let mut passes = Vec::new(); + for (index, (half_fps, full_fps)) in half.into_iter().zip(full).enumerate() { + let repeat = u32::try_from(index + 1).unwrap(); + passes.push(pass( + crate::store::EditorPreviewQuality::Half, + repeat, + half_fps, + 4.0, + [1248, 702], + )); + passes.push(pass( + crate::store::EditorPreviewQuality::Full, + repeat, + full_fps, + 7.0, + [1920, 1080], + )); + } + let report = compare_report(&passes, true); + assert!(!report.failed); + assert!( + report + .text + .contains("quality=half samples=5 playback_fps_median=60.0 range=58.0..62.0") + ); + assert!( + report + .text + .contains("quality=full samples=5 playback_fps_median=42.0 range=40.0..44.0") + ); + assert!(report.text.contains("playback_fps_ranges_overlap=false")); + assert!( + report + .text + .contains("playback_frame_latency_ranges_overlap=false") + ); + } + + #[test] + fn the_same_render_size_is_not_a_comparison() { + let report = compare_report( + &[ + pass( + crate::store::EditorPreviewQuality::Half, + 1, + 30.0, + 8.0, + [1248, 702], + ), + pass( + crate::store::EditorPreviewQuality::Full, + 1, + 30.0, + 8.0, + [1248, 702], + ), + ], + true, + ); + assert!(report.failed); + assert!(report.text.contains("resolution_changed=false")); + } + + #[test] + fn a_pass_with_no_frames_fails() { + let report = compare_report( + &[ + MeasuredPass { + quality: crate::store::EditorPreviewQuality::Half, + repeat: 1, + fps: None, + frame_latency_p95_ms: None, + present_interval_p95_ms: None, + pause_frame_latency_p95_ms: None, + size: None, + errors: 1, + }, + pass( + crate::store::EditorPreviewQuality::Full, + 1, + 30.0, + 8.0, + [1920, 1080], + ), + ], + true, + ); + assert!(report.failed); + assert!(report.text.contains("resolution_changed=unknown")); + assert!(report.text.contains("errors=1")); + } + + #[test] + fn odd_repeats_reverse_the_quality_order() { + let qualities = parse_qualities("half,full").unwrap(); + assert_eq!( + ordered_qualities(&qualities, 0) + .iter() + .map(|quality| quality.as_json()) + .collect::>(), + ["half", "full"] + ); + assert_eq!( + ordered_qualities(&qualities, 1) + .iter() + .map(|quality| quality.as_json()) + .collect::>(), + ["full", "half"] + ); + } + + #[test] + fn qualities_and_repeats_reject_a_bad_value() { + assert!(parse_qualities("half").is_err()); + assert!(parse_qualities("half,bogus").is_err()); + assert!(parse_qualities("half,,full").is_err()); + assert!(parse_repeats("0").is_err()); + assert!(parse_repeats("nope").is_err()); + assert_eq!(parse_repeats("5").unwrap(), 5); + } + + #[test] + fn the_launch_flag_reads_the_project_and_ignores_other_arguments() { + let launch = preview_compare_launch([ + "--preview-compare", + "/tmp/demo.cap", + "--preview-compare-repeats", + "1", + "cap://example", + ]) + .unwrap() + .unwrap(); + assert_eq!(launch.project, "/tmp/demo.cap"); + assert_eq!(launch.repeats.as_deref(), Some("1")); + assert!(preview_compare_launch(["cap://token"]).unwrap().is_none()); + assert!(preview_compare_launch(["--preview-compare"]).is_err()); + assert!(preview_compare_launch(["--preview-compare-repeats", "2"]).is_err()); + } + + #[test] + fn a_software_adapter_is_labeled_as_software() { + let line = format_adapter("llvmpipe (LLVM 18)", "Vulkan", "Cpu", true); + assert!(line.contains("label=software-adapter")); + assert!(line.contains("name=\"llvmpipe (LLVM 18)\"")); + assert!(line.contains("software=true")); + let hardware = format_adapter("Radeon 780M", "Dx12", "IntegratedGpu", false); + assert!(hardware.contains("label=hardware-adapter")); + assert!(hardware.contains("software=false")); + } +} diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index 1b7aa847079..cd210199848 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -8545,6 +8545,14 @@ impl EditorWindow { if !crate::store::set_editor_preview_quality(quality) { tracing::warn!("failed to persist preview quality"); } + self.set_preview_quality_for_measurement(quality, cx); + } + + pub(crate) fn set_preview_quality_for_measurement( + &mut self, + quality: crate::store::EditorPreviewQuality, + cx: &mut Context, + ) { if quality == self.preview_quality { return; } @@ -14626,6 +14634,56 @@ mod tests { } } + mod preview_compare { + struct StoreGuard { + path: std::path::PathBuf, + } + + impl StoreGuard { + fn new(contents: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cap-preview-compare-store-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_nanos()) + )); + std::fs::write(&path, contents).unwrap(); + crate::store::set_test_tauri_store_path(Some(path.clone())); + Self { path } + } + } + + impl Drop for StoreGuard { + fn drop(&mut self) { + crate::store::set_test_tauri_store_path(None); + let _ = std::fs::remove_file(&self.path); + } + } + + #[gpui::test] + fn a_measurement_quality_change_leaves_the_store_file_alone(cx: &mut gpui::TestAppContext) { + let guard = StoreGuard::new(r#"{"general_settings":{"theme":"dark"}}"#); + let (editor, cx) = super::side_panel::fixture(cx); + let before = std::fs::read(&guard.path).unwrap(); + editor.update(cx, |editor, cx| { + let next = match editor.preview_quality { + crate::store::EditorPreviewQuality::Full => { + crate::store::EditorPreviewQuality::Half + } + _ => crate::store::EditorPreviewQuality::Full, + }; + editor.set_preview_quality_for_measurement(next, cx); + assert_eq!(editor.preview_quality, next); + assert_eq!( + editor.preview_resolution(), + super::super::preview_resolution(next) + ); + }); + assert_eq!(std::fs::read(&guard.path).unwrap(), before); + } + } + #[cfg(target_os = "linux")] mod paused_handoff { use super::*; diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index f1d22de8c89..06281ed006a 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -309,6 +309,7 @@ fn main() { // A copy of Cap started to self-test a hardware H264 encoder runs only // that test and exits, before logging, crash capture or single-instance. cap_enc_ffmpeg::isolated_self_test::run_child_or_register_host(); + crate::editor_latency_bench::apply_preview_compare_args(); #[cfg(target_os = "linux")] if let Some(threads) = cap_utils::linux_runtime::llvmpipe_thread_count() { From 1f42c2c2c9d6254834c9d4035b28ac7eb5e7b231 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:00:34 +0000 Subject: [PATCH 2/3] fix(desktop): compare every preview quality pair Range overlap now checks every quality pair, so a non-adjacent overlap is reported. Playback fixtures subtract known offsets with checked_sub. --- apps/desktop-gpui/src/editor_latency.rs | 8 ++- apps/desktop-gpui/src/editor_latency_bench.rs | 54 +++++++++++++++++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/editor_latency.rs b/apps/desktop-gpui/src/editor_latency.rs index e8dba3bd201..9dba8ed365e 100644 --- a/apps/desktop-gpui/src/editor_latency.rs +++ b/apps/desktop-gpui/src/editor_latency.rs @@ -599,13 +599,17 @@ mod tests { Stage::Rendered, frame, 0, - painted - Duration::from_millis(8), + painted + .checked_sub(Duration::from_millis(8)) + .expect("rendered fixture stays after the offset"), )); marks.push(mark( Stage::Arrived, frame, sequence, - painted - Duration::from_millis(2), + painted + .checked_sub(Duration::from_millis(2)) + .expect("arrived fixture stays after the offset"), )); marks.push(mark(Stage::Painted, frame, sequence, painted)); sizes.push((sequence, size)); diff --git a/apps/desktop-gpui/src/editor_latency_bench.rs b/apps/desktop-gpui/src/editor_latency_bench.rs index bce3898579a..bbfa3e58a2a 100644 --- a/apps/desktop-gpui/src/editor_latency_bench.rs +++ b/apps/desktop-gpui/src/editor_latency_bench.rs @@ -1188,11 +1188,13 @@ fn metric_overlap( return "inconclusive"; } let mut saw_overlap = false; - for pair in summaries.windows(2) { - match ranges_overlap(metric(&pair[0]), metric(&pair[1])) { - "inconclusive" => return "inconclusive", - "true" => saw_overlap = true, - _ => {} + for (left_index, left) in summaries.iter().enumerate() { + for right in summaries.iter().skip(left_index + 1) { + match ranges_overlap(metric(left), metric(right)) { + "inconclusive" => return "inconclusive", + "true" => saw_overlap = true, + _ => {} + } } } if saw_overlap { "true" } else { "false" } @@ -1383,6 +1385,48 @@ mod compare_tests { ); } + #[test] + fn non_adjacent_qualities_still_count_as_overlapping() { + let quarter = [50.0, 52.0, 55.0, 58.0, 60.0]; + let half = [20.0, 22.0, 25.0, 28.0, 30.0]; + let full = [55.0, 57.0, 60.0, 63.0, 65.0]; + let mut passes = Vec::new(); + for (index, ((quarter_fps, half_fps), full_fps)) in + quarter.into_iter().zip(half).zip(full).enumerate() + { + let repeat = u32::try_from(index + 1).unwrap(); + passes.push(pass( + crate::store::EditorPreviewQuality::Quarter, + repeat, + quarter_fps, + 1.0, + [480, 270], + )); + passes.push(pass( + crate::store::EditorPreviewQuality::Half, + repeat, + half_fps, + 10.0, + [1248, 702], + )); + passes.push(pass( + crate::store::EditorPreviewQuality::Full, + repeat, + full_fps, + 20.0, + [1920, 1080], + )); + } + let report = compare_report(&passes, true); + assert!(!report.failed); + assert!(report.text.contains("playback_fps_ranges_overlap=true")); + assert!( + report + .text + .contains("playback_frame_latency_ranges_overlap=false") + ); + } + #[test] fn the_same_render_size_is_not_a_comparison() { let report = compare_report( From 9172bcbf1c8bcc2fb86491318b6d7a0ac3cbf438 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:28:19 +0000 Subject: [PATCH 3/3] fix(desktop): compile the preview measurement test off Linux The test uses the Linux editor window fixture, so it is gated the same way as the other editor window tests. --- apps/desktop-gpui/src/editor_window.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index cd210199848..117140d5d92 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -14634,6 +14634,7 @@ mod tests { } } + #[cfg(target_os = "linux")] mod preview_compare { struct StoreGuard { path: std::path::PathBuf,