Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): start recording the instant the start cue ends
Richie McIlroy903ea75428f8
diff --git a/apps/desktop-gpui/src/app_sounds.rs b/apps/desktop-gpui/src/app_sounds.rsindex 1604ab843..c2ab9dd64 100644--- a/apps/desktop-gpui/src/app_sounds.rs+++ b/apps/desktop-gpui/src/app_sounds.rs@@ -6,10 +6,14 @@ use rodio::{Decoder, OutputStream, Sink};#[path = "../../desktop/src-tauri/src/recording_start_sound.rs"]mod recording_start_sound;-pub use recording_start_sound::should_play_countdown_sound;+pub use recording_start_sound::StartCue;-pub async fn play_recording_start_sound() {- recording_start_sound::play(AppSound::StartRecording.bytes()).await;+pub fn prime_recording_start_sound() -> StartCue {+ recording_start_sound::prime(AppSound::StartRecording.bytes())+}++pub async fn play_recording_start_sound(cue: StartCue, gate: cap_recording::RecordingStartGate) {+ recording_start_sound::play(cue, gate).await;}#[derive(Clone, Copy, Debug)]diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex 8c1226e80..539e0dbff 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -6811,6 +6811,7 @@ mod tests {camera_feed: None,mic_feed: None,linux_instant_camera: None,+ start_gate: None,}),gate: CleanCaptureGate::default(),camera: None,diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rsindex a4d52683e..5851c4f6d 100644--- a/apps/desktop-gpui/src/deeplink.rs+++ b/apps/desktop-gpui/src/deeplink.rs@@ -427,6 +427,7 @@ impl DeepLinkAction {mic_feed,#[cfg(target_os = "linux")]linux_instant_camera: None,+ start_gate: None,},permit.clone(),cx,diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex c86f8bac2..be5f5809e 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -2048,6 +2048,7 @@ impl MainWindow {mic_feed,#[cfg(target_os = "linux")]linux_instant_camera: None,+ start_gate: None,};self.start_recording_config(config, cx);diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rsindex 898da7352..3510da972 100644--- a/apps/desktop-gpui/src/recording.rs+++ b/apps/desktop-gpui/src/recording.rs@@ -52,6 +52,9 @@ pub struct StartConfig {pub mic_feed: Option<ActorRef<MicrophoneFeed>>,#[cfg(target_os = "linux")]pub linux_instant_camera: Option<LinuxInstantCameraRequest>,+ /// When set, the pipeline is primed behind this gate and records nothing+ /// until the session arms it at the end of the start cue.+ pub start_gate: Option<cap_recording::RecordingStartGate>,}#[cfg(target_os = "linux")]@@ -86,6 +89,7 @@ impl<A: Actor> Drop for RecordingOwnedFeed<A> {pub struct ActiveRecording {handle: Handle,pub project_dir: PathBuf,+ start_gate: Option<cap_recording::RecordingStartGate>,instant_upload: Option<SharedInstantUpload>,instant_share_link: Option<String>,#[cfg(target_os = "linux")]@@ -1089,6 +1093,9 @@ impl ActiveRecording {/// delete and restart flows. Deleting a directory this app just created is/// app behavior, same as the Tauri delete button.pub async fn cancel_and_delete(self) -> anyhow::Result<()> {+ if let Some(gate) = &self.start_gate {+ gate.arm();+ }#[cfg(target_os = "linux")]if let Some(completion) = &self.instant_completion {completion.deny();@@ -2225,6 +2232,9 @@ async fn start_attempt_with_upload(camera_lock.is_some(),None,);+ if let Some(gate) = config.start_gate.clone() {+ builder = builder.with_start_gate(gate);+ }#[cfg(target_os = "macos")]{builder = builder.with_excluded_windows(excluded_windows.clone());@@ -2250,6 +2260,9 @@ async fn start_attempt_with_upload(instant_recording::Actor::builder(project_dir.clone(), config.target.clone()).with_system_audio(config.system_audio).with_max_output_size(instant_max_resolution);+ if let Some(gate) = config.start_gate.clone() {+ builder = builder.with_start_gate(gate);+ }#[cfg(target_os = "macos")]{builder = builder.with_excluded_windows(excluded_windows.clone());@@ -2328,6 +2341,7 @@ async fn start_attempt_with_upload(Ok(ActiveRecording {handle,project_dir,+ start_gate: config.start_gate.clone(),instant_upload,instant_share_link,#[cfg(target_os = "linux")]diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rsindex 252d6c1ab..62ab507a6 100644--- a/apps/desktop-gpui/src/session.rs+++ b/apps/desktop-gpui/src/session.rs@@ -83,15 +83,14 @@ fn countdown_advance(current_generation: u64,countdown_generation: u64,remaining: Option<u32>,- play_sound: bool,) -> CountdownAdvance {if phase != Phase::Starting || current_generation != countdown_generation {return CountdownAdvance::Ignore;}match remaining {Some(remaining) if remaining > 1 => CountdownAdvance::Tick(remaining - 1),- Some(1) if play_sound => CountdownAdvance::PlaySound,- Some(0 | 1) => CountdownAdvance::Start,+ Some(1) => CountdownAdvance::PlaySound,+ Some(0) => CountdownAdvance::Start,_ => CountdownAdvance::Ignore,}}@@ -436,6 +435,11 @@ pub struct RecordingSession {recording_generation: u64,countdown_remaining: Option<u32>,countdown_cue_abort: Option<futures_util::future::AbortHandle>,+ start_gate: Option<cap_recording::RecordingStartGate>,+ start_cue: Option<crate::app_sounds::StartCue>,+ /// 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>,pause_control: PauseControlState,pause_control_error: Option<String>,#[cfg(target_os = "linux")]@@ -478,6 +482,9 @@ impl RecordingSession {recording_generation: 0,countdown_remaining: None,countdown_cue_abort: None,+ start_gate: None,+ start_cue: None,+ primed: None,pause_control: PauseControlState::default(),pause_control_error: None,#[cfg(target_os = "linux")]@@ -646,10 +653,14 @@ impl RecordingSession {let countdown = crate::store::GeneralSettings::load().recording_countdown.unwrap_or(0);- let play_countdown_sound = crate::app_sounds::should_play_countdown_sound(- Some(countdown),- self.controls_open && !crate::app_windows::clean_capture_owned(cx),- );+ let start_gate = cap_recording::RecordingStartGate::new();+ let config = StartConfig {+ start_gate: Some(start_gate.clone()),+ ..config+ };+ self.start_gate = Some(start_gate);+ self.start_cue = Some(crate::app_sounds::prime_recording_start_sound());+ self.discard_primed(cx);self.pause_control.invalidate();self.pause_control.uncertain = false;self.pause_control_error = None;@@ -667,19 +678,22 @@ impl RecordingSession {self.stopped_for_low_storage = false;self.stopped_elapsed = None;self.last_config = Some(config.clone());- self.countdown_remaining = (countdown > 0).then_some(countdown);+ // `Some(0)` keeps the controls in their pre-start state while the cue plays.+ self.countdown_remaining = Some(countdown);cx.notify();- if countdown == 0 {- self.start_engine(config, generation, true, cx);- return;+ // The pipeline warms up during the final countdown second so capture is+ // live when the cue ends; without a countdown it warms up under the cue.+ if countdown <= 1 {+ self.prime_engine(config.clone(), generation, cx);}+ let initial_cue = (countdown == 0).then(|| self.play_start_cue(cx));cx.spawn(async move |this, cx| {- let mut pending_sound = None;+ let mut pending_cue = initial_cue;loop {- if let Some(sound) = pending_sound.take() {- let _ = sound.await;+ if let Some(cue) = pending_cue.take() {+ cue.await;} else {cx.background_executor().timer(Duration::from_secs(1)).await;}@@ -690,39 +704,27 @@ impl RecordingSession {this.recording_generation,generation,this.countdown_remaining,- play_countdown_sound,) {CountdownAdvance::Ignore => false,CountdownAdvance::Tick(remaining) => {this.countdown_remaining = Some(remaining);+ if remaining == 1 {+ this.prime_engine(config.clone(), generation, cx);+ }cx.notify();true}CountdownAdvance::PlaySound => {this.countdown_remaining = Some(0);- let (abort, registration) =- futures_util::future::AbortHandle::new_pair();- this.countdown_cue_abort = Some(abort);- pending_sound = Some(gpui_tokio::Tokio::spawn(- cx,- futures_util::future::Abortable::new(- crate::app_sounds::play_recording_start_sound(),- registration,- ),- ));+ pending_cue = Some(this.play_start_cue(cx));cx.notify();true}CountdownAdvance::Start => {this.countdown_remaining = None;this.countdown_cue_abort = None;+ this.activate_primed(cx);cx.notify();- this.start_engine(- config.clone(),- generation,- !play_countdown_sound,- cx,- );false}}@@ -736,17 +738,44 @@ impl RecordingSession {.detach();}- fn start_engine(+ /// Plays the start cue; the returned future completes once the recording's+ /// start gate is armed, whether the cue played, failed or was aborted.+ fn play_start_cue(&mut self,- config: StartConfig,- generation: u64,- play_started_sound: bool,cx: &mut Context<Self>,- ) {- if self.phase != Phase::Starting- || self.recording_generation != generation- || self.countdown_remaining.is_some()- {+ ) -> std::pin::Pin<Box<dyn Future<Output = ()>>> {+ let gate = self.start_gate.clone().unwrap_or_default();+ let cue = self.start_cue.take();+ let (abort, registration) = futures_util::future::AbortHandle::new_pair();+ self.countdown_cue_abort = Some(abort);+ let task = gpui_tokio::Tokio::spawn(+ cx,+ futures_util::future::Abortable::new(+ async move {+ match cue {+ Some(cue) => crate::app_sounds::play_recording_start_sound(cue, gate).await,+ None => {+ gate.arm();+ }+ }+ },+ registration,+ ),+ );+ Box::pin(async move {+ let _ = task.await;+ })+ }++ fn abort_start_cue(&mut self) {+ if let Some(abort) = self.countdown_cue_abort.take() {+ abort.abort();+ }+ self.start_cue = None;+ }++ fn prime_engine(&mut self, config: StartConfig, generation: u64, cx: &mut Context<Self>) {+ if self.phase != Phase::Starting || self.recording_generation != generation {return;}if !crate::menus::recording_start_allowed(cx) {@@ -789,40 +818,25 @@ impl RecordingSession {false};this.update(cx, |this, cx| {- #[cfg(target_os = "linux")]if this.recording_generation != generation || this.phase != Phase::Starting {if let Ok(Ok(active)) = result {- gpui_tokio::Tokio::spawn(cx, active.cancel_preserving()).detach();+ this.discard_stale_start(active, cx);}return;}match result {Ok(Ok(active)) => {- tracing::info!(dir = %active.project_dir.display(), "recording started");- let project_dir = active.project_dir.clone();- let done = active.done_fut();- this.active = Some(active);- this.phase = Phase::Recording { paused: false };- // A fresh mic lock always starts unmuted.- this.mic_muted = false;- this.started_at = Some(Instant::now());- this.paused_accum = Duration::ZERO;- this.paused_since = None;- this.monitor_storage(project_dir, cx);- this.monitor_recording_failure(done, cx);- if play_started_sound {- AppSound::StartRecording.play();- }- #[cfg(target_os = "linux")]- if this.stop_requested {- this.stop(cx);- } else if this.show_controls_after_pause {- this.show_clean_capture_controls(cx);+ if this.countdown_remaining.is_some() {+ this.primed = Some(active);+ } else {+ this.activate(active, cx);}}Ok(Err(error)) => {tracing::error!("recording failed to start: {error:#}");this.error = Some(format!("{error:#}"));+ this.abort_start_cue();+ this.countdown_remaining = None;#[cfg(target_os = "linux")]{this.phase = if startup_joined {@@ -839,6 +853,8 @@ impl RecordingSession {Err(join_error) => {tracing::error!("recording start task died: {join_error}");this.error = Some("Recording task failed.".into());+ this.abort_start_cue();+ this.countdown_remaining = None;#[cfg(target_os = "linux")]{this.phase = if startup_joined {@@ -875,6 +891,53 @@ impl RecordingSession {.detach();}+ fn activate_primed(&mut self, cx: &mut Context<Self>) {+ if let Some(active) = self.primed.take() {+ self.activate(active, cx);+ }+ }++ fn activate(&mut self, active: ActiveRecording, cx: &mut Context<Self>) {+ tracing::info!(dir = %active.project_dir.display(), "recording started");+ let project_dir = active.project_dir.clone();+ let done = active.done_fut();+ self.active = Some(active);+ self.phase = Phase::Recording { paused: false };+ // A fresh mic lock always starts unmuted.+ self.mic_muted = false;+ self.started_at = Some(Instant::now());+ self.paused_accum = Duration::ZERO;+ self.paused_since = None;+ self.start_cue = None;+ self.monitor_storage(project_dir, cx);+ self.monitor_recording_failure(done, cx);+ #[cfg(target_os = "linux")]+ if self.stop_requested {+ self.stop(cx);+ } else if self.show_controls_after_pause {+ self.show_clean_capture_controls(cx);+ }+ cx.notify();+ }++ fn discard_primed(&mut self, cx: &mut Context<Self>) {+ if let Some(active) = self.primed.take() {+ self.discard_stale_start(active, cx);+ }+ }++ 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 {+ tracing::warn!(%error, "discarding a cancelled recording start failed");+ }+ })+ .detach();+ }+fn monitor_recording_failure(&mut self, done: cap_recording::DoneFut, cx: &mut Context<Self>) {let generation = self.recording_generation;let task = gpui_tokio::Tokio::spawn(cx, done);@@ -1836,9 +1899,9 @@ impl RecordingSession {}fn finish(&mut self, cx: &mut Context<Self>) {- if let Some(abort) = self.countdown_cue_abort.take() {- abort.abort();- }+ self.abort_start_cue();+ self.discard_primed(cx);+ self.start_gate = None;#[cfg(target_os = "linux")]if !self.instant_cleanup_safe() {self.clean_control.uncertain = true;@@ -1887,19 +1950,19 @@ mod countdown_tests {#[test]fn countdown_ticks_until_the_final_step_before_start() {assert_eq!(- countdown_advance(Phase::Starting, 7, 7, Some(3), false),+ countdown_advance(Phase::Starting, 7, 7, Some(3)),CountdownAdvance::Tick(2));assert_eq!(- countdown_advance(Phase::Starting, 7, 7, Some(2), false),+ countdown_advance(Phase::Starting, 7, 7, Some(2)),CountdownAdvance::Tick(1));assert_eq!(- countdown_advance(Phase::Starting, 7, 7, Some(1), false),- CountdownAdvance::Start+ countdown_advance(Phase::Starting, 7, 7, Some(1)),+ CountdownAdvance::PlaySound);assert_eq!(- countdown_advance(Phase::Starting, 7, 7, None, false),+ countdown_advance(Phase::Starting, 7, 7, None),CountdownAdvance::Ignore);}@@ -1907,15 +1970,15 @@ mod countdown_tests {#[test]fn cancelled_or_superseded_countdown_cannot_start_capture() {assert_eq!(- countdown_advance(Phase::Idle, 7, 7, Some(1), true),+ countdown_advance(Phase::Idle, 7, 7, Some(1)),CountdownAdvance::Ignore);assert_eq!(- countdown_advance(Phase::Starting, 8, 7, Some(1), true),+ countdown_advance(Phase::Starting, 8, 7, Some(1)),CountdownAdvance::Ignore);assert_eq!(- countdown_advance(Phase::Recording { paused: false }, 7, 7, Some(1), true),+ countdown_advance(Phase::Recording { paused: false }, 7, 7, Some(1)),CountdownAdvance::Ignore);}@@ -1923,12 +1986,12 @@ mod countdown_tests {#[test]fn completed_cue_can_only_start_its_own_pending_recording() {assert_eq!(- countdown_advance(Phase::Starting, 7, 7, Some(0), true),+ countdown_advance(Phase::Starting, 7, 7, Some(0)),CountdownAdvance::Start);for (phase, current) in [(Phase::Idle, 7), (Phase::Starting, 8)] {assert_eq!(- countdown_advance(phase, current, 7, Some(0), true),+ countdown_advance(phase, current, 7, Some(0)),CountdownAdvance::Ignore);}@@ -1943,7 +2006,7 @@ mod countdown_tests {(0, CountdownAdvance::Start),] {assert_eq!(- countdown_advance(Phase::Starting, 7, 7, Some(remaining), true),+ countdown_advance(Phase::Starting, 7, 7, Some(remaining)),expected);}diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rsindex 40dfbdeec..d2cb5708c 100644--- a/apps/desktop/src-tauri/src/audio.rs+++ b/apps/desktop/src-tauri/src/audio.rs@@ -3,10 +3,14 @@ use cap_audio::DecodedAudio;#[path = "recording_start_sound.rs"]mod recording_start_sound;-pub use recording_start_sound::should_play_countdown_sound;+pub use recording_start_sound::StartCue;-pub async fn play_recording_start_sound() {- recording_start_sound::play(AppSounds::StartRecording.get_sound_bytes()).await;+pub fn prime_recording_start_sound() -> StartCue {+ recording_start_sound::prime(AppSounds::StartRecording.get_sound_bytes())+}++pub async fn play_recording_start_sound(cue: StartCue, gate: cap_recording::RecordingStartGate) {+ recording_start_sound::play(cue, gate).await;}fn play_audio(bytes: &'static [u8]) {diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 0521c003f..cd83157c4 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -2414,16 +2414,14 @@ async fn start_recording_prepared(}}let countdown = general_settings.and_then(|v| v.recording_countdown);- let mut countdown_visible = false;crate::target_select_overlay::close_target_select_overlay_windows(&app);if clean_generation.is_none() {- countdown_visible = ShowCapWindow::InProgressRecording {+ let _ = ShowCapWindow::InProgressRecording {countdown,capture_target: Some(inputs.capture_target.clone()),}.show(&app)- .await- .is_ok();+ .await;if let Some(window) = CapWindowId::Main.get(&app) {let _ = general_settings@@ -2432,8 +2430,9 @@ async fn start_recording_prepared(.perform(&window);}}- let play_countdown_sound =- crate::audio::should_play_countdown_sound(countdown, countdown_visible);+ let start_gate = cap_recording::RecordingStartGate::new();+ let start_cue = crate::audio::prime_recording_start_sound();+ let start_cancelled: Arc<std::sync::OnceLock<&'static str>> = Arc::default();crate::windows::apply_content_protection(&app, true);if let Some(editor_target) = EditorRecordingTarget::current(&app)@@ -2443,67 +2442,69 @@ async fn start_recording_prepared(let _ = editor_window.minimize();}- if let Some(countdown) = countdown {- for t in 0..countdown {+ let start_cancel_reason = {+ let app = app.clone();+ #[cfg(target_os = "linux")]+ let mode = inputs.mode;+ move || -> Option<&'static str> {+ if clean_generation+ .is_some_and(|generation| crate::clean_capture::stop_requested(&app, generation))+ {+ return Some("Recording cancelled");+ }#[cfg(target_os = "linux")]- if inputs.mode == RecordingMode::Instant+ if mode == RecordingMode::Instant&& linux_instant::current(&app).is_none_or(|attempt| attempt.cancelled()){- return Err("Instant startup cancelled".into());+ return Some("Instant startup cancelled");}- let _ = RecordingEvent::Countdown {- value: countdown - t,+ None+ }+ };++ let countdown = countdown.unwrap_or(0);+ // Every countdown second but the last elapses before the pipeline is+ // primed; the last one overlaps its warm-up so capture is live at the cue.+ for t in 0..countdown.saturating_sub(1) {+ if let Some(reason) = start_cancel_reason() {+ return Err(reason.into());+ }+ let _ = RecordingEvent::Countdown {+ value: countdown - t,+ }+ .emit(&app);+ countdown_tick(&start_cancel_reason).await?;+ }++ let start_cue_flow = {+ let app = app.clone();+ let start_gate = start_gate.clone();+ let start_cancelled = start_cancelled.clone();+ let start_cancel_reason = start_cancel_reason.clone();+ async move {+ if countdown >= 1 {+ let _ = RecordingEvent::Countdown { value: 1 }.emit(&app);+ if let Err(reason) = countdown_tick(&start_cancel_reason).await {+ let _ = start_cancelled.set(reason);+ start_gate.arm();+ return;+ }+ let _ = RecordingEvent::Countdown { value: 0 }.emit(&app);}- .emit(&app);- let tick = tokio::time::sleep(Duration::from_secs(1));- tokio::pin!(tick);+ let cue = crate::audio::play_recording_start_sound(start_cue, start_gate);+ tokio::pin!(cue);loop {tokio::select! {- _ = &mut tick => break,+ _ = &mut cue => break,_ = tokio::time::sleep(Duration::from_millis(50)) => {}}- if clean_generation.is_some_and(|generation| {- crate::clean_capture::stop_requested(&app, generation)- }) {- return Err("Recording cancelled".into());- }- #[cfg(target_os = "linux")]- if inputs.mode == RecordingMode::Instant- && linux_instant::current(&app).is_none_or(|attempt| attempt.cancelled())- {- return Err("Instant startup cancelled".into());+ if let Some(reason) = start_cancel_reason() {+ let _ = start_cancelled.set(reason);+ break;}}- if clean_generation- .is_some_and(|generation| crate::clean_capture::stop_requested(&app, generation))- {- return Err("Recording cancelled".into());- }- }- }-- if play_countdown_sound {- let _ = RecordingEvent::Countdown { value: 0 }.emit(&app);- let sound = crate::audio::play_recording_start_sound();- tokio::pin!(sound);- loop {- tokio::select! {- _ = &mut sound => break,- _ = tokio::time::sleep(Duration::from_millis(50)) => {}- }- if clean_generation- .is_some_and(|generation| crate::clean_capture::stop_requested(&app, generation))- {- return Err("Recording cancelled".into());- }- #[cfg(target_os = "linux")]- if inputs.mode == RecordingMode::Instant- && linux_instant::current(&app).is_none_or(|attempt| attempt.cancelled())- {- return Err("Instant startup cancelled".into());- }}- }+ };let (finish_upload_tx, finish_upload_rx) = flume::bounded(1);#[cfg(target_os = "linux")]@@ -2524,6 +2525,8 @@ async fn start_recording_prepared(let general_settings = general_settings.cloned();let recording_dir = project_file_path.clone();let inputs = inputs.clone();+ let start_gate = start_gate.clone();+ let start_cancelled = start_cancelled.clone();async move {fail!("recording::spawn_actor");@@ -2686,6 +2689,8 @@ async fn start_recording_prepared(None,);+ builder = builder.with_start_gate(start_gate.clone());+#[cfg(target_os = "macos")]{builder = builder.with_excluded_windows(excluded_windows.clone());@@ -2731,6 +2736,8 @@ async fn start_recording_prepared(.with_system_audio(inputs.capture_system_audio).with_max_output_size(instant_mode_max_resolution);+ builder = builder.with_start_gate(start_gate.clone());+#[cfg(target_os = "macos")]{builder = builder.with_excluded_windows(excluded_windows.clone());@@ -2866,6 +2873,11 @@ async fn start_recording_prepared(match actor_result {Ok(mut actor) => {let mut state = state_mtx.write().await;+ if let Some(reason) = start_cancelled.get().copied() {+ drop(state);+ let _ = cancel_discarded_recording(&app_handle, actor).await;+ return Err(anyhow!(reason));+ }if clean_generation.is_some_and(|generation| {!crate::clean_capture::is_current(&app_handle, generation)}) || !matches!(state.recording_state, RecordingState::Pending { .. })@@ -2979,10 +2991,18 @@ async fn start_recording_prepared(}};- let actor_task_res = AssertUnwindSafe(actor_task).catch_unwind().await;+ let (actor_task_res, ()) =+ futures::join!(AssertUnwindSafe(actor_task).catch_unwind(), start_cue_flow);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+ .get()+ .copied()+ .unwrap_or("Recording cancelled")+ .into());+ }Ok(Err(err)) => {let message = format!("{err:#}");handle_spawn_failure(@@ -3401,13 +3421,26 @@ async fn start_recording_prepared(});}- if !play_countdown_sound {- AppSounds::StartRecording.play();- }-Ok(RecordingAction::Started)}+async fn countdown_tick(+ cancel_reason: &impl Fn() -> Option<&'static str>,+) -> Result<(), &'static str> {+ let tick = tokio::time::sleep(Duration::from_secs(1));+ tokio::pin!(tick);+ loop {+ tokio::select! {+ _ = &mut tick => break,+ _ = tokio::time::sleep(Duration::from_millis(50)) => {}+ }+ if let Some(reason) = cancel_reason() {+ return Err(reason);+ }+ }+ cancel_reason().map_or(Ok(()), Err)+}+#[tauri::command]#[specta::specta]#[instrument(skip(app, state))]diff --git a/apps/desktop/src-tauri/src/recording_start_sound.rs b/apps/desktop/src-tauri/src/recording_start_sound.rsindex 378dbe81d..5b533dff6 100644--- a/apps/desktop/src-tauri/src/recording_start_sound.rs+++ b/apps/desktop/src-tauri/src/recording_start_sound.rs@@ -1,192 +1,130 @@-use std::{- io::Cursor,- sync::{Arc, Mutex},- time::Duration,-};+use std::{io::Cursor, sync::mpsc, time::Duration};-use rodio::{Decoder, OutputStream, Sink, Source};+use cap_recording::RecordingStartGate;+use rodio::{Decoder, OutputStream, Sink};const PLAYBACK_TIMEOUT: Duration = Duration::from_secs(3);-const OUTPUT_SETTLING_TIME: Duration = Duration::from_millis(500);-static ACTIVE_WORKER: Mutex<Option<Arc<PlaybackControl>>> = Mutex::new(None);--pub fn should_play_countdown_sound(countdown: Option<u32>, visible: bool) -> bool {- visible && countdown.is_some_and(|seconds| seconds > 1)-}--#[derive(Default)]-struct PlaybackState {- cancelled: bool,- started: bool,- sink: Option<Arc<Sink>>,+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);++struct PlayCommand {+ gate: RecordingStartGate,+ done: tokio::sync::oneshot::Sender<Result<(), String>>,}-#[derive(Default)]-struct PlaybackControl(Mutex<PlaybackState>);--impl PlaybackControl {- fn start<S>(&self, sink: Arc<Sink>, source: S) -> bool- where- S: Source<Item = i16> + Send + 'static,- {- let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());- if state.cancelled {- return false;- }- sink.append(source);- state.started = true;- state.sink = Some(sink);- true+impl PlayCommand {+ fn cancelled(&self) -> bool {+ self.done.is_closed()}- #[cfg(target_os = "macos")]- fn start_native(&self, start: impl FnOnce()) -> bool {- let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());- if state.cancelled {- return false;+ fn finish(self, result: Result<(), String>) {+ if result.is_ok() {+ self.gate.arm();}- state.started = true;- start();- true+ let _ = self.done.send(result);}+}- #[cfg(target_os = "macos")]- fn started(&self) -> bool {- self.0- .lock()- .unwrap_or_else(|error| error.into_inner())- .started+/// An output device opened ahead of the start cue so `play` begins instantly.+/// Dropping it unused releases the device.+pub struct StartCue {+ command: mpsc::Sender<PlayCommand>,+}++impl StartCue {+ #[cfg(test)]+ fn stub() -> (Self, mpsc::Receiver<PlayCommand>) {+ let (command, rx) = mpsc::channel();+ (Self { command }, rx)}+}- fn cancelled(&self) -> bool {- self.0- .lock()- .unwrap_or_else(|error| error.into_inner())- .cancelled+pub fn prime(bytes: &'static [u8]) -> StartCue {+ let (command, rx) = mpsc::channel();+ if let Err(error) = std::thread::Builder::new()+ .name("recording-start-sound".into())+ .spawn(move || worker(bytes, rx))+ {+ tracing::warn!(%error, "Could not start recording sound worker");}+ StartCue { command }+}- fn cancel(&self) -> bool {- let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());- state.cancelled = true;- if let Some(sink) = state.sink.take() {- sink.stop();- }- std::mem::take(&mut state.started)+fn worker(bytes: &'static [u8], rx: mpsc::Receiver<PlayCommand>) {+ #[cfg(target_os = "macos")]+ match native::Output::prepare(bytes) {+ Ok(output) => return output.run(rx),+ Err(error) => tracing::warn!(%error, "Native start sound unavailable; using fallback"),}+ fallback::run(bytes, rx);}-struct CancelOnDrop(Arc<PlaybackControl>);+/// Plays the start cue and arms `gate` the instant its last sample has left the+/// output device. The gate is always armed before this returns, including when+/// playback fails, times out, or the future is dropped mid-cue.+pub async fn play(cue: StartCue, gate: RecordingStartGate) {+ play_with_timeout(cue, gate, PLAYBACK_TIMEOUT).await;+}-impl Drop for CancelOnDrop {- fn drop(&mut self) {- self.0.cancel();+async fn play_with_timeout(cue: StartCue, gate: RecordingStartGate, timeout: Duration) {+ let _arm_on_drop = ArmOnDrop(gate.clone());+ let (done, done_rx) = tokio::sync::oneshot::channel();+ if cue.command.send(PlayCommand { gate, done }).is_err() {+ tracing::warn!("Recording start sound worker is not running");+ return;+ }+ match tokio::time::timeout(timeout, done_rx).await {+ Ok(Ok(Ok(()))) => {}+ Ok(Ok(Err(error))) => tracing::warn!(%error, "Recording start sound unavailable"),+ Ok(Err(_)) => tracing::warn!("Recording start sound worker stopped"),+ Err(_) => tracing::warn!("Recording start sound timed out"),}}-struct WorkerSlot;+struct ArmOnDrop(RecordingStartGate);-impl Drop for WorkerSlot {+impl Drop for ArmOnDrop {fn drop(&mut self) {- *ACTIVE_WORKER- .lock()- .unwrap_or_else(|error| error.into_inner()) = None;+ self.0.arm();}}-pub async fn play(bytes: &'static [u8]) {- let control = {- let mut active = ACTIVE_WORKER- .lock()- .unwrap_or_else(|error| error.into_inner());- match active.as_ref() {- Some(control) => Err(control.clone()),- None => {- let control = Arc::new(PlaybackControl::default());- *active = Some(control.clone());- Ok(control)- }- }- };- let control = match control {- Ok(control) => control,- Err(control) => {- tracing::warn!("Previous start sound worker is still stopping; skipping start sound");- control.cancel();- tokio::time::sleep(OUTPUT_SETTLING_TIME).await;+mod fallback {+ use super::*;++ pub fn run(bytes: &'static [u8], rx: mpsc::Receiver<PlayCommand>) {+ let output = OutputStream::try_default()+ .map_err(|error| error.to_string())+ .and_then(|(stream, handle)| {+ let sink = Sink::try_new(&handle).map_err(|error| error.to_string())?;+ let source = Decoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;+ Ok((stream, sink, source))+ });+ let Ok(command) = rx.recv() else {return;- }- };- let slot = WorkerSlot;- play_with_worker(- control,- PLAYBACK_TIMEOUT,- OUTPUT_SETTLING_TIME,- move |control| {- let _slot = slot;- #[cfg(target_os = "macos")]- match native::play(bytes, &control) {- Ok(()) => return Ok(()),- Err(error) if control.started() || control.cancelled() => return Err(error),- Err(error) => {- tracing::warn!(%error, "Native start sound unavailable; using fallback")- }- }- let (_stream, handle) =- OutputStream::try_default().map_err(|error| error.to_string())?;- let source = Decoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;- let sink = Arc::new(Sink::try_new(&handle).map_err(|error| error.to_string())?);- if !control.start(sink.clone(), source) {- return Ok(());- }- while !sink.empty() && !control.cancelled() {- std::thread::sleep(Duration::from_millis(10));+ };+ let (_stream, sink, source) = match output {+ Ok(output) => output,+ Err(error) => return command.finish(Err(error)),+ };+ let started = std::time::Instant::now();+ sink.append(source);+ tracing::info!("Recording start cue playing");+ while !sink.empty() {+ if command.cancelled() {+ sink.stop();+ return;}- // Rodio drains its queue before buffered output reaches the speakers.- // Keep the stream alive through a quiet interval before admitting capture.- std::thread::sleep(OUTPUT_SETTLING_TIME);- Ok(())- },- )- .await;-}--async fn play_with_worker(- control: Arc<PlaybackControl>,- timeout: Duration,- settling_time: Duration,- worker: impl FnOnce(Arc<PlaybackControl>) -> Result<(), String> + Send + 'static,-) {- let _cancel_on_drop = CancelOnDrop(control.clone());- let (sender, receiver) = tokio::sync::oneshot::channel();- let worker_control = control.clone();- if let Err(error) = std::thread::Builder::new()- .name("recording-start-sound".into())- .spawn(move || {- let result = worker(worker_control);- let _ = sender.send(result);- })- {- tracing::warn!(%error, "Could not start recording sound worker");- return;- }-- let failed = match tokio::time::timeout(timeout, receiver).await {- Ok(Ok(Ok(()))) => false,- Ok(Ok(Err(error))) => {- tracing::warn!(%error, "Recording start sound unavailable");- true- }- Ok(Err(error)) => {- tracing::warn!(%error, "Recording start sound worker stopped");- true+ std::thread::sleep(CANCEL_POLL_INTERVAL);}- Err(_) => {- tracing::warn!("Recording start sound timed out");- true- }- };- if control.cancel() && failed {- tokio::time::sleep(settling_time).await;+ std::thread::sleep(FALLBACK_OUTPUT_LATENCY);+ tracing::info!(+ played_back_after_ms = started.elapsed().as_millis() as u64,+ "Recording start cue finished"+ );+ command.finish(Ok(()));}}@@ -194,9 +132,7 @@ async fn play_with_worker(mod native {use super::*;use cidre::{av, blocks, objc};- use std::sync::mpsc;-- const ACOUSTIC_SETTLING_TIME: Duration = Duration::from_millis(100);+ use rodio::Source;trait PlayedBackScheduling: objc::Obj {#[objc::msg_send(scheduleBuffer:completionCallbackType:completionHandler:)]@@ -210,9 +146,11 @@ mod native {impl PlayedBackScheduling for av::AudioPlayerNode {}- struct Output {+ pub struct Output {engine: cidre::arc::R<av::AudioEngine>,player: cidre::arc::R<av::AudioPlayerNode>,+ buffer: cidre::arc::R<av::AudioPcmBuf>,+ sample_rate: u64,}impl Drop for Output {@@ -224,79 +162,110 @@ mod native {}}- pub fn play(bytes: &'static [u8], control: &PlaybackControl) -> Result<(), String> {- objc::try_catch(|| play_inner(bytes, control))- .map_err(|error| format!("Start sound output exception: {error:?}"))?- }+ impl Output {+ pub fn prepare(bytes: &'static [u8]) -> Result<Self, String> {+ objc::try_catch(|| Self::prepare_inner(bytes))+ .map_err(|error| format!("Start sound output exception: {error:?}"))?+ }- fn play_inner(bytes: &'static [u8], control: &PlaybackControl) -> Result<(), String> {- let source = Decoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;- let channels = usize::from(source.channels());- let rate = source.sample_rate();- let samples: Vec<i16> = source.collect();- let frames = u32::try_from(samples.len() / channels).map_err(|error| error.to_string())?;- let format = av::AudioFormat::standard_with_sample_rate_and_channels(- f64::from(rate),- channels as u32,- )- .ok_or("Could not create start sound format")?;- let mut buffer = av::AudioPcmBuf::with_format(&format, frames)- .ok_or("Could not create start sound buffer")?;- buffer- .set_frame_len(frames)- .map_err(|error| format!("{error:?}"))?;- for channel in 0..channels {- let target = buffer- .data_f32_mut_at(channel)- .ok_or("Could not access start sound samples")?;- for (frame, sample) in target.iter_mut().enumerate() {- *sample = f32::from(samples[frame * channels + channel]) / 32768.0;+ fn prepare_inner(bytes: &'static [u8]) -> Result<Self, String> {+ let source = Decoder::new(Cursor::new(bytes)).map_err(|error| error.to_string())?;+ let channels = usize::from(source.channels());+ let rate = source.sample_rate();+ let samples: Vec<i16> = source.collect();+ let frames =+ u32::try_from(samples.len() / channels).map_err(|error| error.to_string())?;+ let format = av::AudioFormat::standard_with_sample_rate_and_channels(+ f64::from(rate),+ channels as u32,+ )+ .ok_or("Could not create start sound format")?;+ let mut buffer = av::AudioPcmBuf::with_format(&format, frames)+ .ok_or("Could not create start sound buffer")?;+ buffer+ .set_frame_len(frames)+ .map_err(|error| format!("{error:?}"))?;+ for channel in 0..channels {+ let target = buffer+ .data_f32_mut_at(channel)+ .ok_or("Could not access start sound samples")?;+ for (frame, sample) in target.iter_mut().enumerate() {+ *sample = f32::from(samples[frame * channels + channel]) / 32768.0;+ }}- }- let mut output = Output {- engine: av::AudioEngine::new(),- player: av::AudioPlayerNode::new(),- };- output.engine.attach_node(&output.player);- let mixer = output.engine.main_mixer_node().retained();- output- .engine- .connect_node_to_node(&output.player, &mixer, Some(&format));- output.engine.prepare();- output- .engine- .start()- .map_err(|error| format!("{error:?}"))?;- let (sender, receiver) = mpsc::channel();- let mut callback = blocks::EscBlock::new1(move |kind| {- let _ = sender.send(kind);- });- output.player.schedule_played_back(- &buffer,- av::audio::PlayerNodeCompletionCbType::DataPlayedBack,- &mut callback,- );- if !control.start_native(|| output.player.play()) {- return Ok(());+ let mut output = Output {+ engine: av::AudioEngine::new(),+ player: av::AudioPlayerNode::new(),+ buffer,+ sample_rate: u64::from(rate),+ };+ output.engine.attach_node(&output.player);+ let mixer = output.engine.main_mixer_node().retained();+ output+ .engine+ .connect_node_to_node(&output.player, &mixer, Some(&format));+ output.engine.prepare();+ output+ .engine+ .start()+ .map_err(|error| format!("{error:?}"))?;+ Ok(output)}- loop {- if control.cancelled() {- return Ok(());+ pub fn run(self, rx: mpsc::Receiver<PlayCommand>) {+ let Ok(command) = rx.recv() else {+ return;+ };+ let result = objc::try_catch(|| self.play(&command))+ .map_err(|error| format!("Start sound playback exception: {error:?}"))+ .and_then(|result| result);+ match result {+ Ok(true) => command.finish(Ok(())),+ Ok(false) => {}+ Err(error) => command.finish(Err(error)),}- match receiver.recv_timeout(Duration::from_millis(10)) {- Ok(av::audio::PlayerNodeCompletionCbType::DataPlayedBack) => break,- Ok(_) => return Err("Unexpected start sound completion".into()),- Err(mpsc::RecvTimeoutError::Timeout) => {}- Err(mpsc::RecvTimeoutError::Disconnected) => {- return Err("Start sound completion disconnected".into());+ }++ fn play(&self, command: &PlayCommand) -> Result<bool, String> {+ let (sender, receiver) = mpsc::channel();+ let gate = command.gate.clone();+ let started = std::time::Instant::now();+ let mut callback = blocks::EscBlock::new1(move |kind| {+ if kind == av::audio::PlayerNodeCompletionCbType::DataPlayedBack {+ gate.arm();+ tracing::info!(+ played_back_after_ms = started.elapsed().as_millis() as u64,+ "Recording start cue finished"+ );+ }+ let _ = sender.send(kind);+ });+ self.player.schedule_played_back(+ &self.buffer,+ av::audio::PlayerNodeCompletionCbType::DataPlayedBack,+ &mut callback,+ );+ self.player.play();+ tracing::info!(+ buffer_ms = self.buffer.frame_len() as u64 * 1000 / self.sample_rate.max(1),+ "Recording start cue playing"+ );+ loop {+ if command.cancelled() {+ self.player.stop();+ return Ok(false);+ }+ match receiver.recv_timeout(CANCEL_POLL_INTERVAL) {+ Ok(av::audio::PlayerNodeCompletionCbType::DataPlayedBack) => return Ok(true),+ Ok(_) => return Err("Unexpected start sound completion".into()),+ Err(mpsc::RecvTimeoutError::Timeout) => {}+ Err(mpsc::RecvTimeoutError::Disconnected) => {+ return Err("Start sound completion disconnected".into());+ }}}}- // DataPlayedBack includes device latency; allow the speaker's acoustic tail to clear too.- std::thread::sleep(ACOUSTIC_SETTLING_TIME);- Ok(())}}@@ -304,141 +273,63 @@ mod native {mod tests {use super::*;- #[test]- fn pre_capture_sound_requires_a_visible_multi_second_countdown() {- for countdown in [None, Some(0), Some(1), Some(2), Some(3), Some(5), Some(10)] {- assert!(!should_play_countdown_sound(countdown, false));- }- for countdown in [None, Some(0), Some(1)] {- assert!(!should_play_countdown_sound(countdown, true));- }- for countdown in [Some(2), Some(3), Some(5), Some(10)] {- assert!(should_play_countdown_sound(countdown, true));- }+ #[tokio::test]+ async fn successful_playback_arms_the_gate_from_the_worker() {+ let (cue, rx) = StartCue::stub();+ let gate = RecordingStartGate::new();+ let playback = tokio::spawn(play(cue, gate.clone()));+ let command = tokio::task::spawn_blocking(move || rx.recv().unwrap())+ .await+ .unwrap();+ assert!(!gate.is_armed());+ command.finish(Ok(()));+ assert!(gate.is_armed());+ playback.await.unwrap();}#[tokio::test]- async fn waits_for_playback_worker_before_returning() {- let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();- let (finish_tx, finish_rx) = std::sync::mpsc::channel();- let playback = tokio::spawn(play_with_worker(- Arc::new(PlaybackControl::default()),- Duration::from_secs(2),- Duration::ZERO,- move |_| {- entered_tx.send(()).unwrap();- finish_rx.recv().unwrap();- Ok(())- },- ));- entered_rx.await.unwrap();- assert!(!playback.is_finished());- finish_tx.send(()).unwrap();+ async fn failed_playback_still_arms_the_gate() {+ let (cue, rx) = StartCue::stub();+ let gate = RecordingStartGate::new();+ let playback = tokio::spawn(play(cue, gate.clone()));+ let command = tokio::task::spawn_blocking(move || rx.recv().unwrap())+ .await+ .unwrap();+ command.finish(Err("No audio output device".into()));playback.await.unwrap();+ assert!(gate.is_armed());}#[tokio::test]- async fn timeout_prevents_a_delayed_worker_from_playing() {- let (control_tx, control_rx) = tokio::sync::oneshot::channel();- let (finish_tx, finish_rx) = std::sync::mpsc::channel();- play_with_worker(- Arc::new(PlaybackControl::default()),- Duration::from_millis(20),- Duration::ZERO,- move |control| {- control_tx.send(control).ok().unwrap();- finish_rx.recv().unwrap();- Ok(())- },- )- .await;- let control = control_rx.await.unwrap();- let (sink, _output) = Sink::new_idle();- assert!(!control.start(- Arc::new(sink),- rodio::buffer::SamplesBuffer::new(1, 48000, vec![1i16; 10])- ));- finish_tx.send(()).unwrap();+ async fn timed_out_playback_arms_the_gate() {+ let (cue, rx) = StartCue::stub();+ let gate = RecordingStartGate::new();+ play_with_timeout(cue, gate.clone(), Duration::from_millis(20)).await;+ assert!(gate.is_armed());+ assert!(rx.recv().unwrap().cancelled());}#[tokio::test]- async fn dropping_startup_cancels_playback() {- let (control_tx, control_rx) = tokio::sync::oneshot::channel();- let (finish_tx, finish_rx) = std::sync::mpsc::channel();- let playback = tokio::spawn(play_with_worker(- Arc::new(PlaybackControl::default()),- Duration::from_secs(2),- Duration::ZERO,- move |control| {- control_tx.send(control).ok().unwrap();- finish_rx.recv().unwrap();- Ok(())- },- ));- let control = control_rx.await.unwrap();+ async fn dropping_playback_arms_the_gate_and_cancels_the_worker() {+ let (cue, rx) = StartCue::stub();+ let gate = RecordingStartGate::new();+ let playback = tokio::spawn(play(cue, gate.clone()));+ let command = tokio::task::spawn_blocking(move || rx.recv().unwrap())+ .await+ .unwrap();+ assert!(!command.cancelled());playback.abort();assert!(playback.await.unwrap_err().is_cancelled());- assert!(control.cancelled());- finish_tx.send(()).unwrap();- }-- #[cfg(target_os = "macos")]- #[test]- fn cancellation_prevents_late_native_playback() {- let control = PlaybackControl::default();- assert!(!control.cancel());- assert!(!control.start_native(|| panic!("Cancelled output must not play")));- assert!(!control.started());- }-- #[cfg(target_os = "macos")]- #[tokio::test]- async fn native_playback_timeout_waits_for_buffered_audio_to_settle() {- let control = Arc::new(PlaybackControl::default());- assert!(control.start_native(|| {}));- let (finish_tx, finish_rx) = std::sync::mpsc::channel();- let timeout = Duration::from_millis(20);- let settling_time = Duration::from_millis(30);- let started = std::time::Instant::now();- play_with_worker(control.clone(), timeout, settling_time, move |_| {- finish_rx.recv().unwrap();- Ok(())- })- .await;- assert!(control.cancelled());- assert!(started.elapsed() >= timeout + settling_time);- finish_tx.send(()).unwrap();+ assert!(gate.is_armed());+ assert!(command.cancelled());}#[tokio::test]- async fn unavailable_output_does_not_fail_recording_startup() {- play_with_worker(- Arc::new(PlaybackControl::default()),- Duration::from_secs(1),- Duration::ZERO,- |_| Err("No audio output device".into()),- )- .await;- }-- #[tokio::test]- async fn failed_playback_waits_for_buffered_audio_to_settle() {- let started = std::time::Instant::now();- let settling_time = Duration::from_millis(30);- play_with_worker(- Arc::new(PlaybackControl::default()),- Duration::from_secs(1),- settling_time,- |control| {- let (sink, _output) = Sink::new_idle();- assert!(control.start(- Arc::new(sink),- rodio::buffer::SamplesBuffer::new(1, 48000, vec![1i16; 10]),- ));- Err("Output disconnected after playback began".into())- },- )- .await;- assert!(started.elapsed() >= settling_time);+ async fn missing_worker_arms_the_gate() {+ let (cue, rx) = StartCue::stub();+ drop(rx);+ let gate = RecordingStartGate::new();+ play(cue, gate.clone()).await;+ assert!(gate.is_armed());}}diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex 35151b2c6..c55cf72e2 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -60,6 +60,7 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {screen_capture: screen_capture::VideoSourceConfig,output_path: PathBuf,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,fragmented: bool,use_oop_muxer: bool,shared_pause_state: Option<SharedPauseState>,@@ -75,6 +76,7 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {segments_dir: PathBuf,output_size: (u32, u32),start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline>where@@ -89,6 +91,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {screen_capture: screen_capture::VideoSourceConfig,output_path: PathBuf,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,fragmented: bool,use_oop_muxer: bool,shared_pause_state: Option<SharedPauseState>,@@ -159,6 +162,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<OutOfProcessFragmentedM4SMuxer>(OutOfProcessFragmentedM4SMuxerConfig {preset,bpp,@@ -171,6 +175,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig {preset,bpp,@@ -189,6 +194,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {OutputPipeline::builder(output_path.clone()).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<AVFoundationMp4Muxer>(AVFoundationMp4MuxerConfig {output_height: output_size.map(|(_, h)| h),instant_mode: false,@@ -204,11 +210,13 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {segments_dir: PathBuf,output_size: (u32, u32),start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline> {OutputPipeline::builder(segments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig {bpp: H264EncoderBuilder::INSTANT_MODE_BPP,output_size: Some(output_size),@@ -226,6 +234,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {screen_capture: screen_capture::VideoSourceConfig,output_path: PathBuf,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,fragmented: bool,use_oop_muxer: bool,shared_pause_state: Option<SharedPauseState>,@@ -283,6 +292,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsOOPFragmentedM4SMuxer>(WindowsOOPFragmentedM4SMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset,@@ -298,6 +308,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsFragmentedM4SMuxer>(WindowsFragmentedM4SMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset,@@ -316,6 +327,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {OutputPipeline::builder(output_path.clone()).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsMuxer>(WindowsMuxerConfig {pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),d3d_device,@@ -338,11 +350,13 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {segments_dir: PathBuf,output_size: (u32, u32),start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline> {OutputPipeline::builder(segments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsFragmentedM4SMuxer>(WindowsFragmentedM4SMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset: H264Preset::Ultrafast,@@ -362,6 +376,7 @@ impl MakeCapturePipeline for screen_capture::X11Capture {screen_capture: screen_capture::VideoSourceConfig,output_path: PathBuf,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,_fragmented: bool,_use_oop_muxer: bool,shared_pause_state: Option<SharedPauseState>,@@ -377,6 +392,7 @@ impl MakeCapturePipeline for screen_capture::X11Capture {OutputPipeline::builder(fragments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset: if ultra {@@ -396,11 +412,13 @@ impl MakeCapturePipeline for screen_capture::X11Capture {segments_dir: PathBuf,output_size: (u32, u32),start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline> {OutputPipeline::builder(segments_dir).with_video::<screen_capture::VideoSource>(screen_capture).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset: H264Preset::Ultrafast,diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 054df3d2e..4597b8cb9 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -1,4 +1,5 @@#[cfg(target_os = "macos")]+use crate::RecordingStartGate;use crate::SendableShareableContent;#[cfg(target_os = "linux")]mod linux_camera;@@ -707,6 +708,7 @@ async fn create_pipeline(system_audio_source: Option<crate::sources::screen_capture::SystemAudioSourceConfig>,max_output_size: Option<u32>,start_time: Timestamps,+ start_gate: Option<RecordingStartGate>,) -> anyhow::Result<Pipeline> {let ScreenPipelineInput {source: screen_capture,@@ -747,6 +749,7 @@ async fn create_pipeline(segments_dir.clone(),output_resolution,start_time,+ start_gate.clone(),segment_tx_for_video,).await?;@@ -759,6 +762,7 @@ async fn create_pipeline(camera,}).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {segment_duration: std::time::Duration::from_secs(2),preset: cap_enc_ffmpeg::h264::H264Preset::Ultrafast,@@ -773,6 +777,7 @@ async fn create_pipeline(segments_dir.clone(),output_resolution,start_time,+ start_gate.clone(),segment_tx_for_video,).await?@@ -781,8 +786,9 @@ async fn create_pipeline(let has_audio = mic_feed.is_some() || system_audio_source.is_some();let audio = if has_audio {let audio_dir = content_dir.join("audio");- let mut builder =- output_pipeline::OutputPipeline::builder(audio_dir.clone()).with_timestamps(start_time);+ let mut builder = output_pipeline::OutputPipeline::builder(audio_dir.clone())+ .with_timestamps(start_time)+ .with_start_gate(start_gate.clone());#[cfg(target_os = "linux")]{builder = builder.with_audio_anchor(output_pipeline::AudioAnchor::PipelineEpoch);@@ -857,6 +863,7 @@ pub struct ActorBuilder {excluded_windows: Vec<scap_targets::WindowId>,#[cfg(target_os = "linux")]lifetime: InstantLifetimeOwner,+ start_gate: Option<RecordingStartGate>,}impl ActorBuilder {@@ -881,9 +888,17 @@ impl ActorBuilder {lifetime: InstantLifetimeOwner::new(),#[cfg(target_os = "macos")]excluded_windows: Vec::new(),+ start_gate: None,}}+ /// Prime the capture pipeline ahead of the start cue; nothing is recorded+ /// until the gate is armed. See [`RecordingStartGate`].+ pub fn with_start_gate(mut self, start_gate: RecordingStartGate) -> Self {+ self.start_gate = Some(start_gate);+ self+ }+#[cfg(target_os = "linux")]pub fn lifecycle(&self) -> InstantLifecycle {self.lifetime.lifecycle.clone()@@ -961,6 +976,7 @@ impl ActorBuilder {capture_system_audio: self.system_audio,mic_feed: self.mic_feed,camera_feed: self.camera_feed,+ start_gate: self.start_gate,#[cfg(target_os = "macos")]shareable_content,#[cfg(target_os = "macos")]@@ -1246,7 +1262,8 @@ async fn build_instant_recording_actor(let mut builder = OutputPipeline::builder(output_path.clone()).with_video::<crate::sources::NativeCamera>(camera_feed.clone())- .with_timestamps(timestamps);+ .with_timestamps(timestamps)+ .with_start_gate(inputs.start_gate.clone());if let Some(mic_feed) = inputs.mic_feed.clone() {builder = builder.with_audio_source::<crate::sources::Microphone>(mic_feed);@@ -1368,6 +1385,7 @@ async fn build_instant_recording_actor(system_audio_source,max_output_size,timestamps,+ inputs.start_gate.clone(),).await?;diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex e07288d94..a7dcbbcc4 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -89,6 +89,9 @@ pub struct RecordingBaseInputs {pub shareable_content: Option<SendableShareableContent>,#[cfg(target_os = "macos")]pub excluded_windows: Vec<scap_targets::WindowId>,+ /// Present when the pipeline is primed ahead of the start cue; capture is+ /// held back until it is armed.+ pub start_gate: Option<RecordingStartGate>,}#[cfg(target_os = "macos")]diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex a0bd989b6..9f10171ea 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -1,3 +1,4 @@+use super::start_gate::{AudioAdmission, RecordingStartGate};use crate::sources::audio_mixer::AudioMixer;use anyhow::{Context, anyhow};use cap_media_info::{AudioInfo, VideoInfo};@@ -1667,6 +1668,7 @@ impl OutputPipeline {timestamps,master_clock: None,audio_anchor: AudioAnchor::FirstFrame,+ start_gate: None,}}}@@ -1750,6 +1752,7 @@ pub struct OutputPipelineBuilder<TVideo> {timestamps: Timestamps,master_clock: Option<Arc<MasterClock>>,audio_anchor: AudioAnchor,+ start_gate: Option<RecordingStartGate>,}pub struct NoVideo;@@ -1795,6 +1798,12 @@ impl<THasVideo> OutputPipelineBuilder<THasVideo> {self.audio_anchor = anchor;self}++ /// Hold every captured frame until `gate` is armed. See [`RecordingStartGate`].+ pub fn with_start_gate(mut self, gate: Option<RecordingStartGate>) -> Self {+ self.start_gate = gate;+ self+ }}impl OutputPipelineBuilder<NoVideo> {@@ -1809,6 +1818,7 @@ impl OutputPipelineBuilder<NoVideo> {timestamps: self.timestamps,master_clock: self.master_clock,audio_anchor: self.audio_anchor,+ start_gate: self.start_gate,}}}@@ -2353,6 +2363,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {path,master_clock,audio_anchor,+ start_gate,..} = self;@@ -2414,6 +2425,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {master_clock.clone(),video_info,video_start_gate.clone(),+ start_gate.clone(),);let audio_gap_summary = Arc::new(OnceLock::new());@@ -2430,6 +2442,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {shared_pause,true,video_start_gate,+ start_gate,build_ctx.stop_signal,audio_gap_summary.clone(),audio_anchor,@@ -2472,6 +2485,7 @@ impl OutputPipelineBuilder<NoVideo> {path,master_clock,audio_anchor,+ start_gate,..} = self;@@ -2525,6 +2539,7 @@ impl OutputPipelineBuilder<NoVideo> {shared_pause,false,None,+ start_gate,build_ctx.stop_signal,audio_gap_summary.clone(),audio_anchor,@@ -2602,6 +2617,7 @@ async fn finish_build(shared_pause: SharedWallClockPause,has_video: bool,video_start_gate: Option<VideoStartGate>,+ start_gate: Option<RecordingStartGate>,stop_signal: PipelineStopSignal,gap_summary_slot: Arc<OnceLock<AudioGapSummary>>,audio_anchor: AudioAnchor,@@ -2616,6 +2632,7 @@ async fn finish_build(shared_pause,has_video,video_start_gate,+ start_gate,gap_summary_slot,audio_anchor,);@@ -2833,6 +2850,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vmaster_clock: Arc<MasterClock>,video_info: VideoInfo,video_start_gate: Option<VideoStartGate>,+ start_gate: Option<RecordingStartGate>,) -> Option<oneshot::Receiver<Result<(), String>>> {let frame_duration_ns = estimate_video_frame_duration_ns(&video_info);let (start_tx, started) =@@ -2909,6 +2927,8 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vlet mut dropped_during_pause: u64 = 0;let mut last_frame = None;let mut first_frame_offset = None;+ let mut start_gate = start_gate;+ let mut held_before_start: u64 = 0;let res = stop_token.run_until_cancelled(async {@@ -2920,10 +2940,24 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vcontinue;}- frame_count += 1;-let timestamp = frame.timestamp();+ if let Some(gate) = &start_gate {+ if !gate.admits_video(timestamp) {+ held_before_start += 1;+ continue;+ }+ 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"+ );+ start_gate = None;+ }++ frame_count += 1;+let is_first_frame = first_tx.is_some();if let Some(first_tx) = first_tx.take() {let _ = first_tx.send(timestamp);@@ -3254,6 +3288,7 @@ impl PreparedAudioSources {shared_pause: SharedWallClockPause,has_video: bool,video_start_gate: Option<VideoStartGate>,+ start_gate: Option<RecordingStartGate>,gap_summary_slot: Arc<OnceLock<AudioGapSummary>>,audio_anchor: AudioAnchor,) {@@ -3285,6 +3320,7 @@ impl PreparedAudioSources {let mut frame_count: u64 = 0;let mut gap_tracker = AudioGapTracker::new(has_wireless_source, timestamps);let mut gate_applied = video_start_gate.is_none();+ let mut start_gate = StartGateState::new(start_gate);let mut audio_degraded = false;@@ -3300,6 +3336,7 @@ impl PreparedAudioSources {health_tx: &health_tx,shared_pause: &shared_pause,video_start_gate: video_start_gate.as_ref(),+ start_gate: &start_gate.gate,allow_audio_degradation,origin: FrameProcessOrigin::Live,observed_at: Instant::now(),@@ -3310,6 +3347,8 @@ impl PreparedAudioSources {timestamp_generator: &mut timestamp_generator,gap_tracker: &mut gap_tracker,gate_applied: &mut gate_applied,+ held_before_start: &mut start_gate.held,+ start_admitted: &mut start_gate.admitted,first_tx: &mut first_tx,frame_count: &mut frame_count,dropped_during_pause: &mut dropped_during_pause,@@ -3372,6 +3411,7 @@ impl PreparedAudioSources {health_tx: &health_tx,shared_pause: &shared_pause,video_start_gate: video_start_gate.as_ref(),+ start_gate: &start_gate.gate,allow_audio_degradation,origin: FrameProcessOrigin::Drain,observed_at: Instant::now(),@@ -3382,6 +3422,8 @@ impl PreparedAudioSources {timestamp_generator: &mut timestamp_generator,gap_tracker: &mut gap_tracker,gate_applied: &mut gate_applied,+ held_before_start: &mut start_gate.held,+ start_admitted: &mut start_gate.admitted,first_tx: &mut first_tx,frame_count: &mut frame_count,dropped_during_pause: &mut dropped_during_pause,@@ -3449,8 +3491,9 @@ impl PreparedAudioSources {// the fill below covers the full duration and the track// reports a valid start.if audio_anchor == AudioAnchor::PipelineEpoch && !gap_tracker.started() {- let epoch_ts = Timestamp::Instant(timestamps.instant());- gap_tracker.mark_started(epoch_ts, timestamps.instant());+ let epoch = audio_epoch(timestamps, start_gate.gate.as_ref());+ let epoch_ts = Timestamp::Instant(epoch.instant());+ gap_tracker.mark_started(epoch_ts, epoch.instant());if let Some(first_tx) = first_tx.take() {let _ = first_tx.send(epoch_ts);}@@ -3592,6 +3635,7 @@ struct AudioFrameProcessContext<'a, TMutex: AudioMuxer> {health_tx: &'a HealthSender,shared_pause: &'a SharedWallClockPause,video_start_gate: Option<&'a VideoStartGate>,+ start_gate: &'a Option<RecordingStartGate>,allow_audio_degradation: bool,origin: FrameProcessOrigin,observed_at: Instant,@@ -3603,11 +3647,39 @@ struct AudioFrameProcessState<'a> {timestamp_generator: &'a mut AudioTimestampGenerator,gap_tracker: &'a mut AudioGapTracker,gate_applied: &'a mut bool,+ held_before_start: &'a mut u64,+ start_admitted: &'a mut bool,first_tx: &'a mut Option<oneshot::Sender<Timestamp>>,frame_count: &'a mut u64,dropped_during_pause: &'a mut u64,}+struct StartGateState {+ gate: Option<RecordingStartGate>,+ held: u64,+ admitted: bool,+}++impl StartGateState {+ fn new(gate: Option<RecordingStartGate>) -> Self {+ Self {+ gate,+ held: 0,+ admitted: false,+ }+ }+}++/// The instant an epoch-anchored audio track treats as time zero: the start+/// gate's arm point when the pipeline was primed ahead of the recording, else+/// the pipeline epoch.+fn audio_epoch(timestamps: Timestamps, start_gate: Option<&RecordingStartGate>) -> Timestamps {+ start_gate+ .and_then(RecordingStartGate::armed_at)+ .filter(|armed| armed.instant() > timestamps.instant())+ .unwrap_or(timestamps)+}+async fn process_audio_frame<TMutex: AudioMuxer>(ctx: AudioFrameProcessContext<'_, TMutex>,state: AudioFrameProcessState<'_>,@@ -3620,6 +3692,42 @@ async fn process_audio_frame<TMutex: AudioMuxer>(return Ok(AudioFrameOutcome::DroppedPaused);}+ if let Some(gate) = ctx.start_gate {+ match gate.admit_audio(frame.timestamp, frame.inner.samples(), ctx.sample_rate) {+ AudioAdmission::Drop => {+ *state.held_before_start += 1;+ return Ok(AudioFrameOutcome::DropFrame);+ }+ AudioAdmission::Trim { samples } => {+ let Some(trimmed) = trim_audio_frame_front(&frame.inner, samples) else {+ *state.held_before_start += 1;+ return Ok(AudioFrameOutcome::DropFrame);+ };+ let trim_duration = Duration::from_nanos(+ samples as u64 * 1_000_000_000 / u64::from(ctx.sample_rate.max(1)),+ );+ if !std::mem::replace(state.start_admitted, true) {+ info!(+ held_frames = *state.held_before_start,+ trimmed_samples = samples,+ "Start gate admitted first audio frame at the arm point"+ );+ }+ frame = AudioFrame::new(trimmed, frame.timestamp + trim_duration);+ }+ AudioAdmission::Admit => {+ if !std::mem::replace(state.start_admitted, true) {+ info!(+ held_frames = *state.held_before_start,+ admitted_after_arm_ms =+ gate.offset_secs(frame.timestamp).unwrap_or_default() * 1000.0,+ "Start gate admitted first audio frame"+ );+ }+ }+ }+ }+if !*state.gate_applied&& let Some(gate) = ctx.video_start_gate{@@ -3660,17 +3768,16 @@ async fn process_audio_frame<TMutex: AudioMuxer>(&& ctx.video_start_gate.is_none()&& !state.gap_tracker.started(){- let epoch_ts = Timestamp::Instant(ctx.timestamps.instant());- state- .gap_tracker- .mark_started(epoch_ts, ctx.timestamps.instant());+ let epoch = audio_epoch(ctx.timestamps, ctx.start_gate.as_ref());+ let epoch_ts = Timestamp::Instant(epoch.instant());+ state.gap_tracker.mark_started(epoch_ts, epoch.instant());- let head_secs = frame.timestamp.signed_duration_since_secs(ctx.timestamps);+ let head_secs = frame.timestamp.signed_duration_since_secs(epoch);let head = Duration::from_secs_f64(head_secs.max(0.0)).saturating_sub(total_pause_duration)// A capture timestamp can't credibly predate more wall time than// has actually elapsed since the epoch.- .min(observed_at.saturating_duration_since(ctx.timestamps.instant()));+ .min(observed_at.saturating_duration_since(epoch.instant()));if !head.is_zero() {let start_samples = state.timestamp_generator.total_samples;@@ -3715,7 +3822,7 @@ async fn process_audio_frame<TMutex: AudioMuxer>(if let Some(first_tx) = state.first_tx.take() {let anchor_ts =if ctx.anchor == AudioAnchor::PipelineEpoch && ctx.video_start_gate.is_none() {- Timestamp::Instant(ctx.timestamps.instant())+ Timestamp::Instant(audio_epoch(ctx.timestamps, ctx.start_gate.as_ref()).instant())} else {frame.timestamp};@@ -6876,6 +6983,59 @@ mod tests {(timestamps, capture_duration)}+ #[tokio::test]+ async fn primed_pipeline_discards_video_captured_before_the_start_gate_arms() {+ 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("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();++ for _ in 0..3 {+ sender+ .send_async(StaticFrame {+ timestamp: Timestamp::Instant(Instant::now()),+ })+ .await+ .unwrap();+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ tokio::time::sleep(Duration::from_millis(60)).await;+ assert!(sent.lock().unwrap().is_empty());++ assert!(gate.arm());+ let first_admitted = Instant::now();+ for frame in 0..3u32 {+ sender+ .send_async(StaticFrame {+ timestamp: Timestamp::Instant(+ first_admitted + Duration::from_millis(33 * u64::from(frame)),+ ),+ })+ .await+ .unwrap();+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ let outcome = pipeline.stop().await.unwrap();++ match outcome.first_timestamp {+ Timestamp::Instant(instant) => assert_eq!(instant, first_admitted),+ other => panic!("unexpected first timestamp {other:?}"),+ }+ let timestamps = sent.lock().unwrap().clone();+ assert_eq!(timestamps.first(), Some(&Duration::ZERO));+ assert!(timestamps.len() >= 3, "{timestamps:?}");+ }+#[tokio::test]async fn static_capture_finishes_with_two_nominally_spaced_frames() {let (timestamps, _) = record_static_capture(Duration::ZERO).await;@@ -7564,6 +7724,9 @@ mod tests {timestamp_generator: AudioTimestampGenerator,gap_tracker: AudioGapTracker,gate_applied: bool,+ start_gate: Option<RecordingStartGate>,+ held_before_start: u64,+ start_admitted: bool,first_tx: Option<oneshot::Sender<Timestamp>>,frame_count: u64,dropped_during_pause: u64,@@ -7591,6 +7754,9 @@ mod tests {timestamp_generator: AudioTimestampGenerator::from_master_clock(master_clock),gap_tracker: AudioGapTracker::new(false, timestamps),gate_applied: true,+ start_gate: None,+ held_before_start: 0,+ start_admitted: false,first_tx: None,frame_count: 0,dropped_during_pause: 0,@@ -7598,6 +7764,13 @@ mod tests {}}+ fn primed(start_gate: RecordingStartGate) -> Self {+ Self {+ start_gate: Some(start_gate),+ ..Self::new()+ }+ }+fn new_epoch_anchored() -> Self {Self {anchor: AudioAnchor::PipelineEpoch,@@ -7637,6 +7810,7 @@ mod tests {health_tx: &self.health_tx,shared_pause: &self.shared_pause,video_start_gate: None,+ start_gate: &self.start_gate,allow_audio_degradation: true,origin: FrameProcessOrigin::Live,observed_at,@@ -7647,6 +7821,8 @@ mod tests {timestamp_generator: &mut self.timestamp_generator,gap_tracker: &mut self.gap_tracker,gate_applied: &mut self.gate_applied,+ held_before_start: &mut self.held_before_start,+ start_admitted: &mut self.start_admitted,first_tx: &mut self.first_tx,frame_count: &mut self.frame_count,dropped_during_pause: &mut self.dropped_during_pause,@@ -7674,6 +7850,81 @@ mod tests {}}+ #[tokio::test(flavor = "current_thread")]+ async fn primed_track_holds_audio_until_the_start_gate_arms() {+ let gate = RecordingStartGate::new();+ let mut harness = AudioTimelineHarness::primed(gate.clone());++ assert!(matches!(+ harness.process(Duration::ZERO, 480).await,+ AudioFrameOutcome::DropFrame+ ));+ assert!(matches!(+ harness.process(Duration::from_millis(10), 480).await,+ AudioFrameOutcome::DropFrame+ ));+ assert!(harness.sent().is_empty());+ assert_eq!(harness.held_before_start, 2);++ gate.arm_at(harness.timestamps + Duration::from_millis(25));++ assert!(matches!(+ harness.process(Duration::from_millis(20), 480).await,+ AudioFrameOutcome::Sent+ ));+ assert!(matches!(+ harness.process(Duration::from_millis(30), 480).await,+ AudioFrameOutcome::Sent+ ));++ assert_eq!(+ harness.sent(),+ vec![+ SentAudioFrame {+ samples: 240,+ timestamp: Duration::ZERO,+ },+ SentAudioFrame {+ samples: 480,+ timestamp: Duration::from_millis(5),+ },+ ]+ );+ assert_eq!(harness.committed_audio(), Duration::from_millis(15));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn primed_epoch_anchored_track_anchors_at_the_arm_point() {+ let gate = RecordingStartGate::new();+ let mut harness = AudioTimelineHarness {+ start_gate: Some(gate.clone()),+ ..AudioTimelineHarness::new_epoch_anchored()+ };++ assert!(matches!(+ harness.process(Duration::from_millis(500), 480).await,+ AudioFrameOutcome::DropFrame+ ));+ gate.arm_at(harness.timestamps + Duration::from_millis(1_000));++ assert!(matches!(+ harness.process(Duration::from_millis(1_020), 480).await,+ AudioFrameOutcome::Sent+ ));++ let sent = harness.sent();+ let (frame, head) = sent.split_last().unwrap();+ let head_samples: usize = head.iter().map(|frame| frame.samples).sum();+ assert_eq!(head_samples, 960);+ assert_eq!(+ *frame,+ SentAudioFrame {+ samples: 480,+ timestamp: Duration::from_millis(20),+ }+ );+ }+#[tokio::test(flavor = "current_thread")]async fn overlapping_delayed_mic_frame_is_trimmed() {let mut harness = AudioTimelineHarness::new();diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rsindex bd6450ba0..e8f069a70 100644--- a/crates/recording/src/output_pipeline/mod.rs+++ b/crates/recording/src/output_pipeline/mod.rs@@ -8,10 +8,12 @@ mod macos_frame_convert;#[cfg(target_os = "macos")]mod oop_fragmented_m4s;pub mod oop_muxer;+mod start_gate;pub use async_camera::*;pub use core::*;pub use ffmpeg::*;+pub use start_gate::*;#[cfg(target_os = "linux")]#[derive(Clone)]diff --git a/crates/recording/src/output_pipeline/start_gate.rs b/crates/recording/src/output_pipeline/start_gate.rsnew file mode 100644index 000000000..a70b3cde2--- /dev/null+++ b/crates/recording/src/output_pipeline/start_gate.rs@@ -0,0 +1,200 @@+use std::{+ sync::{+ Arc, OnceLock,+ atomic::{AtomicBool, Ordering},+ },+ time::{Duration, Instant},+};++use cap_timestamp::{Timestamp, Timestamps};+use tracing::warn;++/// Longest a primed pipeline will hold frames back without an explicit arm.+/// The apps arm the gate the moment the start cue finishes, so hitting this is+/// a caller bug; admitting everything is safer than recording nothing.+pub const START_GATE_FAILSAFE: Duration = Duration::from_secs(20);++/// Holds captured media back until the recording is allowed to begin.+///+/// Sources, encoders and muxers spin up ahead of the start cue so their warm-up+/// latency overlaps the countdown. Every frame captured before the gate is+/// armed is discarded, so the first admitted frame becomes the recording's+/// timeline zero exactly as if the pipeline had been built at the arm instant.+#[derive(Clone)]+pub struct RecordingStartGate(Arc<Inner>);++struct Inner {+ armed_at: OnceLock<Timestamps>,+ created: Instant,+ failsafe_logged: AtomicBool,+}++impl Default for RecordingStartGate {+ fn default() -> Self {+ Self::new()+ }+}++impl RecordingStartGate {+ pub fn new() -> Self {+ Self(Arc::new(Inner {+ armed_at: OnceLock::new(),+ created: Instant::now(),+ failsafe_logged: AtomicBool::new(false),+ }))+ }++ pub fn arm(&self) -> bool {+ self.arm_at(Timestamps::now())+ }++ pub fn arm_at(&self, at: Timestamps) -> bool {+ let armed = self.0.armed_at.set(at).is_ok();+ if armed {+ tracing::info!(+ primed_for_ms = self.0.created.elapsed().as_millis() as u64,+ "Recording start gate armed"+ );+ }+ armed+ }++ pub fn armed_at(&self) -> Option<Timestamps> {+ self.0.armed_at.get().copied()+ }++ pub fn is_armed(&self) -> bool {+ self.0.armed_at.get().is_some()+ }++ pub fn created_at(&self) -> Instant {+ self.0.created+ }++ fn armed_at_or_failsafe(&self) -> Option<Timestamps> {+ if let Some(at) = self.0.armed_at.get() {+ return Some(*at);+ }+ if self.0.created.elapsed() < START_GATE_FAILSAFE {+ return None;+ }+ let _ = self.0.armed_at.set(Timestamps::now());+ if !self.0.failsafe_logged.swap(true, Ordering::AcqRel) {+ warn!(+ failsafe_secs = START_GATE_FAILSAFE.as_secs(),+ "Recording start gate was never armed; admitting capture"+ );+ }+ self.0.armed_at.get().copied()+ }++ /// Seconds from the arm point to `timestamp`, negative for media captured+ /// before it. `None` while the gate is still closed.+ pub(crate) fn offset_secs(&self, timestamp: Timestamp) -> Option<f64> {+ let armed_at = self.armed_at_or_failsafe()?;+ Some(timestamp.signed_duration_since_secs(armed_at))+ }++ pub(crate) fn admits_video(&self, timestamp: Timestamp) -> bool {+ self.offset_secs(timestamp)+ .is_some_and(|offset| offset >= 0.0)+ }++ pub(crate) fn admit_audio(+ &self,+ timestamp: Timestamp,+ samples: usize,+ sample_rate: u32,+ ) -> AudioAdmission {+ let Some(offset) = self.offset_secs(timestamp) else {+ return AudioAdmission::Drop;+ };+ if offset >= 0.0 {+ return AudioAdmission::Admit;+ }+ let leading = (-offset * f64::from(sample_rate)).round() as usize;+ if leading == 0 {+ AudioAdmission::Admit+ } else if leading >= samples {+ AudioAdmission::Drop+ } else {+ AudioAdmission::Trim { samples: leading }+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum AudioAdmission {+ Drop,+ Trim { samples: usize },+ Admit,+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(base: Timestamps, offset_ms: i64) -> Timestamp {+ let instant = base.instant();+ if offset_ms >= 0 {+ Timestamp::Instant(instant + Duration::from_millis(offset_ms as u64))+ } else {+ Timestamp::Instant(+ instant+ .checked_sub(Duration::from_millis((-offset_ms) as u64))+ .unwrap(),+ )+ }+ }++ #[test]+ fn closed_gate_admits_nothing() {+ let gate = RecordingStartGate::new();+ let now = Timestamps::now();+ assert!(!gate.admits_video(at(now, 0)));+ assert!(!gate.admits_video(at(now, 5_000)));+ assert_eq!(+ gate.admit_audio(at(now, 0), 480, 48_000),+ AudioAdmission::Drop+ );+ assert!(!gate.is_armed());+ }++ #[test]+ fn armed_gate_admits_only_media_from_the_arm_point() {+ let gate = RecordingStartGate::new();+ let armed = Timestamps::now();+ assert!(gate.arm_at(armed));+ assert!(!gate.arm_at(Timestamps::now()));+ assert!(!gate.admits_video(at(armed, -1)));+ assert!(gate.admits_video(at(armed, 0)));+ assert!(gate.admits_video(at(armed, 33)));+ }++ #[test]+ fn audio_straddling_the_arm_point_is_trimmed_to_it() {+ let gate = RecordingStartGate::new();+ let armed = Timestamps::now();+ gate.arm_at(armed);+ assert_eq!(+ gate.admit_audio(at(armed, -20), 480, 48_000),+ AudioAdmission::Drop+ );+ assert_eq!(+ gate.admit_audio(at(armed, -10), 480, 48_000),+ AudioAdmission::Drop+ );+ assert_eq!(+ gate.admit_audio(at(armed, -5), 480, 48_000),+ AudioAdmission::Trim { samples: 240 }+ );+ assert_eq!(+ gate.admit_audio(at(armed, 0), 480, 48_000),+ AudioAdmission::Admit+ );+ assert_eq!(+ gate.admit_audio(at(armed, 7), 480, 48_000),+ AudioAdmission::Admit+ );+ }+}diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 8c35916a2..6e29334f5 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -1,4 +1,5 @@#[cfg(target_os = "macos")]+use crate::RecordingStartGate;use crate::SendableShareableContent;#[cfg(target_os = "macos")]use crate::output_pipeline::{@@ -567,6 +568,12 @@ impl Actor {segment_start_instant,..}) => {+ let segment_start_instant = self+ .segment_factory+ .start_gate()+ .and_then(RecordingStartGate::armed_at)+ .map(|armed| armed.instant().max(segment_start_instant))+ .unwrap_or(segment_start_instant);if let Some(deadline) =minimum_segment_stop_deadline(discard, segment_start_instant){@@ -2029,6 +2036,7 @@ pub struct ActorBuilder {quality: crate::StudioQuality,#[cfg(target_os = "macos")]excluded_windows: Vec<scap_targets::WindowId>,+ start_gate: Option<RecordingStartGate>,}impl ActorBuilder {@@ -2052,6 +2060,7 @@ impl ActorBuilder {quality: crate::StudioQuality::Balanced,#[cfg(target_os = "macos")]excluded_windows: Vec::new(),+ start_gate: None,}}@@ -2060,6 +2069,14 @@ impl ActorBuilder {self}+ /// Prime the capture pipeline ahead of the start cue: every source, encoder+ /// and muxer is live once `build` returns, but nothing is recorded until the+ /// gate is armed. See [`RecordingStartGate`].+ pub fn with_start_gate(mut self, start_gate: RecordingStartGate) -> Self {+ self.start_gate = Some(start_gate);+ self+ }+pub fn with_mic_feed(mut self, mic_feed: Arc<MicrophoneFeedLock>) -> Self {self.mic_feed = Some(mic_feed);self@@ -2132,6 +2149,7 @@ impl ActorBuilder {capture_system_audio: self.system_audio,mic_feed: self.mic_feed,camera_feed: self.camera_feed,+ start_gate: self.start_gate,#[cfg(target_os = "macos")]shareable_content,#[cfg(target_os = "macos")]@@ -2936,7 +2954,7 @@ impl SegmentPipelineFactory {&self.segments_dir,&self.cursors_dir,self.index,- self.base_inputs.clone(),+ self.segment_base_inputs(),cursors,next_cursors_id,self.custom_cursor_capture,@@ -2973,7 +2991,7 @@ impl SegmentPipelineFactory {&self.segments_dir,&self.cursors_dir,self.index,- self.base_inputs.clone(),+ self.segment_base_inputs(),cursors,next_cursors_id,self.custom_cursor_capture,@@ -3005,6 +3023,20 @@ impl SegmentPipelineFactory {Ok(pipeline)}+ /// Only the first segment is primed behind the start gate; resumed+ /// segments record from their own build instant.+ fn segment_base_inputs(&self) -> RecordingBaseInputs {+ let mut inputs = self.base_inputs.clone();+ if self.index > 0 {+ inputs.start_gate = None;+ }+ inputs+ }++ pub fn start_gate(&self) -> Option<&RecordingStartGate> {+ self.base_inputs.start_gate.as_ref()+ }+pub fn set_mic_feed(&mut self, mic_feed: Option<Arc<MicrophoneFeedLock>>) {self.base_inputs.mic_feed = mic_feed;}@@ -3097,6 +3129,8 @@ async fn create_segment_pipeline(trace!("preparing segment pipeline {index}");+ let start_gate = base_inputs.start_gate.clone();+let camera_active = base_inputs.camera_feed.is_some();#[cfg(target_os = "macos")]let segment_fragmented = fragmented && !camera_active;@@ -3138,7 +3172,8 @@ async fn create_segment_pipeline(OutputPipeline::builder(screen_output_path.clone())}.with_video::<sources::Camera>(camera_feed)- .with_timestamps(start_time);+ .with_timestamps(start_time)+ .with_start_gate(start_gate.clone());let screen = if segment_fragmented {builder@@ -3177,6 +3212,7 @@ async fn create_segment_pipeline(let screen = OutputPipeline::builder(screen_output_path.clone()).with_video::<sources::NativeCamera>(camera_feed.clone()).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<AVFoundationCameraMuxer>(AVFoundationCameraMuxerConfig::default()).instrument(error_span!("screen-out")).await@@ -3186,6 +3222,7 @@ async fn create_segment_pipeline(let screen = OutputPipeline::builder(screen_output_path.clone()).with_video::<sources::NativeCamera>(camera_feed.clone()).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig {encoder_preferences: encoder_preferences.clone(),..Default::default()@@ -3252,6 +3289,7 @@ async fn create_segment_pipeline(capture_source,screen_output_path.clone(),start_time,+ start_gate.clone(),segment_fragmented,use_oop_muxer,shared_pause_state.clone(),@@ -3276,6 +3314,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<MacOSFragmentedM4SCameraMuxer>(MacOSFragmentedM4SCameraMuxerConfig {shared_pause_state: shared_pause_state.clone(),..Default::default()@@ -3286,6 +3325,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("camera.mp4")).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<AVFoundationCameraMuxer>(AVFoundationCameraMuxerConfig {compatibility_quality: matches!(quality, crate::StudioQuality::Compatibility),..Default::default()@@ -3307,6 +3347,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsFragmentedM4SCameraMuxer>(WindowsFragmentedM4SCameraMuxerConfig {shared_pause_state: shared_pause_state.clone(),..Default::default()@@ -3317,6 +3358,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("camera.mp4")).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig {encoder_preferences: encoder_preferences.clone(),..Default::default()@@ -3337,6 +3379,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("camera")).with_video::<sources::Camera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {segment_duration: Duration::from_secs(2),@@ -3350,6 +3393,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("camera.mp4")).with_video::<sources::Camera>(camera_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<crate::ffmpeg::Mp4Muxer>(()).instrument(error_span!("camera-out")).await@@ -3365,6 +3409,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(output_path).with_audio_source::<sources::Microphone>(mic_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<FragmentedAudioMuxer>(FragmentedAudioMuxerConfig {shared_pause_state: shared_pause_state.clone(),})@@ -3374,6 +3419,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("audio-input.ogg")).with_audio_source::<sources::Microphone>(mic_feed).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).build::<OggMuxer>(()).instrument(error_span!("mic-out")).await@@ -3394,6 +3440,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(output_path).with_audio_source::<screen_capture::SystemAudioSource>(system_audio_source).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).with_audio_anchor(AudioAnchor::PipelineEpoch).build::<FragmentedAudioMuxer>(FragmentedAudioMuxerConfig {shared_pause_state: shared_pause_state.clone(),@@ -3404,6 +3451,7 @@ async fn create_segment_pipeline(OutputPipeline::builder(dir.join("system_audio.ogg")).with_audio_source::<screen_capture::SystemAudioSource>(system_audio_source).with_timestamps(start_time)+ .with_start_gate(start_gate.clone()).with_audio_anchor(AudioAnchor::PipelineEpoch).build::<OggMuxer>(()).instrument(error_span!("system-audio-out"))@@ -3743,6 +3791,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,#[cfg(target_os = "macos")]shareable_content: None,#[cfg(target_os = "macos")]@@ -3852,6 +3901,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,#[cfg(target_os = "macos")]shareable_content: None,#[cfg(target_os = "macos")]@@ -3949,6 +3999,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,shareable_content: None,excluded_windows: Vec::new(),},@@ -4085,6 +4136,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,#[cfg(target_os = "macos")]shareable_content: None,#[cfg(target_os = "macos")]@@ -4328,6 +4380,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,#[cfg(target_os = "macos")]shareable_content: None,#[cfg(target_os = "macos")]@@ -5822,6 +5875,7 @@ mod tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,},false,false,@@ -6067,6 +6121,7 @@ mod windows_cancel_tests {capture_system_audio: false,mic_feed: None,camera_feed: None,+ start_gate: None,},false,false,diff --git a/crates/timestamp/src/lib.rs b/crates/timestamp/src/lib.rsindex f3f5e7f5e..a8bb0a562 100644--- a/crates/timestamp/src/lib.rs+++ b/crates/timestamp/src/lib.rs@@ -170,3 +170,18 @@ impl Timestamps {self.mach_absolute_time}}++impl std::ops::Add<Duration> for Timestamps {+ type Output = Timestamps;++ fn add(self, rhs: Duration) -> Self::Output {+ Self {+ instant: self.instant + rhs,+ system_time: self.system_time + rhs,+ #[cfg(windows)]+ performance_counter: self.performance_counter + rhs,+ #[cfg(target_os = "macos")]+ mach_absolute_time: self.mach_absolute_time + rhs,+ }+ }+}