Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop): gate graphics recovery on GPU init-phase deaths

Richie McIlroyffdcbb0cb50d
diff --git a/apps/desktop/src-tauri/src/crash_sentinel.rs b/apps/desktop/src-tauri/src/crash_sentinel.rs
index adeaf129d..f3b0807fc 100644
--- a/apps/desktop/src-tauri/src/crash_sentinel.rs
+++ b/apps/desktop/src-tauri/src/crash_sentinel.rs
@@ -25,22 +25,44 @@ struct SessionRecord {
arch: String,
#[serde(default)]
liquid_glass: String,
+ /// True while GPU adapter/device initialisation is in flight. If the process
+ /// dies inside that window, the next launch treats the death as a
+ /// graphics-init crash (the only case that justifies software-rendering
+ /// recovery); a death at any other time says nothing about the GPU.
+ #[serde(default)]
+ gpu_init_phase: bool,
+ /// True when this session was already running in software-graphics recovery
+ /// mode, so a follow-up crash doesn't chain into recovery forever.
+ #[serde(default)]
+ graphics_recovery: bool,
}
struct ActiveSession {
path: PathBuf,
- #[cfg(target_os = "macos")]
record: SessionRecord,
+ gpu_init_depth: u32,
}
static SESSION: Mutex<Option<ActiveSession>> = Mutex::new(None);
+/// How the previous session died, as reconstructed from its surviving sentinel.
+/// Only the Windows graphics-recovery path consumes the fields today.
+#[derive(Clone, Copy)]
+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+pub struct UnexpectedTermination {
+ /// The process died while GPU adapter/device initialisation was in flight.
+ pub during_gpu_init: bool,
+ /// The session was already running in software-graphics recovery mode.
+ pub in_graphics_recovery: bool,
+}
+
/// Arm the sentinel for this session and, if a previous session's sentinel survived,
/// report that unexpected termination to Sentry. Call once at startup, after Sentry
-/// is initialised.
-pub fn init(logs_dir: &Path, app_version: &str) -> bool {
+/// is initialised. Returns details of the previous session's unexpected termination,
+/// or `None` if the previous session shut down cleanly.
+pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination> {
let path = logs_dir.join(SENTINEL_FILE);
- let mut previous_session_terminated_unexpectedly = false;
+ let mut previous_termination = None;
if let Ok(contents) = std::fs::read_to_string(&path) {
match serde_json::from_str::<SessionRecord>(&contents) {
@@ -48,10 +70,13 @@ pub fn init(logs_dir: &Path, app_version: &str) -> bool {
// single-instance double launch (this init runs before the
// single-instance plugin loads), not a crash. Leave it untouched and
// don't arm a competing sentinel for this about-to-exit instance.
- Ok(prev) if process_is_running(prev.pid) => return false,
+ Ok(prev) if process_is_running(prev.pid) => return None,
Ok(prev) => {
report_unexpected_termination(&prev);
- previous_session_terminated_unexpectedly = true;
+ previous_termination = Some(UnexpectedTermination {
+ during_gpu_init: prev.gpu_init_phase,
+ in_graphics_recovery: prev.graphics_recovery,
+ });
}
Err(error) => {
tracing::warn!(%error, "Found unreadable crash sentinel from previous session")
@@ -74,6 +99,8 @@ pub fn init(logs_dir: &Path, app_version: &str) -> bool {
os: os.clone(),
arch: arch.clone(),
liquid_glass: "unknown".to_string(),
+ gpu_init_phase: false,
+ graphics_recovery: false,
};
write_record(&path, &record);
@@ -86,11 +113,57 @@ pub fn init(logs_dir: &Path, app_version: &str) -> bool {
*SESSION.lock().unwrap() = Some(ActiveSession {
path,
- #[cfg(target_os = "macos")]
record,
+ gpu_init_depth: 0,
});
- previous_session_terminated_unexpectedly
+ previous_termination
+}
+
+/// Arm the GPU-init marker while adapter/device initialisation runs. If the process
+/// dies inside this window the next launch sees `during_gpu_init` and can engage
+/// graphics recovery. Nestable; the marker persists until the last exit call.
+pub fn enter_gpu_init_phase() {
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ {
+ session.gpu_init_depth += 1;
+ if !session.record.gpu_init_phase {
+ session.record.gpu_init_phase = true;
+ write_record(&session.path, &session.record);
+ }
+ }
+}
+
+/// Disarm the GPU-init marker once initialisation finished (successfully or not —
+/// a survivable failure is not a crash).
+pub fn exit_gpu_init_phase() {
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ {
+ session.gpu_init_depth = session.gpu_init_depth.saturating_sub(1);
+ if session.gpu_init_depth == 0 && session.record.gpu_init_phase {
+ session.record.gpu_init_phase = false;
+ write_record(&session.path, &session.record);
+ }
+ }
+}
+
+/// Record that this session is running in software-graphics recovery mode, so an
+/// unexpected termination of *this* session doesn't chain into recovery again.
+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+pub fn mark_graphics_recovery() {
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ && !session.record.graphics_recovery
+ {
+ session.record.graphics_recovery = true;
+ write_record(&session.path, &session.record);
+ }
+
+ sentry::configure_scope(|scope| {
+ scope.set_tag("graphics_recovery", "true");
+ });
}
/// Record the result of the macOS Liquid Glass material attempt so that, if this
@@ -128,6 +201,8 @@ fn report_unexpected_termination(prev: &SessionRecord) {
prev_started_at = %prev.started_at,
prev_os = %prev.os,
prev_liquid_glass = %prev.liquid_glass,
+ prev_gpu_init_phase = prev.gpu_init_phase,
+ prev_graphics_recovery = prev.graphics_recovery,
"Previous Cap session terminated without a clean shutdown"
);
@@ -138,6 +213,8 @@ fn report_unexpected_termination(prev: &SessionRecord) {
scope.set_tag("prev.arch", &prev.arch);
scope.set_tag("prev.app_version", &prev.app_version);
scope.set_tag("prev.macos_liquid_glass", &prev.liquid_glass);
+ scope.set_tag("prev.gpu_init_phase", prev.gpu_init_phase.to_string());
+ scope.set_tag("prev.graphics_recovery", prev.graphics_recovery.to_string());
scope.set_extra("prev.pid", prev.pid.into());
scope.set_extra("prev.started_at", prev.started_at.clone().into());
},
diff --git a/apps/desktop/src-tauri/src/gpu_context.rs b/apps/desktop/src-tauri/src/gpu_context.rs
index 5964920e6..7edbe19b2 100644
--- a/apps/desktop/src-tauri/src/gpu_context.rs
+++ b/apps/desktop/src-tauri/src/gpu_context.rs
@@ -49,7 +49,28 @@ pub struct SharedGpuContext {
static GPU: OnceCell<Option<SharedGpuContext>> = OnceCell::const_new();
+/// Marks the crash sentinel while GPU adapter/device initialisation is in flight, so
+/// a process death inside that window is attributable to graphics bring-up. Dropping
+/// the guard (including during unwind from a caught panic) disarms the marker — a
+/// survivable failure is not a GPU crash.
+struct GpuInitPhaseGuard;
+
+impl GpuInitPhaseGuard {
+ fn arm() -> Self {
+ crate::crash_sentinel::enter_gpu_init_phase();
+ Self
+ }
+}
+
+impl Drop for GpuInitPhaseGuard {
+ fn drop(&mut self) {
+ crate::crash_sentinel::exit_gpu_init_phase();
+ }
+}
+
async fn init_gpu_inner() -> Option<SharedGpuContext> {
+ let _gpu_init_phase = GpuInitPhaseGuard::arm();
+
let instance = cap_rendering::create_wgpu_instance().await;
let force_software_adapter = cap_rendering::force_software_wgpu_adapter();
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2e30e9384..42898e466 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -198,6 +198,46 @@ mod tests {
XY::new(1248, 702)
);
}
+
+ #[test]
+ fn graphics_recovery_only_engages_for_gpu_init_deaths() {
+ use crash_sentinel::UnexpectedTermination;
+
+ // Clean previous exit: never engage.
+ assert!(!should_engage_graphics_recovery(None));
+
+ // Died outside GPU init (force-quit, power loss, OS kill): a healthy GPU
+ // machine must keep hardware rendering.
+ assert!(!should_engage_graphics_recovery(Some(
+ UnexpectedTermination {
+ during_gpu_init: false,
+ in_graphics_recovery: false,
+ }
+ )));
+
+ // Died during GPU bring-up on hardware: engage software recovery.
+ assert!(should_engage_graphics_recovery(Some(
+ UnexpectedTermination {
+ during_gpu_init: true,
+ in_graphics_recovery: false,
+ }
+ )));
+
+ // A recovery-mode session that also died must not chain into recovery
+ // forever; retry hardware.
+ assert!(!should_engage_graphics_recovery(Some(
+ UnexpectedTermination {
+ during_gpu_init: true,
+ in_graphics_recovery: true,
+ }
+ )));
+ assert!(!should_engage_graphics_recovery(Some(
+ UnexpectedTermination {
+ during_gpu_init: false,
+ in_graphics_recovery: true,
+ }
+ )));
+ }
}
#[derive(Default)]
@@ -2845,6 +2885,27 @@ struct EditorStateChanged {
playhead_position: u32,
}
+/// Rendered display/camera placement of the latest preview frame, in
+/// output-frame pixels — consumed by the editor's on-canvas layout overlay.
+#[derive(Serialize, specta::Type, tauri_specta::Event, Debug, Clone, PartialEq)]
+pub(crate) struct FrameLayoutEvent {
+ display: [f32; 4],
+ camera: Option<[f32; 4]>,
+ output_width: u32,
+ output_height: u32,
+}
+
+impl From<cap_editor::FrameLayout> for FrameLayoutEvent {
+ fn from(layout: cap_editor::FrameLayout) -> Self {
+ Self {
+ display: layout.display,
+ camera: layout.camera,
+ output_width: layout.output_size[0],
+ output_height: layout.output_size[1],
+ }
+ }
+}
+
impl EditorStateChanged {
fn new(s: &EditorState) -> Self {
Self {
@@ -4535,26 +4596,50 @@ type FilteredRegistry = tracing_subscriber::layer::Layered<
pub type DynLoggingLayer = Box<dyn tracing_subscriber::Layer<FilteredRegistry> + Send + Sync>;
type LoggingHandle = tracing_subscriber::reload::Handle<Option<DynLoggingLayer>, FilteredRegistry>;
+/// Software recovery exists to break GPU-driver crash loops: a process that died
+/// while wgpu adapter/device initialisation was in flight. Any other unexpected
+/// termination (force-quit, power loss, OS kill, a hung shutdown) says nothing
+/// about the GPU, and forcing the WARP software rasterizer would cripple editor
+/// playback (seconds-per-frame renders) on perfectly healthy hardware. A previous
+/// session that was *already* in software recovery and still died shows software
+/// mode isn't saving the machine, so retry hardware rather than chaining recovery
+/// launches forever.
+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+fn should_engage_graphics_recovery(
+ previous_termination: Option<crash_sentinel::UnexpectedTermination>,
+) -> bool {
+ previous_termination.is_some_and(|prev| prev.during_gpu_init && !prev.in_graphics_recovery)
+}
+
#[cfg(target_os = "windows")]
-fn configure_windows_graphics_recovery(previous_session_terminated_unexpectedly: bool) {
- if previous_session_terminated_unexpectedly {
+fn configure_windows_graphics_recovery(
+ previous_termination: Option<crash_sentinel::UnexpectedTermination>,
+) {
+ if should_engage_graphics_recovery(previous_termination) {
cap_rendering::set_force_software_wgpu_adapter(true);
+ crash_sentinel::mark_graphics_recovery();
warn!(
- "Previous Cap session terminated unexpectedly; using Windows software graphics recovery mode for this launch"
+ "Previous Cap session terminated during GPU initialisation; using Windows software graphics recovery mode for this launch"
+ );
+ } else if previous_termination.is_some() {
+ info!(
+ "Previous session terminated unexpectedly, but not during first-time GPU initialisation; keeping hardware graphics"
);
}
}
#[cfg(not(target_os = "windows"))]
-fn configure_windows_graphics_recovery(_previous_session_terminated_unexpectedly: bool) {}
+fn configure_windows_graphics_recovery(
+ _previous_termination: Option<crash_sentinel::UnexpectedTermination>,
+) {
+}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
// Arm the unexpected-termination sentinel before anything else can crash, and
// report any previous session that died without a clean shutdown.
- let previous_session_terminated_unexpectedly =
- crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
- configure_windows_graphics_recovery(previous_session_terminated_unexpectedly);
+ let previous_termination = crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
+ configure_windows_graphics_recovery(previous_termination);
ffmpeg::init()
.map_err(|e| {
@@ -4738,6 +4823,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
NewScreenshotAdded,
RenderFrameEvent,
EditorStateChanged,
+ FrameLayoutEvent,
CurrentRecordingChanged,
RecordingStarted,
RecordingStopped,
@@ -6155,7 +6241,7 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {
async fn create_editor_instance_impl(
app: &AppHandle,
path: PathBuf,
- frame_cb: Box<dyn FnMut(cap_editor::EditorFrameOutput) + Send>,
+ frame_cb: cap_editor::EditorFrameCallback,
) -> Result<(Arc<EditorInstance>, tauri::EventId), String> {
let app = app.clone();
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index b703a76d9..f0c0d1b84 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -83,12 +83,28 @@ fn extract_yuv_planes(frame: &frame::Video) -> Option<(Vec<u8>, PixelFormat, u32
let y_size = (y_stride * height) as usize;
let uv_height = height / 2;
let u_size = (u_stride * uv_height) as usize;
- let v_size = (v_stride * uv_height) as usize;
- let mut data = Vec::with_capacity(y_size + u_size + v_size);
+ let mut data = Vec::with_capacity(y_size + 2 * u_size);
data.extend_from_slice(&frame.data(0)[..y_size]);
data.extend_from_slice(&frame.data(1)[..u_size]);
- data.extend_from_slice(&frame.data(2)[..v_size]);
+
+ // Downstream consumers index both chroma planes with the single
+ // advertised uv_stride (the U stride). FFmpeg almost always gives
+ // U and V identical linesizes, but if they ever differ, repack the
+ // V rows to the U stride — otherwise every V row shifts and the
+ // whole image takes on a uniform wrong-chroma cast.
+ if v_stride == u_stride {
+ data.extend_from_slice(&frame.data(2)[..u_size]);
+ } else {
+ let row_bytes = u_stride.min(v_stride) as usize;
+ let pad = u_stride as usize - row_bytes;
+ let v_data = frame.data(2);
+ for row in 0..uv_height as usize {
+ let start = row * v_stride as usize;
+ data.extend_from_slice(&v_data[start..start + row_bytes]);
+ data.resize(data.len() + pad, 128);
+ }
+ }
Some((data, PixelFormat::Yuv420p, y_stride, u_stride))
}
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index 8614a6d57..1e4b660f2 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -1,4 +1,5 @@
use std::ops::Deref;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tokio::sync::oneshot;
@@ -7,6 +8,27 @@ use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
use crate::{ProjectUniforms, RenderingError};
const GPU_BUFFER_WAIT_TIMEOUT_SECS: u64 = 10;
+const SOFTWARE_GPU_BUFFER_WAIT_TIMEOUT_SECS: u64 = 60;
+
+/// Whether this process has selected a software (CPU rasterizer) wgpu adapter.
+/// Software adapters like Windows WARP legitimately take tens of seconds for the
+/// first cold render (pipeline compilation + full-frame rasterization on the CPU),
+/// so readback waits get a much longer deadline before being treated as failures —
+/// timing out the first frame is what used to leave the editor on a blank screen.
+static SOFTWARE_ADAPTER_IN_USE: AtomicBool = AtomicBool::new(false);
+
+pub(crate) fn note_software_adapter_in_use() {
+ SOFTWARE_ADAPTER_IN_USE.store(true, Ordering::Release);
+}
+
+fn gpu_buffer_wait_timeout() -> std::time::Duration {
+ let secs = if SOFTWARE_ADAPTER_IN_USE.load(Ordering::Acquire) {
+ SOFTWARE_GPU_BUFFER_WAIT_TIMEOUT_SECS
+ } else {
+ GPU_BUFFER_WAIT_TIMEOUT_SECS
+ };
+ std::time::Duration::from_secs(secs)
+}
#[derive(Clone, Copy, Debug, Default)]
pub struct FinishEncoderTimings {
@@ -416,7 +438,7 @@ impl PendingNv12Readback {
let mut poll_count = 0u32;
let start_time = Instant::now();
- let timeout_duration = std::time::Duration::from_secs(GPU_BUFFER_WAIT_TIMEOUT_SECS);
+ let timeout_duration = gpu_buffer_wait_timeout();
loop {
if start_time.elapsed() > timeout_duration {
@@ -545,7 +567,7 @@ impl PendingReadback {
pub async fn wait(mut self, device: &wgpu::Device) -> Result<RenderedFrame, RenderingError> {
let mut poll_count = 0u32;
let start_time = Instant::now();
- let timeout_duration = std::time::Duration::from_secs(GPU_BUFFER_WAIT_TIMEOUT_SECS);
+ let timeout_duration = gpu_buffer_wait_timeout();
loop {
if start_time.elapsed() > timeout_duration {
@@ -554,7 +576,7 @@ impl PendingReadback {
elapsed_secs = start_time.elapsed().as_secs(),
poll_count = poll_count,
"GPU buffer mapping timed out after {}s",
- GPU_BUFFER_WAIT_TIMEOUT_SECS
+ timeout_duration.as_secs()
);
return Err(self.cancel());
}