//! Piper neural TTS backend (rhasspy/piper). //! //! Discovery order for binary: //! 1. env `JARVIS_TTS_PIPER_BIN` //! 2. `/tools/piper/piper.exe` //! 3. `/tools/piper/piper.exe` //! //! Discovery order for voice: //! 1. env `JARVIS_TTS_PIPER_VOICE` (absolute path to .onnx) //! 2. `/voices/ru_RU-irina-medium.onnx` //! 3. first `*.onnx` found in `/voices/` use std::path::{Path, PathBuf}; use super::{SpeakOpts, TtsBackend}; use crate::APP_DIR; pub struct PiperBackend { binary: PathBuf, voice: PathBuf, } impl PiperBackend { pub fn try_new() -> Result { let binary = find_binary().ok_or_else(|| "piper.exe not found".to_string())?; let voice_dir = binary .parent() .map(|p| p.join("voices")) .unwrap_or_else(|| PathBuf::from("voices")); let voice = find_voice(&voice_dir).ok_or_else(|| { format!("no .onnx voice in {}", voice_dir.display()) })?; Ok(Self { binary, voice }) } pub fn binary_display(&self) -> String { self.binary.display().to_string() } pub fn voice_display(&self) -> String { self.voice .file_name() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| self.voice.display().to_string()) } } impl TtsBackend for PiperBackend { fn name(&self) -> &'static str { "piper" } fn speak(&self, text: &str, opts: &SpeakOpts) { if text.trim().is_empty() { return; } let binary = self.binary.clone(); let voice = self.voice.clone(); let text = text.to_string(); let detached = opts.detached; let run = move || synth_and_play(&binary, &voice, &text); if detached { std::thread::spawn(run); } else { run(); } } } fn synth_and_play(binary: &Path, voice: &Path, text: &str) { let tmp = match tempfile::Builder::new() .prefix("jarvis-tts-") .suffix(".wav") .tempfile() { Ok(f) => f, Err(e) => { log::warn!("Piper: cannot create temp wav: {}", e); return; } }; let wav_path = tmp.path().to_path_buf(); drop(tmp); let mut child = match std::process::Command::new(binary) .arg("--model").arg(voice) .arg("--output_file").arg(&wav_path) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .spawn() { Ok(c) => c, Err(e) => { log::warn!("Piper spawn failed: {}", e); return; } }; if let Some(mut stdin) = child.stdin.take() { use std::io::Write; if let Err(e) = stdin.write_all(text.as_bytes()) { log::warn!("Piper stdin write failed: {}", e); } } match child.wait() { Ok(status) if status.success() => { play_wav(&wav_path); } Ok(status) => log::warn!("Piper exited with status {}", status), Err(e) => log::warn!("Piper wait failed: {}", e), } let _ = std::fs::remove_file(&wav_path); } #[cfg(target_os = "windows")] fn play_wav(path: &Path) { let escaped = path.display().to_string().replace('\'', "''"); let ps = format!( "$p = New-Object System.Media.SoundPlayer '{}'; $p.PlaySync()", escaped ); let _ = std::process::Command::new("powershell") .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &ps]) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status(); } #[cfg(not(target_os = "windows"))] fn play_wav(path: &Path) { log::info!("[Piper non-Windows stub] would play: {}", path.display()); } fn find_binary() -> Option { if let Ok(p) = std::env::var("JARVIS_TTS_PIPER_BIN") { let candidate = PathBuf::from(p); if candidate.is_file() { return Some(candidate); } } let bin_name = if cfg!(target_os = "windows") { "piper.exe" } else { "piper" }; if let Ok(exe) = std::env::current_exe() { if let Some(dir) = exe.parent() { let c = dir.join("tools").join("piper").join(bin_name); if c.is_file() { return Some(c); } } } let c = APP_DIR.join("tools").join("piper").join(bin_name); if c.is_file() { return Some(c); } None } fn find_voice(voice_dir: &Path) -> Option { if let Ok(p) = std::env::var("JARVIS_TTS_PIPER_VOICE") { let candidate = PathBuf::from(p); if candidate.is_file() { return Some(candidate); } } let preferred = voice_dir.join("ru_RU-irina-medium.onnx"); if preferred.is_file() { return Some(preferred); } let entries = std::fs::read_dir(voice_dir).ok()?; for entry in entries.flatten() { let p = entry.path(); if p.extension().and_then(|s| s.to_str()) == Some("onnx") { return Some(p); } } None }