//! Output capture that falls back from per-process to device loopback. //! //! Application loopback (`OutputTarget::Process`) needs Windows 10 2004+ and //! a live process; if it cannot be opened, the call is still worth recording //! from the default output. [`crate::Recorder`] keeps a failed track running //! as silence instead of retrying, so the retry happens here, inside //! `start`. use std::sync::{Arc, Mutex, PoisonError}; use recorder_core::capture::{ CaptureError, CaptureSource, DataCallback, OutputTarget, StreamFormat, }; /// Creates the platform source for one output target. pub(crate) type Factory = fn(OutputTarget) -> Box; /// Tries `target`, and if that is a `Process` target that fails to start, /// `DefaultRender`. `stop` and `failure` act on whichever source started. pub(crate) struct FallbackSource { target: OutputTarget, factory: Factory, active: Option>, } impl FallbackSource { pub(crate) fn new(target: OutputTarget, factory: Factory) -> Self { Self { target, factory, active: None, } } } impl CaptureSource for FallbackSource { fn start(&mut self, on_data: DataCallback) -> Result { self.stop(); // A failed start consumes the callback it was given, so each attempt // gets a forwarder to the one shared callback. let on_data = Arc::new(Mutex::new(on_data)); let forward = |on_data: &Arc>| -> DataCallback { let on_data = Arc::clone(on_data); Box::new(move |samples| { (on_data.lock().unwrap_or_else(PoisonError::into_inner))(samples) }) }; let mut source = (self.factory)(self.target.clone()); let format = match source.start(forward(&on_data)) { Ok(format) => { log::info!("output target {:?} started", self.target); format } Err(err) => { let OutputTarget::Process { root_pid } = self.target else { return Err(err); }; log::warn!( "process loopback for pid {root_pid} failed ({err}), \ falling back to DefaultRender" ); source = (self.factory)(OutputTarget::DefaultRender); source.start(forward(&on_data))? } }; self.active = Some(source); Ok(format) } fn stop(&mut self) { if let Some(mut source) = self.active.take() { source.stop(); } } fn failure(&self) -> Option { self.active.as_ref().and_then(|source| source.failure()) } } #[cfg(test)] mod tests { use super::*; const FORMAT: StreamFormat = StreamFormat { rate: 48_000, channels: 2, }; /// Per-test record of what the fake sources saw. Tests run in parallel, /// so each test gets its own log via a thread-local. #[derive(Default)] struct Log { started: Vec, stopped: Vec, delivered: Vec, } thread_local! { static LOG: Arc> = Arc::new(Mutex::new(Log::default())); } fn log() -> Arc> { LOG.with(Arc::clone) } /// Fails to start for `Process` targets whose pid is 0 and for /// `Device("broken")`; otherwise delivers one sample (the call count) /// synchronously from `start` and reports a failure for /// `Device("dying")`. struct FakeOutput { target: OutputTarget, log: Arc>, started: bool, } fn fake(target: OutputTarget) -> Box { Box::new(FakeOutput { target, log: log(), started: false, }) } impl CaptureSource for FakeOutput { fn start(&mut self, mut on_data: DataCallback) -> Result { self.log.lock().unwrap().started.push(self.target.clone()); match &self.target { OutputTarget::Process { root_pid: 0 } => { return Err(CaptureError::Backend("no such process".into())) } OutputTarget::Device(id) if id == "broken" => { return Err(CaptureError::DeviceNotFound(id.clone())) } _ => {} } self.started = true; on_data(&[1.0]); Ok(FORMAT) } fn stop(&mut self) { if std::mem::take(&mut self.started) { self.log.lock().unwrap().stopped.push(self.target.clone()); } } fn failure(&self) -> Option { (self.started && self.target == OutputTarget::Device("dying".into())) .then(|| "device lost".to_string()) } } fn collecting_callback() -> DataCallback { let log = log(); Box::new(move |samples| log.lock().unwrap().delivered.extend_from_slice(samples)) } #[test] fn a_working_process_target_is_used_as_is() { let mut source = FallbackSource::new(OutputTarget::Process { root_pid: 42 }, fake); assert_eq!(source.start(collecting_callback()).unwrap(), FORMAT); source.stop(); let log = log(); let log = log.lock().unwrap(); assert_eq!(log.started, vec![OutputTarget::Process { root_pid: 42 }]); assert_eq!(log.stopped, vec![OutputTarget::Process { root_pid: 42 }]); assert_eq!(log.delivered, vec![1.0]); } #[test] fn a_failing_process_target_falls_back_to_default_render() { let mut source = FallbackSource::new(OutputTarget::Process { root_pid: 0 }, fake); assert_eq!(source.start(collecting_callback()).unwrap(), FORMAT); assert_eq!(source.failure(), None); source.stop(); let log = log(); let log = log.lock().unwrap(); assert_eq!( log.started, vec![ OutputTarget::Process { root_pid: 0 }, OutputTarget::DefaultRender ] ); assert_eq!(log.stopped, vec![OutputTarget::DefaultRender]); // The callback survives the failed first attempt. assert_eq!(log.delivered, vec![1.0]); } #[test] fn other_targets_do_not_fall_back() { let mut source = FallbackSource::new(OutputTarget::Device("broken".into()), fake); assert!(matches!( source.start(collecting_callback()), Err(CaptureError::DeviceNotFound(_)) )); assert_eq!( log().lock().unwrap().started, vec![OutputTarget::Device("broken".into())] ); } #[test] fn failure_and_stop_act_on_the_started_source() { let mut source = FallbackSource::new(OutputTarget::Device("dying".into()), fake); assert_eq!(source.failure(), None); source.start(collecting_callback()).unwrap(); assert_eq!(source.failure().as_deref(), Some("device lost")); source.stop(); assert_eq!(source.failure(), None); source.stop(); assert_eq!(log().lock().unwrap().stopped.len(), 1); } }