Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions apps/desktop-gpui/src/app_windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4866,13 +4866,86 @@ pub(crate) async fn shared_wgpu_device() -> Option<cap_rendering::SharedWgpuDevi
}
}

/// Set once anything has asked for the shared device -- an editor, a
/// screenshot editor or a recording -- so the launch warmup leaves the GPU to
/// it instead of compiling pipelines alongside.
static GPU_WORK_REQUESTED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);

#[cfg(target_os = "macos")]
fn gpu_work_requested() -> bool {
GPU_WORK_REQUESTED.load(std::sync::atomic::Ordering::Acquire)
}

pub(crate) fn prewarm_shared_wgpu_device(cx: &App) {
GPU_WORK_REQUESTED.store(true, std::sync::atomic::Ordering::Release);
gpui_tokio::Tokio::spawn(cx, async {
let _ = shared_wgpu_device().await;
})
.detach();
}

const LAUNCH_RENDER_WARMUP_DELAY: std::time::Duration = std::time::Duration::from_secs(3);

/// The first editor open in a process paid for the system font scan, the
/// shared device and the renderer's first pipeline compiles and draw before
/// its first frame: 0.7-1.2 s, against ~0.2 s for every later open. This warms
/// them a few seconds after launch, off the main thread. The layers are
/// dropped again; only the driver's compiled pipelines, the device and the
/// font database stay.
pub(crate) fn schedule_launch_render_warmup(cx: &App) {
gpui_tokio::Tokio::spawn(cx, async {
tokio::time::sleep(LAUNCH_RENDER_WARMUP_DELAY).await;
let started = std::time::Instant::now();
if tokio::task::spawn_blocking(cap_rendering::prewarm_fonts)
.await
.is_err()
{
return;
}
let fonts_ms = started.elapsed().as_secs_f64() * 1000.0;
let renderer_ms = warm_renderer().await;
tracing::info!(fonts_ms, ?renderer_ms, "launch render warmup finished");
})
.detach();
}

#[cfg(target_os = "macos")]
async fn warm_renderer() -> Option<f64> {
if gpu_work_requested() {
return None;
}
let shared = shared_wgpu_device().await?;
if gpu_work_requested() {
return None;
}
let started = std::time::Instant::now();
let (device, queue, software) = (
shared.device.clone(),
shared.queue.clone(),
shared.is_software_adapter,
);
let mut layers = tokio::task::spawn_blocking(move || {
(!gpu_work_requested())
.then(|| cap_rendering::RendererLayers::new_with_options(&device, &queue, software))
})
.await
.ok()??;
if gpu_work_requested() {
return None;
}
if let Err(error) = cap_rendering::prewarm_first_frame(shared, &mut layers).await {
Comment on lines +4918 to +4937

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Warmup competes with an editor

warm_renderer checks GPU_WORK_REQUESTED only before awaiting device creation. If an editor opens during that wait, the flag becomes true, but warmup still builds another set of layers and draws both frames on the editor's shared device. This adds competing work during the first open. Recheck the flag after device creation, inside the blocking task before building layers, and before drawing.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop-gpui/src/app_windows.rs
Line: 4913-4925

Comment:
**Warmup competes with an editor**

`warm_renderer` checks `GPU_WORK_REQUESTED` only before awaiting device creation. If an editor opens during that wait, the flag becomes true, but warmup still builds another set of layers and draws both frames on the editor's shared device. This adds competing work during the first open. Recheck the flag after device creation, inside the blocking task before building layers, and before drawing.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

tracing::warn!(%error, "launch render warmup frame failed");
}
drop(layers);
Some(started.elapsed().as_secs_f64() * 1000.0)
}

#[cfg(not(target_os = "macos"))]
async fn warm_renderer() -> Option<f64> {
None
}

fn editor_audio_output() -> Arc<cap_editor::AudioOutput> {
if std::env::var("CAP_GPUI_MUTE_AUDIO").is_ok_and(|value| value == "1") {
Arc::new(cap_editor::AudioOutput::new_headless(Box::new(|_, _| {})))
Expand Down
1 change: 1 addition & 0 deletions apps/desktop-gpui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ fn main() {
#[cfg(target_os = "linux")]
single_instance::init_linux_reopen(cx);
updates::schedule_startup_check(cx);
app_windows::schedule_launch_render_warmup(cx);
upload::queue::init(cx);

// The app menu (and with it ⌘W/⌘M/⌘Q) and the status-bar item. Both
Expand Down
93 changes: 83 additions & 10 deletions crates/editor/examples/editor-startup-benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ fn percentile(data: &[f64], p: f64) -> f64 {
sorted[idx.min(sorted.len() - 1)]
}

fn clone_shared_device(
shared: &cap_rendering::SharedWgpuDevice,
) -> cap_rendering::SharedWgpuDevice {
cap_rendering::SharedWgpuDevice {
instance: shared.instance.clone(),
adapter: shared.adapter.clone(),
device: shared.device.clone(),
queue: shared.queue.clone(),
is_software_adapter: shared.is_software_adapter,
}
}

fn has_flag(args: &[String], flag: &str) -> bool {
args.iter().any(|arg| arg == flag)
}
Expand All @@ -43,6 +55,7 @@ fn push_stage(stages: &mut Vec<(&'static str, f64)>, name: &'static str, start:

async fn profile_startup_stages(
recording_path: PathBuf,
shared_device: Option<cap_rendering::SharedWgpuDevice>,
) -> Result<Vec<(&'static str, f64)>, String> {
let mut stages = Vec::new();
let total_start = Instant::now();
Expand All @@ -64,15 +77,23 @@ async fn profile_startup_stages(
)?);
push_stage(&mut stages, "recordings metadata", &mut stage_start);

let render_constants = Arc::new(
let render_constants = Arc::new(if let Some(shared) = shared_device {
RenderVideoConstants::new_with_device(
shared,
&recordings.segments,
recording_meta.clone(),
(**meta).clone(),
)
.map_err(|e| format!("Failed to create render constants: {e}"))?
} else {
RenderVideoConstants::new(
&recordings.segments,
recording_meta.clone(),
(**meta).clone(),
)
.await
.map_err(|e| format!("Failed to create render constants: {e}"))?,
);
.map_err(|e| format!("Failed to create render constants: {e}"))?
});
push_stage(&mut stages, "render constants", &mut stage_start);

let layers_rx = start_renderer_layers_creation(&render_constants, &project);
Expand Down Expand Up @@ -100,13 +121,20 @@ async fn profile_startup_stages(
Ok(stages)
}

async fn run_stage_profile(recording_path: PathBuf, runs: usize) {
async fn run_stage_profile(
recording_path: PathBuf,
runs: usize,
shared_device: Option<&cap_rendering::SharedWgpuDevice>,
) {
let mut stage_values: Vec<(&'static str, Vec<f64>)> = Vec::new();

for _ in 0..runs {
let stages = profile_startup_stages(recording_path.clone())
.await
.expect("Failed to profile startup stages");
let stages = profile_startup_stages(
recording_path.clone(),
shared_device.map(clone_shared_device),
)
.await
.expect("Failed to profile startup stages");

for (stage_idx, (name, value)) in stages.into_iter().enumerate() {
if stage_values.len() <= stage_idx {
Expand Down Expand Up @@ -167,6 +195,8 @@ async fn main() {
let profile_stages = has_flag(&args, "--profile-stages");
let profile_stages_only = has_flag(&args, "--profile-stages-only");
let prewarm_fonts = has_flag(&args, "--prewarm-fonts");
let shared_device_mode = has_flag(&args, "--shared-device");
let prewarm_renderer = has_flag(&args, "--prewarm-renderer");
let resolution_base = cap_project::XY::new(1248, 702);

println!("{}", "=".repeat(64));
Expand All @@ -187,8 +217,44 @@ async fn main() {
started.elapsed().as_secs_f64() * 1000.0
);
}
let mut shared_device = None;
if prewarm_renderer {
let started = Instant::now();
tokio::task::spawn_blocking(cap_rendering::prewarm_fonts)
.await
.expect("Font preparation failed");
let shared = cap_rendering::create_shared_device()
.await
.expect("Failed to create shared device");
let (device, queue, software) = (
shared.device.clone(),
shared.queue.clone(),
shared.is_software_adapter,
);
let mut layers = tokio::task::spawn_blocking(move || {
cap_rendering::RendererLayers::new_with_options(&device, &queue, software)
})
.await
.expect("Renderer warmup failed");
cap_rendering::prewarm_first_frame(clone_shared_device(&shared), &mut layers)
.await
.expect("Renderer warmup frame failed");
drop(layers);
shared_device = Some(shared);
println!(
"Renderer warmup before startup timing: {:.3}ms",
started.elapsed().as_secs_f64() * 1000.0
);
}
if profile_stages_only {
run_stage_profile(recording_path, runs).await;
if shared_device_mode && shared_device.is_none() {
shared_device = Some(
cap_rendering::create_shared_device()
.await
.expect("Failed to create shared device"),
);
}
run_stage_profile(recording_path, runs, shared_device.as_ref()).await;
return;
Comment on lines 249 to 258

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Stage timings ignore device mode

--prewarm-renderer and --shared-device do not carry through to --profile-stages or --profile-stages-only. Those paths call profile_startup_stages, which creates a fresh device through RenderVideoConstants::new. The stage results therefore measure different device behavior from the requested mode. Pass the shared device into stage profiling, or reject these flag combinations.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/editor/examples/editor-startup-benchmark.rs
Line: 233-235

Comment:
**Stage timings ignore device mode**

`--prewarm-renderer` and `--shared-device` do not carry through to `--profile-stages` or `--profile-stages-only`. Those paths call `profile_startup_stages`, which creates a fresh device through `RenderVideoConstants::new`. The stage results therefore measure different device behavior from the requested mode. Pass the shared device into stage profiling, or reject these flag combinations.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

}

Expand All @@ -203,13 +269,20 @@ async fn main() {

let (frame_tx, frame_rx) = mpsc::channel::<()>();
let start = Instant::now();
if (shared_device_mode || prewarm_renderer) && shared_device.is_none() {
shared_device = Some(
cap_rendering::create_shared_device()
.await
.expect("Failed to create shared device"),
);
}
let editor = EditorInstance::new(
recording_path.clone(),
|_| {},
Box::new(move |_: EditorFrameOutput, _: FrameLayout| {
let _ = frame_tx.send(());
}),
None,
shared_device.as_ref().map(clone_shared_device),
)
.await
.expect("Failed to create editor instance");
Expand Down Expand Up @@ -267,6 +340,6 @@ async fn main() {
);

if profile_stages {
run_stage_profile(recording_path, runs).await;
run_stage_profile(recording_path, runs, shared_device.as_ref()).await;
}
}
86 changes: 86 additions & 0 deletions crates/rendering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,92 @@ pub fn prewarm_fonts() {
drop(layers::new_font_system());
}

/// Renders one small RGBA frame and one NV12 frame through the full frame
/// pipeline with `layers`, then discards them. A fresh process waits on the
/// driver finishing each pipeline the first time it draws (the first preview
/// of the first editor took ~50 ms longer than any later one); building
/// `layers` and drawing once off the hot path moves both costs there.
pub async fn prewarm_first_frame(
shared: SharedWgpuDevice,
layers: &mut RendererLayers,
) -> Result<(), RenderingError> {
const SIZE: u32 = 64;
let studio_meta = StudioRecordingMeta::SingleSegment {
segment: cap_project::SingleSegment {
display: cap_project::VideoMeta {
path: "prewarm.png".into(),
fps: 30,
start_time: Some(0.0),
device_id: None,
},
camera: None,
audio: None,
cursor: None,
},
};
let recording_meta = RecordingMeta {
platform: None,
project_path: std::env::temp_dir(),
pretty_name: "Prewarm".to_string(),
sharing: None,
inner: cap_project::RecordingMetaInner::Studio(Box::new(studio_meta.clone())),
upload: None,
};
let constants = RenderVideoConstants::from_shared_device(
shared,
RenderOptions {
screen_size: XY::new(SIZE, SIZE),
camera_size: None,
preserve_screen_alpha: true,
},
studio_meta,
recording_meta,
Arc::new(BackgroundTextureCache::default()),
);
let config = Arc::new(ProjectConfiguration::default());
let cursor_events = CursorEvents::default();
let mut zoom_timeline = ZoomTransformTimeline::new(
&[],
None,
&cursor_events,
config.screen_movement_spring,
0.0,
None,
);
zoom_timeline.ensure_precomputed_until(1.0 / 30.0);
let (base_w, base_h) = ProjectUniforms::get_base_size(&constants.options, &config);
let mut frame_renderer = FrameRenderer::new(&constants);
let pixels = (SIZE * SIZE) as usize;
for screen_frame in [
DecodedFrame::new(vec![255; pixels * 4], SIZE, SIZE),
DecodedFrame::new_nv12(vec![128; pixels * 3 / 2], SIZE, SIZE, SIZE, SIZE),
] {
let segment_frames = DecodedSegmentFrames {
screen_size: XY::new(SIZE, SIZE),
screen_frame: Some(screen_frame),
camera_frame: None,
segment_time: 0.0,
recording_time: 0.0,
segment_has_camera: false,
};
let uniforms = ProjectUniforms::new(
&constants,
&config,
0,
30,
XY::new(base_w, base_h),
&cursor_events,
&segment_frames,
0.0,
&zoom_timeline,
);
frame_renderer
.render_immediate(segment_frames, uniforms, &cursor_events, true, layers)
.await?;
}
Ok(())
}

/// Unique installed font family names, sorted, for the editor's font picker.
/// Reuses the process-wide font database scan (see [`prewarm_fonts`]).
/// Dot-prefixed families (macOS-internal UI fonts) are hidden the same way
Expand Down
Loading