| 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::{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 | |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 20 | pub enum AudioMode { |
| 21 | #[default] |
| 22 | Platform, |
| 23 | Tone, |
| 24 | Silence, |
| 25 | } |
| 26 | |
| 27 | impl 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 | |
| 41 | pub struct AudioSetup { |
| 42 | factory: PeerConnectionFactory, |
| 43 | pub track: RtcAudioTrack, |
| 44 | pub listen_only: bool, |
| 45 | platform_acquired: bool, |
| 46 | feeder: Option<(JoinHandle<()>, Arc<AtomicBool>)>, |
| 47 | } |
| 48 | |
| 49 | impl AudioSetup { |
| 50 | pub fn start( |
| 51 | factory: &PeerConnectionFactory, |
| 52 | mode: AudioMode, |
| 53 | tone_hz: f32, |
| 54 | input: &DeviceChoice, |
| 55 | output: &DeviceChoice, |
| 56 | ) -> Self { |
| 57 | let platform_acquired = mode == AudioMode::Platform && factory.acquire_platform_adm(); |
| 58 | let has_input = platform_acquired && factory.recording_devices() > 0; |
| 59 | let has_output = platform_acquired && factory.playout_devices() > 0; |
| 60 | if platform_acquired { |
| 61 | factory.set_adm_recording_enabled(has_input); |
| 62 | factory.set_adm_playout_enabled(has_output); |
| 63 | if has_input && *input != DeviceChoice::SystemDefault { |
| 64 | devices::select_input(factory, input); |
| 65 | } |
| 66 | if has_output && *output != DeviceChoice::SystemDefault { |
| 67 | devices::select_output(factory, output); |
| 68 | } |
| 69 | } |
| 70 | if has_input { |
| 71 | return AudioSetup { |
| 72 | factory: factory.clone(), |
| 73 | track: factory.create_device_audio_track("microphone"), |
| 74 | listen_only: false, |
| 75 | platform_acquired, |
| 76 | feeder: None, |
| 77 | }; |
| 78 | } |
| 79 | let amplitude = if mode == AudioMode::Tone { TONE_AMPLITUDE } else { 0.0 }; |
| 80 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS); |
| 81 | let track = factory.create_audio_track("microphone", source.clone()); |
| 82 | let running = Arc::new(AtomicBool::new(true)); |
| 83 | let task = tokio::spawn(feed_frames(source, SineGenerator::new(tone_hz, amplitude), running.clone())); |
| 84 | AudioSetup { |
| 85 | factory: factory.clone(), |
| 86 | track, |
| 87 | listen_only: mode == AudioMode::Platform, |
| 88 | platform_acquired, |
| 89 | feeder: Some((task, running)), |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | pub fn uses_devices(&self) -> bool { |
| 94 | self.platform_acquired && self.feeder.is_none() |
| 95 | } |
| 96 | |
| 97 | pub async fn stop(self) { |
| 98 | if let Some((task, running)) = self.feeder { |
| 99 | running.store(false, Ordering::SeqCst); |
| 100 | let _ = task.await; |
| 101 | } |
| 102 | if self.platform_acquired { |
| 103 | self.factory.set_adm_recording_enabled(false); |
| 104 | self.factory.set_adm_playout_enabled(false); |
| 105 | self.factory.release_platform_adm(); |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | async fn feed_frames(source: NativeAudioSource, mut generator: SineGenerator, running: Arc<AtomicBool>) { |
| 111 | let mut tick = interval(FRAME_PERIOD); |
| 112 | while running.load(Ordering::SeqCst) { |
| 113 | tick.tick().await; |
| 114 | let frame = AudioFrame { |
| 115 | data: generator.next_frame().into(), |
| 116 | sample_rate: SAMPLE_RATE, |
| 117 | num_channels: 1, |
| 118 | samples_per_channel: FRAME_SAMPLES as u32, |
| 119 | }; |
| 120 | if source.capture_frame(&frame).await.is_err() { |
| 121 | break; |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | #[cfg(test)] |
| 127 | mod tests { |
| 128 | use super::*; |
| 129 | |
| 130 | #[test] |
| 131 | fn audio_mode_parses_the_environment_value() { |
| 132 | assert_eq!(AudioMode::parse(None), AudioMode::Platform); |
| 133 | assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone); |
| 134 | assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence); |
| 135 | assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform); |
| 136 | } |
| 137 | } |