gemini_adk_rs/live/
input_vad.rs1use std::time::Instant;
4
5pub trait InputAudioProcessor: Send {
11 fn process_frame(&mut self, frame: &mut Vec<i16>);
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum ActivityAuthority {
18 #[default]
20 Server,
21 Client,
26}
27
28use gemini_genai_rs::prelude::{VadConfig, VadEvent, VoiceActivityDetector};
29use gemini_genai_rs::vad::VadState;
30use serde::Serialize;
31
32#[derive(Debug, Clone, Serialize)]
34pub struct BackendVadSnapshot {
35 pub backend: &'static str,
37 pub sample_rate: u32,
39 pub frame_duration_ms: u32,
41 pub frame_size: usize,
43 pub state: &'static str,
45 pub speaking: bool,
47 pub last_probability: Option<f32>,
49 pub frames_processed: u64,
51 pub last_transition_ms_ago: Option<u64>,
53}
54
55pub 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 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 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 pub fn sample_rate(&self) -> u32 {
100 self.config.sample_rate
101 }
102
103 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 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}