BlueGit

ict rusty-teams

Files

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

software_audio.rs

software_audio.rs 12.2 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
4
5use futures_util::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
24const SOURCE_QUEUE_MS: u32 = 100;
25const FRAME_PERIOD: Duration = Duration::from_millis(10);
26const MAX_LAG: Duration = Duration::from_millis(100);
27const SYSTEM_TONE_HZ: f32 = 660.0;
28const SYNTHETIC_AMPLITUDE: f32 = 0.3;
29
30enum FrameSource {
31 Captured(SampleQueue),
32 Tone(SineGenerator),
33 Silence,
34}
35
36impl FrameSource {
37 fn next_frame(&mut self) -> Vec<i16> {
38 match self {
39 FrameSource::Captured(queue) => queue.next_frame().0,
40 FrameSource::Tone(generator) => generator.next_frame(),
41 FrameSource::Silence => vec![0; FRAME_SAMPLES],
42 }
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct SoftwareAudioPlan {
48 pub processing: ApmConfig,
49 pub ml_noise: bool,
50 pub computer_sound: bool,
51}
52
53struct Feeder {
54 processing: ApmConfig,
55 ml_noise: bool,
56 source: NativeAudioSource,
57 microphone: FrameSource,
58 computer: FrameSource,
59 far_end: SampleQueue,
60 microphone_muted: Arc<AtomicBool>,
61 running: Arc<AtomicBool>,
62 runtime: tokio::runtime::Handle,
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 let mut last_capture = Duration::ZERO;
70 while self.running.load(Ordering::SeqCst) {
71 due += FRAME_PERIOD;
72 let now = Instant::now();
73 if due > now {
74 std::thread::sleep(due - now);
75 } else if now - due > MAX_LAG {
76 eprintln!(
77 "calls: audio feeder fell {} ms behind, last capture_frame took {} ms; echo canceller re-aligns",
78 (now - due).as_millis(),
79 last_capture.as_millis()
80 );
81 due = now;
82 }
83 let (mut far_end, has_far_end) = self.far_end.next_frame();
84 if has_far_end {
85 chain.process_far_end(&mut far_end);
86 }
87 let muted = self.microphone_muted.load(Ordering::SeqCst);
88 let mut microphone = self.microphone.next_frame();
89 if !muted {
90 chain.process(&mut microphone);
91 }
92 let computer = self.computer.next_frame();
93 let frame = AudioFrame {
94 data: mix_frames(&microphone, &computer, muted).into(),
95 sample_rate: SAMPLE_RATE,
96 num_channels: 1,
97 samples_per_channel: FRAME_SAMPLES as u32,
98 };
99 let capture_started = Instant::now();
100 if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() {
101 break;
102 }
103 last_capture = capture_started.elapsed();
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(windows: bool, mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
128 (sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| SoftwareAudioPlan {
129 processing: mic.apm_config(),
130 ml_noise: mic.ml_noise_suppression(),
131 computer_sound: sharing_sound,
132 })
133 }
134}
135
136impl SoftwareAudio {
137 pub fn start(
138 factory: &PeerConnectionFactory,
139 mode: AudioMode,
140 tone_hz: f32,
141 input: &DeviceChoice,
142 plan: SoftwareAudioPlan,
143 microphone_muted: bool,
144 remote: Option<RtcAudioTrack>,
145 ) -> Result<Self> {
146 let mut captures = Vec::new();
147 let mut warning = None;
148 let mut microphone_source = None;
149 let (microphone, computer, loopback) = if mode == AudioMode::Platform {
150 let computer_queue = SampleQueue::default();
151 let (computer, loopback) = if plan.computer_sound {
152 let started = start_loopback(computer_queue.clone())?;
153 captures.push(started.capture);
154 warning = started.warning;
155 (FrameSource::Captured(computer_queue), Some(started.kind))
156 } else {
157 (FrameSource::Silence, None)
158 };
159 let microphone_queue = SampleQueue::default();
160 let microphone = match start_microphone(input, microphone_queue.clone()) {
161 Ok(started) => {
162 microphone_source = Some(started.source);
163 captures.push(started.capture);
164 FrameSource::Captured(microphone_queue)
165 }
166 Err(error) => {
167 if !plan.computer_sound {
168 return Err(error);
169 }
170 warning.get_or_insert(format!("microphone not captured while sharing sound: {error}"));
171 FrameSource::Silence
172 }
173 };
174 (microphone, computer, loopback)
175 } else {
176 let microphone = if mode == AudioMode::Tone {
177 FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE))
178 } else {
179 FrameSource::Silence
180 };
181 let computer = if plan.computer_sound {
182 FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE))
183 } else {
184 FrameSource::Silence
185 };
186 (microphone, computer, plan.computer_sound.then_some(LoopbackKind::Synthetic))
187 };
188 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
189 let track = factory.create_audio_track("microphone", source.clone());
190 let far_end = SampleQueue::default();
191 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone())));
192 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
193 let running = Arc::new(AtomicBool::new(true));
194 let feeder = Feeder {
195 processing: plan.processing,
196 ml_noise: plan.ml_noise,
197 source,
198 microphone,
199 computer,
200 far_end,
201 microphone_muted: microphone_muted.clone(),
202 running: running.clone(),
203 runtime: tokio::runtime::Handle::current(),
204 };
205 let thread = std::thread::Builder::new()
206 .name("share-audio".into())
207 .spawn(move || feeder.run())
208 .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?;
209 Ok(SoftwareAudio {
210 track,
211 plan,
212 loopback,
213 warning,
214 microphone_source,
215 microphone_muted,
216 running,
217 feeder: Some(thread),
218 far_end_task,
219 _captures: captures,
220 })
221 }
222
223 pub fn set_microphone_muted(&self, muted: bool) {
224 self.microphone_muted.store(muted, Ordering::SeqCst);
225 }
226}
227
228impl Drop for SoftwareAudio {
229 fn drop(&mut self) {
230 self.running.store(false, Ordering::SeqCst);
231 if let Some(task) = self.far_end_task.take() {
232 task.abort();
233 }
234 if let Some(thread) = self.feeder.take() {
235 let _ = thread.join();
236 }
237 }
238}
239
240async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) {
241 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
242 while let Some(frame) = stream.next().await {
243 queue.push(&frame.data);
244 }
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250 use crate::devices::shared_factory;
251 use crate::mic_processing::NoiseSuppression;
252
253 #[tokio::test(flavor = "multi_thread")]
254 async fn synthetic_sources_start_and_stop_cleanly() {
255 let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: true };
256 let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, plan, true, None).unwrap();
257 assert_eq!(audio.loopback, Some(LoopbackKind::Synthetic));
258 assert!(audio.warning.is_none());
259 audio.set_microphone_muted(false);
260 tokio::time::sleep(Duration::from_millis(60)).await;
261 drop(audio);
262 }
263
264 #[test]
265 fn default_settings_run_the_software_chain_on_both_platforms() {
266 let default = MicSettings::default();
267 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
268 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_some());
269 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
270 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
271 }
272
273 #[test]
274 fn the_plan_follows_sharing_and_the_mic_choice() {
275 let auto = MicSettings::default();
276 let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
277 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
278 assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);
279 assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
280 let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
281 assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
282 let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();
283 assert!(sharing.computer_sound && sharing.processing.echo_canceller);
284 }
285
286 #[test]
287 fn windows_runs_the_software_path_for_every_mic_setting() {
288 for noise_suppression in NoiseSuppression::ALL {
289 for music_mode in [false, true] {
290 let mic = MicSettings { noise_suppression, music_mode };
291 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());
292 assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());
293 assert_eq!(SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(), !mic.uses_device_track_on(false));
294 }
295 }
296 }
297
298 #[test]
299 fn rnnoise_runs_in_the_software_path_only_for_auto() {
300 let ml_noise = |noise_suppression, music_mode| {
301 SoftwareAudioPlan::wanted_on(true, MicSettings { noise_suppression, music_mode }, false, true).unwrap().ml_noise
302 };
303 assert!(ml_noise(NoiseSuppression::Auto, false));
304 assert!(!ml_noise(NoiseSuppression::Low, false));
305 assert!(!ml_noise(NoiseSuppression::Off, false));
306 assert!(!ml_noise(NoiseSuppression::Auto, true));
307 }
308
309 #[tokio::test(flavor = "multi_thread")]
310 async fn a_microphone_only_plan_has_no_computer_sound() {
311 let plan = SoftwareAudioPlan { processing: MicSettings::default().apm_config(), ml_noise: true, computer_sound: false };
312 let audio = SoftwareAudio::start(&shared_factory(), AudioMode::Silence, 440.0, &DeviceChoice::SystemDefault, plan, false, None).unwrap();
313 assert_eq!(audio.loopback, None);
314 tokio::time::sleep(Duration::from_millis(60)).await;
315 drop(audio);
316 }
317}