BlueGit

ict rusty-teams

Files

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

software_audio.rs

software_audio.rs 12.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::peer_connection_factory::native::PeerConnectionFactoryExt;
8use libwebrtc::audio_stream::native::NativeAudioStream;
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_processing::{ApmConfig, MicSettings};
18use crate::mixer::mix_frames;
19use crate::mic_chain::MicChain;
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.computer.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
91 let frame = AudioFrame {
92 data: mix_frames(&microphone, &computer, muted).into(),
93 sample_rate: SAMPLE_RATE,
94 num_channels: 1,
95 samples_per_channel: FRAME_SAMPLES as u32,
96 };
97 match self.source.capture_frame(&frame).now_or_never() {
98 Some(Ok(())) => {}
99 Some(Err(_)) | None => break,
100 }
101 }
102 }
103}
104
105/// Mic through our own processing, plus computer sound when planned, as one track that replaces the device track.
106pub struct SoftwareAudio {
107 pub track: RtcAudioTrack,
108 pub plan: SoftwareAudioPlan,
109 pub loopback: Option<LoopbackKind>,
110 pub warning: Option<String>,
111 pub microphone_source: Option<String>,
112 microphone_muted: Arc<AtomicBool>,
113 running: Arc<AtomicBool>,
114 feeder: Option<std::thread::JoinHandle<()>>,
115 far_end_task: Option<JoinHandle<()>>,
116 _captures: Vec<Capture>,
117}
118
119impl SoftwareAudioPlan {
120 pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
121 Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)
122 }
123
124 pub fn wanted_on(windows: bool, mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
125 (sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| SoftwareAudioPlan {
126 processing: mic.apm_config(),
127 ml_noise: mic.ml_noise_suppression(),
128 computer_sound: sharing_sound,
129 })
130 }
131}
132
133impl SoftwareAudio {
134 pub fn start(
135 factory: &PeerConnectionFactory,
136 mode: AudioMode,
137 tone_hz: f32,
138 input: &DeviceChoice,
139 plan: SoftwareAudioPlan,
140 microphone_muted: bool,
141 remote: Option<RtcAudioTrack>,
142 ) -> Result<Self> {
143 let mut captures = Vec::new();
144 let mut warning = None;
145 let mut microphone_source = None;
146 let (microphone, computer, loopback) = if mode == AudioMode::Platform {
147 let computer_queue = SampleQueue::default();
148 let (computer, loopback) = if plan.computer_sound {
149 let started = start_loopback(computer_queue.clone())?;
150 captures.push(started.capture);
151 warning = started.warning;
152 (FrameSource::Captured(computer_queue), Some(started.kind))
153 } else {
154 (FrameSource::Silence, None)
155 };
156 let microphone_queue = SampleQueue::default();
157 let microphone = match start_microphone(input, microphone_queue.clone()) {
158 Ok(started) => {
159 microphone_source = Some(started.source);
160 captures.push(started.capture);
161 FrameSource::Captured(microphone_queue)
162 }
163 Err(error) => {
164 if !plan.computer_sound {
165 return Err(error);
166 }
167 warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));
168 FrameSource::Silence
169 }
170 };
171 (microphone, computer, loopback)
172 } else {
173 let microphone = if mode == AudioMode::Tone {
174 FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE))
175 } else {
176 FrameSource::Silence
177 };
178 let computer = if plan.computer_sound {
179 FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE))
180 } else {
181 FrameSource::Silence
182 };
183 (microphone, computer, plan.computer_sound.then_some(LoopbackKind::Synthetic))
184 };
185 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
186 let track = factory.create_audio_track("microphone", source.clone());
187 let far_end = SampleQueue::default();
188 let running = Arc::new(AtomicBool::new(true));
189 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone())));
190 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
191 let feeder = Feeder {
192 processing: plan.processing,
193 ml_noise: plan.ml_noise,
194 source,
195 microphone,
196 computer,
197 far_end,
198 microphone_muted: microphone_muted.clone(),
199 running: running.clone(),
200 };
201 let thread = std::thread::Builder::new()
202 .name("share-audio".into())
203 .spawn(move || feeder.run())
204 .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?;
205 Ok(SoftwareAudio {
206 track,
207 plan,
208 loopback,
209 warning,
210 microphone_source,
211 microphone_muted,
212 running,
213 feeder: Some(thread),
214 far_end_task,
215 _captures: captures,
216 })
217 }
218
219 pub fn set_microphone_muted(&self, muted: bool) {
220 self.microphone_muted.store(muted, Ordering::SeqCst);
221 }
222}
223
224impl Drop for SoftwareAudio {
225 fn drop(&mut self) {
226 // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both
227 // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a
228 // drained queue; aborting the far-end mid-OnData raced with remove_sink.
229 self.running.store(false, Ordering::SeqCst);
230 drop(self.far_end_task.take());
231 drop(self.feeder.take());
232 }
233}
234
235async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc<AtomicBool>) {
236 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
237 while running.load(Ordering::SeqCst) {
238 tokio::select! {
239 biased;
240 _ = wait_stopped(&running) => break,
241 frame = stream.next() => match frame {
242 Some(frame) => queue.push(&frame.data),
243 None => break,
244 }
245 }
246 }
247 stream.close();
248}
249
250async fn wait_stopped(running: &AtomicBool) {
251 while running.load(Ordering::SeqCst) {
252 tokio::time::sleep(Duration::from_millis(10)).await;
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use crate::devices::shared_factory;
260 use crate::mic_processing::NoiseSuppression;
261
262 #[tokio::test(flavor = "multi_thread")]
263 async fn synthetic_sources_start_and_stop_cleanly() {
264 let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: true };
265 let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None).unwrap();
266 assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));
267 assert!(audio.warning.is_none());
268 audio.set_microphone_muted(false);
269 tokio::time::sleep(Duration::from_millis(60)).await;
270 drop(audio);
271 }
272
273 #[test]
274 fn default_settings_use_the_device_track_on_linux() {
275 let default = MicSettings::default();
276 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
277 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
278 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
279 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
280 }
281
282 #[test]
283 fn the_plan_follows_sharing_and_the_mic_choice() {
284 let auto = MicSettings::default();
285 let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
286 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
287 assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);
288 assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
289 let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
290 assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
291 let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();
292 assert!(sharing.computer_sound && sharing.processing.echo_canceller);
293 }
294
295 #[test]
296 fn windows_runs_the_software_path_for_every_mic_setting() {
297 for noise_suppression in NoiseSuppression::ALL {
298 for music_mode in [false, true] {
299 let mic = MicSettings { noise_suppression, music_mode };
300 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());
301 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());
302 assert_eq!(SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(), !mic.uses_device_track_on(false));
303 }
304 }
305 }
306
307 #[test]
308 fn rnnoise_runs_in_the_software_path_only_for_auto() {
309 let ml_noise = |noise_suppression, music_mode| {
310 SoftwareAudioPlan::wanted_on(true, MicSettings { noise_suppression, music_mode }, false, true).unwrap().ml_noise
311 };
312 assert!(ml_noise(NoiseSuppression::Auto, false));
313 assert!(!ml_noise(NoiseSuppression::Low, false));
314 assert!(!ml_noise(NoiseSuppression::Off, false));
315 assert!(!ml_noise(NoiseSuppression::Auto, true));
316 }
317
318 #[tokio::test(flavor = "multi_thread")]
319 async fn a_microphone_only_plan_has_no_computer_sound() {
320 let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: false };
321 let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None).unwrap();
322 assert_eq!(audio.loopback, None);
323 tokio::time::sleep(Duration::from_millis(60)).await;
324 drop(audio);
325 }
326}