1use anyhow::{Context as _, Result};
2use collections::HashMap;
3use gpui::{App, BackgroundExecutor, BorrowAppContext, Global};
4use log::info;
5
6#[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
7mod non_windows_and_freebsd_deps {
8 pub(super) use gpui::AsyncApp;
9 pub(super) use libwebrtc::native::apm;
10 pub(super) use parking_lot::Mutex;
11 pub(super) use rodio::cpal::Sample;
12 pub(super) use rodio::source::LimitSettings;
13 pub(super) use std::sync::Arc;
14}
15
16#[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
17use non_windows_and_freebsd_deps::*;
18
19use rodio::{
20 Decoder, OutputStream, OutputStreamBuilder, Source, mixer::Mixer, nz, source::Buffered,
21};
22use settings::Settings;
23use std::{io::Cursor, num::NonZero, path::PathBuf, sync::atomic::Ordering, time::Duration};
24use util::ResultExt;
25
26mod audio_settings;
27mod replays;
28mod rodio_ext;
29pub use audio_settings::AudioSettings;
30pub use rodio_ext::RodioExt;
31
32use crate::audio_settings::LIVE_SETTINGS;
33
34// We are migrating to 16kHz sample rate from 48kHz. In the future
35// once we are reasonably sure most users have upgraded we will
36// remove the LEGACY parameters.
37//
38// We migrate to 16kHz because it is sufficient for speech and required
39// by the denoiser and future Speech to Text layers.
40pub const SAMPLE_RATE: NonZero<u32> = nz!(16000);
41pub const CHANNEL_COUNT: NonZero<u16> = nz!(1);
42pub const BUFFER_SIZE: usize = // echo canceller and livekit want 10ms of audio
43 (SAMPLE_RATE.get() as usize / 100) * CHANNEL_COUNT.get() as usize;
44
45pub const LEGACY_SAMPLE_RATE: NonZero<u32> = nz!(48000);
46pub const LEGACY_CHANNEL_COUNT: NonZero<u16> = nz!(2);
47
48pub const REPLAY_DURATION: Duration = Duration::from_secs(30);
49
50pub fn init(cx: &mut App) {
51 LIVE_SETTINGS.initialize(cx);
52}
53
54#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
55pub enum Sound {
56 Joined,
57 GuestJoined,
58 Leave,
59 Mute,
60 Unmute,
61 StartScreenshare,
62 StopScreenshare,
63 AgentDone,
64}
65
66impl Sound {
67 fn file(&self) -> &'static str {
68 match self {
69 Self::Joined => "joined_call",
70 Self::GuestJoined => "guest_joined_call",
71 Self::Leave => "leave_call",
72 Self::Mute => "mute",
73 Self::Unmute => "unmute",
74 Self::StartScreenshare => "start_screenshare",
75 Self::StopScreenshare => "stop_screenshare",
76 Self::AgentDone => "agent_done",
77 }
78 }
79}
80
81pub struct Audio {
82 output_handle: Option<OutputStream>,
83 output_mixer: Option<Mixer>,
84 #[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
85 pub echo_canceller: Arc<Mutex<apm::AudioProcessingModule>>,
86 source_cache: HashMap<Sound, Buffered<Decoder<Cursor<Vec<u8>>>>>,
87 replays: replays::Replays,
88}
89
90impl Default for Audio {
91 fn default() -> Self {
92 Self {
93 output_handle: Default::default(),
94 output_mixer: Default::default(),
95 #[cfg(not(any(
96 all(target_os = "windows", target_env = "gnu"),
97 target_os = "freebsd"
98 )))]
99 echo_canceller: Arc::new(Mutex::new(apm::AudioProcessingModule::new(
100 true, false, false, false,
101 ))),
102 source_cache: Default::default(),
103 replays: Default::default(),
104 }
105 }
106}
107
108impl Global for Audio {}
109
110impl Audio {
111 fn ensure_output_exists(&mut self) -> Result<&Mixer> {
112 #[cfg(debug_assertions)]
113 log::warn!(
114 "Audio does not sound correct without optimizations. Use a release build to debug audio issues"
115 );
116
117 if self.output_handle.is_none() {
118 let output_handle = OutputStreamBuilder::open_default_stream()
119 .context("Could not open default output stream")?;
120 info!("Output stream: {:?}", output_handle);
121 self.output_handle = Some(output_handle);
122 if let Some(output_handle) = &self.output_handle {
123 let (mixer, source) = rodio::mixer::mixer(CHANNEL_COUNT, SAMPLE_RATE);
124 // or the mixer will end immediately as its empty.
125 mixer.add(rodio::source::Zero::new(CHANNEL_COUNT, SAMPLE_RATE));
126 self.output_mixer = Some(mixer);
127
128 // The webrtc apm is not yet compiling for windows & freebsd
129 #[cfg(not(any(
130 any(all(target_os = "windows", target_env = "gnu")),
131 target_os = "freebsd"
132 )))]
133 let echo_canceller = Arc::clone(&self.echo_canceller);
134 #[cfg(not(any(
135 any(all(target_os = "windows", target_env = "gnu")),
136 target_os = "freebsd"
137 )))]
138 let source = source.inspect_buffer::<BUFFER_SIZE, _>(move |buffer| {
139 let mut buf: [i16; _] = buffer.map(|s| s.to_sample());
140 echo_canceller
141 .lock()
142 .process_reverse_stream(
143 &mut buf,
144 SAMPLE_RATE.get() as i32,
145 CHANNEL_COUNT.get().into(),
146 )
147 .expect("Audio input and output threads should not panic");
148 });
149 output_handle.mixer().add(source);
150 }
151 }
152
153 Ok(self
154 .output_mixer
155 .as_ref()
156 .expect("we only get here if opening the outputstream succeeded"))
157 }
158
159 pub fn save_replays(
160 &self,
161 executor: BackgroundExecutor,
162 ) -> gpui::Task<anyhow::Result<(PathBuf, Duration)>> {
163 self.replays.replays_to_tar(executor)
164 }
165
166 #[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
167 pub fn open_microphone(voip_parts: VoipParts) -> anyhow::Result<impl Source> {
168 let stream = rodio::microphone::MicrophoneBuilder::new()
169 .default_device()?
170 .default_config()?
171 .prefer_sample_rates([
172 SAMPLE_RATE, // sample rates trivially resamplable to `SAMPLE_RATE`
173 SAMPLE_RATE.saturating_mul(nz!(2)),
174 SAMPLE_RATE.saturating_mul(nz!(3)),
175 SAMPLE_RATE.saturating_mul(nz!(4)),
176 ])
177 .prefer_channel_counts([nz!(1), nz!(2), nz!(3), nz!(4)])
178 .prefer_buffer_sizes(512..)
179 .open_stream()?;
180 info!("Opened microphone: {:?}", stream.config());
181
182 let stream = stream
183 .possibly_disconnected_channels_to_mono()
184 .constant_samplerate(SAMPLE_RATE)
185 .limit(LimitSettings::live_performance())
186 .process_buffer::<BUFFER_SIZE, _>(move |buffer| {
187 let mut int_buffer: [i16; _] = buffer.map(|s| s.to_sample());
188 if voip_parts
189 .echo_canceller
190 .lock()
191 .process_stream(
192 &mut int_buffer,
193 SAMPLE_RATE.get() as i32,
194 CHANNEL_COUNT.get() as i32,
195 )
196 .context("livekit audio processor error")
197 .log_err()
198 .is_some()
199 {
200 for (sample, processed) in buffer.iter_mut().zip(&int_buffer) {
201 *sample = (*processed).to_sample();
202 }
203 }
204 })
205 .denoise()
206 .context("Could not set up denoiser")?
207 .automatic_gain_control(0.90, 1.0, 0.0, 5.0)
208 .periodic_access(Duration::from_millis(100), move |agc_source| {
209 agc_source
210 .set_enabled(LIVE_SETTINGS.auto_microphone_volume.load(Ordering::Relaxed));
211 let denoise = agc_source.inner_mut();
212 denoise.set_enabled(LIVE_SETTINGS.denoise.load(Ordering::Relaxed));
213 });
214
215 let stream = if voip_parts.legacy_audio_compatible {
216 stream.constant_params(LEGACY_CHANNEL_COUNT, LEGACY_SAMPLE_RATE)
217 } else {
218 stream.constant_params(CHANNEL_COUNT, SAMPLE_RATE)
219 };
220
221 let (replay, stream) = stream.replayable(REPLAY_DURATION)?;
222 voip_parts
223 .replays
224 .add_voip_stream("local microphone".to_string(), replay);
225
226 Ok(stream)
227 }
228
229 pub fn play_voip_stream(
230 source: impl rodio::Source + Send + 'static,
231 speaker_name: String,
232 is_staff: bool,
233 cx: &mut App,
234 ) -> anyhow::Result<()> {
235 let (replay_source, source) = source
236 .constant_params(CHANNEL_COUNT, SAMPLE_RATE)
237 .automatic_gain_control(0.90, 1.0, 0.0, 5.0)
238 .periodic_access(Duration::from_millis(100), move |agc_source| {
239 agc_source.set_enabled(LIVE_SETTINGS.auto_speaker_volume.load(Ordering::Relaxed));
240 })
241 .replayable(REPLAY_DURATION)
242 .expect("REPLAY_DURATION is longer than 100ms");
243
244 cx.update_default_global(|this: &mut Self, _cx| {
245 let output_mixer = this
246 .ensure_output_exists()
247 .context("Could not get output mixer")?;
248 output_mixer.add(source);
249 if is_staff {
250 this.replays.add_voip_stream(speaker_name, replay_source);
251 }
252 Ok(())
253 })
254 }
255
256 pub fn play_sound(sound: Sound, cx: &mut App) {
257 cx.update_default_global(|this: &mut Self, cx| {
258 let source = this.sound_source(sound, cx).log_err()?;
259 let output_mixer = this
260 .ensure_output_exists()
261 .context("Could not get output mixer")
262 .log_err()?;
263
264 output_mixer.add(source);
265 Some(())
266 });
267 }
268
269 pub fn end_call(cx: &mut App) {
270 cx.update_default_global(|this: &mut Self, _cx| {
271 this.output_handle.take();
272 });
273 }
274
275 fn sound_source(&mut self, sound: Sound, cx: &App) -> Result<impl Source + use<>> {
276 if let Some(wav) = self.source_cache.get(&sound) {
277 return Ok(wav.clone());
278 }
279
280 let path = format!("sounds/{}.wav", sound.file());
281 let bytes = cx
282 .asset_source()
283 .load(&path)?
284 .map(anyhow::Ok)
285 .with_context(|| format!("No asset available for path {path}"))??
286 .into_owned();
287 let cursor = Cursor::new(bytes);
288 let source = Decoder::new(cursor)?.buffered();
289
290 self.source_cache.insert(sound, source.clone());
291
292 Ok(source)
293 }
294}
295
296#[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
297pub struct VoipParts {
298 echo_canceller: Arc<Mutex<apm::AudioProcessingModule>>,
299 replays: replays::Replays,
300 legacy_audio_compatible: bool,
301}
302
303#[cfg(not(any(all(target_os = "windows", target_env = "gnu"), target_os = "freebsd")))]
304impl VoipParts {
305 pub fn new(cx: &AsyncApp) -> anyhow::Result<Self> {
306 let (apm, replays) = cx.try_read_default_global::<Audio, _>(|audio, _| {
307 (Arc::clone(&audio.echo_canceller), audio.replays.clone())
308 })?;
309 let legacy_audio_compatible =
310 AudioSettings::try_read_global(cx, |settings| settings.legacy_audio_compatible)
311 .unwrap_or(true);
312
313 Ok(Self {
314 legacy_audio_compatible,
315 echo_canceller: apm,
316 replays,
317 })
318 }
319}