audio.rs

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