BlueGit

ict rusty-teams

Files

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

audio_io.rs

audio_io.rs 5.1 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::Duration;
4
5use libwebrtc::audio_source::native::NativeAudioSource;
6use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7use libwebrtc::prelude::*;
8use tokio::task::JoinHandle;
9use tokio::time::interval;
10
11use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
12use crate::devices::{self, DeviceChoice};
13
14const TONE_AMPLITUDE: f32 = 0.3;
15const SOURCE_QUEUE_MS: u32 = 100;
16const FRAME_PERIOD: Duration = Duration::from_millis(10);
17pub const AUDIO_MODE_ENV: &str = "CALLING_AUDIO";
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum AudioMode {
21 #[default]
22 Platform,
23 Tone,
24 Silence,
25}
26
27impl AudioMode {
28 pub fn from_env() -> Self {
29 Self::parse(std::env::var(AUDIO_MODE_ENV).ok().as_deref())
30 }
31
32 pub fn parse(value: Option<&str>) -> Self {
33 match value.map(str::to_ascii_lowercase).as_deref() {
34 Some("tone") => AudioMode::Tone,
35 Some("silence") => AudioMode::Silence,
36 _ => AudioMode::Platform,
37 }
38 }
39}
40
41pub struct AudioSetup {
42 factory: PeerConnectionFactory,
43 pub track: RtcAudioTrack,
44 pub listen_only: bool,
45 platform_acquired: bool,
46 pub adm_state: String,
47 feeder: Option<(JoinHandle<()>, Arc<AtomicBool>)>,
48}
49
50fn device_count_text(count: Option<i16>) -> String {
51 count.map_or_else(|| "n/a".to_owned(), |count| count.to_string())
52}
53
54impl AudioSetup {
55 pub fn start(
56 factory: &PeerConnectionFactory,
57 mode: AudioMode,
58 tone_hz: f32,
59 input: &DeviceChoice,
60 output: &DeviceChoice,
61 ) -> Self {
62 let platform_acquired = mode == AudioMode::Platform && factory.acquire_platform_adm();
63 let (recording_devices, playout_devices) = if platform_acquired {
64 (Some(factory.recording_devices()), Some(factory.playout_devices()))
65 } else {
66 (None, None)
67 };
68 let has_input = recording_devices.is_some_and(|count| count > 0);
69 let has_output = playout_devices.is_some_and(|count| count > 0);
70 let adm_state = format!(
71 "acquired {platform_acquired}, recording devices {}, playout devices {}, adm refs {}",
72 device_count_text(recording_devices),
73 device_count_text(playout_devices),
74 factory.platform_adm_ref_count()
75 );
76 if platform_acquired {
77 factory.set_adm_recording_enabled(has_input);
78 factory.set_adm_playout_enabled(has_output);
79 if has_input && *input != DeviceChoice::SystemDefault {
80 devices::select_input(factory, input);
81 }
82 if has_output && *output != DeviceChoice::SystemDefault {
83 devices::select_output(factory, output);
84 }
85 }
86 if has_input {
87 return AudioSetup {
88 factory: factory.clone(),
89 track: factory.create_device_audio_track("microphone"),
90 listen_only: false,
91 platform_acquired,
92 adm_state,
93 feeder: None,
94 };
95 }
96 let amplitude = if mode == AudioMode::Tone { TONE_AMPLITUDE } else { 0.0 };
97 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
98 let track = factory.create_audio_track("microphone", source.clone());
99 let running = Arc::new(AtomicBool::new(true));
100 let task = tokio::spawn(feed_frames(source, SineGenerator::new(tone_hz, amplitude), running.clone()));
101 AudioSetup {
102 factory: factory.clone(),
103 track,
104 listen_only: mode == AudioMode::Platform,
105 platform_acquired,
106 adm_state,
107 feeder: Some((task, running)),
108 }
109 }
110
111 pub fn uses_devices(&self) -> bool {
112 self.platform_acquired && self.feeder.is_none()
113 }
114
115 pub async fn stop(self) {
116 if let Some((task, running)) = self.feeder {
117 running.store(false, Ordering::SeqCst);
118 let _ = task.await;
119 }
120 if self.platform_acquired {
121 self.factory.set_adm_recording_enabled(false);
122 self.factory.set_adm_playout_enabled(false);
123 self.factory.release_platform_adm();
124 }
125 }
126}
127
128async fn feed_frames(source: NativeAudioSource, mut generator: SineGenerator, running: Arc<AtomicBool>) {
129 let mut tick = interval(FRAME_PERIOD);
130 while running.load(Ordering::SeqCst) {
131 tick.tick().await;
132 let frame = AudioFrame {
133 data: generator.next_frame().into(),
134 sample_rate: SAMPLE_RATE,
135 num_channels: 1,
136 samples_per_channel: FRAME_SAMPLES as u32,
137 };
138 if source.capture_frame(&frame).await.is_err() {
139 break;
140 }
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 #[test]
149 fn audio_mode_parses_the_environment_value() {
150 assert_eq!(AudioMode::parse(None), AudioMode::Platform);
151 assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone);
152 assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence);
153 assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);
154 }
155}