BlueGit

ict rusty-teams

Files

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

software_audio.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
software_audio.rs 13.7 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5use futures_util::{FutureExt, StreamExt};
6use libwebrtc::audio_source::native::NativeAudioSource;
7use libwebrtc::audio_stream::native::NativeAudioStream;
8use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
9use libwebrtc::prelude::*;
10use tokio::task::JoinHandle;
11
12use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
13use crate::audio_io::AudioMode;
14use crate::capture::Capture;
15use crate::devices::DeviceChoice;
16use crate::error::{Error, Result};
17use crate::mic_chain::MicChain;
18use crate::mic_processing::{ApmConfig, MicSettings};
19use crate::mixer::mix_frames;
20use crate::pcm::SampleQueue;
21use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
22use crate::wav_dump::StageDumps;
23
24/// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.
25const SOURCE_QUEUE_MS: u32 = 0;
26const FRAME_PERIOD: Duration = Duration::from_millis(10);
27const MAX_LAG: Duration = Duration::from_millis(100);
28const SYSTEM_TONE_HZ: f32 = 660.0;
29const SYNTHETIC_AMPLITUDE: f32 = 0.3;
30
31enum FrameSource {
32 Captured(SampleQueue),
33 Tone(SineGenerator),
34 Silence,
35}
36
37impl 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)]
48pub struct SoftwareAudioPlan {
49 pub processing: ApmConfig,
50 pub ml_noise: bool,
51 pub computer_sound: bool,
52}
53
54struct 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
65impl 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(&microphone, &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/// Mic through our own processing, plus computer sound when planned, as one track that replaces the device track.
109pub struct SoftwareAudio {
110 pub track: RtcAudioTrack,
111 pub plan: SoftwareAudioPlan,
112 pub loopback: Option<LoopbackKind>,
113 pub warning: Option<String>,
114 pub microphone_source: Option<String>,
115 microphone_muted: Arc<AtomicBool>,
116 running: Arc<AtomicBool>,
117 feeder: Option<std::thread::JoinHandle<()>>,
118 far_end_task: Option<JoinHandle<()>>,
119 _captures: Vec<Capture>,
120}
121
122impl SoftwareAudioPlan {
123 pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
124 Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)
125 }
126
127 pub fn wanted_on(
128 windows: bool,
129 mic: MicSettings,
130 sharing_sound: bool,
131 uses_devices: bool,
132 ) -> Option<Self> {
133 (sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| {
134 SoftwareAudioPlan {
135 processing: mic.apm_config(),
136 ml_noise: mic.ml_noise_suppression(),
137 computer_sound: sharing_sound,
138 }
139 })
140 }
141}
142
143impl SoftwareAudio {
144 pub fn start(
145 factory: &PeerConnectionFactory,
146 mode: AudioMode,
147 tone_hz: f32,
148 input: &DeviceChoice,
149 plan: SoftwareAudioPlan,
150 microphone_muted: bool,
151 remote: Option<RtcAudioTrack>,
152 ) -> Result<Self> {
153 let mut captures = Vec::new();
154 let mut warning = None;
155 let mut microphone_source = None;
156 let (microphone, computer, loopback) = if mode == AudioMode::Platform {
157 let computer_queue = SampleQueue::default();
158 let (computer, loopback) = if plan.computer_sound {
159 let started = start_loopback(computer_queue.clone())?;
160 captures.push(started.capture);
161 warning = started.warning;
162 (FrameSource::Captured(computer_queue), Some(started.kind))
163 } else {
164 (FrameSource::Silence, None)
165 };
166 let microphone_queue = SampleQueue::default();
167 let microphone = match start_microphone(input, microphone_queue.clone()) {
168 Ok(started) => {
169 microphone_source = Some(started.source);
170 captures.push(started.capture);
171 FrameSource::Captured(microphone_queue)
172 }
173 Err(error) => {
174 if !plan.computer_sound {
175 return Err(error);
176 }
177 warning.get_or_insert(format!(
178 "microphone not captured while sharing sound: {error}"
179 ));
180 FrameSource::Silence
181 }
182 };
183 (microphone, computer, loopback)
184 } else {
185 let microphone = if mode == AudioMode::Tone {
186 FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE))
187 } else {
188 FrameSource::Silence
189 };
190 let computer = if plan.computer_sound {
191 FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE))
192 } else {
193 FrameSource::Silence
194 };
195 (
196 microphone,
197 computer,
198 plan.computer_sound.then_some(LoopbackKind::Synthetic),
199 )
200 };
201 let source = NativeAudioSource::new(
202 AudioSourceOptions::default(),
203 SAMPLE_RATE,
204 1,
205 SOURCE_QUEUE_MS,
206 );
207 let track = factory.create_audio_track("microphone", source.clone());
208 let far_end = SampleQueue::default();
209 let running = Arc::new(AtomicBool::new(true));
210 let far_end_task = remote
211 .map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone())));
212 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
213 let feeder = Feeder {
214 processing: plan.processing,
215 ml_noise: plan.ml_noise,
216 source,
217 microphone,
218 computer,
219 far_end,
220 microphone_muted: microphone_muted.clone(),
221 running: running.clone(),
222 };
223 let thread = std::thread::Builder::new()
224 .name("share-audio".into())
225 .spawn(move || feeder.run())
226 .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?;
227 Ok(SoftwareAudio {
228 track,
229 plan,
230 loopback,
231 warning,
232 microphone_source,
233 microphone_muted,
234 running,
235 feeder: Some(thread),
236 far_end_task,
237 _captures: captures,
238 })
239 }
240
241 pub fn set_microphone_muted(&self, muted: bool) {
242 self.microphone_muted.store(muted, Ordering::SeqCst);
243 }
244}
245
246impl Drop for SoftwareAudio {
247 fn drop(&mut self) {
248 // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both
249 // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a
250 // drained queue; aborting the far-end mid-OnData raced with remove_sink.
251 self.running.store(false, Ordering::SeqCst);
252 drop(self.far_end_task.take());
253 drop(self.feeder.take());
254 }
255}
256
257async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc<AtomicBool>) {
258 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
259 while running.load(Ordering::SeqCst) {
260 tokio::select! {
261 biased;
262 _ = wait_stopped(&running) => break,
263 frame = stream.next() => match frame {
264 Some(frame) => queue.push(&frame.data),
265 None => break,
266 }
267 }
268 }
269 stream.close();
270}
271
272async fn wait_stopped(running: &AtomicBool) {
273 while running.load(Ordering::SeqCst) {
274 tokio::time::sleep(Duration::from_millis(10)).await;
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use crate::devices::shared_factory;
282 use crate::mic_processing::NoiseSuppression;
283
284 #[tokio::test(flavor = "multi_thread")]
285 async fn synthetic_sources_start_and_stop_cleanly() {
286 let plan = SoftwareAudioPlan {
287 processing: MicSettings::default().apm_config(),
288 ml_noise: true,
289 computer_sound: true,
290 };
291 let audio = SoftwareAudio::start(
292 &shared_factory(),
293 AudioMode::Tone,
294 440.0,
295 &DeviceChoice::SystemDefault,
296 plan,
297 true,
298 None,
299 )
300 .unwrap();
301 assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));
302 assert!(audio.warning.is_none());
303 audio.set_microphone_muted(false);
304 tokio::time::sleep(Duration::from_millis(60)).await;
305 drop(audio);
306 }
307
308 #[test]
309 fn default_settings_use_the_device_track_on_linux() {
310 let default = MicSettings::default();
311 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
312 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
313 let low = MicSettings {
314 noise_suppression: NoiseSuppression::Low,
315 music_mode: false,
316 };
317 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
318 }
319
320 #[test]
321 fn the_plan_follows_sharing_and_the_mic_choice() {
322 let auto = MicSettings::default();
323 let off = MicSettings {
324 noise_suppression: NoiseSuppression::Off,
325 music_mode: false,
326 };
327 let low = MicSettings {
328 noise_suppression: NoiseSuppression::Low,
329 music_mode: false,
330 };
331 assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);
332 assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
333 let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
334 assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
335 let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();
336 assert!(sharing.computer_sound && sharing.processing.echo_canceller);
337 }
338
339 #[test]
340 fn windows_runs_the_software_path_for_every_mic_setting() {
341 for noise_suppression in NoiseSuppression::ALL {
342 for music_mode in [false, true] {
343 let mic = MicSettings {
344 noise_suppression,
345 music_mode,
346 };
347 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());
348 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());
349 assert_eq!(
350 SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(),
351 !mic.uses_device_track_on(false)
352 );
353 }
354 }
355 }
356
357 #[test]
358 fn rnnoise_runs_in_the_software_path_only_for_auto() {
359 let ml_noise = |noise_suppression, music_mode| {
360 SoftwareAudioPlan::wanted_on(
361 true,
362 MicSettings {
363 noise_suppression,
364 music_mode,
365 },
366 false,
367 true,
368 )
369 .unwrap()
370 .ml_noise
371 };
372 assert!(ml_noise(NoiseSuppression::Auto, false));
373 assert!(!ml_noise(NoiseSuppression::Low, false));
374 assert!(!ml_noise(NoiseSuppression::Off, false));
375 assert!(!ml_noise(NoiseSuppression::Auto, true));
376 }
377
378 #[tokio::test(flavor = "multi_thread")]
379 async fn a_microphone_only_plan_has_no_computer_sound() {
380 let plan = SoftwareAudioPlan {
381 processing: MicSettings::default().apm_config(),
382 ml_noise: true,
383 computer_sound: false,
384 };
385 let audio = SoftwareAudio::start(
386 &shared_factory(),
387 AudioMode::Silence,
388 440.0,
389 &DeviceChoice::SystemDefault,
390 plan,
391 false,
392 None,
393 )
394 .unwrap();
395 assert_eq!(audio.loopback, None);
396 tokio::time::sleep(Duration::from_millis(60)).await;
397 drop(audio);
398 }
399}