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