BlueGit

ict rusty-teams

Files

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

software_audio.rs

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