//! Microphone session: capture → segmentation → whisper → wake gate → transcript rules //! (Capri `microphone-service.mjs`). Three threads: capture, controller, decoder. use std::collections::VecDeque; use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::time::{Duration, Instant}; use anyhow::Result; use crossbeam_channel::{Sender, TrySendError, bounded, select, unbounded}; use parking_lot::Mutex; use crate::asr::Recognizer; use crate::echo::{EchoGuard, interruption, local_stop, microphone_off}; use crate::segment::{Detector, Job, Phase, RecEvent, Recognition, Silero, Vad}; use crate::settings::SpeechSettings; use crate::wake::{GateOutput, GateState, WakeEvent, WakeGate, WordBoundary}; use crate::{MicStatus, VoiceEvent}; pub enum MicCommand { /// Follow-up window after a spoken question. Continue { ms: u64 }, /// "Listen now" (composer button): toggles the command window. ListenNow, /// The owner typed instead: close the command window. TypedInput, } const STOPPED: &str = "The local speech recognizer stopped. Restart the microphone."; fn bounded_push(set: &mut VecDeque, value: i64) { set.push_back(value); if set.len() > 64 { set.pop_front(); } } /// Transcript acceptance, wake gate and barge-in rules, independent of audio and threads. pub struct Controller { gate: WakeGate, recognition: Arc>, echo: Arc>, auto_send: bool, barge_in: bool, wake_enabled: bool, follow_ups: u32, finalized: VecDeque, barged: VecDeque, latest: i64, discarded_through: i64, pub phase: Phase, pub out: Vec, } impl Controller { pub fn new(settings: &SpeechSettings, recognition: Arc>, echo: Arc>) -> Self { Self { gate: WakeGate::new(settings.wake_word, settings.command_window_ms, settings.ambiguity_hold_ms), recognition, echo, auto_send: settings.auto_send, barge_in: settings.barge_in, wake_enabled: settings.wake_word, follow_ups: 0, finalized: VecDeque::new(), barged: VecDeque::new(), latest: -1, discarded_through: -1, phase: Phase::Idle, out: Vec::new(), } } pub fn wake_state(&self) -> GateState { self.gate.state } fn barge(&mut self, utterance: i64) { if self.barge_in && !self.barged.contains(&utterance) { bounded_push(&mut self.barged, utterance); self.out.push(VoiceEvent::Interrupt); } } pub fn handle(&mut self, event: RecEvent, now: Instant) { match event { RecEvent::State { phase, .. } => self.phase = phase, RecEvent::Reset { utterance, .. } => { self.discarded_through = self.discarded_through.max(utterance); self.gate.rearm(Some(utterance), "utterance-limit"); } RecEvent::WakeCandidate { utterance, text, boundaries } => self.transcript(utterance, 0, &text, false, boundaries, false, now), RecEvent::Transcript { utterance, revision, text, prefix_removed, .. } => { self.phase = Phase::Idle; self.transcript(utterance, revision, &text, true, Vec::new(), prefix_removed, now) } } self.tick(now); } #[allow(clippy::too_many_arguments)] fn transcript(&mut self, utterance: i64, revision: u64, text: &str, last: bool, boundaries: Vec, prefix_removed: bool, now: Instant) { if utterance <= self.discarded_through { return; } let echo = self.echo.lock().matches(text, now); if echo { self.gate.cancel_candidate(); } if self.finalized.contains(&utterance) { return; } self.latest = self.latest.max(utterance); if last && !echo && microphone_off(text) { self.out.push(VoiceEvent::StopRequest); return; } let observed = if !echo && (self.gate.state != GateState::Waiting || utterance == self.latest) { let event = WakeEvent { utterance, text: text.into(), last, boundaries, prefix_removed, refining: self.phase == Phase::Processing }; Some(self.gate.observe(&event, now, 90_000)) } else { None }; let Some(observed) = observed.filter(|o| o.accepted) else { if last && !self.gate.has_candidate() { bounded_push(&mut self.finalized, utterance); } return; }; if !last { return; // wake probes only open the gate; their words are never shown or sent } if interruption(&observed.text) { self.barge(utterance); } bounded_push(&mut self.finalized, utterance); if echo { return; } let text = observed.text; self.out.push(VoiceEvent::Transcript { utterance, revision, text: text.clone(), is_final: true, auto_send: self.auto_send }); if text.is_empty() { return; } self.gate.rearm(Some(utterance), "submitted"); if local_stop(&text) { self.out.push(VoiceEvent::LocalCommand { text }); } else if self.auto_send { self.follow_ups = 0; self.out.push(VoiceEvent::Submit { utterance, text }); } } pub fn command(&mut self, command: MicCommand, now: Instant) { match command { MicCommand::Continue { ms } => { if self.follow_ups < 3 && self.gate.continue_listening(now, ms) { self.follow_ups += 1; let _ = self.recognition.lock().set_attention(true, None, None); self.out.push(VoiceEvent::Wake { utterance: None, follow_up: true, manual: false }); } } MicCommand::ListenNow => { if self.gate.state == GateState::Command { self.gate.rearm(None, "manual"); } else { self.follow_ups = 0; if self.wake_enabled { self.gate.continue_listening(now, 30_000); } let _ = self.recognition.lock().set_attention(true, None, None); self.out.push(VoiceEvent::Wake { utterance: None, follow_up: false, manual: true }); } } MicCommand::TypedInput => { if self.gate.state == GateState::Command { self.gate.rearm(None, "typed-input"); } } } self.tick(now); } pub fn tick(&mut self, now: Instant) { for output in self.gate.tick(now) { match output { GateOutput::Wake { utterance, wake_end_sample } => { self.follow_ups = 0; let _ = self.recognition.lock().set_attention(true, Some(utterance), wake_end_sample); self.out.push(VoiceEvent::Wake { utterance: Some(utterance), follow_up: false, manual: false }); self.barge(utterance); } GateOutput::Ready(event) => { let (u, text, last, b, p) = (event.utterance, event.text, event.last, event.boundaries, event.prefix_removed); self.transcript(u, 0, &text, last, b, p, now); } GateOutput::Sleep(reason) => { let _ = self.recognition.lock().set_attention(false, None, None); if reason == "timeout" { // Clears the transcript preview. self.out.push(VoiceEvent::Transcript { utterance: -1, revision: 0, text: String::new(), is_final: false, auto_send: false }); } } } } } } /// Speech detector: Silero when downloaded, else the energy fallback. pub fn detector(speech: &Path) -> Detector { let model = crate::asr::silero_path(speech); match model.is_file().then(|| Silero::load(&model)) { Some(Ok(s)) => Detector::Silero(Box::new(s)), Some(Err(e)) => { tracing::warn!(error = %e, "Silero VAD unavailable; using the energy detector"); Detector::Energy } None => Detector::Energy, } } pub fn new_vad(speech: &Path, s: &SpeechSettings) -> Vad { Vad::new(detector(speech), s.vad_threshold, s.min_speech_seconds, s.trailing_silence_seconds, s.max_utterance_seconds) } /// A running microphone. Dropping it stops capture and both worker threads. pub struct Mic { commands: Sender, stop: Arc, _capture: crate::capture::Capture, } impl Mic { pub fn send(&self, command: MicCommand) { let _ = self.commands.send(command); } } impl Drop for Mic { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); } } enum Decoded { Loaded(Result<(), String>), Event(RecEvent), Failed, } pub type Sink = Arc; pub type RecognizerFactory = Box Result> + Send>; /// Starts capture on `settings.microphone_device` (exactly) and the recognizer. Events go to `sink`, /// ending with `Microphone(MicStatus { on: false, .. })`. pub fn start(settings: &SpeechSettings, language: &str, speech: &Path, echo: Arc>, level: Arc, recognizer: RecognizerFactory, sink: Sink) -> Result { let settings = settings.normalized(); let (frames_tx, frames_rx) = bounded(crate::capture::QUEUE_FRAMES); let (fail_tx, fail_rx) = bounded::(1); let capture = crate::capture::start(&settings.microphone_device, frames_tx, level, move |m| { let _ = fail_tx.try_send(m); })?; let vad = new_vad(speech, &settings); let recognition = Arc::new(Mutex::new(Recognition::new(vad, settings.wake_word, settings.max_utterance_seconds, settings.trailing_silence_seconds, settings.wake_probe_seconds))); let (job_tx, job_rx) = bounded::(2); let (dec_tx, dec_rx) = unbounded::(); let (cmd_tx, cmd_rx) = unbounded::(); let busy = Arc::new(AtomicBool::new(false)); let stop = Arc::new(AtomicBool::new(false)); let (rec, flag) = (recognition.clone(), busy.clone()); std::thread::Builder::new().name("capri-asr-decode".into()).spawn(move || { let mut recognizer = match recognizer() { Ok(r) => { let _ = dec_tx.send(Decoded::Loaded(Ok(()))); r } Err(e) => { let _ = dec_tx.send(Decoded::Loaded(Err(format!("{e:#}")))); return; } }; for job in job_rx { let attention = { let r = rec.lock(); if !r.is_current(&job) { continue; } r.attention }; flag.store(true, Ordering::Relaxed); let started = Instant::now(); let result = recognizer.recognize(&job.pcm, job.wake, attention); flag.store(false, Ordering::Relaxed); let elapsed = started.elapsed().as_secs_f64() * 1000.0; let mut r = rec.lock(); match result { Ok(result) => { if let Some(event) = r.deliver(&job, result, elapsed) { let _ = dec_tx.send(Decoded::Event(event)); } } // Decode failures are fatal: there is no weaker fallback. Err(_) if r.is_current(&job) => { let _ = dec_tx.send(Decoded::Failed); } Err(_) => {} } } })?; let language = language.to_string(); let flag = stop.clone(); std::thread::Builder::new().name("capri-microphone-control".into()).spawn(move || { let mut control = Controller::new(&settings, recognition.clone(), echo); let mut listening = false; let status = |c: &Controller, on: bool, listening: bool, error: Option| { VoiceEvent::Microphone(MicStatus { on, listening, wake_state: c.wake_state(), phase: c.phase, language: language.clone(), error }) }; sink(status(&control, true, false, None)); let mut last = (control.wake_state(), control.phase); let error = loop { if flag.load(Ordering::Relaxed) { break None; } let now = Instant::now(); let failure = select! { recv(frames_rx) -> frame => match frame { Ok(frame) => feed(&recognition, &mut control, &frame, &job_tx, &busy, now), Err(_) => Some(STOPPED.to_string()), }, recv(dec_rx) -> message => match message { Ok(Decoded::Loaded(Ok(()))) => { listening = true; sink(status(&control, true, true, None)); None } Ok(Decoded::Loaded(Err(e))) => Some(format!("Speech recognition could not start: {e}")), Ok(Decoded::Event(event)) => { control.handle(event, now); None } Ok(Decoded::Failed) | Err(_) => Some(STOPPED.to_string()), }, recv(cmd_rx) -> command => { if let Ok(c) = command { control.command(c, now); } None }, recv(fail_rx) -> message => Some(message.unwrap_or_else(|_| STOPPED.into())), default(Duration::from_millis(100)) => { control.tick(now); None }, }; for event in control.out.drain(..) { let stop = matches!(event, VoiceEvent::StopRequest); sink(event); if stop { flag.store(true, Ordering::Relaxed); } } if failure.is_some() { break failure; } if (control.wake_state(), control.phase) != last && listening { last = (control.wake_state(), control.phase); sink(status(&control, true, true, None)); } }; recognition.lock().stop(); sink(status(&control, false, false, error)); })?; Ok(Mic { commands: cmd_tx, stop, _capture: capture }) } fn feed(recognition: &Mutex, control: &mut Controller, frame: &[f32], jobs: &Sender, busy: &AtomicBool, now: Instant) -> Option { let idle = !busy.load(Ordering::Relaxed) && jobs.is_empty(); let (events, new_jobs) = match recognition.lock().accept(frame, false, idle) { Ok(v) => v, Err(_) => return Some("Microphone audio could not be delivered reliably. Restart the microphone.".into()), }; for job in new_jobs { match jobs.try_send(job) { Err(TrySendError::Full(job)) if !job.wake => return Some("Speech recognition is busy. Wait a moment, then restart the microphone.".into()), _ => {} } } for event in events { control.handle(event, now); } None } #[cfg(test)] mod tests { use super::*; fn controller(wake: bool) -> Controller { let settings = SpeechSettings { wake_word: wake, ..Default::default() }; let vad = Vad::new(Detector::Energy, 0.5, 0.12, 1.0, 30); let recognition = Arc::new(Mutex::new(Recognition::new(vad, wake, 30, 1.0, 0.8))); Controller::new(&settings, recognition, Arc::new(Mutex::new(EchoGuard::new(1.0)))) } fn final_text(c: &mut Controller, utterance: i64, text: &str, now: Instant) -> Vec { c.handle(RecEvent::Transcript { utterance, revision: 1, text: text.into(), audio_seconds: 1.0, prefix_removed: false, recognition_ms: 1.0 }, now); std::mem::take(&mut c.out) } fn submitted(events: &[VoiceEvent]) -> Option { events.iter().find_map(|e| match e { VoiceEvent::Submit { text, .. } => Some(text.clone()), _ => None, }) } #[test] fn without_wake_word_every_final_is_sent() { let mut c = controller(false); let events = final_text(&mut c, 0, " What time is it? ", Instant::now()); assert_eq!(submitted(&events).as_deref(), Some("What time is it?")); assert!(events.contains(&VoiceEvent::Interrupt), "speech interrupts Capri"); } #[test] fn wake_word_gates_strips_and_rearms() { let t = Instant::now(); let mut c = controller(true); assert!(final_text(&mut c, 0, "just chatting with a friend", t).is_empty()); let events = final_text(&mut c, 1, "Hey Capri, open Spotify", t); assert!(events.iter().any(|e| matches!(e, VoiceEvent::Wake { utterance: Some(1), .. }))); assert_eq!(submitted(&events).as_deref(), Some("open Spotify")); assert_eq!(c.wake_state(), GateState::Waiting, "back to waiting after each command"); assert!(final_text(&mut c, 2, "and the weather", t).is_empty()); } #[test] fn echo_commands_and_follow_up() { let t = Instant::now(); let mut c = controller(false); c.echo.lock().playback(true, "Sure, I am opening Spotify for you now.", t); assert_eq!(submitted(&final_text(&mut c, 0, "opening Spotify for you", t)), None, "own speech is ignored"); assert_eq!(final_text(&mut c, 1, "Microphone off.", t), vec![VoiceEvent::StopRequest]); let stop = final_text(&mut c, 2, "Stop!", t); assert!(stop.iter().any(|e| matches!(e, VoiceEvent::LocalCommand { .. })) && submitted(&stop).is_none()); let mut w = controller(true); for _ in 0..3 { w.command(MicCommand::Continue { ms: 12_000 }, t); assert!(w.out.drain(..).any(|e| matches!(e, VoiceEvent::Wake { follow_up: true, .. }))); w.command(MicCommand::TypedInput, t); } w.command(MicCommand::Continue { ms: 12_000 }, t); assert!(w.out.iter().all(|e| !matches!(e, VoiceEvent::Wake { .. })), "at most three chained follow-ups"); } #[test] fn window_timeout_clears_preview() { let t = Instant::now(); let mut c = controller(true); c.command(MicCommand::ListenNow, t); c.out.clear(); c.tick(t + Duration::from_secs(31)); assert!(c.out.iter().any(|e| matches!(e, VoiceEvent::Transcript { is_final: false, .. }))); assert_eq!(c.wake_state(), GateState::Waiting); } }