BlueGit

ict rusty-teams

Files

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

software_audio.rs

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