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