| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 6 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 7 | use libwebrtc::prelude::*; |
| 8 | use tokio::task::JoinHandle; |
| 9 | use tokio::time::interval; |
| 10 | |
| 11 | use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator}; |
| 12 | use crate::devices::{self, DeviceChoice}; |
| 13 | use crate::mic_processing::{MicSettings, NoiseSuppression}; |
| 14 | |
| 15 | const TONE_AMPLITUDE: f32 = 0.3; |
| 16 | const SOURCE_QUEUE_MS: u32 = 100; |
| 17 | const FRAME_PERIOD: Duration = Duration::from_millis(10); |
| 18 | pub const AUDIO_MODE_ENV: &str = "CALLING_AUDIO"; |
| 19 | pub const AUDIO_FILE_ENV: &str = "CALLING_AUDIO_FILE"; |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 22 | pub enum AudioMode { |
| 23 | #[default] |
| 24 | Platform, |
| 25 | Tone, |
| 26 | Silence, |
| 27 | File, |
| 28 | } |
| 29 | |
| 30 | impl AudioMode { |
| 31 | pub fn from_env() -> Self { |
| 32 | Self::parse(std::env::var(AUDIO_MODE_ENV).ok().as_deref()) |
| 33 | } |
| 34 | |
| 35 | pub fn parse(value: Option<&str>) -> Self { |
| 36 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 37 | Some("tone") => AudioMode::Tone, |
| 38 | Some("silence") => AudioMode::Silence, |
| 39 | Some("file") => AudioMode::File, |
| 40 | _ => AudioMode::Platform, |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub struct AudioSetup { |
| 46 | factory: PeerConnectionFactory, |
| 47 | pub track: RtcAudioTrack, |
| 48 | pub track_with_ns: Option<RtcAudioTrack>, |
| 49 | /// Noise suppression Off: echo cancellation and gain control, no noise suppression. |
| 50 | pub track_without_ns: Option<RtcAudioTrack>, |
| 51 | pub listen_only: bool, |
| 52 | platform_acquired: bool, |
| 53 | pub adm_state: String, |
| 54 | feeder: Option<(JoinHandle<()>, Arc<AtomicBool>)>, |
| 55 | } |
| 56 | |
| 57 | fn device_count_text(count: Option<i16>) -> String { |
| 58 | count.map_or_else(|| "n/a".to_owned(), |count| count.to_string()) |
| 59 | } |
| 60 | |
| 61 | impl AudioSetup { |
| 62 | pub fn start( |
| 63 | factory: &PeerConnectionFactory, |
| 64 | mode: AudioMode, |
| 65 | tone_hz: f32, |
| 66 | input: &DeviceChoice, |
| 67 | output: &DeviceChoice, |
| 68 | ) -> Self { |
| 69 | let platform_acquired = mode == AudioMode::Platform && factory.acquire_platform_adm(); |
| 70 | let (recording_devices, playout_devices) = if platform_acquired { |
| 71 | ( |
| 72 | Some(factory.recording_devices()), |
| 73 | Some(factory.playout_devices()), |
| 74 | ) |
| 75 | } else { |
| 76 | (None, None) |
| 77 | }; |
| 78 | let has_input = recording_devices.is_some_and(|count| count > 0); |
| 79 | let has_output = playout_devices.is_some_and(|count| count > 0); |
| 80 | let adm_state = format!( |
| 81 | "acquired {platform_acquired}, recording devices {}, playout devices {}, adm refs {}", |
| 82 | device_count_text(recording_devices), |
| 83 | device_count_text(playout_devices), |
| 84 | factory.platform_adm_ref_count() |
| 85 | ); |
| 86 | if platform_acquired { |
| 87 | factory.set_adm_recording_enabled(has_input); |
| 88 | factory.set_adm_playout_enabled(has_output); |
| 89 | if has_input && *input != DeviceChoice::SystemDefault { |
| 90 | devices::select_input(factory, input); |
| 91 | } |
| 92 | if has_output && *output != DeviceChoice::SystemDefault { |
| 93 | devices::select_output(factory, output); |
| 94 | } |
| 95 | } |
| 96 | if has_input { |
| 97 | // Windows Auto disables built-in WebRTC NS so DeepFilterNet runs alone on 48 kHz mics |
| 98 | // (with single-stage WebRTC NS fallback inside the capture hook for 16 kHz / warm-up). |
| 99 | // Linux and macOS keep WebRTC NS on that track, then DeepFilterNet, as before. |
| 100 | // Low mode switches to `track_with_ns` with built-in WebRTC NS enabled and hook off. |
| 101 | let track = |
| 102 | factory.create_device_audio_track_with_options("microphone", !cfg!(windows)); |
| 103 | let track_with_ns = Some(factory.create_device_audio_track("microphone-ns")); |
| 104 | let track_without_ns = |
| 105 | Some(factory.create_device_audio_track_with_options("microphone-raw", false)); |
| 106 | return AudioSetup { |
| 107 | factory: factory.clone(), |
| 108 | track, |
| 109 | track_with_ns, |
| 110 | track_without_ns, |
| 111 | listen_only: false, |
| 112 | platform_acquired, |
| 113 | adm_state, |
| 114 | feeder: None, |
| 115 | }; |
| 116 | } |
| 117 | let generator = match mode { |
| 118 | AudioMode::File => std::env::var_os(AUDIO_FILE_ENV) |
| 119 | .and_then(|path| std::fs::read(path).ok()) |
| 120 | .and_then(|bytes| ClipGenerator::from_wav(&bytes)) |
| 121 | .map_or( |
| 122 | FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)), |
| 123 | FrameGenerator::Clip, |
| 124 | ), |
| 125 | AudioMode::Tone => FrameGenerator::Sine(SineGenerator::new(tone_hz, TONE_AMPLITUDE)), |
| 126 | AudioMode::Platform | AudioMode::Silence => { |
| 127 | FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)) |
| 128 | } |
| 129 | }; |
| 130 | let source = NativeAudioSource::new( |
| 131 | AudioSourceOptions::default(), |
| 132 | SAMPLE_RATE, |
| 133 | 1, |
| 134 | SOURCE_QUEUE_MS, |
| 135 | ); |
| 136 | let track = factory.create_audio_track("microphone", source.clone()); |
| 137 | let running = Arc::new(AtomicBool::new(true)); |
| 138 | let task = tokio::spawn(feed_frames(source, generator, running.clone())); |
| 139 | AudioSetup { |
| 140 | factory: factory.clone(), |
| 141 | track, |
| 142 | track_with_ns: None, |
| 143 | track_without_ns: None, |
| 144 | listen_only: mode == AudioMode::Platform, |
| 145 | platform_acquired, |
| 146 | adm_state, |
| 147 | feeder: Some((task, running)), |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | pub fn device_track(&self, settings: MicSettings) -> &RtcAudioTrack { |
| 152 | let other = if classical_noise_track(settings) { |
| 153 | self.track_with_ns.as_ref() |
| 154 | } else if settings.noise_suppression == NoiseSuppression::Off { |
| 155 | self.track_without_ns.as_ref() |
| 156 | } else { |
| 157 | None |
| 158 | }; |
| 159 | other.unwrap_or(&self.track) |
| 160 | } |
| 161 | |
| 162 | pub fn set_device_tracks_enabled(&self, enabled: bool) { |
| 163 | self.track.set_enabled(enabled); |
| 164 | for track in [&self.track_with_ns, &self.track_without_ns] |
| 165 | .into_iter() |
| 166 | .flatten() |
| 167 | { |
| 168 | track.set_enabled(enabled); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | pub fn uses_devices(&self) -> bool { |
| 173 | self.platform_acquired && self.feeder.is_none() |
| 174 | } |
| 175 | |
| 176 | pub async fn stop(self) { |
| 177 | if let Some((task, running)) = self.feeder { |
| 178 | running.store(false, Ordering::SeqCst); |
| 179 | let _ = task.await; |
| 180 | } |
| 181 | if self.platform_acquired { |
| 182 | self.factory.set_adm_recording_enabled(false); |
| 183 | self.factory.set_adm_playout_enabled(false); |
| 184 | self.factory.release_platform_adm(); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | enum FrameGenerator { |
| 190 | Sine(SineGenerator), |
| 191 | Clip(ClipGenerator), |
| 192 | } |
| 193 | |
| 194 | pub(crate) fn classical_noise_track(settings: MicSettings) -> bool { |
| 195 | settings.noise_suppression == NoiseSuppression::Low && !settings.music_mode |
| 196 | } |
| 197 | |
| 198 | impl FrameGenerator { |
| 199 | fn next_frame(&mut self) -> Vec<i16> { |
| 200 | match self { |
| 201 | FrameGenerator::Sine(generator) => generator.next_frame(), |
| 202 | FrameGenerator::Clip(generator) => generator.next_frame(), |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | async fn feed_frames( |
| 208 | source: NativeAudioSource, |
| 209 | mut generator: FrameGenerator, |
| 210 | running: Arc<AtomicBool>, |
| 211 | ) { |
| 212 | let mut tick = interval(FRAME_PERIOD); |
| 213 | while running.load(Ordering::SeqCst) { |
| 214 | tick.tick().await; |
| 215 | let frame = AudioFrame { |
| 216 | data: generator.next_frame().into(), |
| 217 | sample_rate: SAMPLE_RATE, |
| 218 | num_channels: 1, |
| 219 | samples_per_channel: FRAME_SAMPLES as u32, |
| 220 | }; |
| 221 | if source.capture_frame(&frame).await.is_err() { |
| 222 | break; |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[cfg(test)] |
| 228 | mod tests { |
| 229 | use super::*; |
| 230 | |
| 231 | #[test] |
| 232 | fn audio_mode_parses_the_environment_value() { |
| 233 | assert_eq!(AudioMode::parse(None), AudioMode::Platform); |
| 234 | assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone); |
| 235 | assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence); |
| 236 | assert_eq!(AudioMode::parse(Some("file")), AudioMode::File); |
| 237 | assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn only_low_uses_the_classical_noise_track() { |
| 242 | use crate::mic_processing::{MicSettings, NoiseSuppression}; |
| 243 | let mut settings = MicSettings::default(); |
| 244 | assert!(!classical_noise_track(settings)); |
| 245 | settings.noise_suppression = NoiseSuppression::Low; |
| 246 | assert!(classical_noise_track(settings)); |
| 247 | settings.noise_suppression = NoiseSuppression::Off; |
| 248 | assert!(!classical_noise_track(settings)); |
| 249 | settings.noise_suppression = NoiseSuppression::Low; |
| 250 | settings.music_mode = true; |
| 251 | assert!(!classical_noise_track(settings)); |
| 252 | } |
| 253 | } |