| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use futures_util::{FutureExt, StreamExt}; |
| 6 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 7 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 8 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 9 | use libwebrtc::prelude::*; |
| 10 | use tokio::task::JoinHandle; |
| 11 | |
| 12 | use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator}; |
| 13 | use crate::audio_io::AudioMode; |
| 14 | use crate::capture::Capture; |
| 15 | use crate::devices::DeviceChoice; |
| 16 | use crate::error::{Error, Result}; |
| 17 | use crate::mic_chain::MicChain; |
| 18 | use crate::mic_processing::{ApmConfig, MicSettings}; |
| 19 | use crate::mixer::mix_frames; |
| 20 | use crate::pcm::SampleQueue; |
| 21 | use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone}; |
| 22 | use crate::wav_dump::StageDumps; |
| 23 | use crate::win_timer::HighResSleep; |
| 24 | |
| 25 | /// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime. |
| 26 | const SOURCE_QUEUE_MS: u32 = 0; |
| 27 | const FRAME_PERIOD: Duration = Duration::from_millis(10); |
| 28 | const MAX_LAG: Duration = Duration::from_millis(100); |
| 29 | const SYSTEM_TONE_HZ: f32 = 660.0; |
| 30 | const SYNTHETIC_AMPLITUDE: f32 = 0.3; |
| 31 | |
| 32 | enum FrameSource { |
| 33 | Captured(SampleQueue), |
| 34 | Tone(SineGenerator), |
| 35 | Silence, |
| 36 | } |
| 37 | |
| 38 | impl FrameSource { |
| 39 | fn next_frame(&mut self) -> Option<Vec<i16>> { |
| 40 | match self { |
| 41 | FrameSource::Captured(queue) => queue.next_frame(), |
| 42 | FrameSource::Tone(generator) => Some(generator.next_frame()), |
| 43 | FrameSource::Silence => Some(vec![0; FRAME_SAMPLES]), |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 49 | pub struct SoftwareAudioPlan { |
| 50 | pub processing: ApmConfig, |
| 51 | pub ml_noise: bool, |
| 52 | pub computer_sound: bool, |
| 53 | } |
| 54 | |
| 55 | struct Feeder { |
| 56 | processing: ApmConfig, |
| 57 | ml_noise: bool, |
| 58 | source: NativeAudioSource, |
| 59 | microphone: FrameSource, |
| 60 | computer: FrameSource, |
| 61 | far_end: SampleQueue, |
| 62 | microphone_muted: Arc<AtomicBool>, |
| 63 | running: Arc<AtomicBool>, |
| 64 | } |
| 65 | |
| 66 | impl Feeder { |
| 67 | fn run(mut self) { |
| 68 | let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env()); |
| 69 | let sleeper = HighResSleep::new(); |
| 70 | let mut due = Instant::now(); |
| 71 | while self.running.load(Ordering::SeqCst) { |
| 72 | due += FRAME_PERIOD; |
| 73 | let now = Instant::now(); |
| 74 | if due > now { |
| 75 | sleeper.sleep(due - now); |
| 76 | } else if now - due > MAX_LAG { |
| 77 | due = now; |
| 78 | } |
| 79 | if let Some(mut far_end) = self.far_end.next_frame() { |
| 80 | chain.process_far_end(&mut far_end); |
| 81 | } |
| 82 | let muted = self.microphone_muted.load(Ordering::SeqCst); |
| 83 | let captured = self.microphone.next_frame().or_else(|| { |
| 84 | // Small 2 ms cushion for WASAPI/CPAL callback cadence jitter before emitting silence. |
| 85 | sleeper.sleep(Duration::from_millis(2)); |
| 86 | self.microphone.next_frame() |
| 87 | }); |
| 88 | let microphone = match captured { |
| 89 | Some(mut frame) if !muted => { |
| 90 | chain.process(&mut frame); |
| 91 | frame |
| 92 | } |
| 93 | Some(frame) => frame, |
| 94 | // Underrun: send silence without feeding AEC/gain a zero-padded partial. |
| 95 | None => vec![0; FRAME_SAMPLES], |
| 96 | }; |
| 97 | let computer = self |
| 98 | .computer |
| 99 | .next_frame() |
| 100 | .unwrap_or_else(|| vec![0; FRAME_SAMPLES]); |
| 101 | let frame = AudioFrame { |
| 102 | data: mix_frames(µphone, &computer, muted).into(), |
| 103 | sample_rate: SAMPLE_RATE, |
| 104 | num_channels: 1, |
| 105 | samples_per_channel: FRAME_SAMPLES as u32, |
| 106 | }; |
| 107 | match self.source.capture_frame(&frame).now_or_never() { |
| 108 | Some(Ok(())) => {} |
| 109 | Some(Err(_)) | None => break, |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | const DEFAULT_MICROPHONE_NOTICE: &str = |
| 116 | "The picked microphone could not be captured while sharing sound, using the default one"; |
| 117 | const NO_MICROPHONE_NOTICE: &str = |
| 118 | "The microphone could not be captured while sharing sound, others cannot hear you"; |
| 119 | |
| 120 | /// Mic through our own processing, plus computer sound when planned, as one track that replaces the device track. |
| 121 | pub struct SoftwareAudio { |
| 122 | pub track: RtcAudioTrack, |
| 123 | pub plan: SoftwareAudioPlan, |
| 124 | pub loopback: Option<LoopbackKind>, |
| 125 | pub warning: Option<String>, |
| 126 | pub microphone_source: Option<String>, |
| 127 | pub microphone_notice: Option<&'static str>, |
| 128 | microphone_muted: Arc<AtomicBool>, |
| 129 | running: Arc<AtomicBool>, |
| 130 | feeder: Option<std::thread::JoinHandle<()>>, |
| 131 | far_end_task: Option<JoinHandle<()>>, |
| 132 | _captures: Vec<Capture>, |
| 133 | } |
| 134 | |
| 135 | impl SoftwareAudioPlan { |
| 136 | pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> { |
| 137 | Self::wanted_on(mic, sharing_sound, uses_devices) |
| 138 | } |
| 139 | |
| 140 | pub fn wanted_on(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> { |
| 141 | (sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan { |
| 142 | processing: mic.apm_config(), |
| 143 | ml_noise: mic.ml_noise_suppression(), |
| 144 | computer_sound: sharing_sound, |
| 145 | }) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | impl SoftwareAudio { |
| 150 | pub fn start( |
| 151 | factory: &PeerConnectionFactory, |
| 152 | mode: AudioMode, |
| 153 | tone_hz: f32, |
| 154 | input: &DeviceChoice, |
| 155 | plan: SoftwareAudioPlan, |
| 156 | microphone_muted: bool, |
| 157 | remote: Option<RtcAudioTrack>, |
| 158 | ) -> Result<Self> { |
| 159 | let mut captures = Vec::new(); |
| 160 | let mut warning = None; |
| 161 | let mut microphone_source = None; |
| 162 | let mut microphone_notice = None; |
| 163 | let (microphone, computer, loopback) = if mode == AudioMode::Platform { |
| 164 | let computer_queue = SampleQueue::default(); |
| 165 | let (computer, loopback) = if plan.computer_sound { |
| 166 | let started = start_loopback(computer_queue.clone())?; |
| 167 | captures.push(started.capture); |
| 168 | warning = started.warning; |
| 169 | (FrameSource::Captured(computer_queue), Some(started.kind)) |
| 170 | } else { |
| 171 | (FrameSource::Silence, None) |
| 172 | }; |
| 173 | let microphone_queue = SampleQueue::default(); |
| 174 | let label = crate::devices::input_label(factory, input); |
| 175 | let microphone = |
| 176 | match start_microphone(input, label.as_deref(), microphone_queue.clone()) { |
| 177 | Ok(started) => { |
| 178 | microphone_source = Some(started.source); |
| 179 | captures.push(started.capture); |
| 180 | FrameSource::Captured(microphone_queue) |
| 181 | } |
| 182 | Err(error) => { |
| 183 | if !plan.computer_sound { |
| 184 | return Err(error); |
| 185 | } |
| 186 | let fallback_queue = SampleQueue::default(); |
| 187 | let fallback = (input != &DeviceChoice::SystemDefault) |
| 188 | .then(|| { |
| 189 | start_microphone( |
| 190 | &DeviceChoice::SystemDefault, |
| 191 | None, |
| 192 | fallback_queue.clone(), |
| 193 | ) |
| 194 | .ok() |
| 195 | }) |
| 196 | .flatten(); |
| 197 | match fallback { |
| 198 | Some(started) => { |
| 199 | microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE); |
| 200 | microphone_source = |
| 201 | Some(format!("{}, picked one failed: {error}", started.source)); |
| 202 | captures.push(started.capture); |
| 203 | FrameSource::Captured(fallback_queue) |
| 204 | } |
| 205 | None => { |
| 206 | microphone_notice = Some(NO_MICROPHONE_NOTICE); |
| 207 | warning.get_or_insert(format!( |
| 208 | "microphone not captured while sharing sound: {error}" |
| 209 | )); |
| 210 | FrameSource::Silence |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | }; |
| 215 | (microphone, computer, loopback) |
| 216 | } else { |
| 217 | let microphone = if mode == AudioMode::Tone { |
| 218 | FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE)) |
| 219 | } else { |
| 220 | FrameSource::Silence |
| 221 | }; |
| 222 | let computer = if plan.computer_sound { |
| 223 | FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE)) |
| 224 | } else { |
| 225 | FrameSource::Silence |
| 226 | }; |
| 227 | ( |
| 228 | microphone, |
| 229 | computer, |
| 230 | plan.computer_sound.then_some(LoopbackKind::Synthetic), |
| 231 | ) |
| 232 | }; |
| 233 | let source = NativeAudioSource::new( |
| 234 | AudioSourceOptions::default(), |
| 235 | SAMPLE_RATE, |
| 236 | 1, |
| 237 | SOURCE_QUEUE_MS, |
| 238 | ); |
| 239 | let track = factory.create_audio_track("microphone", source.clone()); |
| 240 | let far_end = SampleQueue::default(); |
| 241 | let running = Arc::new(AtomicBool::new(true)); |
| 242 | let far_end_task = remote |
| 243 | .map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone()))); |
| 244 | let microphone_muted = Arc::new(AtomicBool::new(microphone_muted)); |
| 245 | let feeder = Feeder { |
| 246 | processing: plan.processing, |
| 247 | ml_noise: plan.ml_noise, |
| 248 | source, |
| 249 | microphone, |
| 250 | computer, |
| 251 | far_end, |
| 252 | microphone_muted: microphone_muted.clone(), |
| 253 | running: running.clone(), |
| 254 | }; |
| 255 | let thread = std::thread::Builder::new() |
| 256 | .name("share-audio".into()) |
| 257 | .spawn(move || feeder.run()) |
| 258 | .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?; |
| 259 | Ok(SoftwareAudio { |
| 260 | track, |
| 261 | plan, |
| 262 | loopback, |
| 263 | warning, |
| 264 | microphone_source, |
| 265 | microphone_notice, |
| 266 | microphone_muted, |
| 267 | running, |
| 268 | feeder: Some(thread), |
| 269 | far_end_task, |
| 270 | _captures: captures, |
| 271 | }) |
| 272 | } |
| 273 | |
| 274 | pub fn set_microphone_muted(&self, muted: bool) { |
| 275 | self.microphone_muted.store(muted, Ordering::SeqCst); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | impl Drop for SoftwareAudio { |
| 280 | fn drop(&mut self) { |
| 281 | // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both |
| 282 | // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a |
| 283 | // drained queue; aborting the far-end mid-OnData raced with remove_sink. |
| 284 | self.running.store(false, Ordering::SeqCst); |
| 285 | drop(self.far_end_task.take()); |
| 286 | drop(self.feeder.take()); |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc<AtomicBool>) { |
| 291 | let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1); |
| 292 | while running.load(Ordering::SeqCst) { |
| 293 | tokio::select! { |
| 294 | biased; |
| 295 | _ = wait_stopped(&running) => break, |
| 296 | frame = stream.next() => match frame { |
| 297 | Some(frame) => queue.push(&frame.data), |
| 298 | None => break, |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | stream.close(); |
| 303 | } |
| 304 | |
| 305 | async fn wait_stopped(running: &AtomicBool) { |
| 306 | while running.load(Ordering::SeqCst) { |
| 307 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | use crate::devices::shared_factory; |
| 315 | use crate::mic_processing::NoiseSuppression; |
| 316 | |
| 317 | #[tokio::test(flavor = "multi_thread")] |
| 318 | async fn synthetic_sources_start_and_stop_cleanly() { |
| 319 | let plan = SoftwareAudioPlan { |
| 320 | processing: MicSettings::default().apm_config(), |
| 321 | ml_noise: true, |
| 322 | computer_sound: true, |
| 323 | }; |
| 324 | let audio = SoftwareAudio::start( |
| 325 | &shared_factory(), |
| 326 | AudioMode::Tone, |
| 327 | 440.0, |
| 328 | &DeviceChoice::SystemDefault, |
| 329 | plan, |
| 330 | true, |
| 331 | None, |
| 332 | ) |
| 333 | .unwrap(); |
| 334 | assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic)); |
| 335 | assert!(audio.warning.is_none()); |
| 336 | audio.set_microphone_muted(false); |
| 337 | tokio::time::sleep(Duration::from_millis(60)).await; |
| 338 | drop(audio); |
| 339 | } |
| 340 | |
| 341 | #[test] |
| 342 | fn default_settings_use_the_device_track_on_all_platforms() { |
| 343 | let default = MicSettings::default(); |
| 344 | assert!(SoftwareAudioPlan::wanted_on(default, false, true).is_none()); |
| 345 | let low = MicSettings { |
| 346 | noise_suppression: NoiseSuppression::Low, |
| 347 | music_mode: false, |
| 348 | }; |
| 349 | assert!(SoftwareAudioPlan::wanted_on(low, false, true).is_none()); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn the_plan_follows_sharing_and_the_mic_choice() { |
| 354 | let auto = MicSettings::default(); |
| 355 | let off = MicSettings { |
| 356 | noise_suppression: NoiseSuppression::Off, |
| 357 | music_mode: false, |
| 358 | }; |
| 359 | let low = MicSettings { |
| 360 | noise_suppression: NoiseSuppression::Low, |
| 361 | music_mode: false, |
| 362 | }; |
| 363 | assert_eq!(SoftwareAudioPlan::wanted_on(low, false, true), None); |
| 364 | assert_eq!(SoftwareAudioPlan::wanted_on(off, false, false), None); |
| 365 | assert_eq!(SoftwareAudioPlan::wanted_on(off, false, true), None); |
| 366 | let off_sharing = SoftwareAudioPlan::wanted_on(off, true, true).unwrap(); |
| 367 | assert!(off_sharing.processing.echo_canceller && off_sharing.processing.gain_controller); |
| 368 | assert!(!off_sharing.processing.noise_suppression && !off_sharing.ml_noise); |
| 369 | let sharing = SoftwareAudioPlan::wanted_on(auto, true, false).unwrap(); |
| 370 | assert!(sharing.computer_sound && sharing.processing.echo_canceller); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn windows_uses_software_path_only_when_not_on_device_track() { |
| 375 | for noise_suppression in NoiseSuppression::ALL { |
| 376 | for music_mode in [false, true] { |
| 377 | let mic = MicSettings { |
| 378 | noise_suppression, |
| 379 | music_mode, |
| 380 | }; |
| 381 | assert_eq!( |
| 382 | SoftwareAudioPlan::wanted_on(mic, false, true).is_some(), |
| 383 | !mic.uses_device_track() |
| 384 | ); |
| 385 | assert!(SoftwareAudioPlan::wanted_on(mic, false, false).is_none()); |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn rnnoise_runs_in_the_software_path_only_for_auto() { |
| 392 | let ml_noise = |noise_suppression, music_mode| { |
| 393 | SoftwareAudioPlan::wanted_on( |
| 394 | MicSettings { |
| 395 | noise_suppression, |
| 396 | music_mode, |
| 397 | }, |
| 398 | true, |
| 399 | true, |
| 400 | ) |
| 401 | .unwrap() |
| 402 | .ml_noise |
| 403 | }; |
| 404 | assert!(ml_noise(NoiseSuppression::Auto, false)); |
| 405 | assert!(!ml_noise(NoiseSuppression::Low, false)); |
| 406 | assert!(!ml_noise(NoiseSuppression::Off, false)); |
| 407 | assert!(!ml_noise(NoiseSuppression::Auto, true)); |
| 408 | } |
| 409 | |
| 410 | #[tokio::test(flavor = "multi_thread")] |
| 411 | async fn a_microphone_only_plan_has_no_computer_sound() { |
| 412 | let plan = SoftwareAudioPlan { |
| 413 | processing: MicSettings::default().apm_config(), |
| 414 | ml_noise: true, |
| 415 | computer_sound: false, |
| 416 | }; |
| 417 | let audio = SoftwareAudio::start( |
| 418 | &shared_factory(), |
| 419 | AudioMode::Silence, |
| 420 | 440.0, |
| 421 | &DeviceChoice::SystemDefault, |
| 422 | plan, |
| 423 | false, |
| 424 | None, |
| 425 | ) |
| 426 | .unwrap(); |
| 427 | assert_eq!(audio.loopback, None); |
| 428 | tokio::time::sleep(Duration::from_millis(60)).await; |
| 429 | drop(audio); |
| 430 | } |
| 431 | } |