BlueGit

ict rusty-teams

Files

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

software_audio.rs

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