//! Microphone capture: cpal (PipeWire through ALSA) resampled to 16 kHz mono with rubato, or a named //! PipeWire/Pulse source through `parec`. Emits 100 ms frames (1600 samples) and a level meter. use std::io::Read; use std::str::FromStr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use anyhow::{Context, Result, bail}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use crossbeam_channel::{Sender, TrySendError}; use rubato::Resampler; pub const FRAME: usize = 1600; /// At most 5 s of audio waits for the recognizer. pub const QUEUE_FRAMES: usize = 50; const PULSE: &str = "pulse:"; pub const UNAVAILABLE: &str = "The selected microphone is unavailable. Choose a device in Menu → Microphone input."; pub const OVERFLOW: &str = "Microphone audio could not keep up. Enable the microphone to retry."; #[derive(Clone, Debug, PartialEq)] pub struct InputDevice { pub id: String, pub label: String, } fn clean_label(label: &str, n: usize) -> String { let label: String = label.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::().trim().chars().take(180).collect(); if label.is_empty() { format!("Microphone {n}") } else { label } } /// Input devices: ALSA/cpal devices, then PipeWire sources (`pulse:`, monitors and Capri's own excluded). /// Only metadata is read; no stream is opened. pub fn input_devices() -> Vec { let mut out = Vec::new(); if let Ok(devices) = cpal::default_host().input_devices() { for device in devices.take(64) { if let (Ok(id), Ok(description)) = (device.id(), device.description()) { out.push(InputDevice { id: id.to_string(), label: clean_label(description.name(), out.len() + 1) }); } } } if let Ok(output) = std::process::Command::new("pactl").args(["--format=json", "list", "sources"]).output() { out.extend(pulse_sources(&String::from_utf8_lossy(&output.stdout))); } out.truncate(128); out } fn pulse_sources(json: &str) -> Vec { let list: Vec = serde_json::from_str(json).unwrap_or_default(); list.iter() .filter_map(|s| { let name = s["name"].as_str()?; let monitor = s["monitor_source_of_sink"].as_str().is_some_and(|m| !m.is_empty() && m != "n/a") || name.ends_with(".monitor"); (!monitor && !name.starts_with("capri_") && name.len() <= 512).then(|| InputDevice { id: format!("{PULSE}{name}"), label: clean_label(s["description"].as_str().unwrap_or(name), 0), }) }) .collect() } /// Groups 16 kHz mono samples into 100 ms frames and updates the level meter (`min(1, rms × 10)`). pub struct Framer { pending: Vec, level: Arc, } impl Framer { pub fn new(level: Arc) -> Self { Self { pending: Vec::with_capacity(FRAME * 2), level } } pub fn push(&mut self, samples: &[f32], mut frame: impl FnMut(Vec) -> Result<()>) -> Result<()> { self.pending.extend(samples.iter().map(|x| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 })); while self.pending.len() >= FRAME { let f: Vec = self.pending.drain(..FRAME).collect(); let rms = (f.iter().map(|x| x * x).sum::() / FRAME as f32).sqrt(); self.level.store((rms * 10.0).min(1.0).to_bits(), Ordering::Relaxed); frame(f)?; } Ok(()) } } /// Running capture; dropping it stops the device. pub struct Capture { stop: Arc, } impl Drop for Capture { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); } } fn deliver(frames: &Sender>) -> impl FnMut(Vec) -> Result<()> + '_ { |f| match frames.try_send(f) { Ok(()) => Ok(()), Err(TrySendError::Full(_)) => bail!(OVERFLOW), Err(TrySendError::Disconnected(_)) => bail!("stopped"), } } /// Opens `device_id` (empty = system default) exactly; never falls back to another device. /// Frames go to `frames` (bounded to [`QUEUE_FRAMES`]); a failure calls `on_error` once and ends capture. pub fn start(device_id: &str, frames: Sender>, level: Arc, on_error: impl Fn(String) + Send + 'static) -> Result { let stop = Arc::new(AtomicBool::new(false)); let flag = stop.clone(); let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1); let device_id = device_id.to_string(); std::thread::Builder::new().name("capri-microphone".into()).spawn(move || { let result = if let Some(source) = device_id.strip_prefix(PULSE) { pulse_loop(source, &flag, &frames, level, &ready_tx) } else { cpal_loop(&device_id, &flag, &frames, level, &ready_tx) }; if let Err(e) = result { let message = e.to_string(); if ready_tx.try_send(Err(e)).is_err() && !flag.load(Ordering::Relaxed) && message != "stopped" { on_error(message); } } })?; ready_rx.recv().context("Microphone thread failed")??; Ok(Capture { stop }) } type Ready = std::sync::mpsc::SyncSender>; fn pulse_loop(source: &str, stop: &AtomicBool, frames: &Sender>, level: Arc, ready: &Ready) -> Result<()> { use std::os::unix::process::CommandExt; let mut command = std::process::Command::new("parec"); command.args([&format!("--device={source}"), "--format=float32le", "--rate=16000", "--channels=1", "--raw", "--latency-msec=50", "--client-name=Capri", "--stream-name=Capri microphone"]); unsafe { command.pre_exec(|| { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); Ok(()) }); } let mut child = command.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).spawn().context(UNAVAILABLE)?; let mut stdout = child.stdout.take().context(UNAVAILABLE)?; let _ = ready.try_send(Ok(())); let mut framer = Framer::new(level); let mut bytes = vec![0u8; FRAME * 4]; let result = loop { if stop.load(Ordering::Relaxed) { break Ok(()); } if stdout.read_exact(&mut bytes).is_err() { break Err(anyhow::anyhow!("The microphone disconnected. Choose an available device in Menu → Microphone input.")); } let samples: Vec = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); if let Err(e) = framer.push(&samples, deliver(frames)) { break Err(e); } }; let _ = child.kill(); let _ = child.wait(); result } fn cpal_loop(device_id: &str, stop: &AtomicBool, frames: &Sender>, level: Arc, ready: &Ready) -> Result<()> { let host = cpal::default_host(); let device = if device_id.is_empty() { host.default_input_device() } else { cpal::DeviceId::from_str(device_id).ok().and_then(|id| host.device_by_id(&id)) } .context(UNAVAILABLE)?; let config = device.default_input_config().context(UNAVAILABLE)?; let (channels, rate) = (config.channels() as usize, config.sample_rate()); let (raw_tx, raw_rx) = crossbeam_channel::bounded::>(64); let (err_tx, err_rx) = crossbeam_channel::bounded::(1); let mono = move |data: &[f32]| data.chunks(channels).map(|c| c.iter().sum::() / channels as f32).collect::>(); let on_error = move |e: cpal::Error| { let _ = err_tx.try_send(format!("The microphone disconnected. Choose an available device in Menu → Microphone input. ({e})")); }; let stream = match config.sample_format() { cpal::SampleFormat::F32 => { let tx = raw_tx.clone(); device.build_input_stream::(config.config(), move |d, _| { let _ = tx.try_send(mono(d)); }, on_error, None) } cpal::SampleFormat::I16 => { let tx = raw_tx.clone(); device.build_input_stream::( config.config(), move |d, _| { let f: Vec = d.iter().map(|s| *s as f32 / 32768.0).collect(); let _ = tx.try_send(mono(&f)); }, on_error, None, ) } other => bail!("Unsupported microphone sample format {other:?}"), } .context(UNAVAILABLE)?; stream.play().context(UNAVAILABLE)?; let _ = ready.try_send(Ok(())); let mut framer = Framer::new(level); let mut resampler = (rate != 16_000).then(|| rubato::Fft::::new(rate as usize, 16_000, 1024, 1, rubato::FixedSync::Input)).transpose()?; let mut pending: Vec = Vec::new(); while !stop.load(Ordering::Relaxed) { if let Ok(message) = err_rx.try_recv() { bail!(message); } let Ok(block) = raw_rx.recv_timeout(std::time::Duration::from_millis(100)) else { continue }; let Some(r) = resampler.as_mut() else { framer.push(&block, deliver(frames))?; continue; }; pending.extend(block); while pending.len() >= r.input_frames_next() { let n = r.input_frames_next(); let input = rubato::audioadapter_buffers::direct::InterleavedSlice::new(&pending[..n], 1, n)?; let out = r.process(&input, None)?.take_data(); pending.drain(..n); framer.push(&out, deliver(frames))?; } } Ok(()) } /// One-shot resampling of a whole clip (e.g. Piper's 22.05 kHz voice to 24 kHz). pub fn resample_clip(pcm: &[f32], from: u32, to: u32) -> Result> { if from == to || pcm.is_empty() { return Ok(pcm.to_vec()); } let mut r = rubato::Fft::::new(from as usize, to as usize, 1024, 1, rubato::FixedSync::Input)?; let input = rubato::audioadapter_buffers::direct::InterleavedSlice::new(pcm, 1, pcm.len())?; Ok(r.process_all(&input, pcm.len(), None)?.take_data()) } #[cfg(test)] mod tests { use super::*; #[test] fn framer_emits_100ms_frames_and_level() { let level = Arc::new(AtomicU32::new(0)); let mut framer = Framer::new(level.clone()); let mut frames = Vec::new(); framer.push(&vec![0.05; 1000], |f| { frames.push(f); Ok(()) }).unwrap(); assert!(frames.is_empty()); framer.push(&[vec![0.05; 2300], vec![f32::NAN; 1]].concat(), |f| { frames.push(f); Ok(()) }).unwrap(); assert_eq!(frames.len(), 2); assert!((f32::from_bits(level.load(Ordering::Relaxed)) - 0.5).abs() < 1e-5); let (tx, rx) = crossbeam_channel::bounded(1); let mut send = deliver(&tx); send(vec![]).unwrap(); assert_eq!(send(vec![]).unwrap_err().to_string(), OVERFLOW); drop(rx); } #[test] fn resampling_keeps_duration_and_tone() { let tone: Vec = (0..48_000).map(|i| (i as f32 * 2.0 * std::f32::consts::PI * 440.0 / 48_000.0).sin() * 0.5).collect(); let out = resample_clip(&tone, 48_000, 16_000).unwrap(); assert!((out.len() as i64 - 16_000).abs() < 10, "{}", out.len()); let rms = (out[2000..14000].iter().map(|x| x * x).sum::() / 12000.0).sqrt(); assert!((rms - 0.5 / 2f32.sqrt()).abs() < 0.02, "{rms}"); } #[test] fn pulse_sources_skip_monitors_and_capri() { let json = r#"[{"name":"alsa_input.usb-Mic","description":"USB\u0007 Mic","monitor_source_of_sink":"n/a"}, {"name":"alsa_output.pci.monitor","description":"Monitor","monitor_source_of_sink":"alsa_output.pci"}, {"name":"capri_call_mic","description":"Capri"}]"#; assert_eq!(pulse_sources(json), vec![InputDevice { id: "pulse:alsa_input.usb-Mic".into(), label: "USB Mic".into() }]); } }