Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): harden the primed recording start
Richie McIlroydae17890119f
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rsindex 3510da972..8497cd546 100644--- a/apps/desktop-gpui/src/recording.rs+++ b/apps/desktop-gpui/src/recording.rs@@ -1061,6 +1061,9 @@ impl ActiveRecording {#[cfg(target_os = "linux")]pub(crate) async fn cancel_preserving(self) -> anyhow::Result<()> {+ if let Some(gate) = &self.start_gate {+ gate.arm();+ }if let Some(completion) = &self.instant_completion {completion.deny();}diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rsindex 62ab507a6..7fbc1855c 100644--- a/apps/desktop-gpui/src/session.rs+++ b/apps/desktop-gpui/src/session.rs@@ -440,6 +440,9 @@ pub struct RecordingSession {/// A capture pipeline that finished warming up while the countdown or the/// start cue was still running; activated the moment the cue ends.primed: Option<ActiveRecording>,+ /// Teardown of a cancelled primed start still releasing its devices; the+ /// next start waits for it before locking the mic and camera again.+ discarding: Option<Task<Result<(), tokio::task::JoinError>>>,pause_control: PauseControlState,pause_control_error: Option<String>,#[cfg(target_os = "linux")]@@ -485,6 +488,7 @@ impl RecordingSession {start_gate: None,start_cue: None,primed: None,+ discarding: None,pause_control: PauseControlState::default(),pause_control_error: None,#[cfg(target_os = "linux")]@@ -799,7 +803,13 @@ impl RecordingSession {};#[cfg(not(target_os = "linux"))]let start = recording::start(config);- let task = gpui_tokio::Tokio::spawn(cx, start);+ let discarding = self.discarding.take();+ let task = gpui_tokio::Tokio::spawn(cx, async move {+ if let Some(discarding) = discarding {+ let _ = discarding.await;+ }+ start.await+ });cx.spawn(async move |this, cx| {let result = task.await;#[cfg(target_os = "linux")]@@ -927,15 +937,19 @@ impl RecordingSession {}fn discard_stale_start(&mut self, active: ActiveRecording, cx: &mut Context<Self>) {- #[cfg(target_os = "linux")]- gpui_tokio::Tokio::spawn(cx, active.cancel_preserving()).detach();- #[cfg(not(target_os = "linux"))]- gpui_tokio::Tokio::spawn(cx, async move {- if let Err(error) = active.cancel_and_delete().await {+ let previous = self.discarding.take();+ self.discarding = Some(gpui_tokio::Tokio::spawn(cx, async move {+ if let Some(previous) = previous {+ let _ = previous.await;+ }+ #[cfg(target_os = "linux")]+ let discarded = active.cancel_preserving().await;+ #[cfg(not(target_os = "linux"))]+ let discarded = active.cancel_and_delete().await;+ if let Err(error) = discarded {tracing::warn!(%error, "discarding a cancelled recording start failed");}- })- .detach();+ }));}fn monitor_recording_failure(&mut self, done: cap_recording::DoneFut, cx: &mut Context<Self>) {diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex cd83157c4..ac77ea3c5 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -2872,6 +2872,12 @@ async fn start_recording_prepared(match actor_result {Ok(mut actor) => {+ // The recording stays out of app state until the cue has+ // armed the gate, so nothing reports "recording" while the+ // primed pipeline is still discarding frames.+ while !start_gate.is_armed() && start_cancelled.get().is_none() {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }let mut state = state_mtx.write().await;if let Some(reason) = start_cancelled.get().copied() {drop(state);@@ -2996,12 +3002,12 @@ async fn start_recording_prepared(let (actor_done_fut, health_rx, automatic_stop) = match actor_task_res {Ok(Ok(v)) => v,- Ok(Err(_)) if start_cancelled.get().is_some() => {- return Err(start_cancelled+ Ok(Err(err))+ if start_cancelled.get()- .copied()- .unwrap_or("Recording cancelled")- .into());+ .is_some_and(|reason| err.to_string() == *reason) =>+ {+ return Err(err.to_string());}Ok(Err(err)) => {let message = format!("{err:#}");diff --git a/apps/desktop/src-tauri/src/recording_start_sound.rs b/apps/desktop/src-tauri/src/recording_start_sound.rsindex 5b533dff6..241600816 100644--- a/apps/desktop/src-tauri/src/recording_start_sound.rs+++ b/apps/desktop/src-tauri/src/recording_start_sound.rs@@ -3,11 +3,15 @@ use std::{io::Cursor, sync::mpsc, time::Duration};use cap_recording::RecordingStartGate;use rodio::{Decoder, OutputStream, Sink};-const PLAYBACK_TIMEOUT: Duration = Duration::from_secs(3);+// The cue is under half a second; a device that has not finished it by now+// (route change mid-countdown, stalled engine) must not hold the recording back.+const PLAYBACK_TIMEOUT: Duration = Duration::from_millis(1500);const CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(5);// Rodio reports an empty sink once the mixer has consumed the last sample; that-// buffer still has to play out through the device before the cue is audible-done.-const FALLBACK_OUTPUT_LATENCY: Duration = Duration::from_millis(40);+// buffer still has to play out through the device before the cue is audibly+// done. Shared-mode WASAPI and PulseAudio devices commonly sit at 30-100ms, so+// err towards the cue preceding capture rather than landing inside it.+const FALLBACK_OUTPUT_LATENCY: Duration = Duration::from_millis(150);struct PlayCommand {gate: RecordingStartGate,diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex 908da0373..c0cd93f18 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -1,3 +1,4 @@+use crate::RecordingStartGate;use cap_cursor_capture::CursorCropBounds;use cap_cursor_info::CursorShape;use cap_project::{@@ -292,6 +293,16 @@ fn keycode_to_string(key: &device_query::Keycode) -> (String, String) {(display.to_string(), code.to_string())}+/// Time zero for cursor, click and key events: the start gate's arm point+/// when the pipeline was primed ahead of the recording, else the pipeline+/// epoch. `None` while a primed recording is still waiting for its cue.+fn input_epoch(start_gate: Option<&RecordingStartGate>, start_time: Timestamps) -> Option<Instant> {+ match start_gate {+ Some(gate) => gate.armed_at().map(|armed| armed.instant()),+ None => Some(start_time.instant()),+ }+}+#[tracing::instrument(name = "cursor", skip_all)]pub fn spawn_cursor_recorder(target: CursorCaptureTarget,@@ -299,6 +310,7 @@ pub fn spawn_cursor_recorder(prev_cursors: Cursors,next_cursor_id: u32,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,incremental_outputs: IncrementalCaptureOutputs,) -> CursorActor {#[cfg(target_os = "linux")]@@ -365,6 +377,7 @@ pub fn spawn_cursor_recorder(let mut last_flush = Instant::now();let flush_interval = Duration::from_secs(CURSOR_FLUSH_INTERVAL_SECS);let mut last_cursor_id: Option<String> = None;+ let mut awaiting_start = start_gate.is_some();loop {if stop_token_child.is_cancelled() {@@ -378,11 +391,16 @@ pub fn spawn_cursor_recorder(break;}- let elapsed = start_time.instant().elapsed().as_secs_f64() * 1000.0;+ let Some(epoch) = input_epoch(start_gate.as_ref(), start_time) else {+ continue;+ };+ let elapsed = epoch.elapsed().as_secs_f64() * 1000.0;let mouse_state = device_state.get_mouse();let position = cap_cursor_capture::RawCursorPosition::get();- let position_changed = position != last_position;+ // The first sample after the gate opens is always recorded so the+ // cursor has a known position at the recording's time zero.+ let position_changed = position != last_position || std::mem::take(&mut awaiting_start);if position_changed {last_position = position;@@ -1055,3 +1073,21 @@ fn get_cursor_data() -> Option<CursorData> {})}}++#[cfg(test)]+mod input_epoch_tests {+ use super::*;++ #[test]+ fn primed_input_waits_for_the_gate_and_then_starts_at_the_arm_point() {+ let start_time = Timestamps::now();+ assert_eq!(input_epoch(None, start_time), Some(start_time.instant()));++ let gate = RecordingStartGate::new();+ assert_eq!(input_epoch(Some(&gate), start_time), None);++ let armed = Timestamps::now() + std::time::Duration::from_millis(250);+ gate.arm_at(armed);+ assert_eq!(input_epoch(Some(&gate), start_time), Some(armed.instant()));+ }+}diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 4597b8cb9..759025f1f 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -1,5 +1,5 @@-#[cfg(target_os = "macos")]use crate::RecordingStartGate;+#[cfg(target_os = "macos")]use crate::SendableShareableContent;#[cfg(target_os = "linux")]mod linux_camera;diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex 9f10171ea..5982f6fbc 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -40,6 +40,10 @@ pub const STALL_BUDGET_MS: u64 = 50;pub(crate) const STALL_POLL_INTERVAL: Duration = Duration::from_micros(500);pub const VIDEO_START_GATE_TIMEOUT: Duration = Duration::from_millis(500);+/// How long a primed video track waits after the arm point for a fresh frame+/// before releasing the last pre-arm frame as the recording's first frame.+const STATIC_SOURCE_RELEASE_DELAY: Duration = Duration::from_millis(50);+const STATIC_SOURCE_RELEASE_POLL: Duration = Duration::from_millis(10);fn remap_video_timestamp(source_clock: &mut SourceClockState,@@ -2929,10 +2933,40 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vlet mut first_frame_offset = None;let mut start_gate = start_gate;let mut held_before_start: u64 = 0;+ // Screen capture only delivers on change, so a static screen may never+ // produce a frame after the arm point. The last frame captured before it+ // is kept and released, stamped at the arm point, once no fresh frame has+ // followed the arm within a frame interval.+ let mut held_frame: Option<TVideo::Frame> = None;+ let mut wall_clock_origin = timestamps.instant();let res = stop_token.run_until_cancelled(async {- while let Some(frame) = video_rx.next().await {+ loop {+ let (frame, released_at_arm) = if let Some(gate) = &start_gate+ && held_frame.is_some()+ {+ tokio::select! {+ next = video_rx.next() => match next {+ Some(frame) => (frame, false),+ None => break,+ },+ _ = tokio::time::sleep(STATIC_SOURCE_RELEASE_POLL) => {+ let static_since_arm = gate.armed_at().is_some_and(|armed| {+ armed.instant().elapsed() >= STATIC_SOURCE_RELEASE_DELAY+ });+ if !static_since_arm {+ continue;+ }+ (held_frame.take().expect("held frame presence checked"), true)+ }+ }+ } else {+ match video_rx.next().await {+ Some(frame) => (frame, false),+ None => break,+ }+ };let (is_paused, total_pause_duration) = shared_pause.check();if is_paused {@@ -2940,20 +2974,33 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vcontinue;}- let timestamp = frame.timestamp();+ let mut timestamp = frame.timestamp();if let Some(gate) = &start_gate {- if !gate.admits_video(timestamp) {+ if released_at_arm {+ let armed = gate.armed_at().expect("released only once armed");+ timestamp = Timestamp::Instant(armed.instant());+ info!(+ held_frames = held_before_start,+ "Start gate released the frame on screen at the arm point"+ );+ } else if !gate.admits_video(timestamp) {held_before_start += 1;+ held_frame = Some(frame);continue;+ } else {+ info!(+ held_frames = held_before_start,+ admitted_after_arm_ms =+ gate.offset_secs(timestamp).unwrap_or_default() * 1000.0,+ "Start gate admitted first video frame"+ );}- info!(- held_frames = held_before_start,- admitted_after_arm_ms =- gate.offset_secs(timestamp).unwrap_or_default() * 1000.0,- "Start gate admitted first video frame"- );+ wall_clock_origin = gate+ .armed_at()+ .map_or(timestamps.instant(), |armed| armed.instant());start_gate = None;+ held_frame = None;}frame_count += 1;@@ -2994,8 +3041,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V+ remap.duration().saturating_sub(total_pause_duration),);- let wall_clock_elapsed = timestamps- .instant()+ let wall_clock_elapsed = wall_clock_origin.elapsed().saturating_sub(total_pause_duration);@@ -3083,11 +3129,20 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vmatch tokio::time::timeout_at(drain_deadline, video_rx.next()).await {Ok(Some(frame)) => {+ let timestamp = frame.timestamp();+ if let Some(gate) = &start_gate {+ if !gate.admits_video(timestamp) {+ held_before_start += 1;+ continue;+ }+ wall_clock_origin = gate+ .armed_at()+ .map_or(timestamps.instant(), |armed| armed.instant());+ start_gate = None;+ }frame_count += 1;drained += 1;- let timestamp = frame.timestamp();-let is_first_frame = first_tx.is_some();if let Some(first_tx) = first_tx.take() {let _ = first_tx.send(timestamp);@@ -3115,8 +3170,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V.saturating_sub(shared_pause.total_pause_duration()),);- let wall_clock_elapsed = timestamps- .instant()+ let wall_clock_elapsed = wall_clock_origin.elapsed().saturating_sub(shared_pause.total_pause_duration());@@ -7036,6 +7090,45 @@ mod tests {assert!(timestamps.len() >= 3, "{timestamps:?}");}+ #[tokio::test]+ async fn primed_static_screen_opens_on_the_frame_held_at_the_arm_point() {+ let temp_dir = tempfile::tempdir().unwrap();+ let gate = RecordingStartGate::new();+ let (sender, receiver) = flume::bounded(8);+ let sent = Arc::new(std::sync::Mutex::new(Vec::new()));+ let pipeline = OutputPipeline::builder(temp_dir.path().join("static-primed.mp4"))+ .with_video::<ChannelVideoSource<StaticFrame>>(ChannelVideoSourceConfig::new(+ VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 16, 16, 30),+ receiver,+ ))+ .with_timestamps(Timestamps::now())+ .with_start_gate(Some(gate.clone()))+ .build::<ObservedMuxer>(sent.clone())+ .await+ .unwrap();++ sender+ .send_async(StaticFrame {+ timestamp: Timestamp::Instant(Instant::now()),+ })+ .await+ .unwrap();+ tokio::time::sleep(Duration::from_millis(80)).await;+ assert!(sent.lock().unwrap().is_empty());++ let armed = Timestamps::now();+ assert!(gate.arm_at(armed));+ tokio::time::sleep(Duration::from_millis(200)).await;+ let outcome = pipeline.stop().await.unwrap();++ match outcome.first_timestamp {+ Timestamp::Instant(instant) => assert_eq!(instant, armed.instant()),+ other => panic!("unexpected first timestamp {other:?}"),+ }+ let timestamps = sent.lock().unwrap().clone();+ assert_eq!(timestamps.first(), Some(&Duration::ZERO));+ }+#[tokio::test]async fn static_capture_finishes_with_two_nominally_spaced_frames() {let (timestamps, _) = record_static_capture(Duration::ZERO).await;diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 6e29334f5..a4a6b63a9 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -1,5 +1,5 @@-#[cfg(target_os = "macos")]use crate::RecordingStartGate;+#[cfg(target_os = "macos")]use crate::SendableShareableContent;#[cfg(target_os = "macos")]use crate::output_pipeline::{@@ -1247,6 +1247,9 @@ pub struct ScreenPipelineOutput {struct Pipeline {pub start_time: Timestamps,+ /// Present for a primed first segment; its arm point is the epoch every+ /// persisted start time and input event is measured from.+ pub start_gate: Option<RecordingStartGate>,// sourcespub screen: OutputPipeline,pub microphone: Option<OutputPipeline>,@@ -1438,6 +1441,14 @@ fn write_recording_failure_diagnostics(}impl Pipeline {+ fn epoch(&self) -> Timestamps {+ self.start_gate+ .as_ref()+ .and_then(RecordingStartGate::armed_at)+ .filter(|armed| armed.instant() > self.start_time.instant())+ .unwrap_or(self.start_time)+ }+#[cfg(target_os = "linux")]fn completed_before_resume(&self) -> Option<String> {[@@ -1461,6 +1472,7 @@ impl Pipeline {pub async fn stop(mut self) -> anyhow::Result<PipelineStopOutcome> {let stop_started = Instant::now();+ let epoch = self.epoch();#[cfg(any(target_os = "linux", windows))]self.stopping.store(true, std::sync::atomic::Ordering::Release);@@ -1581,7 +1593,7 @@ impl Pipeline {Ok(PipelineStopOutcome {pipeline: FinishedPipeline {- start_time: self.start_time,+ start_time: epoch,screen: screen.context("display")?.finished,microphone: finalize_optional_track(RecordingTrackKind::Microphone,@@ -3130,6 +3142,7 @@ async fn create_segment_pipeline(trace!("preparing segment pipeline {index}");let start_gate = base_inputs.start_gate.clone();+ let pipeline_start_gate = start_gate.clone();let camera_active = base_inputs.camera_feed.is_some();#[cfg(target_os = "macos")]@@ -3498,6 +3511,7 @@ async fn create_segment_pipeline(prev_cursors,next_cursors_id,start_time,+ start_gate.clone(),IncrementalCaptureOutputs {cursor: incremental_output,keyboard: keyboard_incremental_output,@@ -3517,6 +3531,7 @@ async fn create_segment_pipeline(Ok(Pipeline {start_time,+ start_gate: pipeline_start_gate,screen,microphone,camera,@@ -5004,6 +5019,7 @@ mod tests {.unwrap();let pipeline = Pipeline {start_time: timestamps,+ start_gate: None,screen,microphone: Some(microphone),camera: None,@@ -5126,6 +5142,7 @@ mod tests {.unwrap();let pipeline = Pipeline {start_time: timestamps,+ start_gate: None,screen,microphone: Some(microphone),camera: Some(camera),@@ -5750,6 +5767,7 @@ mod tests {actor.state = Some(ActorState::Recording {pipeline: Pipeline {start_time: timestamps,+ start_gate: None,screen,microphone: None,camera: None,@@ -5837,6 +5855,7 @@ mod tests {let microphone_done = microphone.done_fut();let mut pipeline = Pipeline {start_time: timestamps,+ start_gate: None,screen,microphone: None,camera: None,@@ -6022,6 +6041,7 @@ mod tests {let mut pipeline = Pipeline {start_time: timestamps,+ start_gate: None,screen,microphone: Some(microphone),camera: None,