Skip to main content

gemini_adk_rs/live/
input_vad.rs

1//! Backend input VAD for browser microphone PCM.
2
3use std::time::Instant;
4
5/// A per-frame processor applied to outgoing microphone audio inside
6/// [`LiveHandle::send_audio`](super::LiveHandle::send_audio) — the L1 seam
7/// the L2 `voice` chain (denoiser, noise gate) plugs into so hosted
8/// surfaces (web bridge, API server) get the same hardened path as native
9/// pumps. Runs on the send path: keep it fast and allocation-light.
10pub trait InputAudioProcessor: Send {
11    /// Process one PCM16 frame in place (the frame may change length).
12    fn process_frame(&mut self, frame: &mut Vec<i16>);
13}
14
15/// Who decides when user speech interrupts the model.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum ActivityAuthority {
18    /// The Live API's automatic activity detection decides (default).
19    #[default]
20    Server,
21    /// This client's input VAD decides: `send_audio` emits
22    /// `activityStart`/`activityEnd` marks on speech edges. Only meaningful
23    /// when the session was configured with automatic activity detection
24    /// disabled — otherwise the server ignores the marks.
25    Client,
26}
27
28use gemini_genai_rs::prelude::{VadConfig, VadEvent, VoiceActivityDetector};
29use gemini_genai_rs::vad::VadState;
30use serde::Serialize;
31
32/// Snapshot of backend VAD state for devtools and diagnostics.
33#[derive(Debug, Clone, Serialize)]
34pub struct BackendVadSnapshot {
35    /// Active detector backend name.
36    pub backend: &'static str,
37    /// Input sample rate in Hz.
38    pub sample_rate: u32,
39    /// Detector frame duration in milliseconds.
40    pub frame_duration_ms: u32,
41    /// Detector frame size in samples.
42    pub frame_size: usize,
43    /// Current detector state.
44    pub state: &'static str,
45    /// Whether the detector is currently in a speech state.
46    pub speaking: bool,
47    /// Last normalized speech probability or binary decision.
48    pub last_probability: Option<f32>,
49    /// Number of complete frames processed by the backend detector.
50    pub frames_processed: u64,
51    /// Milliseconds since the last speech start/end transition.
52    pub last_transition_ms_ago: Option<u64>,
53}
54
55/// Incremental VAD over arbitrary PCM16 byte chunks.
56pub struct BackendInputVad {
57    detector: VoiceActivityDetector,
58    config: VadConfig,
59    pending_samples: Vec<i16>,
60    frames_processed: u64,
61    last_transition_at: Option<Instant>,
62}
63
64impl BackendInputVad {
65    /// Create a backend input VAD with explicit detector configuration.
66    pub fn new(config: VadConfig) -> Self {
67        Self {
68            detector: VoiceActivityDetector::new(config.clone()),
69            config,
70            pending_samples: Vec::new(),
71            frames_processed: 0,
72            last_transition_at: None,
73        }
74    }
75
76    /// Process arbitrary little-endian PCM16 bytes and return speech edge events.
77    pub fn process_pcm_bytes(&mut self, bytes: &[u8]) -> Vec<VadEvent> {
78        self.pending_samples
79            .extend(gemini_genai_rs::buffer::convert::pcm16_le_samples(bytes));
80
81        let frame_size = self.config.frame_size();
82        if frame_size == 0 {
83            return Vec::new();
84        }
85
86        let mut events = Vec::new();
87        while self.pending_samples.len() >= frame_size {
88            let frame: Vec<i16> = self.pending_samples.drain(..frame_size).collect();
89            self.frames_processed += 1;
90            if let Some(event) = self.detector.process_frame(&frame) {
91                self.last_transition_at = Some(Instant::now());
92                events.push(event);
93            }
94        }
95        events
96    }
97
98    /// The detector's configured input sample rate in Hz.
99    pub fn sample_rate(&self) -> u32 {
100        self.config.sample_rate
101    }
102
103    /// Return a diagnostics snapshot suitable for UI/devtools display.
104    pub fn snapshot(&self) -> BackendVadSnapshot {
105        BackendVadSnapshot {
106            backend: self.detector.backend_name(),
107            sample_rate: self.config.sample_rate,
108            frame_duration_ms: self.config.frame_duration_ms,
109            frame_size: self.config.frame_size(),
110            state: state_name(self.detector.state()),
111            speaking: self.detector.is_speaking(),
112            last_probability: self.detector.last_probability(),
113            frames_processed: self.frames_processed,
114            last_transition_ms_ago: self
115                .last_transition_at
116                .map(|instant| instant.elapsed().as_millis() as u64),
117        }
118    }
119
120    #[cfg(test)]
121    /// Whether the detector is currently speaking.
122    pub fn is_speaking(&self) -> bool {
123        self.detector.is_speaking()
124    }
125}
126
127impl Default for BackendInputVad {
128    fn default() -> Self {
129        Self::new(VadConfig {
130            sample_rate: 16000,
131            frame_duration_ms: 30,
132            min_speech_frames: 2,
133            hangover_frames: 8,
134            ..VadConfig::default()
135        })
136    }
137}
138
139fn state_name(state: VadState) -> &'static str {
140    match state {
141        VadState::Silence => "silence",
142        VadState::PendingSpeech => "pending_speech",
143        VadState::Speech => "speech",
144        VadState::Hangover => "hangover",
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    fn speech_frame(len: usize, amplitude: i16) -> Vec<i16> {
153        (0..len)
154            .map(|i| if i % 4 < 2 { amplitude } else { -amplitude })
155            .collect()
156    }
157
158    fn bytes(samples: &[i16]) -> Vec<u8> {
159        gemini_genai_rs::buffer::convert::i16_to_pcm16_le(samples)
160    }
161
162    #[test]
163    fn buffers_arbitrary_chunks_into_vad_frames() {
164        let mut vad = BackendInputVad::new(VadConfig {
165            sample_rate: 16000,
166            frame_duration_ms: 20,
167            min_speech_frames: 2,
168            hangover_frames: 2,
169            speech_zcr_range: (0.01, 0.9),
170            ..VadConfig::default()
171        });
172        let speech = speech_frame(640, 10000);
173        let half = bytes(&speech[..100]);
174        assert!(vad.process_pcm_bytes(&half).is_empty());
175
176        let rest = bytes(&speech[100..]);
177        let events = vad.process_pcm_bytes(&rest);
178        assert!(events.contains(&VadEvent::SpeechStart));
179        assert!(vad.is_speaking());
180    }
181}