use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use futures_util::{FutureExt, StreamExt}; use libwebrtc::audio_source::native::NativeAudioSource; use libwebrtc::audio_stream::native::NativeAudioStream; use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; use libwebrtc::prelude::*; use tokio::task::JoinHandle; use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator}; use crate::audio_io::AudioMode; use crate::capture::Capture; use crate::devices::DeviceChoice; use crate::error::{Error, Result}; use crate::mic_chain::MicChain; use crate::mic_processing::{ApmConfig, MicSettings}; use crate::mixer::mix_frames; use crate::pcm::SampleQueue; use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone}; use crate::wav_dump::StageDumps; use crate::win_timer::HighResSleep; /// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime. const SOURCE_QUEUE_MS: u32 = 0; const FRAME_PERIOD: Duration = Duration::from_millis(10); const MAX_LAG: Duration = Duration::from_millis(100); const SYSTEM_TONE_HZ: f32 = 660.0; const SYNTHETIC_AMPLITUDE: f32 = 0.3; enum FrameSource { Captured(SampleQueue), Tone(SineGenerator), Silence, } impl FrameSource { fn next_frame(&mut self) -> Option> { match self { FrameSource::Captured(queue) => queue.next_frame(), FrameSource::Tone(generator) => Some(generator.next_frame()), FrameSource::Silence => Some(vec![0; FRAME_SAMPLES]), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SoftwareAudioPlan { pub processing: ApmConfig, pub ml_noise: bool, pub computer_sound: bool, } struct Feeder { processing: ApmConfig, ml_noise: bool, source: NativeAudioSource, microphone: FrameSource, computer: FrameSource, far_end: SampleQueue, microphone_muted: Arc, running: Arc, } impl Feeder { fn run(mut self) { let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env()); let sleeper = HighResSleep::new(); let mut due = Instant::now(); while self.running.load(Ordering::SeqCst) { due += FRAME_PERIOD; let now = Instant::now(); if due > now { sleeper.sleep(due - now); } else if now - due > MAX_LAG { due = now; } if let Some(mut far_end) = self.far_end.next_frame() { chain.process_far_end(&mut far_end); } let muted = self.microphone_muted.load(Ordering::SeqCst); let captured = self.microphone.next_frame().or_else(|| { // Small 2 ms cushion for WASAPI/CPAL callback cadence jitter before emitting silence. sleeper.sleep(Duration::from_millis(2)); self.microphone.next_frame() }); let microphone = match captured { Some(mut frame) if !muted => { chain.process(&mut frame); frame } Some(frame) => frame, // Underrun: send silence without feeding AEC/gain a zero-padded partial. None => vec![0; FRAME_SAMPLES], }; let computer = self .computer .next_frame() .unwrap_or_else(|| vec![0; FRAME_SAMPLES]); let frame = AudioFrame { data: mix_frames(µphone, &computer, muted).into(), sample_rate: SAMPLE_RATE, num_channels: 1, samples_per_channel: FRAME_SAMPLES as u32, }; match self.source.capture_frame(&frame).now_or_never() { Some(Ok(())) => {} Some(Err(_)) | None => break, } } } } const DEFAULT_MICROPHONE_NOTICE: &str = "The picked microphone could not be captured while sharing sound, using the default one"; const NO_MICROPHONE_NOTICE: &str = "The microphone could not be captured while sharing sound, others cannot hear you"; /// Mic through our own processing, plus computer sound when planned, as one track that replaces the device track. pub struct SoftwareAudio { pub track: RtcAudioTrack, pub plan: SoftwareAudioPlan, pub loopback: Option, pub warning: Option, pub microphone_source: Option, pub microphone_notice: Option<&'static str>, microphone_muted: Arc, running: Arc, feeder: Option>, far_end_task: Option>, _captures: Vec, } impl SoftwareAudioPlan { pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option { Self::wanted_on(mic, sharing_sound, uses_devices) } pub fn wanted_on(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option { (sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan { processing: mic.apm_config(), ml_noise: mic.ml_noise_suppression(), computer_sound: sharing_sound, }) } } impl SoftwareAudio { pub fn start( factory: &PeerConnectionFactory, mode: AudioMode, tone_hz: f32, input: &DeviceChoice, plan: SoftwareAudioPlan, microphone_muted: bool, remote: Option, ) -> Result { let mut captures = Vec::new(); let mut warning = None; let mut microphone_source = None; let mut microphone_notice = None; let (microphone, computer, loopback) = if mode == AudioMode::Platform { let computer_queue = SampleQueue::default(); let (computer, loopback) = if plan.computer_sound { let started = start_loopback(computer_queue.clone())?; captures.push(started.capture); warning = started.warning; (FrameSource::Captured(computer_queue), Some(started.kind)) } else { (FrameSource::Silence, None) }; let microphone_queue = SampleQueue::default(); let label = crate::devices::input_label(factory, input); let microphone = match start_microphone(input, label.as_deref(), microphone_queue.clone()) { Ok(started) => { microphone_source = Some(started.source); captures.push(started.capture); FrameSource::Captured(microphone_queue) } Err(error) => { if !plan.computer_sound { return Err(error); } let fallback_queue = SampleQueue::default(); let fallback = (input != &DeviceChoice::SystemDefault) .then(|| { start_microphone( &DeviceChoice::SystemDefault, None, fallback_queue.clone(), ) .ok() }) .flatten(); match fallback { Some(started) => { microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE); microphone_source = Some(format!("{}, picked one failed: {error}", started.source)); captures.push(started.capture); FrameSource::Captured(fallback_queue) } None => { microphone_notice = Some(NO_MICROPHONE_NOTICE); warning.get_or_insert(format!( "microphone not captured while sharing sound: {error}" )); FrameSource::Silence } } } }; (microphone, computer, loopback) } else { let microphone = if mode == AudioMode::Tone { FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE)) } else { FrameSource::Silence }; let computer = if plan.computer_sound { FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE)) } else { FrameSource::Silence }; ( microphone, computer, plan.computer_sound.then_some(LoopbackKind::Synthetic), ) }; let source = NativeAudioSource::new( AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS, ); let track = factory.create_audio_track("microphone", source.clone()); let far_end = SampleQueue::default(); let running = Arc::new(AtomicBool::new(true)); let far_end_task = remote .map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone()))); let microphone_muted = Arc::new(AtomicBool::new(microphone_muted)); let feeder = Feeder { processing: plan.processing, ml_noise: plan.ml_noise, source, microphone, computer, far_end, microphone_muted: microphone_muted.clone(), running: running.clone(), }; let thread = std::thread::Builder::new() .name("share-audio".into()) .spawn(move || feeder.run()) .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?; Ok(SoftwareAudio { track, plan, loopback, warning, microphone_source, microphone_notice, microphone_muted, running, feeder: Some(thread), far_end_task, _captures: captures, }) } pub fn set_microphone_muted(&self, muted: bool) { self.microphone_muted.store(muted, Ordering::SeqCst); } } impl Drop for SoftwareAudio { fn drop(&mut self) { // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a // drained queue; aborting the far-end mid-OnData raced with remove_sink. self.running.store(false, Ordering::SeqCst); drop(self.far_end_task.take()); drop(self.feeder.take()); } } async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc) { let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1); while running.load(Ordering::SeqCst) { tokio::select! { biased; _ = wait_stopped(&running) => break, frame = stream.next() => match frame { Some(frame) => queue.push(&frame.data), None => break, } } } stream.close(); } async fn wait_stopped(running: &AtomicBool) { while running.load(Ordering::SeqCst) { tokio::time::sleep(Duration::from_millis(10)).await; } } #[cfg(test)] mod tests { use super::*; use crate::devices::shared_factory; use crate::mic_processing::NoiseSuppression; #[tokio::test(flavor = "multi_thread")] async fn synthetic_sources_start_and_stop_cleanly() { let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: true, }; let audio = SoftwareAudio::start( &shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None, ) .unwrap(); assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic)); assert!(audio.warning.is_none()); audio.set_microphone_muted(false); tokio::time::sleep(Duration::from_millis(60)).await; drop(audio); } #[test] fn default_settings_use_the_device_track_on_all_platforms() { let default = MicSettings::default(); assert!(SoftwareAudioPlan::wanted_on(default, false, true).is_none()); let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false, }; assert!(SoftwareAudioPlan::wanted_on(low, false, true).is_none()); } #[test] fn the_plan_follows_sharing_and_the_mic_choice() { let auto = MicSettings::default(); let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false, }; let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false, }; assert_eq!(SoftwareAudioPlan::wanted_on(low, false, true), None); assert_eq!(SoftwareAudioPlan::wanted_on(off, false, false), None); let mic_only = SoftwareAudioPlan::wanted_on(off, false, true).unwrap(); assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough()); let sharing = SoftwareAudioPlan::wanted_on(auto, true, false).unwrap(); assert!(sharing.computer_sound && sharing.processing.echo_canceller); } #[test] fn windows_uses_software_path_only_when_not_on_device_track() { for noise_suppression in NoiseSuppression::ALL { for music_mode in [false, true] { let mic = MicSettings { noise_suppression, music_mode, }; assert_eq!( SoftwareAudioPlan::wanted_on(mic, false, true).is_some(), !mic.uses_device_track() ); assert!(SoftwareAudioPlan::wanted_on(mic, false, false).is_none()); } } } #[test] fn rnnoise_runs_in_the_software_path_only_for_auto() { let ml_noise = |noise_suppression, music_mode| { SoftwareAudioPlan::wanted_on( MicSettings { noise_suppression, music_mode, }, true, true, ) .unwrap() .ml_noise }; assert!(ml_noise(NoiseSuppression::Auto, false)); assert!(!ml_noise(NoiseSuppression::Low, false)); assert!(!ml_noise(NoiseSuppression::Off, false)); assert!(!ml_noise(NoiseSuppression::Auto, true)); } #[tokio::test(flavor = "multi_thread")] async fn a_microphone_only_plan_has_no_computer_sound() { let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: false, }; let audio = SoftwareAudio::start( &shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None, ) .unwrap(); assert_eq!(audio.loopback, None); tokio::time::sleep(Duration::from_millis(60)).await; drop(audio); } }