| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use futures_util::StreamExt; |
| 6 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 7 | use libwebrtc::native::apm::AudioProcessingModule; |
| 8 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 9 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 10 | use libwebrtc::prelude::*; |
| 11 | use tokio::task::JoinHandle; |
| 12 | |
| 13 | use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator}; |
| 14 | use crate::audio_io::AudioMode; |
| 15 | use crate::capture::Capture; |
| 16 | use crate::devices::DeviceChoice; |
| 17 | use crate::error::{Error, Result}; |
| 18 | use crate::mixer::mix_frames; |
| 19 | use crate::pcm::SampleQueue; |
| 20 | use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone}; |
| 21 | |
| 22 | const SOURCE_QUEUE_MS: u32 = 100; |
| 23 | const FRAME_PERIOD: Duration = Duration::from_millis(10); |
| 24 | const MAX_LAG: Duration = Duration::from_millis(100); |
| 25 | const SYSTEM_TONE_HZ: f32 = 660.0; |
| 26 | const SYNTHETIC_AMPLITUDE: f32 = 0.3; |
| 27 | |
| 28 | enum FrameSource { |
| 29 | Captured(SampleQueue), |
| 30 | Tone(SineGenerator), |
| 31 | Silence, |
| 32 | } |
| 33 | |
| 34 | impl 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 | struct Feeder { |
| 45 | source: NativeAudioSource, |
| 46 | microphone: FrameSource, |
| 47 | computer: FrameSource, |
| 48 | far_end: SampleQueue, |
| 49 | microphone_muted: Arc<AtomicBool>, |
| 50 | running: Arc<AtomicBool>, |
| 51 | runtime: tokio::runtime::Handle, |
| 52 | } |
| 53 | |
| 54 | impl Feeder { |
| 55 | fn run(mut self) { |
| 56 | let mut processing = AudioProcessingModule::new(true, false, true, true); |
| 57 | let mut due = Instant::now(); |
| 58 | while self.running.load(Ordering::SeqCst) { |
| 59 | due += FRAME_PERIOD; |
| 60 | let now = Instant::now(); |
| 61 | if due > now { |
| 62 | std::thread::sleep(due - now); |
| 63 | } else if now - due > MAX_LAG { |
| 64 | due = now; |
| 65 | } |
| 66 | let (mut far_end, has_far_end) = self.far_end.next_frame(); |
| 67 | if has_far_end { |
| 68 | let _ = processing.process_reverse_stream(&mut far_end, SAMPLE_RATE as i32, 1); |
| 69 | } |
| 70 | let muted = self.microphone_muted.load(Ordering::SeqCst); |
| 71 | let mut microphone = self.microphone.next_frame(); |
| 72 | if !muted { |
| 73 | let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1); |
| 74 | } |
| 75 | let computer = self.computer.next_frame(); |
| 76 | let frame = AudioFrame { |
| 77 | data: mix_frames(µphone, &computer, muted).into(), |
| 78 | sample_rate: SAMPLE_RATE, |
| 79 | num_channels: 1, |
| 80 | samples_per_channel: FRAME_SAMPLES as u32, |
| 81 | }; |
| 82 | if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() { |
| 83 | break; |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// Mic plus computer sound mixed into one track that replaces the device track while sharing. |
| 90 | pub struct ShareAudio { |
| 91 | pub track: RtcAudioTrack, |
| 92 | pub loopback: LoopbackKind, |
| 93 | pub warning: Option<String>, |
| 94 | microphone_muted: Arc<AtomicBool>, |
| 95 | running: Arc<AtomicBool>, |
| 96 | feeder: Option<std::thread::JoinHandle<()>>, |
| 97 | far_end_task: Option<JoinHandle<()>>, |
| 98 | _captures: Vec<Capture>, |
| 99 | } |
| 100 | |
| 101 | impl ShareAudio { |
| 102 | pub fn start( |
| 103 | factory: &PeerConnectionFactory, |
| 104 | mode: AudioMode, |
| 105 | tone_hz: f32, |
| 106 | input: &DeviceChoice, |
| 107 | microphone_muted: bool, |
| 108 | remote: Option<RtcAudioTrack>, |
| 109 | ) -> Result<Self> { |
| 110 | let mut captures = Vec::new(); |
| 111 | let mut warning = None; |
| 112 | let (microphone, computer, loopback) = if mode == AudioMode::Platform { |
| 113 | let computer_queue = SampleQueue::default(); |
| 114 | let started = start_loopback(computer_queue.clone())?; |
| 115 | captures.push(started.capture); |
| 116 | warning = started.warning; |
| 117 | let microphone_queue = SampleQueue::default(); |
| 118 | let microphone = match start_microphone(input, microphone_queue.clone()) { |
| 119 | Ok(capture) => { |
| 120 | captures.push(capture); |
| 121 | FrameSource::Captured(microphone_queue) |
| 122 | } |
| 123 | Err(error) => { |
| 124 | warning.get_or_insert(format!("microphone not captured while sharing sound: {error}")); |
| 125 | FrameSource::Silence |
| 126 | } |
| 127 | }; |
| 128 | (microphone, FrameSource::Captured(computer_queue), started.kind) |
| 129 | } else { |
| 130 | let microphone = if mode == AudioMode::Tone { |
| 131 | FrameSource::Tone(SineGenerator::new(tone_hz, SYNTHETIC_AMPLITUDE)) |
| 132 | } else { |
| 133 | FrameSource::Silence |
| 134 | }; |
| 135 | (microphone, FrameSource::Tone(SineGenerator::new(SYSTEM_TONE_HZ, SYNTHETIC_AMPLITUDE)), LoopbackKind::Synthetic) |
| 136 | }; |
| 137 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS); |
| 138 | let track = factory.create_audio_track("microphone", source.clone()); |
| 139 | let far_end = SampleQueue::default(); |
| 140 | let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone()))); |
| 141 | let microphone_muted = Arc::new(AtomicBool::new(microphone_muted)); |
| 142 | let running = Arc::new(AtomicBool::new(true)); |
| 143 | let feeder = Feeder { |
| 144 | source, |
| 145 | microphone, |
| 146 | computer, |
| 147 | far_end, |
| 148 | microphone_muted: microphone_muted.clone(), |
| 149 | running: running.clone(), |
| 150 | runtime: tokio::runtime::Handle::current(), |
| 151 | }; |
| 152 | let thread = std::thread::Builder::new() |
| 153 | .name("share-audio".into()) |
| 154 | .spawn(move || feeder.run()) |
| 155 | .map_err(|error| Error::Audio(format!("share audio thread: {error}")))?; |
| 156 | Ok(ShareAudio { |
| 157 | track, |
| 158 | loopback, |
| 159 | warning, |
| 160 | microphone_muted, |
| 161 | running, |
| 162 | feeder: Some(thread), |
| 163 | far_end_task, |
| 164 | _captures: captures, |
| 165 | }) |
| 166 | } |
| 167 | |
| 168 | pub fn set_microphone_muted(&self, muted: bool) { |
| 169 | self.microphone_muted.store(muted, Ordering::SeqCst); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | impl Drop for ShareAudio { |
| 174 | fn drop(&mut self) { |
| 175 | self.running.store(false, Ordering::SeqCst); |
| 176 | if let Some(task) = self.far_end_task.take() { |
| 177 | task.abort(); |
| 178 | } |
| 179 | if let Some(thread) = self.feeder.take() { |
| 180 | let _ = thread.join(); |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) { |
| 186 | let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1); |
| 187 | while let Some(frame) = stream.next().await { |
| 188 | queue.push(&frame.data); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | #[cfg(test)] |
| 193 | mod tests { |
| 194 | use super::*; |
| 195 | use crate::devices::shared_factory; |
| 196 | |
| 197 | #[tokio::test(flavor = "multi_thread")] |
| 198 | async fn synthetic_sources_start_and_stop_cleanly() { |
| 199 | let audio = ShareAudio::start(&shared_factory(), AudioMode::Tone, 440.0, &DeviceChoice::SystemDefault, true, None).unwrap(); |
| 200 | assert_eq!(audio.loopback, LoopbackKind::Synthetic); |
| 201 | assert!(audio.warning.is_none()); |
| 202 | audio.set_microphone_muted(false); |
| 203 | tokio::time::sleep(Duration::from_millis(60)).await; |
| 204 | drop(audio); |
| 205 | } |
| 206 | } |