diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index 4be6ffd238b..d3798221f8f 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -2277,14 +2277,14 @@ fn sleep_action( } } -/// On macOS a pipeline only finishes cleanly before Stop when ScreenCaptureKit -/// lost what it was capturing: the display slept or went away, the window -/// closed, or sharing was stopped from the menu bar. Everything captured so far -/// is intact, so the recording is stopped and saved instead of failed. +/// A pipeline that finishes with Ok before Stop lost its capture source: +/// macOS ScreenCaptureKit (display asleep, window closed, sharing stopped) or +/// a Linux Audio Only output monitor. Everything captured so far is intact, +/// so the recording is stopped and saved instead of failed. fn capture_ended_cleanly( outcome: &Result, E>, ) -> bool { - cfg!(target_os = "macos") && matches!(outcome, Ok(Ok(()))) + cfg!(any(target_os = "macos", target_os = "linux")) && matches!(outcome, Ok(Ok(()))) } fn recording_failure_is_current(phase: Phase, current: u64, completed: u64) -> bool { @@ -2890,7 +2890,10 @@ mod recording_failure_tests { #[test] fn a_capture_that_ends_cleanly_before_stop_is_saved_not_failed() { let ended: Result, ()> = Ok(Ok(())); - assert_eq!(capture_ended_cleanly(&ended), cfg!(target_os = "macos")); + assert_eq!( + capture_ended_cleanly(&ended), + cfg!(any(target_os = "macos", target_os = "linux")) + ); let task_died: Result, ()> = Err(()); assert!(!capture_ended_cleanly(&task_died)); } diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index 861319d25d1..67194a2b467 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -98,6 +98,25 @@ const STANDARD_SAMPLE_RATES: [u32; 13] = [ 192_000, ]; +#[cfg(target_os = "linux")] +fn sample_follows_route_resume( + resume: &RouteResume, + callback_received: Instant, + capture_delay: Option, +) -> bool { + let not_before_nanos = resume.not_before_nanos.load(Ordering::Acquire); + if not_before_nanos == 0 { + return true; + } + let captured_at = capture_delay + .and_then(|delay| callback_received.checked_sub(delay)) + .unwrap_or(callback_received); + captured_at + .saturating_duration_since(resume.base) + .as_nanos() + >= u128::from(not_before_nanos) +} + #[cfg(target_os = "linux")] fn audio_follows_confirmed_route( callback_received: Instant, @@ -360,6 +379,8 @@ pub struct MicrophoneSamples { pub channels: u16, pub info: InputCallbackInfo, pub timestamp: Timestamp, + #[cfg(target_os = "linux")] + pub(crate) capture_epoch: u64, } /// Debounces sample-rate changes: a freshly-inferred rate is only adopted after it is @@ -714,6 +735,148 @@ fn enqueue_microphone_samples( } } +#[cfg(target_os = "linux")] +fn release_staged_system_audio( + staging: &Arc< + std::sync::Mutex>, + >, + event: crate::sources::screen_capture::SystemAudioWatch, +) -> Vec { + use crate::sources::screen_capture::{ + SystemAudioRouteCheck, SystemAudioRoutePlan, SystemAudioWatch, + }; + let mut staging = staging.lock().unwrap(); + match event { + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Keep, + check_started, + } => staging.observe(SystemAudioRouteCheck::OnMonitor { check_started }), + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Reattach | SystemAudioRoutePlan::Lost, + .. + } => staging.observe(SystemAudioRouteCheck::NotOnMonitor { + observed_at: Instant::now(), + }), + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Ignore, + .. + } => Vec::new(), + SystemAudioWatch::Reattached { at } => { + staging.note_attached(at); + Vec::new() + } + } +} + +#[cfg(target_os = "linux")] +fn on_system_audio_route_event( + staging: &Arc< + std::sync::Mutex>, + >, + health: Option<&RecordingSourceHealth>, + stream_id: u32, + event: crate::sources::screen_capture::SystemAudioWatch, +) -> Vec { + use crate::sources::screen_capture::{SystemAudioRoutePlan, SystemAudioWatch}; + let released = release_staged_system_audio(staging, event); + if let Some(health) = health { + match event { + SystemAudioWatch::Checked { plan, .. } => { + health.apply_system_audio_route(stream_id, plan); + } + SystemAudioWatch::Reattached { .. } => { + health.apply_system_audio_route(stream_id, SystemAudioRoutePlan::Keep); + } + } + } + released +} + +#[cfg(target_os = "linux")] +struct SystemAudioRouteWatchSlot { + cancel: tokio_util::sync::CancellationToken, + generation: u64, + running: Option, +} + +#[cfg(target_os = "linux")] +struct SystemAudioRouteWatch { + slot: std::sync::Mutex, + health: Arc>>, +} + +#[cfg(target_os = "linux")] +impl SystemAudioRouteWatch { + fn new() -> Self { + Self { + slot: std::sync::Mutex::new(SystemAudioRouteWatchSlot { + cancel: tokio_util::sync::CancellationToken::new(), + generation: 0, + running: None, + }), + health: Arc::new(std::sync::Mutex::new(None)), + } + } + + fn set_health(&self, health: Option) { + *self.health.lock().unwrap() = health; + } + + fn stop(&self) { + let mut slot = self.slot.lock().unwrap(); + slot.cancel.cancel(); + slot.running = None; + drop(slot); + self.set_health(None); + } + + fn ensure_started( + &self, + actor: ActorRef, + staging: Arc< + std::sync::Mutex>, + >, + route: Arc< + std::sync::Mutex>, + >, + dropped: Arc, + ) { + let cancel = { + let mut slot = self.slot.lock().unwrap(); + if slot.running.is_some() && !slot.cancel.is_cancelled() { + return; + } + slot.cancel.cancel(); + slot.cancel = tokio_util::sync::CancellationToken::new(); + slot.generation = slot.generation.wrapping_add(1); + slot.running = Some(slot.generation); + slot.cancel.clone() + }; + let health = self.health.clone(); + let _ = std::thread::Builder::new() + .name("system-audio-route".into()) + .spawn(move || { + let mut failure_log = EnqueueFailureLog::default(); + crate::sources::screen_capture::watch_system_audio_route( + cancel, + route, + move |stream_id, event| { + let attached = health.lock().unwrap().clone(); + let released = on_system_audio_route_event( + &staging, + attached.as_ref(), + stream_id, + event, + ); + for sample in released { + enqueue_microphone_samples(&actor, &dropped, &mut failure_log, sample); + } + }, + ); + }); + } +} + #[cfg(any(target_os = "linux", windows))] struct StreamHealth { id: u32, @@ -772,15 +935,94 @@ struct RecordingSourceHealthState { pending: Option>, recovery_origin: Option, terminal: Option, + deferred: Option<(std::time::Instant, String)>, + defer_for: std::time::Duration, + capture_blocked: bool, + capture_gate: Arc, + route_lost_until: Option<(std::time::Instant, String)>, last_frame: Option, /// Since the last frame before a rebuild found no device to open. missing_since: Option, missing_total: Duration, } +#[cfg(target_os = "linux")] +struct RouteResume { + base: Instant, + not_before_nanos: AtomicU64, +} + +#[cfg(target_os = "linux")] +struct SystemCaptureGate { + open: AtomicBool, + epoch: AtomicU64, + resume: RouteResume, +} + +#[cfg(target_os = "linux")] +impl SystemCaptureGate { + fn open() -> Self { + Self { + open: AtomicBool::new(true), + epoch: AtomicU64::new(0), + resume: RouteResume { + base: Instant::now(), + not_before_nanos: AtomicU64::new(0), + }, + } + } +} + +#[cfg(target_os = "linux")] +impl RecordingSourceHealthState { + fn remember_loss(&mut self, error: String) { + if self.terminal.is_some() { + return; + } + if self.defer_for.is_zero() { + self.terminal.get_or_insert(error); + return; + } + if self.deferred.is_none() { + self.deferred = Some((std::time::Instant::now(), error)); + } + } + + fn promote_deferred_loss(&mut self) { + let ready = self + .deferred + .as_ref() + .is_some_and(|(since, _)| since.elapsed() >= self.defer_for); + if ready && let Some((_, error)) = self.deferred.take() { + self.terminal.get_or_insert(error); + } + let route_ready = self + .route_lost_until + .as_ref() + .is_some_and(|(deadline, _)| std::time::Instant::now() >= *deadline); + if route_ready && let Some((_, error)) = self.route_lost_until.take() { + self.terminal.get_or_insert(error); + } + } +} + +// Same window as the audio-only reconnect grace. A monitor that returns is +// captured again. One that stays gone ends the system-audio track. +#[cfg(target_os = "linux")] +const SYSTEM_AUDIO_ROUTE_GRACE: Duration = Duration::from_secs(3); + #[cfg(target_os = "linux")] impl RecordingSourceHealth { + #[cfg(test)] fn new(generation: u64, current: Arc) -> Self { + Self::with_capture_gate(generation, current, Arc::new(SystemCaptureGate::open())) + } + + fn with_capture_gate( + generation: u64, + current: Arc, + capture_gate: Arc, + ) -> Self { Self(Arc::new(std::sync::Mutex::new( RecordingSourceHealthState { generation, @@ -788,6 +1030,11 @@ impl RecordingSourceHealth { pending: None, recovery_origin: None, terminal: None, + deferred: None, + defer_for: std::time::Duration::ZERO, + capture_blocked: false, + capture_gate, + route_lost_until: None, last_frame: None, missing_since: None, missing_total: Duration::ZERO, @@ -795,6 +1042,84 @@ impl RecordingSourceHealth { ))) } + fn invalidate_system_audio_capture(state: &mut RecordingSourceHealthState) { + state.capture_gate.open.store(false, Ordering::Release); + state.capture_blocked = true; + state.capture_gate.epoch.fetch_add(1, Ordering::Release); + } + + pub(crate) fn capture_epoch_current(&self, epoch: u64) -> bool { + self.0 + .lock() + .unwrap() + .capture_gate + .epoch + .load(Ordering::Acquire) + == epoch + } + + fn apply_system_audio_route( + &self, + stream_id: u32, + plan: crate::sources::screen_capture::SystemAudioRoutePlan, + ) { + use crate::sources::screen_capture::SystemAudioRoutePlan; + match plan { + SystemAudioRoutePlan::Keep => self.restore_system_audio_capture(stream_id), + SystemAudioRoutePlan::Reattach => self.block_system_audio_capture(stream_id), + SystemAudioRoutePlan::Lost => { + self.note_system_audio_route_loss(stream_id, SYSTEM_AUDIO_ROUTE_GRACE) + } + SystemAudioRoutePlan::Ignore => {} + } + } + + fn block_system_audio_capture(&self, stream_id: u32) { + let mut state = self.0.lock().unwrap(); + if state.terminal.is_some() || state.current.id != stream_id { + return; + } + Self::invalidate_system_audio_capture(&mut state); + } + + fn note_system_audio_route_loss(&self, stream_id: u32, grace: Duration) { + let mut state = self.0.lock().unwrap(); + if state.terminal.is_some() || state.current.id != stream_id { + return; + } + Self::invalidate_system_audio_capture(&mut state); + if state.route_lost_until.is_none() { + state.route_lost_until = Some(( + std::time::Instant::now() + grace, + "System audio capture left the output monitor".into(), + )); + } + } + + fn restore_system_audio_capture(&self, stream_id: u32) { + let mut state = self.0.lock().unwrap(); + if state.terminal.is_some() || state.current.id != stream_id { + return; + } + let was_blocked = state.capture_blocked; + state.capture_blocked = false; + if was_blocked { + state.route_lost_until = None; + let elapsed = Instant::now() + .saturating_duration_since(state.capture_gate.resume.base) + .as_nanos(); + state.capture_gate.resume.not_before_nanos.store( + u64::try_from(elapsed).unwrap_or(u64::MAX), + Ordering::Release, + ); + } + state.capture_gate.open.store(true, Ordering::Release); + } + + pub(crate) fn defer_loss(&self, defer_for: std::time::Duration) { + self.0.lock().unwrap().defer_for = defer_for; + } + #[cfg(test)] pub(crate) fn test_healthy(id: u32) -> Self { Self::new(1, Arc::new(StreamHealth::new(id))) @@ -875,9 +1200,10 @@ impl RecordingSourceHealth { return; }; if pending.failed.load(Ordering::Acquire) { - state.terminal = Some("Replacement audio stream failed before acceptance".into()); + state.remember_loss("Replacement audio stream failed before acceptance".into()); return; } + state.deferred = None; if state.current.failed.load(Ordering::Acquire) || state.recovery_origin.is_some() { state.recovery_origin = Some(state.current.id); } @@ -901,7 +1227,7 @@ impl RecordingSourceHealth { .as_ref() .is_some_and(|pending| pending.id == id) { - state.terminal.get_or_insert(error); + state.remember_loss(error); } } @@ -934,12 +1260,29 @@ impl RecordingSourceHealth { } pub(crate) fn terminal_error(&self) -> Option { - self.0.lock().unwrap().terminal.clone() + let mut state = self.0.lock().unwrap(); + state.promote_deferred_loss(); + state.terminal.clone() + } + + pub(crate) fn reconnectable_frame(&self, id: u32) -> bool { + let state = self.0.lock().unwrap(); + state.terminal.is_none() + && state.current.id == id + && !state.capture_blocked + && !state.current.failed.load(Ordering::Acquire) + } + + #[cfg(test)] + pub(crate) fn test_recover_backend(&self) { + let mut state = self.0.lock().unwrap(); + state.current.failed.store(false, Ordering::Release); + state.deferred = None; } pub(crate) fn frame_is_current(&self, id: u32) -> bool { let mut state = self.0.lock().unwrap(); - if state.current.id != id || state.terminal.is_some() { + if state.current.id != id || state.terminal.is_some() || state.capture_blocked { return false; } if state.current.failed.load(Ordering::Acquire) { @@ -974,7 +1317,8 @@ impl RecordingSourceHealth { } pub(crate) fn stop_error(&self) -> Option { - let state = self.0.lock().unwrap(); + let mut state = self.0.lock().unwrap(); + state.promote_deferred_loss(); if state.terminal.is_none() && let Some(since) = state.missing_since { @@ -1217,6 +1561,19 @@ pub struct MicrophoneFeed { system_failed_input: Option, #[cfg(target_os = "linux")] system_reconnect: Option, + #[cfg(target_os = "linux")] + system_capture_route: + Arc>>, + #[cfg(target_os = "linux")] + system_capture_gate: Arc>>, + #[cfg(target_os = "linux")] + system_audio_staging: Option< + Arc< + std::sync::Mutex>, + >, + >, + #[cfg(target_os = "linux")] + route_watch: Arc, input_id_counter: u32, lock_generation: u64, state: State, @@ -1238,7 +1595,10 @@ struct SystemReconnect { impl Drop for MicrophoneFeed { fn drop(&mut self) { #[cfg(target_os = "linux")] - self.system_stream_cancel.cancel(); + { + self.system_stream_cancel.cancel(); + self.route_watch.stop(); + } } } @@ -1562,6 +1922,16 @@ impl MicrophoneFeed { system_failed_input: None, #[cfg(target_os = "linux")] system_reconnect: None, + #[cfg(target_os = "linux")] + system_capture_route: Arc::new(std::sync::Mutex::new(None)), + #[cfg(target_os = "linux")] + system_capture_gate: Arc::new(std::sync::Mutex::new(Arc::new( + SystemCaptureGate::open(), + ))), + #[cfg(target_os = "linux")] + system_audio_staging: None, + #[cfg(target_os = "linux")] + route_watch: Arc::new(SystemAudioRouteWatch::new()), #[cfg(any(target_os = "linux", windows))] stream_health: std::collections::HashMap::new(), #[cfg(target_os = "linux")] @@ -1587,9 +1957,27 @@ impl MicrophoneFeed { pub(crate) fn new_system_audio(error_sender: flume::Sender) -> Self { let mut feed = Self::new(error_sender); feed.pulse_input_role = crate::sources::screen_capture::PulseInputRole::SystemAudio; + feed.system_audio_staging = Some(Arc::new(std::sync::Mutex::new( + crate::sources::screen_capture::SystemAudioStaging::new( + crate::sources::screen_capture::SYSTEM_AUDIO_STAGING_HOLD, + ), + ))); feed } + #[cfg(target_os = "linux")] + fn start_system_audio_route_watch(&self, actor: ActorRef) { + let Some(staging) = self.system_audio_staging.clone() else { + return; + }; + self.route_watch.ensure_started( + actor, + staging, + self.system_capture_route.clone(), + self.dropped_message_count.clone(), + ); + } + pub fn default_device() -> Option<(String, Device, SupportedStreamConfig)> { let host = cpal::default_host(); #[cfg(target_os = "linux")] @@ -1727,6 +2115,14 @@ impl MicrophoneFeed { pulse_input_role, #[cfg(target_os = "linux")] system_stream_cancel, + #[cfg(target_os = "linux")] + system_capture_gate, + #[cfg(target_os = "linux")] + system_capture_route, + #[cfg(target_os = "linux")] + system_audio_staging, + #[cfg(target_os = "linux")] + route_watch, id, label, settings, @@ -1864,6 +2260,50 @@ impl MicrophoneFeed { let route_required = input_route.is_some(); #[cfg(target_os = "linux")] let routed_at = Arc::new(std::sync::OnceLock::::new()); + #[cfg(target_os = "linux")] + enum PreparedLinuxInput { + Route(crate::sources::screen_capture::PulseInputRoute), + Direct(crate::sources::screen_capture::PendingSystemAudioOutput), + Open, + } + #[cfg(target_os = "linux")] + let prepared_input = { + use crate::sources::screen_capture::{ + PendingSystemAudioOutput, SystemAudioStartupAttach, + system_audio_startup_attach, + }; + let direct_through_pulse = input_route.is_none() + && pulse_input_role + == crate::sources::screen_capture::PulseInputRole::SystemAudio + && crate::sources::screen_capture::input_runs_through_pulse(&label); + match ( + system_audio_startup_attach( + pulse_input_role, + input_route.is_some(), + direct_through_pulse, + ), + input_route, + ) { + (Some(SystemAudioStartupAttach::WatchDirectOutput), _) => { + match PendingSystemAudioOutput::snapshot() { + Ok(pending) => PreparedLinuxInput::Direct(pending), + Err(error) => { + let _ = ready_tx.send(Err(SetInputError::BuildStream(format!( + "Could not inspect the Linux system-audio input: {error}" + )))); + return; + } + } + } + (_, Some(route)) => PreparedLinuxInput::Route(route), + (_, None) => PreparedLinuxInput::Open, + } + }; + // Only a watched stream holds its samples: nothing would + // release them on an input the route watch never follows. + #[cfg(target_os = "linux")] + let system_audio_staging = system_audio_staging + .filter(|_| !matches!(prepared_input, PreparedLinuxInput::Open)); if setup_cancel.is_cancelled() || ready_tx.is_canceled() { return; @@ -1882,6 +2322,14 @@ impl MicrophoneFeed { let routed_at = routed_at.clone(); #[cfg(target_os = "linux")] let system_stream_cancel = system_stream_cancel.clone(); + #[cfg(target_os = "linux")] + let system_capture_gate = system_capture_gate.clone(); + #[cfg(target_os = "linux")] + let system_audio_staging = system_audio_staging.clone(); + #[cfg(target_os = "linux")] + let mut pending_capture = VecDeque::new(); + #[cfg(target_os = "linux")] + let dropped_message_count = dropped_message_count.clone(); let mut callback_count = 0u64; let mut enqueue_failures = EnqueueFailureLog::default(); #[cfg(target_os = "linux")] @@ -1933,6 +2381,42 @@ impl MicrophoneFeed { return; } #[cfg(target_os = "linux")] + let capture_gate = system_capture_gate.lock().unwrap().clone(); + #[cfg(target_os = "linux")] + if !capture_gate.open.load(Ordering::Acquire) { + pending_samples.clear(); + pending_capture.clear(); + return; + } + #[cfg(target_os = "linux")] + let capture_epoch = capture_gate.epoch.load(Ordering::Acquire); + #[cfg(target_os = "linux")] + if !capture_gate.open.load(Ordering::Acquire) + || capture_gate.epoch.load(Ordering::Acquire) != capture_epoch + { + pending_samples.clear(); + pending_capture.clear(); + return; + } + #[cfg(target_os = "linux")] + if !sample_follows_route_resume( + &capture_gate.resume, + callback_received, + input_timestamp + .callback + .duration_since(&input_timestamp.capture), + ) { + return; + } + #[cfg(target_os = "linux")] + let captured_at = input_timestamp + .callback + .duration_since(&input_timestamp.capture) + .and_then(|delay| callback_received.checked_sub(delay)) + .unwrap_or(callback_received); + #[cfg(not(target_os = "linux"))] + let captured_at = Instant::now(); + #[cfg(target_os = "linux")] let timestamp = match delivery_clock.as_mut() { Some(clock) => clock.timestamp( callback_received, @@ -1958,20 +2442,40 @@ impl MicrophoneFeed { channels: callback_channels, info: info.clone(), timestamp: timestamp - capture_latency, + #[cfg(target_os = "linux")] + capture_epoch, + }; + + let mut forward = |captured_at: Instant, samples: MicrophoneSamples| { + #[cfg(target_os = "linux")] + if let Some(staging) = &system_audio_staging { + let _ = staging.lock().unwrap().push(captured_at, samples); + return; + } + #[cfg(not(target_os = "linux"))] + let _ = captured_at; + enqueue_microphone_samples( + &actor_ref, + &dropped_message_count, + &mut enqueue_failures, + samples, + ); }; if !effective_sample_rate.settled { pending_samples.push_back(samples); + #[cfg(target_os = "linux")] + pending_capture.push_back(captured_at); if pending_samples.len() >= SAMPLE_RATE_ESTIMATE_MAX_PENDING { let sample_rate = sample_rate_estimator.force_current(); prepare_pending_samples(&mut pending_samples, sample_rate); while let Some(pending) = pending_samples.pop_front() { - enqueue_microphone_samples( - &actor_ref, - &dropped_message_count, - &mut enqueue_failures, - pending, - ); + #[cfg(target_os = "linux")] + let pending_at = + pending_capture.pop_front().unwrap_or(captured_at); + #[cfg(not(target_os = "linux"))] + let pending_at = captured_at; + forward(pending_at, pending); } } return; @@ -1982,20 +2486,14 @@ impl MicrophoneFeed { effective_sample_rate.sample_rate, ); while let Some(pending) = pending_samples.pop_front() { - enqueue_microphone_samples( - &actor_ref, - &dropped_message_count, - &mut enqueue_failures, - pending, - ); + #[cfg(target_os = "linux")] + let pending_at = pending_capture.pop_front().unwrap_or(captured_at); + #[cfg(not(target_os = "linux"))] + let pending_at = captured_at; + forward(pending_at, pending); } - enqueue_microphone_samples( - &actor_ref, - &dropped_message_count, - &mut enqueue_failures, - samples, - ); + forward(captured_at, samples); } }, microphone_stream_error_handler(error_sender, { @@ -2034,13 +2532,67 @@ impl MicrophoneFeed { } #[cfg(target_os = "linux")] - if let Some(route) = input_route - && let Err(error) = route.apply(&input_callback_observed, &system_stream_cancel) { - let _ = ready_tx.send(Err(SetInputError::BuildStream(format!( - "Could not confirm the Linux audio input route: {error}" - )))); - return; + use crate::sources::screen_capture::SystemAudioStartupAttach; + let source_output = match prepared_input { + PreparedLinuxInput::Route(route) => { + match route.apply(&input_callback_observed, &system_stream_cancel) { + Ok(source_output) + if crate::sources::screen_capture::system_audio_startup_attach( + pulse_input_role, + true, + false, + ) == Some(SystemAudioStartupAttach::FollowPreparedRoute) => + { + Some(source_output) + } + Ok(_) => None, + Err(error) => { + let _ = + ready_tx.send(Err(SetInputError::BuildStream(format!( + "Could not confirm the Linux audio input route: {error}" + )))); + return; + } + } + } + PreparedLinuxInput::Direct(pending) => { + match pending + .started_output(&input_callback_observed, &system_stream_cancel) + { + Ok(source_output) => Some(source_output), + Err(error) => { + let _ = + ready_tx.send(Err(SetInputError::BuildStream(format!( + "Could not confirm the Linux system-audio input: {error}" + )))); + return; + } + } + } + PreparedLinuxInput::Open => None, + }; + if let Some(source_output) = source_output { + *system_capture_route.lock().unwrap() = + Some(crate::sources::screen_capture::SystemAudioCaptureRoute { + stream_id: id, + source_output, + }); + if let Some(staging) = system_audio_staging.clone() { + staging.lock().unwrap().note_attached(Instant::now()); + // The startup observer waits for a released sample. + // Lock is what used to start these checks, and it + // runs only after that wait, so the watcher has to + // be running before the stream reports ready. A + // named monitor never builds a PulseInputRoute. + route_watch.ensure_started( + actor_ref.clone(), + staging, + system_capture_route.clone(), + dropped_message_count.clone(), + ); + } + } } #[cfg(target_os = "linux")] @@ -2283,12 +2835,47 @@ fn latency_ms_to_frames(sample_rate: u32, milliseconds: u32) -> u32 { frames.max(1) as u32 } +#[cfg(target_os = "linux")] +struct SystemAudioHold { + staging: Arc< + std::sync::Mutex>, + >, + route: Arc>>, +} + +#[cfg(target_os = "linux")] +impl SystemAudioHold { + fn flush_confirmed(&self) -> Vec { + use crate::sources::screen_capture::{ + SystemAudioRouteCheck, system_audio_output_is_monitor, + }; + let check_started = Instant::now(); + let source_output = self + .route + .lock() + .unwrap() + .as_ref() + .map(|route| route.source_output); + let on_monitor = source_output.is_some_and(system_audio_output_is_monitor); + let check = if on_monitor { + SystemAudioRouteCheck::OnMonitor { check_started } + } else { + SystemAudioRouteCheck::NotOnMonitor { + observed_at: Instant::now(), + } + }; + self.staging.lock().unwrap().observe(check) + } +} + #[derive(Reply)] pub struct MicrophoneFeedLock { #[cfg(windows)] generation: u64, #[cfg(target_os = "linux")] source_health: RecordingSourceHealth, + #[cfg(target_os = "linux")] + system_audio_hold: Option>, actor: ActorRef, config: SupportedStreamConfig, audio_info: AudioInfo, @@ -2364,6 +2951,24 @@ impl MicrophoneFeedLock { self.source_health.clone() } + #[cfg(target_os = "linux")] + pub(crate) fn has_system_audio_hold(&self) -> bool { + self.system_audio_hold.is_some() + } + + #[cfg(target_os = "linux")] + pub(crate) async fn flush_confirmed_system_audio(&self) { + let Some(hold) = self.system_audio_hold.clone() else { + return; + }; + let released = tokio::task::spawn_blocking(move || hold.flush_confirmed()) + .await + .unwrap_or_default(); + for sample in released { + let _ = self.actor.tell(sample).await; + } + } + pub fn config(&self) -> &SupportedStreamConfig { &self.config } @@ -2526,6 +3131,19 @@ struct StreamSpawnParams { pulse_input_role: crate::sources::screen_capture::PulseInputRole, #[cfg(target_os = "linux")] system_stream_cancel: tokio_util::sync::CancellationToken, + #[cfg(target_os = "linux")] + system_capture_gate: Arc>>, + #[cfg(target_os = "linux")] + system_capture_route: + Arc>>, + #[cfg(target_os = "linux")] + system_audio_staging: Option< + Arc< + std::sync::Mutex>, + >, + >, + #[cfg(target_os = "linux")] + route_watch: Arc, id: u32, label: String, settings: Option, @@ -2617,6 +3235,14 @@ impl MicrophoneFeed { pulse_input_role: self.pulse_input_role, #[cfg(target_os = "linux")] system_stream_cancel: self.system_stream_cancel.clone(), + #[cfg(target_os = "linux")] + system_capture_gate: self.system_capture_gate.clone(), + #[cfg(target_os = "linux")] + system_capture_route: self.system_capture_route.clone(), + #[cfg(target_os = "linux")] + system_audio_staging: self.system_audio_staging.clone(), + #[cfg(target_os = "linux")] + route_watch: self.route_watch.clone(), id, label: label.clone(), settings: msg.settings, @@ -2751,6 +3377,14 @@ impl MicrophoneFeed { pulse_input_role: self.pulse_input_role, #[cfg(target_os = "linux")] system_stream_cancel: self.system_stream_cancel.clone(), + #[cfg(target_os = "linux")] + system_capture_gate: self.system_capture_gate.clone(), + #[cfg(target_os = "linux")] + system_capture_route: self.system_capture_route.clone(), + #[cfg(target_os = "linux")] + system_audio_staging: self.system_audio_staging.clone(), + #[cfg(target_os = "linux")] + route_watch: self.route_watch.clone(), id: new_id, label: label.clone(), settings: msg.settings, @@ -2893,6 +3527,14 @@ impl Message for MicrophoneFeed { self.selection_generation = self.selection_generation.wrapping_add(1); self.recording_reconnect = None; } + #[cfg(target_os = "linux")] + if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio { + self.route_watch.stop(); + self.system_stream_cancel.cancel(); + if let Some(staging) = &self.system_audio_staging { + staging.lock().unwrap().clear(); + } + } state.connecting = None; if let Some(AttachedState { done_tx, .. }) = state.attached.take() { @@ -3246,17 +3888,30 @@ impl Message for MicrophoneFeed { } let generation = self.lock_generation; #[cfg(target_os = "linux")] - let source_health = RecordingSourceHealth::new( - generation, - self.stream_health - .get(&attached.id) - .cloned() - .unwrap_or_else(|| Arc::new(StreamHealth::new(attached.id))), - ); - #[cfg(target_os = "linux")] - { + let (source_health, system_audio_hold) = { + let capture_gate = Arc::new(SystemCaptureGate::open()); + *self.system_capture_gate.lock().unwrap() = capture_gate.clone(); + let source_health = RecordingSourceHealth::with_capture_gate( + generation, + self.stream_health + .get(&attached.id) + .cloned() + .unwrap_or_else(|| Arc::new(StreamHealth::new(attached.id))), + capture_gate, + ); self.recording_health = Some(source_health.clone()); - } + self.route_watch.set_health(Some(source_health.clone())); + let system_audio_hold = self.system_audio_staging.clone().map(|staging| { + Arc::new(SystemAudioHold { + staging, + route: self.system_capture_route.clone(), + }) + }); + if system_audio_hold.is_some() { + self.start_system_audio_route_watch(ctx.actor_ref()); + } + (source_health, system_audio_hold) + }; let token = Arc::new(()); let token_weak = Arc::downgrade(&token); @@ -3286,6 +3941,8 @@ impl Message for MicrophoneFeed { generation, #[cfg(target_os = "linux")] source_health, + #[cfg(target_os = "linux")] + system_audio_hold, audio_info, actor: ctx.actor_ref(), config, @@ -3630,7 +4287,12 @@ impl Message for MicrophoneFeed { #[cfg(target_os = "linux")] if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio { self.system_stream_cancel.cancel(); + self.route_watch.stop(); self.system_reconnect = None; + *self.system_capture_gate.lock().unwrap() = Arc::new(SystemCaptureGate::open()); + if let Some(staging) = &self.system_audio_staging { + staging.lock().unwrap().clear(); + } } replace_with_or_abort(&mut self.state, |state| { if let State::Locked { inner, .. } = state { @@ -3756,6 +4418,8 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] + capture_epoch: 0, }) .await; } @@ -3780,6 +4444,8 @@ pub mod synthetic { channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] + capture_epoch: 0, }) .await; } @@ -3798,6 +4464,8 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] + capture_epoch: 0, }) .try_send(), ) @@ -3884,6 +4552,8 @@ mod tests { channels: 1, info: synthetic::zero_callback_info(), timestamp: Timestamp::Instant(Instant::now()), + #[cfg(target_os = "linux")] + capture_epoch: 0, }, ); } @@ -4453,6 +5123,36 @@ mod tests { assert!(feed.take_system_error_reconnect(7).is_none()); } + #[cfg(target_os = "linux")] + #[tokio::test] + async fn lost_system_audio_device_records_silence_and_is_reported_at_stop() { + let (mut feed, _token, _config) = system_recovery_fixture(); + let health = RecordingSourceHealth::new(11, Arc::new(StreamHealth::new(7))); + feed.recording_health = Some(health.clone()); + let actor = MicrophoneFeed::spawn(feed); + let ready = actor + .ask(ReconnectSystemInput { + id: 7, + generation: 11, + }) + .await + .unwrap(); + let error = ready.await.expect_err("missing monitor must not reopen"); + tokio::time::timeout(Duration::from_secs(2), async { + while health.stop_error().is_none() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("reconnect error {error} was not reported at Stop")); + assert!( + health.terminal_error().is_none(), + "a device that is gone records silence instead of failing the take" + ); + actor.kill(); + actor.wait_for_stop().await; + } + #[cfg(target_os = "linux")] #[tokio::test] async fn watchdog_joins_pending_system_reconnect_without_reopening_device() { @@ -5329,6 +6029,65 @@ mod required_recording_health_tests { ); } + #[test] + fn system_audio_reconnect_failure_stays_quiet_until_the_grace_ends() { + let health = RecordingSourceHealth::new(1, Arc::new(StreamHealth::new(7))); + health.defer_loss(Duration::from_millis(40)); + health.begin_reconnect(1, Arc::new(StreamHealth::new(8))); + health.fail_reconnect(1, 8, "DeviceNotFound".into()); + assert!(health.terminal_error().is_none()); + std::thread::sleep(Duration::from_millis(50)); + assert!(health.terminal_error().unwrap().contains("DeviceNotFound")); + } + + #[test] + fn system_audio_moved_onto_a_microphone_is_dropped_until_the_grace_ends() { + let health = RecordingSourceHealth::new(1, Arc::new(StreamHealth::new(7))); + health.note_system_audio_route_loss(7, Duration::from_millis(40)); + assert!(!health.reconnectable_frame(7)); + assert!(!health.frame_is_current(7)); + assert!(!health.capture_epoch_current(0)); + assert!(health.terminal_error().is_none()); + health.note_system_audio_route_loss(9, Duration::from_millis(40)); + std::thread::sleep(Duration::from_millis(50)); + assert!( + health + .terminal_error() + .unwrap() + .contains("left the output monitor") + ); + health.restore_system_audio_capture(7); + assert!(health.terminal_error().is_some()); + assert!(!health.reconnectable_frame(7)); + } + + #[test] + fn system_audio_reattach_clears_the_route_loss_before_the_grace_ends() { + let health = RecordingSourceHealth::new(1, Arc::new(StreamHealth::new(7))); + health.block_system_audio_capture(7); + health.note_system_audio_route_loss(7, Duration::from_millis(40)); + assert!(!health.reconnectable_frame(7)); + health.restore_system_audio_capture(7); + std::thread::sleep(Duration::from_millis(50)); + assert!(health.terminal_error().is_none()); + assert!(health.reconnectable_frame(7)); + health.block_system_audio_capture(8); + assert!(health.reconnectable_frame(7)); + } + + #[test] + fn system_audio_reconnect_during_the_grace_clears_the_loss() { + let health = RecordingSourceHealth::new(1, Arc::new(StreamHealth::new(7))); + health.defer_loss(Duration::from_millis(40)); + let replacement = Arc::new(StreamHealth::new(8)); + health.begin_reconnect(1, replacement.clone()); + health.fail_reconnect(1, 8, "DeviceNotFound".into()); + health.commit_reconnect(1, 8); + std::thread::sleep(Duration::from_millis(50)); + assert!(health.terminal_error().is_none()); + assert!(health.reconnectable_frame(8)); + } + #[test] fn discovery_failure_is_sticky_without_a_silence_threshold() { let health = RecordingSourceHealth::test_healthy(7); diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs index 9e850ff41f8..82dc2feb5b1 100644 --- a/crates/recording/src/output_pipeline/core.rs +++ b/crates/recording/src/output_pipeline/core.rs @@ -4338,6 +4338,12 @@ impl PreparedAudioSources { self.erased_audio_sources.clear(); } + if was_cancelled && !mixed_audio { + for source in &mut self.erased_audio_sources { + (source.finish_capture_fn)(source.inner.as_mut()).await; + } + } + if was_cancelled && !audio_degraded { let drain_start = std::time::Instant::now(); let drain_deadline = tokio::time::Instant::now() + MIXER_STOP_TIMEOUT; @@ -5488,6 +5494,7 @@ struct ErasedAudioSource { inner: Box, audio_info: AudioInfo, start_fn: fn(&mut dyn Any) -> BoxFuture<'_, anyhow::Result<()>>, + finish_capture_fn: fn(&mut dyn Any) -> BoxFuture<'_, ()>, stop_fn: fn(&mut dyn Any) -> BoxFuture<'_, anyhow::Result<()>>, } @@ -5502,6 +5509,12 @@ impl ErasedAudioSource { .start() .boxed() }, + finish_capture_fn: |raw| { + raw.downcast_mut::() + .expect("Wrong type") + .finish_capture() + .boxed() + }, stop_fn: |raw| { raw.downcast_mut::() .expect("Wrong type") @@ -5540,6 +5553,13 @@ pub trait AudioSource: Send + 'static { async { Ok(()) } } + /// Hands over everything the source still holds before a single-source + /// track takes its final drain at Stop. Sources that send every frame as + /// it is captured have nothing to do. + fn finish_capture(&mut self) -> impl Future + Send { + async {} + } + fn stop(&mut self) -> impl Future> + Send { async { Ok(()) } } @@ -10100,6 +10120,64 @@ mod tests { assert!(frames.iter().map(|frame| frame.samples).sum::() >= 4_800); } + struct HeldFrameSource { + output: mpsc::Sender, + held: Option, + } + + impl AudioSource for HeldFrameSource { + type Config = AudioFrame; + + fn setup( + held: Self::Config, + output: mpsc::Sender, + _: &mut SetupCtx, + ) -> impl Future> + Send + 'static { + std::future::ready(Ok(Self { + output, + held: Some(held), + })) + } + + fn audio_info(&self) -> AudioInfo { + AudioMixer::INFO + } + + async fn finish_capture(&mut self) { + if let Some(frame) = self.held.take() { + self.output.send(frame).await.unwrap(); + } + } + } + + #[tokio::test] + async fn single_source_stop_keeps_audio_the_source_still_held() { + let temp = tempfile::tempdir().unwrap(); + let timestamps = Timestamps::now(); + let sent = Arc::new(std::sync::Mutex::new(Vec::new())); + let pipeline = OutputPipeline::builder(temp.path().join("held-stop.ogg")) + .with_timestamps(timestamps) + .with_audio_source::(AudioFrame::new( + AudioMixer::INFO.empty_frame(4_800), + Timestamp::Instant(timestamps.instant()), + )) + .build::(sent.clone()) + .await + .unwrap(); + tokio::time::sleep_until((timestamps.instant() + Duration::from_millis(150)).into()) + .await; + tokio::time::timeout(Duration::from_secs(3), pipeline.stop()) + .await + .unwrap() + .unwrap(); + let frames = sent.lock().unwrap(); + assert!( + frames.iter().map(|frame| frame.samples).sum::() >= 4_800, + "audio handed over at Stop was not muxed: {:?}", + frames.iter().map(|frame| frame.samples).collect::>() + ); + } + struct AudioTimelineHarness { info: AudioInfo, timestamps: Timestamps, diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index 8b38dd55365..3a5a1b022e4 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -25,6 +25,25 @@ const SILENCE_TIMEOUT_WIRELESS: Duration = Duration::from_millis(200); const SILENCE_CHUNK_DURATION: Duration = Duration::from_millis(20); const MIC_RECONNECT_AFTER: Duration = Duration::from_secs(2); const MIC_RECONNECT_BACKOFF_MAX: Duration = Duration::from_secs(30); +// The first stall reconnect runs at 2s. This has to outlast that attempt so a +// monitor that returns is accepted instead of ending an Audio Only take. +#[cfg(target_os = "linux")] +const SYSTEM_AUDIO_RECONNECT_GRACE: Duration = Duration::from_secs(3); +#[cfg(target_os = "linux")] +const SYSTEM_AUDIO_STOP_FLUSH: Duration = Duration::from_secs(2); +#[cfg(target_os = "linux")] +const SYSTEM_AUDIO_STOP_DRAIN: Duration = Duration::from_millis(50); + +fn stop_drain_deadline(until: Option) -> tokio::time::Instant { + until.unwrap_or_else(tokio::time::Instant::now) +} + +#[cfg(target_os = "linux")] +#[derive(Clone, Copy)] +pub(crate) enum LinuxSourceLoss { + FailRecording, + EndThisTrack, +} // A stalled callback usually means CoreAudio/cpal is delivering buffers late, not that // audio was lost: the real samples arrive with their original capture timestamps once the @@ -193,6 +212,8 @@ pub struct Microphone { capture_scope: crate::output_pipeline::PipelineBuildScope, #[cfg(target_os = "linux")] required_health: Option, + #[cfg(target_os = "linux")] + capture_task: Option>, info: AudioInfo, // Holds the current feed lock for the source's lifetime; Windows also // reads it to retire the current subscription. @@ -238,6 +259,21 @@ impl Drop for Microphone { } } +#[cfg(target_os = "linux")] +async fn await_capture_stop(task: Option>) { + let Some(mut task) = task else { + return; + }; + match tokio::time::timeout(SYSTEM_AUDIO_STOP_FLUSH, &mut task).await { + Ok(Ok(())) => {} + Ok(Err(_)) => warn!("System audio capture task stopped with a panic"), + Err(_) => { + task.abort(); + warn!("Timed out waiting for system audio to flush on stop"); + } + } +} + pub struct MicrophoneSwitchRequest { lock: Arc, reply: tokio::sync::oneshot::Sender>, @@ -396,21 +432,65 @@ impl MicResampler { struct RequiredMicrophoneHealth { source: microphone::RecordingSourceHealth, scope: crate::output_pipeline::PipelineBuildScope, + loss: LinuxSourceLoss, + stop_token: CancellationToken, + stop_signal: crate::output_pipeline::PipelineStopSignal, } #[cfg(target_os = "linux")] impl RequiredMicrophoneHealth { + fn for_scope( + source: microphone::RecordingSourceHealth, + scope: crate::output_pipeline::PipelineBuildScope, + ) -> Self { + Self { + source, + scope, + loss: LinuxSourceLoss::FailRecording, + stop_token: CancellationToken::new(), + stop_signal: crate::output_pipeline::PipelineStopSignal::default(), + } + } + + fn ending_track( + source: microphone::RecordingSourceHealth, + scope: crate::output_pipeline::PipelineBuildScope, + stop_token: CancellationToken, + stop_signal: crate::output_pipeline::PipelineStopSignal, + ) -> Self { + source.defer_loss(SYSTEM_AUDIO_RECONNECT_GRACE); + Self { + source, + scope, + loss: LinuxSourceLoss::EndThisTrack, + stop_token, + stop_signal, + } + } + fn check_terminal(&self) -> bool { - if let Some(error) = self.source.terminal_error() { - self.scope.fail_required(error); - true - } else { - false + let Some(error) = self.source.terminal_error() else { + return false; + }; + match self.loss { + LinuxSourceLoss::FailRecording => self.scope.fail_required(error), + LinuxSourceLoss::EndThisTrack => { + self.stop_signal.mark_user_stopped(); + self.stop_token.cancel(); + } } + true + } + + fn capture_epoch_current(&self, epoch: u64) -> bool { + self.source.capture_epoch_current(epoch) } fn accepts_frame(&self, id: u32) -> bool { - let current = self.source.frame_is_current(id); + let current = match self.loss { + LinuxSourceLoss::FailRecording => self.source.frame_is_current(id), + LinuxSourceLoss::EndThisTrack => self.source.reconnectable_frame(id), + }; if !current { self.check_terminal(); } @@ -426,6 +506,9 @@ impl RequiredMicrophoneHealth { if let Some(report) = self.source.missing_report() { warn!("{report}"); } + if matches!(self.loss, LinuxSourceLoss::EndThisTrack) { + return; + } if let Some(error) = self.source.stop_error() { self.scope.fail_required(error); } @@ -439,6 +522,7 @@ impl Microphone { ctx: &mut crate::SetupCtx, target_channels: usize, switch_requests: Option>, + #[cfg(target_os = "linux")] loss: LinuxSourceLoss, ) -> impl Future> + 'static { let health_tx = ctx.health_tx().clone(); let digital_silence_ms = ctx.digital_silence_ms(); @@ -474,9 +558,16 @@ impl Microphone { #[cfg(target_os = "linux")] let required_health = crate::output_pipeline::PipelineBuildScope::current() .filter(crate::output_pipeline::PipelineBuildScope::requires_source_health) - .map(|scope| RequiredMicrophoneHealth { - source: feed_lock.source_health(), - scope, + .map(|scope| match loss { + LinuxSourceLoss::FailRecording => { + RequiredMicrophoneHealth::for_scope(feed_lock.source_health(), scope) + } + LinuxSourceLoss::EndThisTrack => RequiredMicrophoneHealth::ending_track( + feed_lock.source_health(), + scope, + ctx.stop_token(), + ctx.stop_signal(), + ), }); #[cfg(windows)] let setup_scope = capture_scope.clone(); @@ -554,7 +645,7 @@ impl Microphone { let recording_muted = feed_lock.recording_muted_handle(); - crate::output_pipeline::spawn_capture_task({ + let capture_task = crate::output_pipeline::spawn_capture_task({ let frame_counter = mic_frame_counter.clone(); let drop_counter = mic_drop_counter.clone(); let silence_counter = mic_silence_counter.clone(); @@ -591,6 +682,16 @@ impl Microphone { // switched-to one delivers its first frame. let mut switched_from: Option = None; let mut logged_current_source: Option<(u32, u16, SampleFormat)> = None; + // Set once Stop has flushed held system audio: the loop + // drains what that flush sent until this deadline. A + // fixed deadline, because live frames keep the receive + // branch ready and would starve a fresh per-loop timer. + #[cfg(target_os = "linux")] + let mut system_stop_drain_until: Option< + tokio::time::Instant, + > = None; + #[cfg(not(target_os = "linux"))] + let system_stop_drain_until: Option = None; loop { #[cfg(windows)] @@ -605,9 +706,24 @@ impl Microphone { { break; } + if system_stop_drain_until + .is_some_and(|until| tokio::time::Instant::now() >= until) + { + break; + } let recv_result = tokio::select! { biased; - _ = cancel.cancelled() => break, + _ = cancel.cancelled(), if system_stop_drain_until.is_none() => { + #[cfg(target_os = "linux")] + if feed_lock.has_system_audio_hold() { + feed_lock.flush_confirmed_system_audio().await; + system_stop_drain_until = Some( + tokio::time::Instant::now() + SYSTEM_AUDIO_STOP_DRAIN, + ); + continue; + } + break; + } request = next_switch_request(&mut switch_requests) => { let Some(MicrophoneSwitchRequest { lock: next, reply }) = request else { continue; @@ -699,6 +815,8 @@ impl Microphone { continue; } r = tokio::time::timeout(silence_timeout, rx.recv_async()) => r, + _ = tokio::time::sleep_until(stop_drain_deadline(system_stop_drain_until)), + if system_stop_drain_until.is_some() => break, }; match recv_result { Ok(Ok(frame)) => { @@ -707,10 +825,10 @@ impl Microphone { continue; } #[cfg(target_os = "linux")] - if required_health - .as_ref() - .is_some_and(|health| !health.accepts_frame(frame.stream_id)) - { + if required_health.as_ref().is_some_and(|health| { + !health.accepts_frame(frame.stream_id) + || !health.capture_epoch_current(frame.capture_epoch) + }) { continue; } if silence_mode { @@ -1150,6 +1268,8 @@ impl Microphone { #[cfg(windows)] drop(setup_cancel.disarm()); + #[cfg(not(target_os = "linux"))] + drop(capture_task); Ok(Self { #[cfg(windows)] capture_scope, @@ -1157,6 +1277,8 @@ impl Microphone { _binding: binding, #[cfg(target_os = "linux")] required_health, + #[cfg(target_os = "linux")] + capture_task: Some(capture_task), cancel, }) }; @@ -1185,6 +1307,8 @@ impl AudioSource for Microphone { ctx, usize::from(MICROPHONE_TARGET_CHANNELS), None, + #[cfg(target_os = "linux")] + LinuxSourceLoss::FailRecording, ) } @@ -1192,6 +1316,19 @@ impl AudioSource for Microphone { self.info } + async fn finish_capture(&mut self) { + // Linux system audio holds samples until their route is proven: end + // capture here so that flush reaches the track before its last drain. + #[cfg(target_os = "linux")] + { + let holds_system_audio = self._binding.lock().unwrap().lock.has_system_audio_hold(); + if holds_system_audio { + self.cancel.cancel(); + await_capture_stop(self.capture_task.take()).await; + } + } + } + fn stop(&mut self) -> impl Future> + Send { #[cfg(target_os = "linux")] if let Some(health) = &self.required_health { @@ -1206,11 +1343,15 @@ impl AudioSource for Microphone { self.cancel.cancel(); #[cfg(windows)] let scope = self.capture_scope.clone(); + #[cfg(target_os = "linux")] + let capture_task = self.capture_task.take(); async move { #[cfg(windows)] { finish_recording_subscription(&scope, &feed, subscription).await } + #[cfg(target_os = "linux")] + await_capture_stop(capture_task).await; #[cfg(not(windows))] { Ok(()) @@ -1242,6 +1383,8 @@ impl AudioSource for SwitchableMicrophone { ctx, usize::from(MICROPHONE_TARGET_CHANNELS), Some(config.switch_requests), + #[cfg(target_os = "linux")] + LinuxSourceLoss::FailRecording, ); async move { setup.await.map(Self) } } @@ -1325,6 +1468,25 @@ mod tests { use super::*; use cap_media_info::{Sample, Type}; + #[cfg(target_os = "linux")] + #[tokio::test] + async fn system_audio_stop_delivers_held_audio_before_the_feed_is_killed() { + let killed = Arc::new(AtomicBool::new(false)); + let seen = killed.clone(); + let (tx, rx) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(async move { + tokio::task::yield_now().await; + assert!( + !seen.load(Ordering::SeqCst), + "the feed was killed before held system audio was delivered" + ); + tx.send("held").expect("stop dropped the held audio"); + }); + await_capture_stop(Some(task)).await; + killed.store(true, Ordering::SeqCst); + assert_eq!(rx.await.expect("held audio missing"), "held"); + } + #[tokio::test] async fn ready_success_without_frames_retries_only_after_existing_backoff() { let in_flight = Arc::new(AtomicBool::new(true)); @@ -1778,10 +1940,10 @@ mod required_source_outcome_tests { let scope = PipelineBuildScope::new_studio_lifetime(); let cancel = CancellationToken::new(); scope.register_token(cancel.clone()); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(7), - scope: scope.clone(), - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(7), + scope.clone(), + ); let (sender, receiver) = flume::bounded(128); for _ in 0..128 { sender.try_send(7).unwrap(); @@ -1818,10 +1980,10 @@ mod required_source_outcome_tests { let scope = PipelineBuildScope::new_studio_lifetime(); let cancel = CancellationToken::new(); scope.register_token(cancel.clone()); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(7), - scope: scope.clone(), - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(7), + scope.clone(), + ); for _ in 0..128 { assert!(health.accepts_frame(7)); assert!(!health.accepts_frame(6)); @@ -1841,10 +2003,10 @@ mod required_source_outcome_tests { let cancel = CancellationToken::new(); child.register_token(cancel.clone()); assert!(child.commit()); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(8), - scope: child, - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(8), + child, + ); health.source.test_backend_failure(); assert!(!health.accepts_frame(8)); assert!(cancel.is_cancelled()); @@ -1865,10 +2027,10 @@ mod required_source_outcome_tests { let cancel = CancellationToken::new(); scope.register_token(cancel.clone()); let completion = scope.task_completion(); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(0), - scope: scope.clone(), - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(0), + scope.clone(), + ); let (release, released) = tokio::sync::oneshot::channel(); let writer = tokio::spawn(async move { let _completion = completion; @@ -1890,10 +2052,10 @@ mod required_source_outcome_tests { #[tokio::test] async fn feed_eof_cannot_be_a_successful_required_source_stop() { let scope = PipelineBuildScope::new_studio_lifetime(); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(7), - scope: scope.clone(), - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(7), + scope.clone(), + ); health.fail("Requested audio feed closed before Stop".into()); health.stop(); let report = scope.cancel_and_join_report().await; @@ -1904,10 +2066,10 @@ mod required_source_outcome_tests { #[tokio::test] async fn healthy_required_source_stop_does_not_invent_failure() { let scope = PipelineBuildScope::new_studio_lifetime(); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(7), - scope: scope.clone(), - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(7), + scope.clone(), + ); assert!(!health.check_terminal()); health.stop(); let report = scope.cancel_and_join_report().await; @@ -1924,10 +2086,10 @@ mod required_source_outcome_tests { let cancel = CancellationToken::new(); child.register_token(cancel.clone()); assert!(child.commit()); - let health = RequiredMicrophoneHealth { - source: microphone::RecordingSourceHealth::test_healthy(8), - scope: child, - }; + let health = RequiredMicrophoneHealth::for_scope( + microphone::RecordingSourceHealth::test_healthy(8), + child, + ); health.fail("current replacement failed".into()); assert!(cancel.is_cancelled()); let report = parent.cancel_and_join_report().await; diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 8f23d830674..335186b0873 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -44,6 +44,9 @@ mod x11_tests; #[cfg(test)] mod system_audio_channel_tests; +#[cfg(test)] +mod audio_only_null_sink_tests; + #[cfg(test)] mod wayland_portal_tests; @@ -1421,6 +1424,14 @@ pub struct SystemAudioSourceConfig { device_name: String, monitor_route: Option, feed: OwnedSystemAudioFeed, + ends_take_when_lost: bool, +} + +impl SystemAudioSourceConfig { + pub(crate) fn end_take_when_lost(mut self) -> Self { + self.ends_take_when_lost = true; + self + } } pub struct SystemAudioSource { @@ -1863,7 +1874,7 @@ impl PulseInputRoute { self, input_callback_observed: &AtomicBool, cancel: &CancellationToken, - ) -> anyhow::Result<()> { + ) -> anyhow::Result { let output = wait_for_started_source_output( &self.previous_outputs, input_callback_observed, @@ -1874,7 +1885,7 @@ impl PulseInputRoute { // Pulse remembers the generic ALSA application's last route, including speaker capture. move_pactl_source_output(output.id, &self.source)?; } - Ok(()) + Ok(output.id) } } @@ -1949,6 +1960,71 @@ fn uses_default_pulse_input(device_name: &str) -> bool { device_name.eq_ignore_ascii_case("default") || device_name.eq_ignore_ascii_case("pulse") } +/// How system audio learns its Pulse source-output before the stream is +/// reported ready. +/// +/// `PulseInputRoute` is only built for the `default` and `pulse` device +/// names. A monitor that cpal already lists by name never takes that path, +/// but its samples are still held until a later source-output check. That +/// check has to be running before startup waits for a released sample. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemAudioStartupAttach { + FollowPreparedRoute, + WatchDirectOutput, +} + +/// `direct_through_pulse`: a named input whose ALSA chain ends in the Pulse +/// plugin. A loopback or "Stereo Mix" opened straight from the card has no +/// Pulse stream to watch, and the server cannot move it onto a microphone, +/// so it records as it always did. +pub(crate) fn system_audio_startup_attach( + role: PulseInputRole, + prepared_route: bool, + direct_through_pulse: bool, +) -> Option { + if role != PulseInputRole::SystemAudio { + return None; + } + if prepared_route { + Some(SystemAudioStartupAttach::FollowPreparedRoute) + } else if direct_through_pulse { + Some(SystemAudioStartupAttach::WatchDirectOutput) + } else { + None + } +} + +pub(crate) fn input_runs_through_pulse(device_name: &str) -> bool { + alsa_input_backend::capture_backend(device_name) + .is_ok_and(|backend| backend == alsa_input_backend::CaptureBackend::Pulse) +} + +pub(crate) struct PendingSystemAudioOutput { + previous: Vec, +} + +impl PendingSystemAudioOutput { + pub(crate) fn snapshot() -> anyhow::Result { + Ok(Self { + previous: current_process_source_outputs()?, + }) + } + + pub(crate) fn started_output( + self, + input_callback_observed: &AtomicBool, + cancel: &CancellationToken, + ) -> anyhow::Result { + wait_for_started_source_output( + &self.previous, + input_callback_observed, + cancel, + current_process_source_outputs, + ) + .map(|output| output.id) + } +} + /// The ALSA input to open for the microphone the user selected, when it is /// not the selection itself. /// @@ -2009,12 +2085,18 @@ impl AudioSource for SystemAudioSource { Self: Sized, { let device_name = config.device_name.clone(); + let loss = if config.ends_take_when_lost { + crate::sources::microphone::LinuxSourceLoss::EndThisTrack + } else { + crate::sources::microphone::LinuxSourceLoss::FailRecording + }; let setup = crate::sources::Microphone::setup_with_channels( config.feed_lock, tx, ctx, X11Capture::audio_info().channels, None, + loss, ); async move { let inner = setup @@ -2037,8 +2119,14 @@ impl AudioSource for SystemAudioSource { self.inner.audio_info() } + async fn finish_capture(&mut self) { + self.inner.finish_capture().await; + } + async fn stop(&mut self) -> anyhow::Result<()> { drop(self.monitor_route.take()); + // Stop waits until held samples have been handed to the muxer. + // Killing the feed first drops that flush on a dead actor. self.inner.stop().await?; self.feed.actor.kill(); self.feed.actor.wait_for_stop().await; @@ -2112,6 +2200,7 @@ pub async fn create_system_audio_source_config() -> anyhow::Result) -> Option<(u Some((u8::from(!is_default_sink), rank)) } +// PipeWire and Pulse rescue a capture when its monitor disappears by moving +// the stream onto the default source. That source is the microphone, and the +// stream keeps delivering samples, so the device-loss path never sees an +// error. Only a `.monitor` name is still system audio. +fn output_monitor_source_name(name: &str) -> bool { + name.strip_suffix(".monitor") + .is_some_and(|sink| !sink.is_empty()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemAudioRoutePlan { + Keep, + Reattach, + Lost, + Ignore, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct SystemAudioCaptureRoute { + pub stream_id: u32, + pub source_output: u32, +} + +fn plan_system_audio_route( + source_output_id: u32, + outputs: &[(u32, u32)], + sources_short: &str, + monitor_name: Option<&str>, +) -> SystemAudioRoutePlan { + let Some((_, source_index)) = outputs + .iter() + .copied() + .find(|(id, _)| *id == source_output_id) + else { + return SystemAudioRoutePlan::Ignore; + }; + let Some(name) = pactl_source_name(sources_short, source_index) else { + return SystemAudioRoutePlan::Ignore; + }; + if output_monitor_source_name(name) { + return SystemAudioRoutePlan::Keep; + } + if monitor_name.is_some_and(output_monitor_source_name) { + SystemAudioRoutePlan::Reattach + } else { + SystemAudioRoutePlan::Lost + } +} + +fn pactl_source_name(sources: &str, index: u32) -> Option<&str> { + sources.lines().find_map(|line| { + let mut fields = line.split_whitespace(); + let found = fields.next()?.parse::().ok()?; + let name = fields.next()?; + (found == index).then_some(name) + }) +} + +fn current_output_monitor_name(sources: &str) -> Option { + pulse_input_route_destination( + sources, + PulseInputRole::SystemAudio, + None, + pactl_default_sink().as_deref(), + ) + .map(|(_, name)| name) + .filter(|name| output_monitor_source_name(name)) +} + +fn inspect_system_audio_source_output( + source_output: u32, +) -> (SystemAudioRoutePlan, Option) { + let Ok(outputs) = current_process_source_outputs() else { + return (SystemAudioRoutePlan::Ignore, None); + }; + let Ok(output) = Command::new("pactl") + .args(["list", "short", "sources"]) + .output() + else { + return (SystemAudioRoutePlan::Ignore, None); + }; + if !output.status.success() { + return (SystemAudioRoutePlan::Ignore, None); + } + let sources = String::from_utf8_lossy(&output.stdout); + let monitor = current_output_monitor_name(&sources); + let pairs = outputs + .iter() + .map(|item| (item.id, item.source)) + .collect::>(); + let plan = plan_system_audio_route(source_output, &pairs, &sources, monitor.as_deref()); + (plan, monitor) +} + +// Samples stay here until a later source read still sees a sink monitor. +// `unsafe_cutoff` is the latest instant that was not a proven monitor, so +// audio captured at or before it is dropped even when the callback arrives +// late. `proven_until` is only the last successful check: a chunk captured +// before that check, but after `unsafe_cutoff`, stays queued for the next +// check instead of being discarded. A non-monitor read drops every sample +// not yet released, including audio captured on the monitor just before the +// move. Releasing that audio would write the microphone into the system track. +pub(crate) const SYSTEM_AUDIO_STAGING_HOLD: Duration = Duration::from_secs(2); +const SYSTEM_AUDIO_STAGING_LIMIT: usize = 256; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemAudioRouteCheck { + OnMonitor { check_started: Instant }, + NotOnMonitor { observed_at: Instant }, +} + +struct StagedSystemAudio { + captured_at: Instant, + value: T, +} + +pub(crate) struct SystemAudioStaging { + pending: std::collections::VecDeque>, + proven_until: Option, + unsafe_cutoff: Option, + max_hold: Duration, +} + +impl SystemAudioStaging { + pub(crate) fn new(max_hold: Duration) -> Self { + Self { + pending: std::collections::VecDeque::new(), + proven_until: None, + unsafe_cutoff: None, + max_hold, + } + } + + pub(crate) fn clear(&mut self) { + self.pending.clear(); + self.proven_until = None; + self.unsafe_cutoff = None; + } + + fn mark_unsafe(&mut self, at: Instant) { + let cutoff = self + .unsafe_cutoff + .map(|existing| existing.max(at)) + .unwrap_or(at); + self.unsafe_cutoff = Some(cutoff); + self.pending.retain(|chunk| chunk.captured_at > cutoff); + self.proven_until = None; + } + + /// `at` is the instant the capture was placed on a monitor. Samples + /// captured at or before that instant are not released by a later check. + pub(crate) fn note_attached(&mut self, at: Instant) { + self.mark_unsafe(at); + self.proven_until = Some(at); + } + + pub(crate) fn push(&mut self, captured_at: Instant, value: T) -> bool { + if self + .unsafe_cutoff + .is_some_and(|cutoff| captured_at <= cutoff) + { + return false; + } + self.pending + .push_back(StagedSystemAudio { captured_at, value }); + self.trim(); + true + } + + fn trim(&mut self) { + while self.pending.len() > SYSTEM_AUDIO_STAGING_LIMIT || self.held_too_long() { + let Some(index) = self.oldest_index() else { + break; + }; + self.pending.remove(index); + } + } + + fn oldest_index(&self) -> Option { + self.pending + .iter() + .enumerate() + .min_by_key(|(_, chunk)| chunk.captured_at) + .map(|(index, _)| index) + } + + fn held_too_long(&self) -> bool { + let Some(oldest) = self.pending.iter().map(|chunk| chunk.captured_at).min() else { + return false; + }; + let Some(newest) = self.pending.iter().map(|chunk| chunk.captured_at).max() else { + return false; + }; + newest.saturating_duration_since(oldest) > self.max_hold + } + + pub(crate) fn observe(&mut self, check: SystemAudioRouteCheck) -> Vec { + match check { + SystemAudioRouteCheck::NotOnMonitor { observed_at } => { + self.mark_unsafe(observed_at); + Vec::new() + } + SystemAudioRouteCheck::OnMonitor { check_started } => { + let Some(proven_until) = self.proven_until else { + self.mark_unsafe(check_started); + self.proven_until = Some(check_started); + return Vec::new(); + }; + if check_started < proven_until { + return Vec::new(); + } + let cutoff = self.unsafe_cutoff; + let mut released = Vec::new(); + let mut kept = std::collections::VecDeque::new(); + while let Some(chunk) = self.pending.pop_front() { + if cutoff.is_some_and(|cutoff| chunk.captured_at <= cutoff) { + continue; + } + if chunk.captured_at <= check_started { + released.push(chunk.value); + } else { + kept.push_back(chunk); + } + } + self.pending = kept; + self.proven_until = Some(check_started); + released + } + } + } + + #[cfg(test)] + fn pending_len(&self) -> usize { + self.pending.len() + } +} + +pub(crate) const SYSTEM_AUDIO_ROUTE_POLL: Duration = Duration::from_millis(20); +// Running `pactl` for every proof cost about a core between Cap and the sound +// server. A quiet `pactl subscribe` is the proof instead: any route change +// arrives there as an event, so audio older than this margin before a quiet +// tick is released, and only events (plus a slow recheck) run `pactl list`. +const SYSTEM_AUDIO_EVENT_MARGIN: Duration = Duration::from_millis(50); +const SYSTEM_AUDIO_ROUTE_RECHECK: Duration = Duration::from_secs(2); +const SYSTEM_AUDIO_SUBSCRIBE_RESTART: Duration = Duration::from_millis(200); +const SYSTEM_AUDIO_SUBSCRIBE_BACKOFF_MAX: Duration = Duration::from_secs(2); + +/// How long to wait after `pactl subscribe` closes, and the next backoff. +/// A closed subscription makes `recv_timeout` return immediately, so the +/// wait is what keeps the inspection from spinning. A live subscription is +/// polled sooner than this floor, so held audio is confirmed before the +/// capture loop treats the gap as a stall. +pub(crate) fn route_watch_after_disconnect(backoff: Duration) -> (Duration, Duration) { + let wait = backoff.max(SYSTEM_AUDIO_SUBSCRIBE_RESTART); + let next = wait + .saturating_mul(2) + .min(SYSTEM_AUDIO_SUBSCRIBE_BACKOFF_MAX); + (wait, next) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemAudioWatch { + Checked { + plan: SystemAudioRoutePlan, + check_started: Instant, + }, + Reattached { + at: Instant, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RouteWatchStep { + Inspect, + QuietProof, + Wait, +} + +pub(crate) fn route_watch_step( + event_pending: bool, + since_inspection: Option, + announced: Option, +) -> RouteWatchStep { + if event_pending || since_inspection.is_none_or(|since| since >= SYSTEM_AUDIO_ROUTE_RECHECK) { + RouteWatchStep::Inspect + } else if announced == Some(SystemAudioRoutePlan::Keep) { + RouteWatchStep::QuietProof + } else { + RouteWatchStep::Wait + } +} + +/// Whether a `pactl subscribe` line can mean the system-audio capture moved: +/// a capture stream, source, sink, card or default changed. Other apps' +/// playback streams and clients change constantly and are ignored. +pub(crate) fn route_event_is_relevant(line: &str) -> bool { + let Some((_, target)) = line.split_once(" on ") else { + return !line.trim().is_empty(); + }; + let kind = target.split(" #").next().unwrap_or(target).trim(); + matches!( + kind, + "source-output" | "source" | "sink" | "card" | "server" + ) +} + +fn wait_for_route_poll(cancel: &CancellationToken, wait: Duration) { + let deadline = Instant::now() + wait; + while !cancel.is_cancelled() { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + std::thread::sleep(remaining.min(Duration::from_millis(50))); + } +} + +fn spawn_route_subscribe() -> (std::sync::mpsc::Receiver<()>, Option) { + let (wake_tx, wake_rx) = std::sync::mpsc::channel(); + let mut child = Command::new("pactl") + .arg("subscribe") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .ok(); + if let Some(stdout) = child.as_mut().and_then(|child| child.stdout.take()) { + let _ = std::thread::Builder::new() + .name("system-audio-subscribe".into()) + .spawn(move || { + use std::io::BufRead; + let mut reader = std::io::BufReader::new(stdout); + let mut line = String::new(); + loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(_) => { + if route_event_is_relevant(&line) && wake_tx.send(()).is_err() { + break; + } + } + } + } + }); + } + (wake_rx, child) +} + +fn stop_route_subscribe(child: &mut Option) { + if let Some(mut child) = child.take() { + let _ = child.kill(); + let _ = child.wait(); + } +} + +pub(crate) fn watch_system_audio_route( + cancel: CancellationToken, + route: Arc>>, + mut on_watch: impl FnMut(u32, SystemAudioWatch), +) { + let (mut wake_rx, mut subscribe) = spawn_route_subscribe(); + let mut announced = None; + let mut backoff = SYSTEM_AUDIO_SUBSCRIBE_RESTART; + let mut event_pending = true; + let mut last_inspection: Option = None; + while !cancel.is_cancelled() { + let current = route.lock().unwrap().as_ref().copied(); + if current.is_some() && !event_pending && wake_rx.try_recv().is_ok() { + event_pending = true; + } + let step = route_watch_step( + event_pending, + last_inspection.map(|at| at.elapsed()), + announced, + ); + if let Some(current) = current + && step == RouteWatchStep::QuietProof + { + if let Some(check_started) = Instant::now().checked_sub(SYSTEM_AUDIO_EVENT_MARGIN) { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Keep, + check_started, + }, + ); + } + } else if let Some(current) = current + && step == RouteWatchStep::Inspect + && !cancel.is_cancelled() + { + event_pending = false; + let check_started = Instant::now(); + last_inspection = Some(check_started); + let (plan, monitor) = inspect_system_audio_source_output(current.source_output); + let resolved = match plan { + SystemAudioRoutePlan::Reattach => { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Reattach, + check_started, + }, + ); + match monitor { + Some(monitor) => { + match move_pactl_source_output(current.source_output, &monitor) { + Ok(()) => { + let at = Instant::now(); + on_watch( + current.stream_id, + SystemAudioWatch::Reattached { at }, + ); + SystemAudioRoutePlan::Keep + } + Err(error) => { + if announced != Some(SystemAudioRoutePlan::Lost) { + tracing::warn!( + %error, + "Could not move system audio back onto an output monitor" + ); + } + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Lost, + check_started, + }, + ); + SystemAudioRoutePlan::Lost + } + } + } + None => { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Lost, + check_started, + }, + ); + SystemAudioRoutePlan::Lost + } + } + } + other => { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: other, + check_started, + }, + ); + other + } + }; + if announced != Some(resolved) { + match resolved { + SystemAudioRoutePlan::Lost => tracing::warn!( + source_output = current.source_output, + "System audio capture is not on an output monitor" + ), + SystemAudioRoutePlan::Keep + if matches!( + announced, + Some(SystemAudioRoutePlan::Lost | SystemAudioRoutePlan::Reattach) + ) => + { + tracing::info!("System audio capture is back on an output monitor"); + } + _ => {} + } + announced = Some(resolved); + } + } + if cancel.is_cancelled() { + break; + } + match wake_rx.recv_timeout(SYSTEM_AUDIO_ROUTE_POLL) { + Ok(()) => { + event_pending = true; + backoff = SYSTEM_AUDIO_SUBSCRIBE_RESTART; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + backoff = SYSTEM_AUDIO_SUBSCRIBE_RESTART; + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + // Without a subscription nothing proves the route between + // checks, so every pass after a restart inspects. + event_pending = true; + let (wait, next) = route_watch_after_disconnect(backoff); + backoff = next; + stop_route_subscribe(&mut subscribe); + wait_for_route_poll(&cancel, wait); + if cancel.is_cancelled() { + break; + } + (wake_rx, subscribe) = spawn_route_subscribe(); + } + } + } + + stop_route_subscribe(&mut subscribe); +} + +pub(crate) fn system_audio_output_is_monitor(source_output: u32) -> bool { + matches!( + inspect_system_audio_source_output(source_output).0, + SystemAudioRoutePlan::Keep + ) +} + fn pactl_default_sink() -> Option { pactl_default_device("get-default-sink") } @@ -3510,11 +4111,14 @@ fn x11_source_pixel( #[cfg(test)] mod system_audio_tests { use super::{ - OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, newly_created_source_output, - pactl_monitor_preference, pactl_source_index, preferred_system_audio_device, - previous_source_destination, process_source_output_ids, pulse_input_route_destination, - retry_system_audio_connection, routes_default_microphone_through_server, - source_output_needs_move, source_output_route_matches, started_input_source_output, + OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, RouteWatchStep, + SystemAudioRouteCheck, SystemAudioRoutePlan, SystemAudioStaging, SystemAudioStartupAttach, + newly_created_source_output, pactl_monitor_preference, pactl_source_index, + plan_system_audio_route, preferred_system_audio_device, previous_source_destination, + process_source_output_ids, pulse_input_route_destination, retry_system_audio_connection, + route_event_is_relevant, route_watch_after_disconnect, route_watch_step, + routes_default_microphone_through_server, source_output_needs_move, + source_output_route_matches, started_input_source_output, system_audio_startup_attach, uses_default_pulse_input, wait_for_audio_after_route, wait_for_started_source_output, }; use tokio_util::sync::CancellationToken; @@ -3584,6 +4188,267 @@ mod system_audio_tests { Some((3, "new.monitor".to_string())) ); } + + #[test] + fn system_audio_stays_on_an_output_monitor() { + let sources = "74\talsa_input.pci-analog-stereo\n42\tcap_null.monitor\n"; + assert_eq!( + plan_system_audio_route(10, &[(10, 42), (11, 74)], sources, Some("cap_null.monitor")), + SystemAudioRoutePlan::Keep + ); + assert_eq!( + plan_system_audio_route(10, &[(10, 42)], "42\tauto_null.monitor\n", None), + SystemAudioRoutePlan::Keep + ); + } + + #[test] + fn system_audio_on_a_microphone_reattaches_when_a_monitor_exists() { + let sources = "74\talsa_input.pci-analog-stereo\n42\tspeakers.monitor\n"; + assert_eq!( + plan_system_audio_route(10, &[(10, 74), (11, 74)], sources, Some("speakers.monitor")), + SystemAudioRoutePlan::Reattach + ); + } + + #[test] + fn system_audio_on_a_microphone_is_lost_without_an_output_monitor() { + let sources = "74\talsa_input.pci-analog-stereo\n"; + for monitor in [None, Some("alsa_input.pci-analog-stereo"), Some(".monitor")] { + assert_eq!( + plan_system_audio_route(10, &[(10, 74)], sources, monitor), + SystemAudioRoutePlan::Lost, + "{monitor:?}" + ); + } + assert_eq!( + plan_system_audio_route( + 10, + &[(10, 3)], + "3\tOutput Monitor\n", + Some("Output Monitor") + ), + SystemAudioRoutePlan::Lost + ); + } + + #[test] + fn system_audio_chunks_before_a_microphone_reroute_are_never_forwarded() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(10), "monitor")); + assert!(staging.push(started + Duration::from_millis(20), "microphone")); + + let released = staging.observe(SystemAudioRouteCheck::NotOnMonitor { + observed_at: started + Duration::from_millis(25), + }); + assert!(released.is_empty()); + assert_eq!(staging.pending_len(), 0); + + let reattached = started + Duration::from_millis(30); + staging.note_attached(reattached); + assert!(!staging.push(started + Duration::from_millis(20), "late microphone")); + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(80), + }); + assert!( + released.is_empty(), + "microphone audio was forwarded: {released:?}" + ); + } + + #[test] + fn system_audio_samples_staged_before_lock_are_released_by_a_monitor_check() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(5), "startup")); + + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(15), + }); + assert_eq!(released, vec!["startup"]); + } + + #[test] + fn system_audio_delayed_chunk_after_a_monitor_check_is_kept_for_the_next_check() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(10), "live")); + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(30), + }); + assert_eq!(released, vec!["live"]); + + assert!( + staging.push(started + Duration::from_millis(60), "later"), + "audio captured after the check was discarded" + ); + assert!( + staging.push(started + Duration::from_millis(20), "delayed"), + "a safe chunk captured before the check was discarded when it arrived late" + ); + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(50), + }); + assert_eq!(released, vec!["delayed"]); + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(80), + }); + assert_eq!(released, vec!["later"]); + } + + #[test] + fn system_audio_late_chunk_from_before_a_microphone_reroute_is_dropped() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(10), "monitor")); + let released = staging.observe(SystemAudioRouteCheck::NotOnMonitor { + observed_at: started + Duration::from_millis(40), + }); + assert!(released.is_empty()); + assert_eq!(staging.pending_len(), 0); + assert!( + !staging.push(started + Duration::from_millis(20), "during microphone"), + "audio captured before the reroute was staged" + ); + } + + #[test] + fn system_audio_confirmed_monitor_releases_only_chunks_from_before_the_check() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(10), "before")); + assert!(staging.push(started + Duration::from_millis(50), "during")); + + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(30), + }); + assert_eq!(released, vec!["before"]); + + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(80), + }); + assert_eq!(released, vec!["during"]); + } + + #[test] + fn system_audio_staging_drops_audio_held_longer_than_the_bound() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(1)); + staging.note_attached(started); + assert!(staging.push(started + Duration::from_millis(10), "old")); + assert!(staging.push(started + Duration::from_secs(2), "new")); + assert_eq!(staging.pending_len(), 1); + + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_secs(3), + }); + assert_eq!(released, vec!["new"]); + } + + #[test] + fn system_audio_first_monitor_read_does_not_release_unproven_chunks() { + let started = Instant::now(); + let mut staging = SystemAudioStaging::new(Duration::from_secs(2)); + assert!(staging.push(started + Duration::from_millis(10), "unproven")); + let released = staging.observe(SystemAudioRouteCheck::OnMonitor { + check_started: started + Duration::from_millis(20), + }); + assert!(released.is_empty()); + assert_eq!(staging.pending_len(), 0); + } + + #[test] + fn only_capture_route_events_wake_the_system_audio_check() { + for line in [ + "Event 'change' on source-output #42", + "Event 'remove' on sink #7", + "Event 'new' on source #9", + "Event 'change' on server #4294967295", + "Event 'change' on card #3", + ] { + assert!(route_event_is_relevant(line), "{line}"); + } + for line in [ + "Event 'change' on sink-input #12", + "Event 'new' on client #88", + "Event 'remove' on module #5", + ] { + assert!(!route_event_is_relevant(line), "{line}"); + } + } + + #[test] + fn a_quiet_subscription_proves_the_route_without_running_pactl() { + let keep = Some(SystemAudioRoutePlan::Keep); + let recent = Some(Duration::from_millis(100)); + assert_eq!( + route_watch_step(false, recent, keep), + RouteWatchStep::QuietProof + ); + assert_eq!( + route_watch_step(true, recent, keep), + RouteWatchStep::Inspect + ); + assert_eq!(route_watch_step(false, None, keep), RouteWatchStep::Inspect); + assert_eq!( + route_watch_step(false, Some(Duration::from_secs(2)), keep), + RouteWatchStep::Inspect + ); + for unproven in [ + None, + Some(SystemAudioRoutePlan::Lost), + Some(SystemAudioRoutePlan::Reattach), + Some(SystemAudioRoutePlan::Ignore), + ] { + assert_eq!( + route_watch_step(false, recent, unproven), + RouteWatchStep::Wait, + "{unproven:?}" + ); + } + } + + #[test] + fn closed_system_audio_subscription_waits_instead_of_spinning() { + let mut backoff = Duration::from_millis(200); + let mut previous = Duration::ZERO; + for _ in 0..6 { + let (wait, next) = route_watch_after_disconnect(backoff); + assert!(wait >= Duration::from_millis(200)); + assert!(wait >= previous); + assert!(wait > Duration::ZERO); + previous = wait; + backoff = next; + } + assert_eq!(backoff, Duration::from_secs(2)); + assert_eq!( + route_watch_after_disconnect(backoff).1, + Duration::from_secs(2) + ); + assert_eq!( + route_watch_after_disconnect(Duration::ZERO).0, + Duration::from_millis(200) + ); + } + + #[test] + fn system_audio_route_ignores_a_missing_stream_or_source_name() { + let sources = "42\tcap_null.monitor\n"; + assert_eq!( + plan_system_audio_route(10, &[(11, 42)], sources, Some("cap_null.monitor")), + SystemAudioRoutePlan::Ignore + ); + assert_eq!( + plan_system_audio_route(10, &[(10, 99)], sources, Some("cap_null.monitor")), + SystemAudioRoutePlan::Ignore + ); + } use crate::feeds::microphone::MicrophoneFeed; use cap_timestamp::{Timestamp, Timestamps}; use kameo::Actor as _; @@ -3979,6 +4844,44 @@ mod system_audio_tests { } } + #[test] + fn named_monitor_input_watches_its_own_output_before_ready() { + assert_eq!( + system_audio_startup_attach(PulseInputRole::SystemAudio, false, true), + Some(SystemAudioStartupAttach::WatchDirectOutput) + ); + assert_eq!( + system_audio_startup_attach(PulseInputRole::SystemAudio, true, false), + Some(SystemAudioStartupAttach::FollowPreparedRoute) + ); + assert_eq!( + system_audio_startup_attach(PulseInputRole::SystemAudio, false, false), + None, + "a loopback opened straight from the card has no Pulse stream to wait for" + ); + assert_eq!( + system_audio_startup_attach(PulseInputRole::Microphone, false, true), + None + ); + assert!(!uses_default_pulse_input( + "alsa_output.pci-0000_00_1f.3.analog-stereo.monitor" + )); + let previous = [PactlSourceOutput { id: 1, source: 2 }]; + let started = wait_for_started_source_output( + &previous, + &std::sync::atomic::AtomicBool::new(true), + &CancellationToken::new(), + || { + Ok(vec![ + PactlSourceOutput { id: 1, source: 2 }, + PactlSourceOutput { id: 9, source: 4 }, + ]) + }, + ) + .unwrap(); + assert_eq!(started.id, 9); + } + #[test] fn only_generic_pulse_devices_follow_the_default_input() { assert!(uses_default_pulse_input("default")); diff --git a/crates/recording/src/sources/screen_capture/linux/audio_only_null_sink_tests.rs b/crates/recording/src/sources/screen_capture/linux/audio_only_null_sink_tests.rs new file mode 100644 index 00000000000..924a2596649 --- /dev/null +++ b/crates/recording/src/sources/screen_capture/linux/audio_only_null_sink_tests.rs @@ -0,0 +1,422 @@ +use crate::{ + feeds::microphone::synthetic::SyntheticMicrophone, + sources::screen_capture::ScreenCaptureTarget, studio_recording::Actor, +}; +use cap_project::StudioRecordingStatus; +use std::{ + path::{Path, PathBuf}, + process::Command, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::Duration, +}; + +fn pulse_lock() -> &'static tokio::sync::Mutex<()> { + static LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); + LOCK.get_or_init(|| tokio::sync::Mutex::new(())) +} + +fn module_ids(name: &str) -> Vec { + pactl(&["list", "short", "modules"]) + .lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + let id = fields.next()?; + let module = fields.next()?; + (module == name).then(|| id.to_string()) + }) + .collect() +} + +fn unload_module(name: &str) { + for id in module_ids(name) { + let _ = Command::new("pactl").args(["unload-module", &id]).output(); + } +} + +struct NoPulseMonitor; + +impl NoPulseMonitor { + fn enforce() -> Self { + unload_module("module-always-sink"); + unload_module("module-null-sink"); + Self + } +} + +impl Drop for NoPulseMonitor { + fn drop(&mut self) { + let _ = Command::new("pactl") + .args(["load-module", "module-always-sink"]) + .output(); + } +} + +fn pactl(args: &[&str]) -> String { + let output = Command::new("pactl") + .args(args) + .output() + .unwrap_or_else(|error| panic!("pactl {args:?} failed to start: {error}")); + assert!( + output.status.success(), + "pactl {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).trim().to_string() +} + +struct NullSink { + module: String, + name: String, +} + +impl NullSink { + fn start(name: &str) -> Self { + let module = pactl(&[ + "load-module", + "module-null-sink", + &format!("sink_name={name}"), + &format!("sink_properties=device.description={name}"), + ]); + pactl(&["set-default-sink", name]); + pactl(&["set-default-source", &format!("{name}.monitor")]); + Self { + module, + name: name.to_string(), + } + } + + fn reload(&mut self) { + pactl(&["unload-module", &self.module]); + self.module = pactl(&[ + "load-module", + "module-null-sink", + &format!("sink_name={}", self.name), + &format!("sink_properties=device.description={}", self.name), + ]); + pactl(&["set-default-sink", &self.name]); + pactl(&["set-default-source", &format!("{}.monitor", self.name)]); + } + + fn unload(&mut self) { + if self.module.is_empty() { + return; + } + let module = std::mem::take(&mut self.module); + let _ = Command::new("pactl") + .args(["unload-module", &module]) + .output(); + } +} + +impl Drop for NullSink { + fn drop(&mut self) { + self.unload(); + } +} + +struct Tone { + stop: Arc, + thread: Option>, +} + +impl Tone { + fn start(device: &str, wav: PathBuf) -> Self { + let stop = Arc::new(AtomicBool::new(false)); + let thread = std::thread::spawn({ + let stop = stop.clone(); + let device = device.to_string(); + move || { + while !stop.load(Ordering::Relaxed) { + let _ = Command::new("paplay") + .args(["--device", &device, &wav.to_string_lossy()]) + .status(); + } + } + }); + Self { + stop, + thread: Some(thread), + } + } + + fn stop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for Tone { + fn drop(&mut self) { + self.stop(); + } +} + +fn sine_wav(path: &Path, frequency: u32) { + let status = Command::new("ffmpeg") + .args([ + "-y", + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + &format!("sine=frequency={frequency}:sample_rate=48000:duration=0.4"), + "-c:a", + "pcm_s16le", + &path.to_string_lossy(), + ]) + .status() + .expect("ffmpeg"); + assert!(status.success(), "ffmpeg could not write the test tone"); +} + +fn decode_f32_mono(path: &Path) -> Vec { + let output = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-i", + &path.to_string_lossy(), + "-ac", + "1", + "-ar", + "48000", + "-f", + "f32le", + "-", + ]) + .output() + .expect("ffmpeg"); + assert!( + output.status.success(), + "{} did not decode: {}", + path.display(), + String::from_utf8_lossy(&output.stderr) + ); + output + .stdout + .chunks_exact(4) + .map(|sample| f32::from_le_bytes(sample.try_into().expect("f32"))) + .collect() +} + +fn tone_power(pcm: &[f32], frequency: f32) -> f32 { + let sample_rate = 48_000.0; + let omega = std::f32::consts::TAU * frequency / sample_rate; + let coeff = 2.0 * omega.cos(); + let mut first = 0.0; + let mut second = 0.0; + for &sample in pcm { + let next = sample + coeff * first - second; + second = first; + first = next; + } + first * first + second * second - coeff * first * second +} + +fn assert_tail_is_frequency(path: &Path, frequency: f32) { + let pcm = decode_f32_mono(path); + let tail_samples = (48_000.0 * 0.4) as usize; + assert!( + pcm.len() > tail_samples + (48_000.0 * 0.3) as usize, + "system audio is too short to contain audio from after the reload ({})", + pcm.len() + ); + let tail = &pcm[pcm.len() - tail_samples..]; + let wanted = tone_power(tail, frequency); + let other = tone_power(tail, if frequency == 880.0 { 440.0 } else { 880.0 }); + assert!( + wanted > other * 4.0 && wanted > 1.0, + "the end of {} is not {frequency} Hz (wanted={wanted}, other={other})", + path.display() + ); +} + +fn playable_seconds(path: &Path) -> f64 { + let decoded = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-i", + &path.to_string_lossy(), + "-f", + "null", + "-", + ]) + .status() + .expect("ffmpeg"); + assert!( + decoded.success(), + "{} did not decode to the end", + path.display() + ); + let output = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + &path.to_string_lossy(), + ]) + .output() + .expect("ffprobe"); + assert!( + output.status.success(), + "{} is not playable: {}", + path.display(), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout) + .trim() + .parse() + .unwrap_or_else(|_| panic!("{} has no duration", path.display())) +} + +async fn push_mic(mic: &SyntheticMicrophone) { + let samples = vec![0.2_f32; 4_800]; + mic.push( + &samples, + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + ) + .await; +} + +fn segment_file(project: &Path, name: &str) -> PathBuf { + project.join(format!("content/segments/segment-0/{name}")) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "PulseAudio null sink"] +async fn unloading_a_null_monitor_ends_audio_only_and_keeps_the_mic() { + let _guard = pulse_lock().lock().await; + pactl(&["info"]); + let sink = NullSink::start("cap_loss_permanent"); + let temp = tempfile::tempdir().unwrap(); + let wav = temp.path().join("tone.wav"); + sine_wav(&wav, 440); + let mut tone = Tone::start(&sink.name, wav); + tokio::time::sleep(Duration::from_millis(300)).await; + let mic = SyntheticMicrophone::spawn("test-mic", 48_000, 1); + let project = temp.path().join("project"); + let handle = Actor::builder(project.clone(), ScreenCaptureTarget::AudioOnly) + .with_system_audio(true) + .with_mic_feed(Arc::new(mic.lock().await.unwrap())) + .build() + .await + .expect("audio-only recording did not start against the null sink"); + let mic_stop = Arc::new(AtomicBool::new(false)); + let mic_pump = tokio::spawn({ + let mic_stop = mic_stop.clone(); + async move { + while !mic_stop.load(Ordering::Relaxed) { + push_mic(&mic).await; + tokio::time::sleep(Duration::from_millis(80)).await; + } + } + }); + tokio::time::sleep(Duration::from_millis(700)).await; + tone.stop(); + let _no_monitor = NoPulseMonitor::enforce(); + drop(sink); + let sources = pactl(&["list", "short", "sources"]); + assert!( + !sources.contains(".monitor"), + "a monitor was still available after unload:\n{sources}" + ); + let outcome = tokio::time::timeout(Duration::from_secs(12), handle.done_fut()) + .await + .unwrap_or_else(|_| { + panic!( + "unloading the monitor left the audio-only take running; sources:\n{}", + pactl(&["list", "short", "sources"]) + ) + }); + outcome.expect("unloading the monitor failed the take"); + tokio::time::sleep(Duration::from_millis(200)).await; + mic_stop.store(true, Ordering::Relaxed); + mic_pump.abort(); + let stop_result = tokio::time::timeout(Duration::from_secs(20), handle.stop()) + .await + .expect("stop hung after the monitor was unloaded"); + assert_saved_audio(&project, &stop_result, true); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "PulseAudio null sink"] +async fn reloading_a_null_monitor_keeps_audio_only_running() { + let _guard = pulse_lock().lock().await; + pactl(&["info"]); + let _only_this_sink = NoPulseMonitor::enforce(); + let mut sink = NullSink::start("cap_loss_transient"); + let temp = tempfile::tempdir().unwrap(); + let before = temp.path().join("tone-440.wav"); + let after = temp.path().join("tone-880.wav"); + sine_wav(&before, 440); + sine_wav(&after, 880); + let mut tone = Tone::start(&sink.name, before); + tokio::time::sleep(Duration::from_millis(300)).await; + let project = temp.path().join("project"); + let handle = Actor::builder(project.clone(), ScreenCaptureTarget::AudioOnly) + .with_system_audio(true) + .build() + .await + .expect("audio-only recording did not start against the null sink"); + tokio::time::sleep(Duration::from_millis(500)).await; + tone.stop(); + sink.reload(); + let mut tone = Tone::start(&sink.name, after); + tokio::time::sleep(Duration::from_millis(1500)).await; + let still_running = tokio::time::timeout(Duration::from_secs(4), handle.done_fut()).await; + assert!( + still_running.is_err(), + "reloading the monitor ended the take: {still_running:?}" + ); + tone.stop(); + let stop_result = tokio::time::timeout(Duration::from_secs(20), handle.stop()) + .await + .expect("stop hung after the monitor was reloaded"); + assert_saved_audio(&project, &stop_result, false); + assert_tail_is_frequency(&segment_file(&project, "system_audio.m4a"), 880.0); +} + +fn assert_saved_audio( + project: &Path, + stop_result: &anyhow::Result, + expect_mic: bool, +) { + match stop_result { + Ok(completed) => assert!( + matches!(completed.meta.status(), StudioRecordingStatus::Complete), + "saved status was {:?}", + completed.meta.status() + ), + Err(error) => { + let message = format!("{error:#}"); + assert!( + message.contains("audio-only display track") && message.contains("Codec not found"), + "stop failed: {message}" + ); + } + } + let system = segment_file(project, "system_audio.m4a"); + assert!( + playable_seconds(&system) > 0.05, + "system audio file did not play" + ); + if expect_mic { + let microphone = segment_file(project, "audio-input.m4a"); + assert!( + playable_seconds(µphone) > 0.05, + "mic audio was dropped when the monitor was unloaded" + ); + } +} diff --git a/crates/recording/src/sources/screen_capture/linux/system_audio_channel_tests.rs b/crates/recording/src/sources/screen_capture/linux/system_audio_channel_tests.rs index d7bb7570d35..080b1ca20ac 100644 --- a/crates/recording/src/sources/screen_capture/linux/system_audio_channel_tests.rs +++ b/crates/recording/src/sources/screen_capture/linux/system_audio_channel_tests.rs @@ -1,7 +1,10 @@ use super::*; use crate::{ feeds::microphone::synthetic::SyntheticMicrophone, - output_pipeline::{AudioMuxer, Muxer, OutputPipeline, TaskPool}, + output_pipeline::{ + AudioFrame, AudioMuxer, ChannelAudioSource, ChannelAudioSourceConfig, Muxer, + OutputPipeline, PipelineBuildScope, TaskPool, + }, }; use std::ops::Deref; @@ -54,6 +57,7 @@ async fn linux_system_audio_preserves_stereo_channels() { build_scope: None, stopped: false, }, + ends_take_when_lost: false, }; let (frames, received) = flume::unbounded(); let temp = tempfile::tempdir().unwrap(); @@ -86,3 +90,149 @@ async fn linux_system_audio_preserves_stereo_channels() { } } } + +#[tokio::test] +async fn terminal_system_audio_failure_ends_its_pipeline_and_leaves_the_mic() { + let scope = PipelineBuildScope::new_studio_lifetime(); + let input = SyntheticMicrophone::spawn("speakers.monitor", 48_000, 2); + let lock = input.lock().await.unwrap(); + let health = lock.source_health(); + let actor = lock.deref().clone(); + let (frames, received) = flume::unbounded(); + let (mic_frames, mic_received) = flume::unbounded(); + let temp = tempfile::tempdir().unwrap(); + let built = scope + .run(async { + let pipeline = OutputPipeline::builder(temp.path().join("system.ogg")) + .with_audio_source::(SystemAudioSourceConfig { + feed_lock: Arc::new(lock), + device_name: "speakers.monitor".into(), + monitor_route: None, + feed: OwnedSystemAudioFeed { + actor, + build_scope: PipelineBuildScope::current(), + stopped: false, + }, + ends_take_when_lost: true, + }) + .build::(frames) + .await + .unwrap(); + let mic_info = AudioInfo::new_raw( + cap_media_info::Sample::F32(cap_media_info::Type::Packed), + 48_000, + 1, + ); + let (mic_tx, mic_rx) = futures::channel::mpsc::channel(4); + let microphone = OutputPipeline::builder(temp.path().join("mic.ogg")) + .with_audio_source::(ChannelAudioSourceConfig::new( + mic_info, mic_rx, + )) + .build::(mic_frames) + .await + .unwrap(); + (pipeline, microphone.cancel_token(), microphone, mic_tx) + }) + .await; + let (pipeline, microphone_cancel, microphone, mut mic_tx) = built; + let _microphone = microphone; + input + .push( + &[0.25, -0.25], + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + ) + .await; + tokio::time::timeout(Duration::from_secs(2), received.recv_async()) + .await + .expect("system audio reached the muxer") + .unwrap(); + health.fail("speakers.monitor removed".into()); + tokio::time::timeout(Duration::from_secs(3), pipeline.done_fut()) + .await + .expect("terminal system audio loss left the pipeline running") + .expect("terminal system audio loss failed the pipeline"); + assert!( + !microphone_cancel.is_cancelled(), + "an active mic was cancelled with system audio" + ); + let mic_info = AudioInfo::new_raw( + cap_media_info::Sample::F32(cap_media_info::Type::Packed), + 48_000, + 1, + ); + mic_tx + .try_send(AudioFrame::new( + mic_info.wrap_frame(&0.5f32.to_ne_bytes()), + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + )) + .expect("mic sender closed after system audio ended"); + tokio::time::timeout(Duration::from_secs(2), mic_received.recv_async()) + .await + .expect("mic audio did not reach its muxer after system audio ended") + .unwrap(); +} + +#[tokio::test] +async fn transient_system_audio_failure_keeps_the_pipeline_and_later_samples() { + let scope = PipelineBuildScope::new_studio_lifetime(); + let input = SyntheticMicrophone::spawn("speakers.monitor", 48_000, 2); + let lock = input.lock().await.unwrap(); + let health = lock.source_health(); + let actor = lock.deref().clone(); + let (frames, received) = flume::unbounded(); + let temp = tempfile::tempdir().unwrap(); + let pipeline = scope + .run(async { + OutputPipeline::builder(temp.path().join("system.ogg")) + .with_audio_source::(SystemAudioSourceConfig { + feed_lock: Arc::new(lock), + device_name: "speakers.monitor".into(), + monitor_route: None, + feed: OwnedSystemAudioFeed { + actor, + build_scope: PipelineBuildScope::current(), + stopped: false, + }, + ends_take_when_lost: true, + }) + .build::(frames) + .await + .unwrap() + }) + .await; + input + .push( + &[0.25, -0.25], + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + ) + .await; + tokio::time::timeout(Duration::from_secs(2), received.recv_async()) + .await + .expect("system audio reached the muxer") + .unwrap(); + health.test_backend_failure(); + input + .push( + &[0.5, -0.5], + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + ) + .await; + let still_running = tokio::time::timeout(Duration::from_millis(400), pipeline.done_fut()).await; + assert!( + still_running.is_err(), + "a transient system audio error ended the pipeline" + ); + health.test_recover_backend(); + input + .push( + &[0.25, -0.25], + cap_timestamp::Timestamp::Instant(std::time::Instant::now()), + ) + .await; + tokio::time::timeout(Duration::from_secs(2), received.recv_async()) + .await + .expect("system audio did not recover") + .unwrap(); + let still_running = tokio::time::timeout(Duration::from_millis(200), pipeline.done_fut()).await; + assert!(still_running.is_err(), "recovered system audio ended"); +} diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index c74c27ef9e4..5a24b7b7b7b 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -1477,10 +1477,10 @@ struct Pipeline { pub track_failures: SharedTrackFailures, pub watcher_task: Option>, stopping: Arc, - /// macOS records an audio-only segment's system audio from its own - /// ScreenCaptureKit stream, so that stream ending (sharing stopped, the - /// display gone, a system stop) has to end the recording the way the - /// screen ending does, instead of leaving only the black canvas running. + /// Audio-only system audio is the recording. On macOS that stream is a + /// ScreenCaptureKit capture. On Linux it is the output monitor. Either + /// one ending has to end the take, instead of leaving the stand-in clock + /// running. system_audio_required: bool, } @@ -2079,6 +2079,23 @@ impl Pipeline { }); continue; } + #[cfg(target_os = "linux")] + if matches!(track, RecordingTrackKind::SystemAudio) + && required + && res.is_ok() + && !stopping.load(std::sync::atomic::Ordering::Acquire) + { + warn!(?track, "Audio-only system audio ended before Stop"); + completion_tx.send_if_modified(|current| { + if current.is_none() { + *current = Some(Ok(())); + true + } else { + false + } + }); + continue; + } #[cfg(any(target_os = "linux", windows))] let res = match res { Ok(()) if !stopping.load(std::sync::atomic::Ordering::Acquire) => { @@ -4178,7 +4195,7 @@ async fn create_segment_pipeline( track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), - system_audio_required: audio_only && cfg!(target_os = "macos"), + system_audio_required: audio_only && cfg!(any(target_os = "macos", target_os = "linux")), }) } @@ -4199,7 +4216,9 @@ async fn audio_only_system_audio( #[cfg(target_os = "linux")] { let _ = (base_inputs, start_time); - screen_capture::create_system_audio_source_config().await + screen_capture::create_system_audio_source_config() + .await + .map(screen_capture::SystemAudioSourceConfig::end_take_when_lost) } #[cfg(target_os = "macos")]