From f7982acabe6e0a01ec088691c64ec1845506e778 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:20:00 +0000 Subject: [PATCH 01/12] fix: end a Linux audio-only take when system audio stays gone Audio-only system audio now ends its own track after the reconnect grace, and the take saves with the microphone still in it. A monitor that returns during the grace keeps the take running. Screen recordings are unchanged. Co-authored-by: Kyzer --- apps/desktop-gpui/src/session.rs | 15 +- crates/recording/src/feeds/microphone.rs | 104 +++++- crates/recording/src/sources/microphone.rs | 140 +++++-- .../src/sources/screen_capture/linux.rs | 18 + .../linux/audio_only_null_sink_tests.rs | 353 ++++++++++++++++++ .../linux/system_audio_channel_tests.rs | 152 +++++++- crates/recording/src/studio_recording.rs | 31 +- 7 files changed, 760 insertions(+), 53 deletions(-) create mode 100644 crates/recording/src/sources/screen_capture/linux/audio_only_null_sink_tests.rs diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index d7f4348e7b6..576d940535a 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -2249,14 +2249,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 { @@ -2862,7 +2862,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 1ca771ce7ee..d9c9430825f 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -512,6 +512,34 @@ struct RecordingSourceHealthState { pending: Option>, recovery_origin: Option, terminal: Option, + deferred: Option<(std::time::Instant, String)>, + defer_for: std::time::Duration, +} + +#[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); + } + } } #[cfg(target_os = "linux")] @@ -524,10 +552,16 @@ impl RecordingSourceHealth { pending: None, recovery_origin: None, terminal: None, + deferred: None, + defer_for: std::time::Duration::ZERO, }, ))) } + 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))) @@ -595,9 +629,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); } @@ -621,7 +656,7 @@ impl RecordingSourceHealth { .as_ref() .is_some_and(|pending| pending.id == id) { - state.terminal.get_or_insert(error); + state.remember_loss(error); } } @@ -630,7 +665,23 @@ 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.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 { @@ -3861,6 +3912,29 @@ mod tests { assert!(feed.take_system_error_reconnect(7).is_none()); } + #[cfg(target_os = "linux")] + #[tokio::test] + async fn lost_system_audio_device_sets_terminal_health() { + 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"); + assert!( + health.terminal_error().is_some(), + "reconnect error {error} left system audio healthy" + ); + actor.kill(); + actor.wait_for_stop().await; + } + #[cfg(target_os = "linux")] #[tokio::test] async fn watchdog_joins_pending_system_reconnect_without_reopening_device() { @@ -4600,6 +4674,30 @@ mod required_recording_health_tests { assert!(health.stop_error().is_some()); } + #[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_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/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index 85a5b0a90a6..10876aa31a7 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -25,6 +25,17 @@ 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")] +#[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 @@ -396,21 +407,61 @@ 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 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(); } @@ -423,6 +474,9 @@ impl RequiredMicrophoneHealth { } fn stop(&self) { + if matches!(self.loss, LinuxSourceLoss::EndThisTrack) { + return; + } if let Some(error) = self.source.stop_error() { self.scope.fail_required(error); } @@ -436,6 +490,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(); @@ -471,9 +526,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(); @@ -1182,6 +1244,8 @@ impl AudioSource for Microphone { ctx, usize::from(MICROPHONE_TARGET_CHANNELS), None, + #[cfg(target_os = "linux")] + LinuxSourceLoss::FailRecording, ) } @@ -1239,6 +1303,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) } } @@ -1775,10 +1841,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(); @@ -1815,10 +1881,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)); @@ -1838,10 +1904,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()); @@ -1862,10 +1928,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; @@ -1887,10 +1953,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; @@ -1901,10 +1967,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; @@ -1921,10 +1987,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 bd767a84f7d..a42929a1ce1 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 { @@ -1857,12 +1868,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 @@ -1960,6 +1977,7 @@ pub async fn create_system_audio_source_config() -> anyhow::Result &'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) { + let status = Command::new("ffmpeg") + .args([ + "-y", + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=440: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 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); + 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 mut sink = NullSink::start("cap_loss_transient"); + let temp = tempfile::tempdir().unwrap(); + let wav = temp.path().join("tone.wav"); + sine_wav(&wav); + let mut tone = Tone::start(&sink.name, wav); + 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(400)).await; + sink.reload(); + 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); +} + +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 676a181178b..b25fa032997 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -1464,10 +1464,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, } @@ -2066,6 +2066,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) => { @@ -4128,7 +4145,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")), }) } @@ -4149,7 +4166,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")] From 7cb7681adb079837d019d8a97c8e79f62a7354cf Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:05:38 +0000 Subject: [PATCH 02/12] fix: stop Linux system audio from recording the microphone PipeWire moves a capture onto the default source when its monitor disappears, and the stream stays open. Treat a source that is not a sink .monitor as a system-audio loss: drop those samples, move the stream back onto the current output monitor when one exists, and otherwise end the track after the reconnect grace. A stream that errors still follows the existing PulseAudio path. Co-authored-by: Kyzer --- crates/recording/src/feeds/microphone.rs | 313 +++++++++++++++++- crates/recording/src/sources/microphone.rs | 12 +- .../src/sources/screen_capture/linux.rs | 262 ++++++++++++++- 3 files changed, 564 insertions(+), 23 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index d9c9430825f..aff3b64b25d 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, @@ -161,6 +180,7 @@ pub struct MicrophoneSamples { pub channels: u16, pub info: InputCallbackInfo, pub timestamp: Timestamp, + pub(crate) capture_epoch: u64, } /// Debounces sample-rate changes: a freshly-inferred rate is only adopted after it is @@ -514,6 +534,36 @@ struct RecordingSourceHealthState { 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)>, +} + +#[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")] @@ -539,12 +589,32 @@ impl RecordingSourceHealthState { 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. +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, @@ -554,10 +624,87 @@ impl RecordingSourceHealth { terminal: None, deferred: None, defer_for: std::time::Duration::ZERO, + capture_blocked: false, + capture_gate, + route_lost_until: None, }, ))) } + 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; } @@ -674,6 +821,7 @@ impl RecordingSourceHealth { let state = self.0.lock().unwrap(); state.terminal.is_none() && state.current.id == id + && !state.capture_blocked && !state.current.failed.load(Ordering::Acquire) } @@ -686,7 +834,7 @@ impl RecordingSourceHealth { 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) { @@ -709,7 +857,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(); state.terminal.clone().or_else(|| { (state.current.failed.load(Ordering::Acquire) || state @@ -944,6 +1093,13 @@ 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")] + route_watch_cancel: tokio_util::sync::CancellationToken, input_id_counter: u32, lock_generation: u64, state: State, @@ -965,7 +1121,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_cancel.cancel(); + } } } @@ -1222,6 +1381,14 @@ 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")] + route_watch_cancel: tokio_util::sync::CancellationToken::new(), #[cfg(any(target_os = "linux", windows))] stream_health: std::collections::HashMap::new(), #[cfg(target_os = "linux")] @@ -1250,6 +1417,26 @@ impl MicrophoneFeed { feed } + #[cfg(target_os = "linux")] + fn start_system_audio_route_watch(&mut self) { + let Some(health) = self.recording_health.clone() else { + return; + }; + self.route_watch_cancel.cancel(); + self.route_watch_cancel = tokio_util::sync::CancellationToken::new(); + let cancel = self.route_watch_cancel.clone(); + let route = self.system_capture_route.clone(); + let _ = std::thread::Builder::new() + .name("system-audio-route".into()) + .spawn(move || { + crate::sources::screen_capture::watch_system_audio_route( + cancel, + route, + move |stream_id, plan| health.apply_system_audio_route(stream_id, plan), + ); + }); + } + pub fn default_device() -> Option<(String, Device, SupportedStreamConfig)> { let host = cpal::default_host(); host.default_input_device() @@ -1341,6 +1528,10 @@ 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, id, label, settings, @@ -1482,6 +1673,8 @@ 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(); let mut callback_count = 0u64; move |data, info| { #[cfg(target_os = "linux")] @@ -1524,6 +1717,34 @@ 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(); + 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(); + 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(not(target_os = "linux"))] + let capture_epoch = 0; #[cfg(windows)] let timestamp = capture_clock.timestamp( timestamp, @@ -1541,6 +1762,7 @@ impl MicrophoneFeed { channels: callback_channels, info: info.clone(), timestamp: timestamp - capture_latency, + capture_epoch, }; if !effective_sample_rate.settled { @@ -1614,13 +1836,26 @@ 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; + if let Some(route) = input_route { + match route.apply(&input_callback_observed, &system_stream_cancel) { + Ok(source_output) + if pulse_input_role + == crate::sources::screen_capture::PulseInputRole::SystemAudio => + { + *system_capture_route.lock().unwrap() = + Some(crate::sources::screen_capture::SystemAudioCaptureRoute { + stream_id: id, + source_output, + }); + } + Ok(_) => {} + Err(error) => { + let _ = ready_tx.send(Err(SetInputError::BuildStream(format!( + "Could not confirm the Linux audio input route: {error}" + )))); + return; + } + } } #[cfg(target_os = "linux")] @@ -2104,6 +2339,11 @@ 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>>, id: u32, label: String, settings: Option, @@ -2195,6 +2435,8 @@ impl MicrophoneFeed { pulse_input_role: self.pulse_input_role, #[cfg(target_os = "linux")] system_stream_cancel: self.system_stream_cancel.clone(), + system_capture_gate: self.system_capture_gate.clone(), + system_capture_route: self.system_capture_route.clone(), id, label: label.clone(), settings: msg.settings, @@ -2329,6 +2571,8 @@ impl MicrophoneFeed { pulse_input_role: self.pulse_input_role, #[cfg(target_os = "linux")] system_stream_cancel: self.system_stream_cancel.clone(), + system_capture_gate: self.system_capture_gate.clone(), + system_capture_route: self.system_capture_route.clone(), id: new_id, label: label.clone(), settings: msg.settings, @@ -2813,16 +3057,23 @@ impl Message for MicrophoneFeed { } let generation = self.lock_generation; #[cfg(target_os = "linux")] - let source_health = RecordingSourceHealth::new( + 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, ); #[cfg(target_os = "linux")] { self.recording_health = Some(source_health.clone()); + if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio + { + self.start_system_audio_route_watch(); + } } let token = Arc::new(()); let token_weak = Arc::downgrade(&token); @@ -3193,7 +3444,9 @@ 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_cancel.cancel(); self.system_reconnect = None; + *self.system_capture_gate.lock().unwrap() = Arc::new(SystemCaptureGate::open()); } replace_with_or_abort(&mut self.state, |state| { if let State::Locked { inner, .. } = state { @@ -3319,6 +3572,7 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + capture_epoch: 0, }) .await; } @@ -3343,6 +3597,7 @@ pub mod synthetic { channels, info: zero_callback_info(), timestamp, + capture_epoch: 0, }) .await; } @@ -3361,6 +3616,7 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + capture_epoch: 0, }) .try_send(), ) @@ -4685,6 +4941,41 @@ mod required_recording_health_tests { 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))); diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index 10876aa31a7..728f7e2ab71 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -457,6 +457,10 @@ impl RequiredMicrophoneHealth { true } + fn capture_epoch_current(&self, epoch: u64) -> bool { + self.source.capture_epoch_current(epoch) + } + fn accepts_frame(&self, id: u32) -> bool { let current = match self.loss { LinuxSourceLoss::FailRecording => self.source.frame_is_current(id), @@ -766,10 +770,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 { diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index a42929a1ce1..8ae109c9df1 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -1770,7 +1770,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, @@ -1781,7 +1781,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) } } @@ -2425,6 +2425,196 @@ fn pactl_monitor_preference(name: &str, default_sink: Option<&str>) -> 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) +} + +pub(crate) fn watch_system_audio_route( + cancel: CancellationToken, + route: Arc>>, + mut on_plan: impl FnMut(u32, SystemAudioRoutePlan), +) { + let (wake_tx, wake_rx) = std::sync::mpsc::channel(); + let mut subscribe = Command::new("pactl") + .arg("subscribe") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .ok(); + if let Some(child) = subscribe.as_mut() + && let Some(stdout) = 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 wake_tx.send(()).is_err() { + break; + } + } + } + } + }); + } + + let mut announced = None; + while !cancel.is_cancelled() { + let current = route.lock().unwrap().as_ref().copied(); + if let Some(current) = current + && !cancel.is_cancelled() + { + let (plan, monitor) = inspect_system_audio_source_output(current.source_output); + let resolved = match plan { + SystemAudioRoutePlan::Reattach => { + on_plan(current.stream_id, SystemAudioRoutePlan::Reattach); + match monitor { + Some(monitor) => { + match move_pactl_source_output(current.source_output, &monitor) { + Ok(()) => SystemAudioRoutePlan::Keep, + Err(error) => { + if announced != Some(SystemAudioRoutePlan::Lost) { + tracing::warn!( + %error, + "Could not move system audio back onto an output monitor" + ); + } + SystemAudioRoutePlan::Lost + } + } + } + None => SystemAudioRoutePlan::Lost, + } + } + other => 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() { + on_plan(current.stream_id, resolved); + } + } + let _ = wake_rx.recv_timeout(Duration::from_millis(200)); + } + + if let Some(mut child) = subscribe { + let _ = child.kill(); + let _ = child.wait(); + } +} + fn pactl_default_sink() -> Option { pactl_default_device("get-default-sink") } @@ -3359,12 +3549,12 @@ 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, source_output_needs_move, source_output_route_matches, - started_input_source_output, uses_default_pulse_input, wait_for_audio_after_route, - wait_for_started_source_output, + OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, SystemAudioRoutePlan, + 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, + source_output_needs_move, source_output_route_matches, started_input_source_output, + uses_default_pulse_input, wait_for_audio_after_route, wait_for_started_source_output, }; use tokio_util::sync::CancellationToken; @@ -3433,6 +3623,62 @@ 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_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 _; From fe7e7db8f1fc9a0cf2cc990521ed6d9279ed5388 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:13:27 +0000 Subject: [PATCH 03/12] fix: drop unconfirmed Linux system audio before it is muxed Windows and macOS builds no longer reference the Linux capture gate. System-audio samples stay staged until a later pactl read still sees a sink monitor; a microphone reroute drops every unconfirmed chunk. A closed pactl subscribe waits out its backoff instead of spinning, and the null-sink reload test checks the post-reload tone. Co-authored-by: Kyzer --- crates/recording/src/feeds/microphone.rs | 241 ++++++++++-- crates/recording/src/sources/microphone.rs | 12 +- .../src/sources/screen_capture/linux.rs | 344 ++++++++++++++++-- .../linux/audio_only_null_sink_tests.rs | 83 ++++- 4 files changed, 615 insertions(+), 65 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index aff3b64b25d..0a9b021f3dd 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -501,6 +501,37 @@ 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), + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Ignore, + .. + } => Vec::new(), + SystemAudioWatch::Reattached { at } => { + staging.note_attached(at); + Vec::new() + } + } +} + #[cfg(any(target_os = "linux", windows))] struct StreamHealth { id: u32, @@ -1099,6 +1130,12 @@ pub struct MicrophoneFeed { #[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_cancel: tokio_util::sync::CancellationToken, input_id_counter: u32, lock_generation: u64, @@ -1388,6 +1425,8 @@ impl MicrophoneFeed { SystemCaptureGate::open(), ))), #[cfg(target_os = "linux")] + system_audio_staging: None, + #[cfg(target_os = "linux")] route_watch_cancel: tokio_util::sync::CancellationToken::new(), #[cfg(any(target_os = "linux", windows))] stream_health: std::collections::HashMap::new(), @@ -1414,25 +1453,53 @@ 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(&mut self) { + fn start_system_audio_route_watch(&mut self, actor: ActorRef) { let Some(health) = self.recording_health.clone() else { return; }; + let Some(staging) = self.system_audio_staging.clone() else { + return; + }; self.route_watch_cancel.cancel(); self.route_watch_cancel = tokio_util::sync::CancellationToken::new(); let cancel = self.route_watch_cancel.clone(); let route = self.system_capture_route.clone(); + let dropped = self.dropped_message_count.clone(); let _ = std::thread::Builder::new() .name("system-audio-route".into()) .spawn(move || { crate::sources::screen_capture::watch_system_audio_route( cancel, route, - move |stream_id, plan| health.apply_system_audio_route(stream_id, plan), + move |stream_id, event| { + let released = release_staged_system_audio(&staging, event); + for sample in released { + enqueue_microphone_samples(&actor, &dropped, sample); + } + use crate::sources::screen_capture::{ + SystemAudioRoutePlan, SystemAudioWatch, + }; + match event { + SystemAudioWatch::Checked { plan, .. } => { + health.apply_system_audio_route(stream_id, plan); + } + SystemAudioWatch::Reattached { .. } => { + health.apply_system_audio_route( + stream_id, + SystemAudioRoutePlan::Keep, + ); + } + } + }, ); }); } @@ -1532,6 +1599,8 @@ impl MicrophoneFeed { system_capture_gate, #[cfg(target_os = "linux")] system_capture_route, + #[cfg(target_os = "linux")] + system_audio_staging, id, label, settings, @@ -1675,6 +1744,10 @@ impl MicrophoneFeed { 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(); let mut callback_count = 0u64; move |data, info| { #[cfg(target_os = "linux")] @@ -1722,6 +1795,7 @@ impl MicrophoneFeed { #[cfg(target_os = "linux")] if !capture_gate.open.load(Ordering::Acquire) { pending_samples.clear(); + pending_capture.clear(); return; } #[cfg(target_os = "linux")] @@ -1731,6 +1805,7 @@ impl MicrophoneFeed { || capture_gate.epoch.load(Ordering::Acquire) != capture_epoch { pending_samples.clear(); + pending_capture.clear(); return; } #[cfg(target_os = "linux")] @@ -1743,6 +1818,14 @@ impl MicrophoneFeed { ) { 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(not(target_os = "linux"))] let capture_epoch = 0; #[cfg(windows)] @@ -1765,17 +1848,35 @@ impl MicrophoneFeed { capture_epoch, }; + let 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, + 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, - 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; @@ -1786,18 +1887,14 @@ impl MicrophoneFeed { effective_sample_rate.sample_rate, ); while let Some(pending) = pending_samples.pop_front() { - enqueue_microphone_samples( - &actor_ref, - &dropped_message_count, - 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, - samples, - ); + forward(captured_at, samples); } }, microphone_stream_error_handler(error_sender, { @@ -1847,6 +1944,9 @@ impl MicrophoneFeed { stream_id: id, source_output, }); + if let Some(staging) = &system_audio_staging { + staging.lock().unwrap().note_attached(Instant::now()); + } } Ok(_) => {} Err(error) => { @@ -2098,12 +2198,45 @@ 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 + }; + 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, @@ -2179,6 +2312,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 } @@ -2344,6 +2495,12 @@ struct StreamSpawnParams { #[cfg(target_os = "linux")] system_capture_route: Arc>>, + #[cfg(target_os = "linux")] + system_audio_staging: Option< + Arc< + std::sync::Mutex>, + >, + >, id: u32, label: String, settings: Option, @@ -2435,8 +2592,12 @@ 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(), id, label: label.clone(), settings: msg.settings, @@ -2571,8 +2732,12 @@ 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(), id: new_id, label: label.clone(), settings: msg.settings, @@ -3057,24 +3222,29 @@ impl Message for MicrophoneFeed { } let generation = self.lock_generation; #[cfg(target_os = "linux")] - 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, - ); - #[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()); - if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio - { - self.start_system_audio_route_watch(); + 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); @@ -3104,6 +3274,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, @@ -3447,6 +3619,9 @@ impl Message for MicrophoneFeed { self.route_watch_cancel.cancel(); 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 { diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index 728f7e2ab71..b1e2f060bc8 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -654,6 +654,7 @@ 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; + let mut system_stop_flushed = false; loop { #[cfg(windows)] @@ -670,7 +671,15 @@ impl Microphone { } let recv_result = tokio::select! { biased; - _ = cancel.cancelled() => break, + _ = cancel.cancelled(), if !system_stop_flushed => { + #[cfg(target_os = "linux")] + if feed_lock.has_system_audio_hold() { + system_stop_flushed = true; + feed_lock.flush_confirmed_system_audio().await; + continue; + } + break; + } request = next_switch_request(&mut switch_requests) => { let Some(MicrophoneSwitchRequest { lock: next, reply }) = request else { continue; @@ -762,6 +771,7 @@ impl Microphone { continue; } r = tokio::time::timeout(silence_timeout, rx.recv_async()) => r, + _ = tokio::time::sleep(Duration::from_millis(50)), if system_stop_flushed => break, }; match recv_result { Ok(Ok(frame)) => { diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 8ae109c9df1..b7d155a7d08 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -2519,21 +2519,150 @@ fn inspect_system_audio_source_output( (plan, monitor) } -pub(crate) fn watch_system_audio_route( - cancel: CancellationToken, - route: Arc>>, - mut on_plan: impl FnMut(u32, SystemAudioRoutePlan), -) { +// Samples stay here until a later source read still sees a sink monitor. +// A read that sees anything else drops every sample not yet released, +// including audio captured on the monitor in the moment 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, +} + +struct StagedSystemAudio { + captured_at: Instant, + value: T, +} + +pub(crate) struct SystemAudioStaging { + pending: std::collections::VecDeque>, + proven_until: Option, + max_hold: Duration, +} + +impl SystemAudioStaging { + pub(crate) fn new(max_hold: Duration) -> Self { + Self { + pending: std::collections::VecDeque::new(), + proven_until: None, + max_hold, + } + } + + pub(crate) fn clear(&mut self) { + self.pending.clear(); + 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.pending.retain(|chunk| chunk.captured_at > at); + self.proven_until = Some(at); + } + + pub(crate) fn push(&mut self, captured_at: Instant, value: T) -> bool { + if self.proven_until.is_some_and(|until| captured_at <= until) { + return false; + } + self.pending + .push_back(StagedSystemAudio { captured_at, value }); + let newest = captured_at; + while self.pending.len() > SYSTEM_AUDIO_STAGING_LIMIT + || self.pending.front().is_some_and(|chunk| { + newest.saturating_duration_since(chunk.captured_at) > self.max_hold + }) + { + self.pending.pop_front(); + } + true + } + + pub(crate) fn observe(&mut self, check: SystemAudioRouteCheck) -> Vec { + match check { + SystemAudioRouteCheck::NotOnMonitor => { + self.clear(); + Vec::new() + } + SystemAudioRouteCheck::OnMonitor { check_started } => { + let Some(proven_until) = self.proven_until else { + self.note_attached(check_started); + return Vec::new(); + }; + if check_started < proven_until { + return Vec::new(); + } + let mut released = Vec::new(); + while self + .pending + .front() + .is_some_and(|chunk| chunk.captured_at <= check_started) + { + released.push(self.pending.pop_front().expect("front").value); + } + 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(40); +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, + }, +} + +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 subscribe = Command::new("pactl") + let mut child = Command::new("pactl") .arg("subscribe") .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::null()) .spawn() .ok(); - if let Some(child) = subscribe.as_mut() - && let Some(stdout) = child.stdout.take() - { + 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 || { @@ -2553,21 +2682,51 @@ pub(crate) fn watch_system_audio_route( } }); } + (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; while !cancel.is_cancelled() { let current = route.lock().unwrap().as_ref().copied(); if let Some(current) = current && !cancel.is_cancelled() { + let check_started = Instant::now(); let (plan, monitor) = inspect_system_audio_source_output(current.source_output); let resolved = match plan { SystemAudioRoutePlan::Reattach => { - on_plan(current.stream_id, 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(()) => SystemAudioRoutePlan::Keep, + Ok(()) => { + let at = Instant::now(); + on_watch( + current.stream_id, + SystemAudioWatch::Reattached { at }, + ); + SystemAudioRoutePlan::Keep + } Err(error) => { if announced != Some(SystemAudioRoutePlan::Lost) { tracing::warn!( @@ -2575,14 +2734,39 @@ pub(crate) fn watch_system_audio_route( "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 => SystemAudioRoutePlan::Lost, + None => { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: SystemAudioRoutePlan::Lost, + check_started, + }, + ); + SystemAudioRoutePlan::Lost + } } } - other => other, + other => { + on_watch( + current.stream_id, + SystemAudioWatch::Checked { + plan: other, + check_started, + }, + ); + other + } }; if announced != Some(resolved) { match resolved { @@ -2602,17 +2786,35 @@ pub(crate) fn watch_system_audio_route( } announced = Some(resolved); } - if !cancel.is_cancelled() { - on_plan(current.stream_id, resolved); + } + if cancel.is_cancelled() { + break; + } + match wake_rx.recv_timeout(SYSTEM_AUDIO_ROUTE_POLL) { + Ok(()) | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + backoff = SYSTEM_AUDIO_SUBSCRIBE_RESTART; + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + 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(); } } - let _ = wake_rx.recv_timeout(Duration::from_millis(200)); } - if let Some(mut child) = subscribe { - let _ = child.kill(); - let _ = child.wait(); - } + 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 { @@ -3549,10 +3751,11 @@ fn x11_source_pixel( #[cfg(test)] mod system_audio_tests { use super::{ - OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, SystemAudioRoutePlan, - 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, + OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, SystemAudioRouteCheck, + SystemAudioRoutePlan, SystemAudioStaging, 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_watch_after_disconnect, source_output_needs_move, source_output_route_matches, started_input_source_output, uses_default_pulse_input, wait_for_audio_after_route, wait_for_started_source_output, }; @@ -3667,6 +3870,99 @@ mod system_audio_tests { ); } + #[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); + 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_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 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"; 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 index 9ce5e71c665..924a2596649 100644 --- 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 @@ -157,7 +157,7 @@ impl Drop for Tone { } } -fn sine_wav(path: &Path) { +fn sine_wav(path: &Path, frequency: u32) { let status = Command::new("ffmpeg") .args([ "-y", @@ -167,7 +167,7 @@ fn sine_wav(path: &Path) { "-f", "lavfi", "-i", - "sine=frequency=440:sample_rate=48000:duration=0.4", + &format!("sine=frequency={frequency}:sample_rate=48000:duration=0.4"), "-c:a", "pcm_s16le", &path.to_string_lossy(), @@ -177,6 +177,68 @@ fn sine_wav(path: &Path) { 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([ @@ -240,7 +302,7 @@ async fn unloading_a_null_monitor_ends_audio_only_and_keeps_the_mic() { let sink = NullSink::start("cap_loss_permanent"); let temp = tempfile::tempdir().unwrap(); let wav = temp.path().join("tone.wav"); - sine_wav(&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); @@ -293,11 +355,14 @@ async fn unloading_a_null_monitor_ends_audio_only_and_keeps_the_mic() { 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 wav = temp.path().join("tone.wav"); - sine_wav(&wav); - let mut tone = Tone::start(&sink.name, wav); + 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) @@ -305,8 +370,11 @@ async fn reloading_a_null_monitor_keeps_audio_only_running() { .build() .await .expect("audio-only recording did not start against the null sink"); - tokio::time::sleep(Duration::from_millis(400)).await; + 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(), @@ -317,6 +385,7 @@ async fn reloading_a_null_monitor_keeps_audio_only_running() { .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( From 8d69f788495275a331fc38c99a47bc87c307471d Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:37:01 +0000 Subject: [PATCH 04/12] fix: keep Linux system audio moving through startup and stop Route checks start when the system-audio stream starts, so the startup observer can receive a sample before Lock. Delayed chunks captured on a monitor stay queued for the next check, while audio from before a microphone reroute is still dropped. Stop waits for the held samples to reach the muxer before the feed is killed. The Linux-only capture epoch, route grace, and stop flag no longer fail Windows or macOS clippy. --- crates/recording/src/feeds/microphone.rs | 207 ++++++++++++++---- crates/recording/src/sources/microphone.rs | 51 ++++- .../src/sources/screen_capture/linux.rs | 158 +++++++++++-- 3 files changed, 345 insertions(+), 71 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index 0a9b021f3dd..f29e18904f0 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -180,6 +180,7 @@ pub struct MicrophoneSamples { pub channels: u16, pub info: InputCallbackInfo, pub timestamp: Timestamp, + #[cfg(target_os = "linux")] pub(crate) capture_epoch: u64, } @@ -520,7 +521,9 @@ fn release_staged_system_audio( SystemAudioWatch::Checked { plan: SystemAudioRoutePlan::Reattach | SystemAudioRoutePlan::Lost, .. - } => staging.observe(SystemAudioRouteCheck::NotOnMonitor), + } => staging.observe(SystemAudioRouteCheck::NotOnMonitor { + observed_at: Instant::now(), + }), SystemAudioWatch::Checked { plan: SystemAudioRoutePlan::Ignore, .. @@ -532,6 +535,114 @@ fn release_staged_system_audio( } } +#[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 || { + 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, sample); + } + }, + ); + }); + } +} + #[cfg(any(target_os = "linux", windows))] struct StreamHealth { id: u32, @@ -632,6 +743,7 @@ impl RecordingSourceHealthState { // 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")] @@ -1136,7 +1248,7 @@ pub struct MicrophoneFeed { >, >, #[cfg(target_os = "linux")] - route_watch_cancel: tokio_util::sync::CancellationToken, + route_watch: Arc, input_id_counter: u32, lock_generation: u64, state: State, @@ -1160,7 +1272,7 @@ impl Drop for MicrophoneFeed { #[cfg(target_os = "linux")] { self.system_stream_cancel.cancel(); - self.route_watch_cancel.cancel(); + self.route_watch.stop(); } } } @@ -1427,7 +1539,7 @@ impl MicrophoneFeed { #[cfg(target_os = "linux")] system_audio_staging: None, #[cfg(target_os = "linux")] - route_watch_cancel: tokio_util::sync::CancellationToken::new(), + route_watch: Arc::new(SystemAudioRouteWatch::new()), #[cfg(any(target_os = "linux", windows))] stream_health: std::collections::HashMap::new(), #[cfg(target_os = "linux")] @@ -1462,46 +1574,16 @@ impl MicrophoneFeed { } #[cfg(target_os = "linux")] - fn start_system_audio_route_watch(&mut self, actor: ActorRef) { - let Some(health) = self.recording_health.clone() else { - return; - }; + fn start_system_audio_route_watch(&self, actor: ActorRef) { let Some(staging) = self.system_audio_staging.clone() else { return; }; - self.route_watch_cancel.cancel(); - self.route_watch_cancel = tokio_util::sync::CancellationToken::new(); - let cancel = self.route_watch_cancel.clone(); - let route = self.system_capture_route.clone(); - let dropped = self.dropped_message_count.clone(); - let _ = std::thread::Builder::new() - .name("system-audio-route".into()) - .spawn(move || { - crate::sources::screen_capture::watch_system_audio_route( - cancel, - route, - move |stream_id, event| { - let released = release_staged_system_audio(&staging, event); - for sample in released { - enqueue_microphone_samples(&actor, &dropped, sample); - } - use crate::sources::screen_capture::{ - SystemAudioRoutePlan, SystemAudioWatch, - }; - match event { - SystemAudioWatch::Checked { plan, .. } => { - health.apply_system_audio_route(stream_id, plan); - } - SystemAudioWatch::Reattached { .. } => { - health.apply_system_audio_route( - stream_id, - SystemAudioRoutePlan::Keep, - ); - } - } - }, - ); - }); + 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)> { @@ -1601,6 +1683,8 @@ impl MicrophoneFeed { system_capture_route, #[cfg(target_os = "linux")] system_audio_staging, + #[cfg(target_os = "linux")] + route_watch, id, label, settings, @@ -1748,6 +1832,8 @@ impl MicrophoneFeed { 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; move |data, info| { #[cfg(target_os = "linux")] @@ -1826,8 +1912,6 @@ impl MicrophoneFeed { .unwrap_or(callback_received); #[cfg(not(target_os = "linux"))] let captured_at = Instant::now(); - #[cfg(not(target_os = "linux"))] - let capture_epoch = 0; #[cfg(windows)] let timestamp = capture_clock.timestamp( timestamp, @@ -1845,6 +1929,7 @@ impl MicrophoneFeed { channels: callback_channels, info: info.clone(), timestamp: timestamp - capture_latency, + #[cfg(target_os = "linux")] capture_epoch, }; @@ -1944,8 +2029,18 @@ impl MicrophoneFeed { stream_id: id, source_output, }); - if let Some(staging) = &system_audio_staging { + 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. + route_watch.ensure_started( + actor_ref.clone(), + staging, + system_capture_route.clone(), + dropped_message_count.clone(), + ); } } Ok(_) => {} @@ -2223,7 +2318,9 @@ impl SystemAudioHold { let check = if on_monitor { SystemAudioRouteCheck::OnMonitor { check_started } } else { - SystemAudioRouteCheck::NotOnMonitor + SystemAudioRouteCheck::NotOnMonitor { + observed_at: Instant::now(), + } }; self.staging.lock().unwrap().observe(check) } @@ -2501,6 +2598,8 @@ struct StreamSpawnParams { std::sync::Mutex>, >, >, + #[cfg(target_os = "linux")] + route_watch: Arc, id: u32, label: String, settings: Option, @@ -2598,6 +2697,8 @@ impl MicrophoneFeed { 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, @@ -2738,6 +2839,8 @@ impl MicrophoneFeed { 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, @@ -2869,6 +2972,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() { @@ -3234,6 +3345,7 @@ impl Message for MicrophoneFeed { 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, @@ -3616,7 +3728,7 @@ 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_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 { @@ -3747,6 +3859,7 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] capture_epoch: 0, }) .await; @@ -3772,6 +3885,7 @@ pub mod synthetic { channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] capture_epoch: 0, }) .await; @@ -3791,6 +3905,7 @@ pub mod synthetic { channels: self.channels, info: zero_callback_info(), timestamp, + #[cfg(target_os = "linux")] capture_epoch: 0, }) .try_send(), diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index b1e2f060bc8..76c1db880c3 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -29,6 +29,8 @@ const MIC_RECONNECT_BACKOFF_MAX: Duration = Duration::from_secs(30); // 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")] #[derive(Clone, Copy)] @@ -204,6 +206,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. @@ -249,6 +253,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>, @@ -617,7 +636,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(); @@ -654,7 +673,10 @@ 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; + #[cfg(target_os = "linux")] let mut system_stop_flushed = false; + #[cfg(not(target_os = "linux"))] + let system_stop_flushed = false; loop { #[cfg(windows)] @@ -1223,6 +1245,8 @@ impl Microphone { #[cfg(windows)] drop(setup_cancel.disarm()); + #[cfg(not(target_os = "linux"))] + drop(capture_task); Ok(Self { #[cfg(windows)] capture_scope, @@ -1230,6 +1254,8 @@ impl Microphone { _binding: binding, #[cfg(target_os = "linux")] required_health, + #[cfg(target_os = "linux")] + capture_task: Some(capture_task), cancel, }) }; @@ -1281,11 +1307,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(()) @@ -1402,6 +1432,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)); diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index b7d155a7d08..e82b2865ddc 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -1904,6 +1904,8 @@ impl AudioSource for SystemAudioSource { 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; @@ -2520,16 +2522,20 @@ fn inspect_system_audio_source_output( } // Samples stay here until a later source read still sees a sink monitor. -// A read that sees anything else drops every sample not yet released, -// including audio captured on the monitor in the moment before the move. -// Releasing that audio would write the microphone into the system track. +// `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, + NotOnMonitor { observed_at: Instant }, } struct StagedSystemAudio { @@ -2540,6 +2546,7 @@ struct StagedSystemAudio { pub(crate) struct SystemAudioStaging { pending: std::collections::VecDeque>, proven_until: Option, + unsafe_cutoff: Option, max_hold: Duration, } @@ -2548,6 +2555,7 @@ impl SystemAudioStaging { Self { pending: std::collections::VecDeque::new(), proven_until: None, + unsafe_cutoff: None, max_hold, } } @@ -2555,54 +2563,95 @@ impl SystemAudioStaging { 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.pending.retain(|chunk| chunk.captured_at > at); + self.mark_unsafe(at); self.proven_until = Some(at); } pub(crate) fn push(&mut self, captured_at: Instant, value: T) -> bool { - if self.proven_until.is_some_and(|until| captured_at <= until) { + if self + .unsafe_cutoff + .is_some_and(|cutoff| captured_at <= cutoff) + { return false; } self.pending .push_back(StagedSystemAudio { captured_at, value }); - let newest = captured_at; - while self.pending.len() > SYSTEM_AUDIO_STAGING_LIMIT - || self.pending.front().is_some_and(|chunk| { - newest.saturating_duration_since(chunk.captured_at) > self.max_hold - }) - { - self.pending.pop_front(); - } + 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 => { - self.clear(); + SystemAudioRouteCheck::NotOnMonitor { observed_at } => { + self.mark_unsafe(observed_at); Vec::new() } SystemAudioRouteCheck::OnMonitor { check_started } => { let Some(proven_until) = self.proven_until else { - self.note_attached(check_started); + 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(); - while self - .pending - .front() - .is_some_and(|chunk| chunk.captured_at <= check_started) - { - released.push(self.pending.pop_front().expect("front").value); + 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 } @@ -3878,7 +3927,9 @@ mod system_audio_tests { assert!(staging.push(started + Duration::from_millis(10), "monitor")); assert!(staging.push(started + Duration::from_millis(20), "microphone")); - let released = staging.observe(SystemAudioRouteCheck::NotOnMonitor); + let released = staging.observe(SystemAudioRouteCheck::NotOnMonitor { + observed_at: started + Duration::from_millis(25), + }); assert!(released.is_empty()); assert_eq!(staging.pending_len(), 0); @@ -3894,6 +3945,65 @@ mod system_audio_tests { ); } + #[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(); From 9b21df328923779e71e3f962f680e755447ddf83 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:34:13 +0000 Subject: [PATCH 05/12] fix: confirm a named Linux monitor before startup waits A monitor device cpal lists by name never builds a PulseInputRoute, so its staged samples were never released and system-audio startup timed out. Snapshot that source output and start the route watcher before the stream is reported ready. --- crates/recording/src/feeds/microphone.rs | 116 +++++++++++++----- .../src/sources/screen_capture/linux.rs | 101 +++++++++++++-- 2 files changed, 181 insertions(+), 36 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index 6d0c276bda5..fc3d0813319 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -1984,6 +1984,37 @@ 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, + }; + match ( + system_audio_startup_attach(pulse_input_role, input_route.is_some()), + 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, + } + }; if setup_cancel.is_cancelled() || ready_tx.is_canceled() { return; @@ -2212,37 +2243,64 @@ impl MicrophoneFeed { } #[cfg(target_os = "linux")] - if let Some(route) = input_route { - match route.apply(&input_callback_observed, &system_stream_cancel) { - Ok(source_output) - if pulse_input_role - == crate::sources::screen_capture::PulseInputRole::SystemAudio => - { - *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. - route_watch.ensure_started( - actor_ref.clone(), - staging, - system_capture_route.clone(), - dropped_message_count.clone(), - ); + { + 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, + ) == 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; + } } } - Ok(_) => {} - Err(error) => { - let _ = ready_tx.send(Err(SetInputError::BuildStream(format!( - "Could not confirm the Linux audio input route: {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(), + ); } } } diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 3bb040fd52e..95ebbebd791 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -1960,6 +1960,59 @@ 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, +} + +pub(crate) fn system_audio_startup_attach( + role: PulseInputRole, + prepared_route: bool, +) -> Option { + if role != PulseInputRole::SystemAudio { + return None; + } + Some(if prepared_route { + SystemAudioStartupAttach::FollowPreparedRoute + } else { + SystemAudioStartupAttach::WatchDirectOutput + }) +} + +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. /// @@ -3953,13 +4006,14 @@ fn x11_source_pixel( mod system_audio_tests { use super::{ OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, SystemAudioRouteCheck, - SystemAudioRoutePlan, SystemAudioStaging, 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_watch_after_disconnect, - routes_default_microphone_through_server, source_output_needs_move, - source_output_route_matches, started_input_source_output, uses_default_pulse_input, - wait_for_audio_after_route, wait_for_started_source_output, + 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_watch_after_disconnect, 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; @@ -4612,6 +4666,39 @@ mod system_audio_tests { } } + #[test] + fn named_monitor_input_watches_its_own_output_before_ready() { + assert_eq!( + system_audio_startup_attach(PulseInputRole::SystemAudio, false), + Some(SystemAudioStartupAttach::WatchDirectOutput) + ); + assert_eq!( + system_audio_startup_attach(PulseInputRole::SystemAudio, true), + Some(SystemAudioStartupAttach::FollowPreparedRoute) + ); + assert_eq!( + system_audio_startup_attach(PulseInputRole::Microphone, false), + 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")); From fa152bfd83bccd6824cc510338f720356dfd68b8 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:47:28 +0000 Subject: [PATCH 06/12] fix: stop waiting the full flush timeout when Linux system audio stops --- crates/recording/src/sources/microphone.rs | 27 ++++++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index 90272abdd26..e4e9439a80e 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -31,6 +31,8 @@ const MIC_RECONNECT_BACKOFF_MAX: Duration = Duration::from_secs(30); 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); #[cfg(target_os = "linux")] #[derive(Clone, Copy)] @@ -676,10 +678,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_flushed = false; + let mut system_stop_drain_until: Option< + tokio::time::Instant, + > = None; #[cfg(not(target_os = "linux"))] - let system_stop_flushed = false; + let system_stop_drain_until: Option = None; loop { #[cfg(windows)] @@ -694,13 +702,20 @@ 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(), if !system_stop_flushed => { + _ = cancel.cancelled(), if system_stop_drain_until.is_none() => { #[cfg(target_os = "linux")] if feed_lock.has_system_audio_hold() { - system_stop_flushed = true; feed_lock.flush_confirmed_system_audio().await; + system_stop_drain_until = Some( + tokio::time::Instant::now() + SYSTEM_AUDIO_STOP_DRAIN, + ); continue; } break; @@ -796,7 +811,9 @@ impl Microphone { continue; } r = tokio::time::timeout(silence_timeout, rx.recv_async()) => r, - _ = tokio::time::sleep(Duration::from_millis(50)), if system_stop_flushed => break, + _ = tokio::time::sleep_until( + system_stop_drain_until.unwrap_or_else(tokio::time::Instant::now), + ), if system_stop_drain_until.is_some() => break, }; match recv_result { Ok(Ok(frame)) => { From c62f176b87cb654ba4af4fcd321c27688ba83c10 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:47:44 +0000 Subject: [PATCH 07/12] perf: prove the Linux system-audio route from pactl subscribe instead of polling --- .../src/sources/screen_capture/linux.rs | 142 ++++++++++++++++-- 1 file changed, 133 insertions(+), 9 deletions(-) diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 2d0daa9538d..3a8b581ca4e 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -2870,7 +2870,13 @@ impl SystemAudioStaging { } } -pub(crate) const SYSTEM_AUDIO_ROUTE_POLL: Duration = Duration::from_millis(40); +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); @@ -2898,6 +2904,41 @@ pub(crate) enum SystemAudioWatch { }, } +#[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() { @@ -2929,7 +2970,7 @@ fn spawn_route_subscribe() -> (std::sync::mpsc::Receiver<()>, Option break, Ok(_) => { - if wake_tx.send(()).is_err() { + if route_event_is_relevant(&line) && wake_tx.send(()).is_err() { break; } } @@ -2955,12 +2996,37 @@ pub(crate) fn watch_system_audio_route( 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 => { @@ -3046,10 +3112,17 @@ pub(crate) fn watch_system_audio_route( break; } match wake_rx.recv_timeout(SYSTEM_AUDIO_ROUTE_POLL) { - Ok(()) | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + 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); @@ -4022,15 +4095,15 @@ fn x11_source_pixel( #[cfg(test)] mod system_audio_tests { use super::{ - OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, SystemAudioRouteCheck, - SystemAudioRoutePlan, SystemAudioStaging, SystemAudioStartupAttach, + 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_watch_after_disconnect, 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, + 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; @@ -4274,6 +4347,57 @@ mod system_audio_tests { 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); From 291d746a144d4532ce0ba84835b93c8370c2a75b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:11:37 +0000 Subject: [PATCH 08/12] fix: keep the stop drain deadline lint-clean on every platform --- crates/recording/src/sources/microphone.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index e4e9439a80e..c3b4f802f40 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -34,6 +34,10 @@ 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 { @@ -811,9 +815,8 @@ impl Microphone { continue; } r = tokio::time::timeout(silence_timeout, rx.recv_async()) => r, - _ = tokio::time::sleep_until( - system_stop_drain_until.unwrap_or_else(tokio::time::Instant::now), - ), if system_stop_drain_until.is_some() => break, + _ = 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)) => { From 735c09ea94d31ca2a65066ca2cb559ae45afe69c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:11:37 +0000 Subject: [PATCH 09/12] test: expect a lost system-audio device to be reported at Stop --- crates/recording/src/feeds/microphone.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index 9e70d9a4480..2f84f06c019 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -5111,7 +5111,7 @@ mod tests { #[cfg(target_os = "linux")] #[tokio::test] - async fn lost_system_audio_device_sets_terminal_health() { + 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()); @@ -5124,9 +5124,16 @@ mod tests { .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_some(), - "reconnect error {error} left system audio healthy" + health.terminal_error().is_none(), + "a device that is gone records silence instead of failing the take" ); actor.kill(); actor.wait_for_stop().await; From 27a546337324ab9afeded0c0a9d88c6ddaa55b27 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:17:31 +0000 Subject: [PATCH 10/12] fix: record direct ALSA loopback system audio without waiting for a Pulse stream --- crates/recording/src/feeds/microphone.rs | 16 +++++++++- .../src/sources/screen_capture/linux.rs | 31 ++++++++++++++----- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs index 2f84f06c019..67194a2b467 100644 --- a/crates/recording/src/feeds/microphone.rs +++ b/crates/recording/src/feeds/microphone.rs @@ -2272,8 +2272,16 @@ impl MicrophoneFeed { 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()), + system_audio_startup_attach( + pulse_input_role, + input_route.is_some(), + direct_through_pulse, + ), input_route, ) { (Some(SystemAudioStartupAttach::WatchDirectOutput), _) => { @@ -2291,6 +2299,11 @@ impl MicrophoneFeed { (_, 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; @@ -2528,6 +2541,7 @@ impl MicrophoneFeed { if crate::sources::screen_capture::system_audio_startup_attach( pulse_input_role, true, + false, ) == Some(SystemAudioStartupAttach::FollowPreparedRoute) => { Some(source_output) diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 3a8b581ca4e..3abfa79c2be 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -1973,18 +1973,30 @@ pub(crate) enum SystemAudioStartupAttach { 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; } - Some(if prepared_route { - SystemAudioStartupAttach::FollowPreparedRoute + if prepared_route { + Some(SystemAudioStartupAttach::FollowPreparedRoute) + } else if direct_through_pulse { + Some(SystemAudioStartupAttach::WatchDirectOutput) } else { - SystemAudioStartupAttach::WatchDirectOutput - }) + 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 { @@ -4831,15 +4843,20 @@ mod system_audio_tests { #[test] fn named_monitor_input_watches_its_own_output_before_ready() { assert_eq!( - system_audio_startup_attach(PulseInputRole::SystemAudio, false), + system_audio_startup_attach(PulseInputRole::SystemAudio, false, true), Some(SystemAudioStartupAttach::WatchDirectOutput) ); assert_eq!( - system_audio_startup_attach(PulseInputRole::SystemAudio, true), + system_audio_startup_attach(PulseInputRole::SystemAudio, true, false), Some(SystemAudioStartupAttach::FollowPreparedRoute) ); assert_eq!( - system_audio_startup_attach(PulseInputRole::Microphone, false), + 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( From b68bc443c2da6e9f02006f5516abba41127c2031 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:17:32 +0000 Subject: [PATCH 11/12] fix: hand held Linux system audio to the track before its final drain --- crates/recording/src/output_pipeline/core.rs | 78 +++++++++++++++++++ crates/recording/src/sources/microphone.rs | 21 +++++ .../src/sources/screen_capture/linux.rs | 4 + 3 files changed, 103 insertions(+) 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 c3b4f802f40..ce2777bbc77 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -1316,6 +1316,27 @@ impl AudioSource for Microphone { self.info } + fn finish_capture(&mut self) -> impl Future + Send { + // 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 capture_task = self + ._binding + .lock() + .unwrap() + .lock + .has_system_audio_hold() + .then(|| { + self.cancel.cancel(); + self.capture_task.take() + }) + .flatten(); + async move { + #[cfg(target_os = "linux")] + await_capture_stop(capture_task).await; + } + } + fn stop(&mut self) -> impl Future> + Send { #[cfg(target_os = "linux")] if let Some(health) = &self.required_health { diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 3abfa79c2be..335186b0873 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -2119,6 +2119,10 @@ 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. From 40ca328d914697693edbd8236cab80dd1fc73fca Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:45:42 +0000 Subject: [PATCH 12/12] fix: write the microphone finish_capture hook as an async fn --- crates/recording/src/sources/microphone.rs | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs index ce2777bbc77..3a5a1b022e4 100644 --- a/crates/recording/src/sources/microphone.rs +++ b/crates/recording/src/sources/microphone.rs @@ -1316,24 +1316,16 @@ impl AudioSource for Microphone { self.info } - fn finish_capture(&mut self) -> impl Future + Send { + 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 capture_task = self - ._binding - .lock() - .unwrap() - .lock - .has_system_audio_hold() - .then(|| { + { + let holds_system_audio = self._binding.lock().unwrap().lock.has_system_audio_hold(); + if holds_system_audio { self.cancel.cancel(); - self.capture_task.take() - }) - .flatten(); - async move { - #[cfg(target_os = "linux")] - await_capture_stop(capture_task).await; + await_capture_stop(self.capture_task.take()).await; + } } }