BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / audio_io.rs

audio_io.rs

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