Skip to main content

hematite/ui/
voice.rs

1use crate::agent::inference::InferenceEvent;
2#[cfg(feature = "embedded-voice-assets")]
3use kokoros::tts::koko::TTSKoko;
4#[cfg(feature = "embedded-voice-assets")]
5use rodio::OutputStream;
6use rodio::Sink;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::mpsc;
9use std::sync::Arc;
10use tokio::sync::mpsc as tokio_mpsc;
11
12/// Manages the local Text-to-Speech pipeline.
13/// Uses the all-Rust `kokoros` engine for streaming synthesis.
14pub struct VoiceManager {
15    sender: mpsc::SyncSender<String>,
16    enabled: Arc<AtomicBool>,
17    available: Arc<AtomicBool>,
18    cancelled: Arc<AtomicBool>, // Immediate abort flag
19    sink: Arc<tokio::sync::Mutex<Option<Sink>>>,
20    /// Currently active voice ID — updated live by /voice command.
21    current_voice: Arc<std::sync::Mutex<String>>,
22    /// Speech speed multiplier (0.5–2.0). Read at synthesis time.
23    current_speed: Arc<std::sync::Mutex<f32>>,
24    /// Output volume (0.0–3.0). Applied to the rodio Sink.
25    current_volume: Arc<std::sync::Mutex<f32>>,
26}
27
28impl VoiceManager {
29    pub fn new(event_tx: tokio_mpsc::Sender<InferenceEvent>) -> Self {
30        let cfg = crate::agent::config::load_config();
31        let initial_voice = crate::agent::config::effective_voice(&cfg);
32        let initial_speed = crate::agent::config::effective_voice_speed(&cfg);
33        let initial_volume = crate::agent::config::effective_voice_volume(&cfg);
34        // Large buffer so tokens arriving during model load (~30-60s) aren't dropped.
35        let (tx, rx) = mpsc::sync_channel::<String>(1024);
36        let enabled = Arc::new(AtomicBool::new(true));
37        let available = Arc::new(AtomicBool::new(cfg!(feature = "embedded-voice-assets")));
38        let cancelled = Arc::new(AtomicBool::new(false));
39        let enabled_ctx = enabled.clone();
40        let available_ctx = available.clone();
41        let _cancelled_ctx = cancelled.clone();
42        let sink_shared = Arc::new(tokio::sync::Mutex::new(None));
43        let current_voice = Arc::new(std::sync::Mutex::new(initial_voice));
44        let current_speed = Arc::new(std::sync::Mutex::new(initial_speed));
45        let current_volume = Arc::new(std::sync::Mutex::new(initial_volume));
46        let _voice_synth = Arc::clone(&current_voice);
47        let _speed_synth = Arc::clone(&current_speed);
48        let _volume_synth = Arc::clone(&current_volume);
49        let sink_manager_clone = Arc::clone(&sink_shared);
50
51        // Dedicated thread for voice synthesis and playback
52        // This solves the 'rodio::OutputStream is not Send' issue.
53        let _ = std::thread::Builder::new()
54            .name("VoiceManager".into())
55            .stack_size(32 * 1024 * 1024) // 32MB Stack for deep ONNX graph optimization
56            .spawn(move || {
57                #[cfg(not(feature = "embedded-voice-assets"))]
58                {
59                    enabled_ctx.store(false, Ordering::SeqCst);
60                    available_ctx.store(false, Ordering::SeqCst);
61                    let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
62                        "Voice Engine: Disabled in crates.io/source build (use packaged releases for baked-in voice).".into(),
63                    ));
64                    while rx.recv().is_ok() {}
65                    return;
66                }
67
68                #[cfg(feature = "embedded-voice-assets")]
69                {
70                let mut _stream: Option<OutputStream> = None;
71
72                let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
73                    "Voice Engine: Initializing Audio Pipeline...".into(),
74                ));
75                let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
76                    "Voice Engine: Activating Baked-In Weights...".into(),
77                ));
78
79                // --- STATIC BAKE: Include weights in binary ---
80                const MODEL_BYTES: &[u8] =
81                    include_bytes!("../../.hematite/assets/voice/kokoro-v1.0.onnx");
82                const VOICES_BYTES: &[u8] =
83                    include_bytes!("../../.hematite/assets/voice/voices.bin");
84
85                let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
86                    "Voice Engine: Loading model (first start may take ~30s)...".into(),
87                ));
88
89                // Catch panics from ONNX Runtime init (e.g. API version mismatch with system DLL)
90                let tts_result = std::panic::catch_unwind(|| {
91                    TTSKoko::new_from_memory(MODEL_BYTES, VOICES_BYTES)
92                });
93
94                let tts = match tts_result {
95                    Ok(Ok(engine)) => {
96                        enabled_ctx.store(true, Ordering::SeqCst);
97                        if let Ok((s, handle)) = OutputStream::try_default() {
98                            _stream = Some(s);
99                            if let Ok(new_sink) = Sink::try_new(&handle) {
100                                let mut lock = sink_shared.blocking_lock();
101                                *lock = Some(new_sink);
102                            }
103                            let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
104                                "Voice Engine: Vibrant & Ready ✅".into(),
105                            ));
106                        } else {
107                            let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(
108                                "Voice Engine: ERROR - No audio device found ❌".into(),
109                            ));
110                        }
111                        Some(engine)
112                    }
113                    Ok(Err(e)) => {
114                        let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(format!(
115                            "Voice Engine: ERROR - {} ❌",
116                            e
117                        )));
118                        None
119                    }
120                    Err(panic_val) => {
121                        let msg = panic_val
122                            .downcast_ref::<String>()
123                            .map(|s| s.as_str())
124                            .or_else(|| panic_val.downcast_ref::<&str>().copied())
125                            .unwrap_or("unknown panic");
126                        let _ = event_tx.blocking_send(InferenceEvent::VoiceStatus(format!(
127                            "Voice Engine: CRASH - {} ❌",
128                            msg
129                        )));
130                        None
131                    }
132                };
133
134                // Stage 2: Background Synthesizer
135                let (synth_tx, mut synth_rx) = tokio_mpsc::channel::<String>(64);
136                let tts_shared = Arc::new(tokio::sync::Mutex::new(tts));
137                let tts_synth_clone = Arc::clone(&tts_shared);
138                let sink_synth_clone = Arc::clone(&sink_shared);
139                let event_tx_synth = event_tx.clone();
140
141                std::thread::spawn(move || {
142                    let rt = tokio::runtime::Builder::new_current_thread()
143                        .enable_all()
144                        .build()
145                        .unwrap();
146
147                    rt.block_on(async {
148                        while let Some(to_speak) = synth_rx.recv().await {
149                            let mut engine_opt = tts_synth_clone.lock().await;
150                            if let Some(ref mut engine) = *engine_opt {
151                                let voice_id = _voice_synth
152                                    .lock()
153                                    .map(|v| v.clone())
154                                    .unwrap_or_else(|_| "af_sky".to_string());
155                                let speed = _speed_synth.lock().map(|v| *v).unwrap_or(1.0);
156                                let volume = _volume_synth.lock().map(|v| *v).unwrap_or(1.0);
157                                let res = engine.tts_raw_audio_streaming(
158                                    &to_speak,
159                                    "en-us",
160                                    &voice_id,
161                                    speed,
162                                    None,
163                                    None,
164                                    None,
165                                    None,
166                                    |chunk| {
167                                        if _cancelled_ctx.load(Ordering::SeqCst) {
168                                            return Err(Box::new(std::io::Error::new(
169                                                std::io::ErrorKind::Interrupted,
170                                                "Silenced",
171                                            )));
172                                        }
173                                        if !chunk.is_empty() {
174                                            if let Ok(mut snk_opt) = sink_synth_clone.try_lock() {
175                                                if let Some(ref mut snk) = *snk_opt {
176                                                    snk.set_volume(volume);
177                                                    let source = rodio::buffer::SamplesBuffer::new(
178                                                        1, 24000, chunk,
179                                                    );
180                                                    snk.append(source);
181                                                    snk.play();
182                                                }
183                                            }
184                                        }
185                                        Ok(())
186                                    },
187                                );
188                                if let Err(e) = res {
189                                    if e.to_string() != "Silenced" {
190                                        let _ = event_tx_synth
191                                            .send(InferenceEvent::VoiceStatus(format!(
192                                                "Audio Pipeline: Synthesis Error - {}",
193                                                e
194                                            )))
195                                            .await;
196                                    }
197                                }
198                            }
199                            drop(engine_opt);
200                        }
201                    });
202                });
203
204                // Stage 1: Token Collector — builds tokens into sentences, then forwards to Stage 2.
205                // Runs after model load. Tokens that arrived during load are buffered in the 1024-cap channel.
206                let mut sentence_buffer = String::new();
207                let mut last_activity = std::time::Instant::now();
208
209                loop {
210                    let timeout = std::time::Duration::from_millis(150);
211                    let result = rx.recv_timeout(timeout);
212
213                    let token = match result {
214                        Ok(t) => {
215                            last_activity = std::time::Instant::now();
216                            Some(t)
217                        }
218                        Err(mpsc::RecvTimeoutError::Timeout) => {
219                            if !sentence_buffer.is_empty() && last_activity.elapsed() > timeout {
220                                None
221                            } else {
222                                continue;
223                            }
224                        }
225                        Err(mpsc::RecvTimeoutError::Disconnected) => break,
226                    };
227
228                    if let Some(ref text) = token {
229                        if !enabled_ctx.load(Ordering::Relaxed) || text == "\x03" {
230                            sentence_buffer.clear();
231                            continue;
232                        }
233                        if text == "\x04" {
234                            if !sentence_buffer.is_empty() {
235                                let to_speak = sentence_buffer.trim().to_string();
236                                sentence_buffer.clear();
237                                let _ = synth_tx.blocking_send(to_speak);
238                            }
239                            continue;
240                        }
241                        sentence_buffer.push_str(text);
242                    }
243
244                    let to_speak = sentence_buffer.trim().to_string();
245                    let has_punctuation = to_speak.ends_with('.')
246                        || to_speak.ends_with('!')
247                        || to_speak.ends_with('?')
248                        || to_speak.ends_with(':')
249                        || to_speak.ends_with('\n');
250
251                    let is_word_boundary = token
252                        .as_ref()
253                        .map(|t| t.starts_with(' ') || t.starts_with('\n') || t.starts_with('\t'))
254                        .unwrap_or(true);
255
256                    let is_done = token.is_none();
257
258                    if (!to_speak.is_empty() && has_punctuation && is_word_boundary)
259                        || (is_done && !to_speak.is_empty())
260                    {
261                        sentence_buffer.clear();
262                        let _ = synth_tx.blocking_send(to_speak);
263                    }
264                }
265                }
266            });
267
268        Self {
269            sender: tx,
270            enabled,
271            available,
272            cancelled,
273            sink: sink_manager_clone,
274            current_voice,
275            current_speed,
276            current_volume,
277        }
278    }
279
280    pub fn speak(&self, text: String) {
281        if self.enabled.load(Ordering::Relaxed) {
282            // New utterance: reset cancellation
283            self.cancelled.store(false, Ordering::SeqCst);
284            let _ = self.sender.try_send(text);
285        }
286    }
287
288    /// Forces a flush of the current sentence buffer.
289    pub fn stop(&self) {
290        self.cancelled.store(true, Ordering::SeqCst);
291        let _ = self.sender.try_send("\x03".to_string());
292        if let Ok(mut lock) = self.sink.try_lock() {
293            if let Some(sink) = lock.as_mut() {
294                sink.stop();
295                sink.pause();
296                sink.play();
297            }
298        }
299    }
300
301    pub fn flush(&self) {
302        if self.enabled.load(Ordering::Relaxed) {
303            let _ = self.sender.try_send("\x04".to_string());
304        }
305    }
306
307    pub fn toggle(&self) -> bool {
308        if !self.available.load(Ordering::Relaxed) {
309            self.enabled.store(false, Ordering::Relaxed);
310            return false;
311        }
312        let current = self.enabled.load(Ordering::Relaxed);
313        let next = !current;
314        self.enabled.store(next, Ordering::Relaxed);
315        next
316    }
317
318    pub fn is_enabled(&self) -> bool {
319        self.available.load(Ordering::Relaxed) && self.enabled.load(Ordering::Relaxed)
320    }
321
322    pub fn is_available(&self) -> bool {
323        self.available.load(Ordering::Relaxed)
324    }
325
326    /// Change the active voice. Takes effect on the next spoken sentence.
327    pub fn set_voice(&self, voice_id: &str) {
328        if let Ok(mut v) = self.current_voice.lock() {
329            *v = voice_id.to_string();
330        }
331    }
332
333    pub fn current_voice_id(&self) -> String {
334        self.current_voice
335            .lock()
336            .map(|v| v.clone())
337            .unwrap_or_else(|_| "af_sky".to_string())
338    }
339
340    pub fn set_speed(&self, speed: f32) {
341        if let Ok(mut v) = self.current_speed.lock() {
342            *v = speed.clamp(0.5, 2.0);
343        }
344    }
345
346    pub fn set_volume(&self, volume: f32) {
347        if let Ok(mut v) = self.current_volume.lock() {
348            *v = volume.clamp(0.0, 3.0);
349        }
350    }
351}
352
353/// All voices baked into voices.bin, grouped for display.
354pub const VOICE_LIST: &[(&str, &str)] = &[
355    ("af_alloy", "American Female — Alloy"),
356    ("af_aoede", "American Female — Aoede"),
357    ("af_bella", "American Female — Bella ⭐"),
358    ("af_heart", "American Female — Heart ⭐"),
359    ("af_jessica", "American Female — Jessica"),
360    ("af_kore", "American Female — Kore"),
361    ("af_nicole", "American Female — Nicole"),
362    ("af_nova", "American Female — Nova"),
363    ("af_river", "American Female — River"),
364    ("af_sarah", "American Female — Sarah"),
365    ("af_sky", "American Female — Sky (default)"),
366    ("am_adam", "American Male   — Adam"),
367    ("am_echo", "American Male   — Echo"),
368    ("am_eric", "American Male   — Eric"),
369    ("am_fenrir", "American Male   — Fenrir"),
370    ("am_liam", "American Male   — Liam"),
371    ("am_michael", "American Male   — Michael ⭐"),
372    ("am_onyx", "American Male   — Onyx"),
373    ("am_puck", "American Male   — Puck"),
374    ("bf_alice", "British Female  — Alice"),
375    ("bf_emma", "British Female  — Emma ⭐"),
376    ("bf_isabella", "British Female  — Isabella"),
377    ("bf_lily", "British Female  — Lily"),
378    ("bm_daniel", "British Male    — Daniel"),
379    ("bm_fable", "British Male    — Fable ⭐"),
380    ("bm_george", "British Male    — George ⭐"),
381    ("bm_lewis", "British Male    — Lewis"),
382    ("ef_dora", "Spanish Female  — Dora"),
383    ("em_alex", "Spanish Male    — Alex"),
384    ("ff_siwis", "French Female   — Siwis"),
385    ("hf_alpha", "Hindi Female    — Alpha"),
386    ("hf_beta", "Hindi Female    — Beta"),
387    ("hm_omega", "Hindi Male      — Omega"),
388    ("hm_psi", "Hindi Male      — Psi"),
389    ("if_sara", "Italian Female  — Sara"),
390    ("im_nicola", "Italian Male    — Nicola"),
391    ("jf_alpha", "Japanese Female — Alpha"),
392    ("jf_gongitsune", "Japanese Female — Gongitsune"),
393    ("jf_nezumi", "Japanese Female — Nezumi"),
394    ("jf_tebukuro", "Japanese Female — Tebukuro"),
395    ("jm_kumo", "Japanese Male   — Kumo"),
396    ("zf_xiaobei", "Chinese Female  — Xiaobei"),
397    ("zf_xiaoni", "Chinese Female  — Xiaoni"),
398    ("zf_xiaoxiao", "Chinese Female  — Xiaoxiao"),
399    ("zf_xiaoyi", "Chinese Female  — Xiaoyi"),
400    ("zm_yunjian", "Chinese Male    — Yunjian"),
401    ("zm_yunxi", "Chinese Male    — Yunxi"),
402    ("zm_yunxia", "Chinese Male    — Yunxia"),
403    ("zm_yunyang", "Chinese Male    — Yunyang"),
404];