| 1 | use std::f32::consts::TAU; |
| 2 | |
| 3 | use anyhow::anyhow; |
| 4 | use cpal::{ |
| 5 | FromSample, Sample, SampleFormat, SizedSample, StreamConfig, |
| 6 | traits::{DeviceTrait as _, HostTrait as _, StreamTrait as _}, |
| 7 | }; |
| 8 | use gpui::{App, Subscription}; |
| 9 | use smol::channel::{Sender, unbounded}; |
| 10 | |
| 11 | use super::{AudioFormat, AudioInput, AudioSink, SpeechError}; |
| 12 | |
| 13 | /// The default audio input device, captured through the platform's audio API |
| 14 | /// (Core Audio, WASAPI or ALSA). |
| 15 | /// |
| 16 | /// The device's own format is mixed down to mono and resampled to the format |
| 17 | /// the recognizer asks for. |
| 18 | /// |
| 19 | /// On macOS the application's `Info.plist` must describe why it uses the |
| 20 | /// microphone (`NSMicrophoneUsageDescription`), or the system refuses access |
| 21 | /// without asking. |
| 22 | #[derive(Debug, Default, Clone)] |
| 23 | pub struct Microphone { |
| 24 | _private: (), |
| 25 | } |
| 26 | |
| 27 | impl AudioInput for Microphone { |
| 28 | fn start( |
| 29 | &self, |
| 30 | format: AudioFormat, |
| 31 | sink: AudioSink, |
| 32 | cx: &mut App, |
| 33 | ) -> Result<Subscription, SpeechError> { |
| 34 | #[cfg(target_os = "macos")] |
| 35 | if super::system::macos::is_microphone_denied() { |
| 36 | return Err(SpeechError::PermissionDenied); |
| 37 | } |
| 38 | |
| 39 | let device = cpal::default_host() |
| 40 | .default_input_device() |
| 41 | .ok_or(SpeechError::NoInputDevice)?; |
| 42 | let supported = device.default_input_config().map_err(SpeechError::input)?; |
| 43 | let sample_format = supported.sample_format(); |
| 44 | let config: StreamConfig = supported.into(); |
| 45 | let source_rate = config.sample_rate.0; |
| 46 | |
| 47 | let (tx, rx) = unbounded(); |
| 48 | let stream = match sample_format { |
| 49 | SampleFormat::F32 => build_stream::<f32>(&device, &config, tx), |
| 50 | SampleFormat::I16 => build_stream::<i16>(&device, &config, tx), |
| 51 | SampleFormat::U16 => build_stream::<u16>(&device, &config, tx), |
| 52 | SampleFormat::I32 => build_stream::<i32>(&device, &config, tx), |
| 53 | other => { |
| 54 | return Err(SpeechError::input(anyhow!( |
| 55 | "unsupported sample format {other}" |
| 56 | ))); |
| 57 | } |
| 58 | }?; |
| 59 | stream.play().map_err(SpeechError::input)?; |
| 60 | |
| 61 | let task = cx.spawn(async move |cx| { |
| 62 | let mut converter = Converter::new(source_rate, format); |
| 63 | let mut mono = Vec::new(); |
| 64 | while let Ok(first) = rx.recv().await { |
| 65 | // The device delivers ~10 ms chunks; forward what has queued up |
| 66 | // as one push so the state updates once per batch. |
| 67 | let mut error = None; |
| 68 | for capture in |
| 69 | std::iter::once(first).chain(std::iter::from_fn(|| rx.try_recv().ok())) |
| 70 | { |
| 71 | match capture { |
| 72 | Capture::Samples(samples) => mono.extend_from_slice(&samples), |
| 73 | Capture::Error(message) => error = Some(message), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | let samples = converter.convert(&mono); |
| 78 | mono.clear(); |
| 79 | cx.update(|cx| { |
| 80 | if !samples.is_empty() { |
| 81 | sink.push(samples, cx); |
| 82 | } |
| 83 | if let Some(message) = error.take() { |
| 84 | sink.error(SpeechError::input(anyhow!(message)), cx); |
| 85 | } |
| 86 | }); |
| 87 | } |
| 88 | }); |
| 89 | |
| 90 | Ok(Subscription::new(move || { |
| 91 | drop(stream); |
| 92 | drop(task); |
| 93 | })) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | enum Capture { |
| 98 | Samples(Vec<f32>), |
| 99 | Error(String), |
| 100 | } |
| 101 | |
| 102 | /// Open an input stream that sends each callback's frames, mixed down to mono, |
| 103 | /// through `tx`. Runs on the audio thread, so it only converts and sends. |
| 104 | fn build_stream<T>( |
| 105 | device: &cpal::Device, |
| 106 | config: &StreamConfig, |
| 107 | tx: Sender<Capture>, |
| 108 | ) -> Result<cpal::Stream, SpeechError> |
| 109 | where |
| 110 | T: SizedSample, |
| 111 | f32: FromSample<T>, |
| 112 | { |
| 113 | let channels = config.channels.max(1) as usize; |
| 114 | let error_tx = tx.clone(); |
| 115 | device |
| 116 | .build_input_stream( |
| 117 | config, |
| 118 | move |data: &[T], _| { |
| 119 | let mono = data |
| 120 | .chunks(channels) |
| 121 | .map(|frame| { |
| 122 | frame |
| 123 | .iter() |
| 124 | .map(|&sample| f32::from_sample(sample)) |
| 125 | .sum::<f32>() |
| 126 | / frame.len() as f32 |
| 127 | }) |
| 128 | .collect(); |
| 129 | _ = tx.try_send(Capture::Samples(mono)); |
| 130 | }, |
| 131 | move |error| { |
| 132 | _ = error_tx.try_send(Capture::Error(error.to_string())); |
| 133 | }, |
| 134 | None, |
| 135 | ) |
| 136 | .map_err(|error| match error { |
| 137 | cpal::BuildStreamError::DeviceNotAvailable => SpeechError::NoInputDevice, |
| 138 | error => SpeechError::input(error), |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | /// Converts mono `f32` audio at the device rate to interleaved `i16` audio in |
| 143 | /// the recognizer's format, carrying state across chunks. |
| 144 | struct Converter { |
| 145 | /// Source samples per output sample. |
| 146 | step: f64, |
| 147 | /// Position of the next output sample, in source samples, where `0.0` is |
| 148 | /// the last sample of the previous chunk. |
| 149 | position: f64, |
| 150 | previous: f32, |
| 151 | low_pass: Option<LowPass>, |
| 152 | channels: usize, |
| 153 | } |
| 154 | |
| 155 | impl Converter { |
| 156 | fn new(source_rate: u32, format: AudioFormat) -> Self { |
| 157 | let target_rate = format.sample_rate().max(1); |
| 158 | let source_rate = source_rate.max(1); |
| 159 | Self { |
| 160 | step: source_rate as f64 / target_rate as f64, |
| 161 | position: 1., |
| 162 | previous: 0., |
| 163 | // Downsampling folds everything above the new Nyquist rate back |
| 164 | // into the band speech lives in; filter it out first. |
| 165 | low_pass: (source_rate > target_rate) |
| 166 | .then(|| LowPass::new(target_rate as f32 * 0.45, source_rate as f32)), |
| 167 | channels: format.channels().max(1) as usize, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | fn convert(&mut self, input: &[f32]) -> Vec<i16> { |
| 172 | if input.is_empty() { |
| 173 | return Vec::new(); |
| 174 | } |
| 175 | let filtered; |
| 176 | let input = match self.low_pass.as_mut() { |
| 177 | Some(low_pass) => { |
| 178 | filtered = input |
| 179 | .iter() |
| 180 | .map(|&x| low_pass.process(x)) |
| 181 | .collect::<Vec<_>>(); |
| 182 | &filtered[..] |
| 183 | } |
| 184 | None => input, |
| 185 | }; |
| 186 | |
| 187 | let sample = |ix: usize| { |
| 188 | if ix == 0 { |
| 189 | self.previous |
| 190 | } else { |
| 191 | input[ix - 1] |
| 192 | } |
| 193 | }; |
| 194 | let last = input.len(); |
| 195 | let len = last as f64; |
| 196 | let mut output = Vec::with_capacity(((len / self.step) as usize + 1) * self.channels); |
| 197 | while self.position <= len { |
| 198 | let ix = self.position.floor() as usize; |
| 199 | let frac = (self.position - ix as f64) as f32; |
| 200 | let next = sample((ix + 1).min(last)); |
| 201 | let value = sample(ix) * (1. - frac) + next * frac; |
| 202 | let value = (value.clamp(-1., 1.) * i16::MAX as f32) as i16; |
| 203 | output.extend(std::iter::repeat_n(value, self.channels)); |
| 204 | self.position += self.step; |
| 205 | } |
| 206 | self.position -= len; |
| 207 | self.previous = input[input.len() - 1]; |
| 208 | output |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// Two cascaded one-pole low-pass filters, 12 dB per octave. |
| 213 | struct LowPass { |
| 214 | alpha: f32, |
| 215 | stages: [f32; 2], |
| 216 | } |
| 217 | |
| 218 | impl LowPass { |
| 219 | fn new(cutoff: f32, sample_rate: f32) -> Self { |
| 220 | Self { |
| 221 | alpha: 1. - (-TAU * cutoff / sample_rate).exp(), |
| 222 | stages: [0.; 2], |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | fn process(&mut self, mut x: f32) -> f32 { |
| 227 | for stage in &mut self.stages { |
| 228 | *stage += self.alpha * (x - *stage); |
| 229 | x = *stage; |
| 230 | } |
| 231 | x |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | #[cfg(test)] |
| 236 | mod tests { |
| 237 | use super::*; |
| 238 | |
| 239 | #[test] |
| 240 | fn converter_keeps_rate_and_duplicates_channels() { |
| 241 | let mut converter = Converter::new(16_000, AudioFormat::new(16_000, 2)); |
| 242 | let output = converter.convert(&[0., 0.5, -0.5]); |
| 243 | assert_eq!(output, vec![0, 0, 16383, 16383, -16383, -16383]); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn converter_downsamples_across_chunks() { |
| 248 | let mut converter = Converter::new(48_000, AudioFormat::default()); |
| 249 | let total: usize = (0..10).map(|_| converter.convert(&[0.; 480]).len()).sum(); |
| 250 | // 100 ms at 48 kHz is 100 ms at 16 kHz, whatever the chunking. |
| 251 | assert_eq!(total, 1_600); |
| 252 | } |
| 253 | |
| 254 | #[test] |
| 255 | fn converter_upsamples() { |
| 256 | let mut converter = Converter::new(8_000, AudioFormat::default()); |
| 257 | let total: usize = (0..10).map(|_| converter.convert(&[0.; 80]).len()).sum(); |
| 258 | // The first output lands on the first input sample, so the half step |
| 259 | // before it is never produced. |
| 260 | assert_eq!(total, 1_599); |
| 261 | } |
| 262 | } |