Skip to main content

gemini_adk_fluent_rs/voice/
devices.rs

1//! The `cpal` device adapter behind [`Talk`] — default microphone in, default
2//! speakers out, barge-in flush, drain signaling. Feature `voice-io`.
3
4use parking_lot::Mutex;
5use std::collections::VecDeque;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::time::Duration;
9
10use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
11use gemini_adk_rs::live::LiveHandle;
12use tokio::sync::mpsc;
13
14use super::{Playback, downmix, pump};
15
16/// Errors from the device layer.
17#[derive(Debug, thiserror::Error)]
18pub enum VoiceIoError {
19    /// No default input (microphone) device.
20    #[error("no default input device")]
21    NoInputDevice,
22    /// No default output (speaker) device.
23    #[error("no default output device")]
24    NoOutputDevice,
25    /// The audio backend refused a stream.
26    #[error("audio backend: {0}")]
27    Backend(String),
28}
29
30/// Run a full-duplex voice conversation on the system's default audio
31/// devices.
32///
33/// `talk()` bridges the default microphone and speakers into the session via
34/// [`pump`](super::pump): capture is down-mixed to mono and resampled to the
35/// session's input rate; model speech is resampled to the device rate and
36/// buffered; an interruption flushes the buffer instantly (barge-in); the
37/// session's voice reactor is told when playback drains. Returns when the
38/// session ends or on Ctrl-C.
39#[allow(async_fn_in_trait)]
40pub trait Talk {
41    /// See the trait docs. The five-line voice app:
42    ///
43    /// ```ignore
44    /// // `ignore`: opens the default microphone and speakers (feature `voice-io`).
45    /// Live::builder()
46    ///     .instruction("You are a helpful concierge.")
47    ///     .greeting("Greet the caller.")
48    ///     .connect_from_env().await?
49    ///     .talk().await?;
50    /// ```
51    async fn talk(&self) -> Result<(), VoiceIoError>;
52}
53
54impl Talk for LiveHandle {
55    async fn talk(&self) -> Result<(), VoiceIoError> {
56        let host = cpal::default_host();
57        let input = host
58            .default_input_device()
59            .ok_or(VoiceIoError::NoInputDevice)?;
60        let output = host
61            .default_output_device()
62            .ok_or(VoiceIoError::NoOutputDevice)?;
63        let input_config = input
64            .default_input_config()
65            .map_err(|e| VoiceIoError::Backend(e.to_string()))?;
66        let output_config = output
67            .default_output_config()
68            .map_err(|e| VoiceIoError::Backend(e.to_string()))?;
69
70        let mic_hz = input_config.sample_rate();
71        let mic_channels = input_config.channels();
72        let speaker_hz = output_config.sample_rate();
73        let speaker_channels = output_config.channels();
74
75        // Microphone → pump. Bounded; a saturated channel drops the frame
76        // (mic loss under pressure beats blocking the audio callback).
77        let (mic_tx, mic_rx) = mpsc::channel::<Vec<i16>>(64);
78        let capture = move |mono: Vec<i16>| {
79            let _ = mic_tx.try_send(mono);
80        };
81        let input_stream = build_input_stream(&input, &input_config, mic_channels, capture)?;
82
83        // Pump → speaker ring. The cpal output callback drains the ring;
84        // `Flush` clears it — barge-in silences the device within one buffer.
85        let ring: Arc<Mutex<VecDeque<i16>>> = Arc::new(Mutex::new(VecDeque::new()));
86        let was_playing = Arc::new(AtomicBool::new(false));
87        let (spk_tx, mut spk_rx) = mpsc::channel::<Playback>(64);
88        {
89            let ring = ring.clone();
90            let was_playing = was_playing.clone();
91            tokio::spawn(async move {
92                while let Some(playback) = spk_rx.recv().await {
93                    let mut ring = ring.lock();
94                    match playback {
95                        Playback::Chunk(samples) => {
96                            ring.extend(samples);
97                            was_playing.store(true, Ordering::Relaxed);
98                        }
99                        Playback::Flush => ring.clear(),
100                    }
101                }
102            });
103        }
104        let output_stream =
105            build_output_stream(&output, &output_config, speaker_channels, ring.clone())?;
106
107        input_stream
108            .play()
109            .map_err(|e| VoiceIoError::Backend(e.to_string()))?;
110        output_stream
111            .play()
112            .map_err(|e| VoiceIoError::Backend(e.to_string()))?;
113
114        let running = pump(self, mic_rx, mic_hz, spk_tx, speaker_hz);
115
116        // Tell the voice reactor when the speaker goes quiet, so prompt
117        // gating and barge-in accounting see real playback state.
118        let drain_handle = self.clone();
119        let drain_task = tokio::spawn(async move {
120            let mut interval = tokio::time::interval(Duration::from_millis(50));
121            loop {
122                interval.tick().await;
123                let empty = ring.lock().is_empty();
124                if empty && was_playing.swap(false, Ordering::Relaxed) {
125                    let _ = drain_handle.playback_drained().await;
126                }
127            }
128        });
129
130        // Converse until the session ends or the user hits Ctrl-C.
131        tokio::select! {
132            _ = running.join() => {}
133            _ = tokio::signal::ctrl_c() => {
134                let _ = self.disconnect().await;
135            }
136        }
137        drain_task.abort();
138        drop(input_stream);
139        drop(output_stream);
140        Ok(())
141    }
142}
143
144fn build_input_stream(
145    device: &cpal::Device,
146    config: &cpal::SupportedStreamConfig,
147    channels: u16,
148    on_mono: impl Fn(Vec<i16>) + Send + 'static,
149) -> Result<cpal::Stream, VoiceIoError> {
150    let stream_config: cpal::StreamConfig = config.config();
151    let err = |e: cpal::Error| VoiceIoError::Backend(e.to_string());
152    let stream = match config.sample_format() {
153        cpal::SampleFormat::I16 => device
154            .build_input_stream(
155                stream_config,
156                move |data: &[i16], _| on_mono(downmix(data, channels)),
157                |e| tracing::warn!("input stream error: {e}"),
158                None,
159            )
160            .map_err(err)?,
161        cpal::SampleFormat::F32 => device
162            .build_input_stream(
163                stream_config,
164                move |data: &[f32], _| {
165                    let pcm: Vec<i16> = data
166                        .iter()
167                        .map(|&s| (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)
168                        .collect();
169                    on_mono(downmix(&pcm, channels));
170                },
171                |e| tracing::warn!("input stream error: {e}"),
172                None,
173            )
174            .map_err(err)?,
175        other => {
176            return Err(VoiceIoError::Backend(format!(
177                "unsupported input sample format {other:?}"
178            )));
179        }
180    };
181    Ok(stream)
182}
183
184fn build_output_stream(
185    device: &cpal::Device,
186    config: &cpal::SupportedStreamConfig,
187    channels: u16,
188    ring: Arc<Mutex<VecDeque<i16>>>,
189) -> Result<cpal::Stream, VoiceIoError> {
190    let stream_config: cpal::StreamConfig = config.config();
191    let err = |e: cpal::Error| VoiceIoError::Backend(e.to_string());
192    let channels = channels as usize;
193    let stream = match config.sample_format() {
194        cpal::SampleFormat::I16 => device
195            .build_output_stream(
196                stream_config,
197                move |data: &mut [i16], _| {
198                    let mut ring = ring.lock();
199                    for frame in data.chunks_mut(channels) {
200                        let sample = ring.pop_front().unwrap_or(0);
201                        frame.fill(sample);
202                    }
203                },
204                |e| tracing::warn!("output stream error: {e}"),
205                None,
206            )
207            .map_err(err)?,
208        cpal::SampleFormat::F32 => device
209            .build_output_stream(
210                stream_config,
211                move |data: &mut [f32], _| {
212                    let mut ring = ring.lock();
213                    for frame in data.chunks_mut(channels) {
214                        let sample = ring.pop_front().unwrap_or(0) as f32 / i16::MAX as f32;
215                        frame.fill(sample);
216                    }
217                },
218                |e| tracing::warn!("output stream error: {e}"),
219                None,
220            )
221            .map_err(err)?,
222        other => {
223            return Err(VoiceIoError::Backend(format!(
224                "unsupported output sample format {other:?}"
225            )));
226        }
227    };
228    Ok(stream)
229}