forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

tts.rs361 lines, 14.6 KiBHistoryRawDownload
1//! Text to speech with a local Piper voice: the voices on this machine, and a voiceover rendered
2//! to a WAV. Shared by the MCP server's `voiceover` and the GUI's Voiceover card.
3//!
4//! Piper is an external binary (`EDITH_PIPER`, else `~/.local/share/piper-venv/bin/piper`)
5//! fed the text on stdin. A voice is a `<name>.onnx` file with a `<name>.onnx.json`
6//! beside it, read from `EDITH_PIPER_VOICES` or `~/.local/share/piper-voices`. Renders
7//! are cached by a hash of (text, voice, speed, pause, model) in `voiceover/.renders/`:
8//! a repeat reuses the render, and the named WAV beside the project is a copy of it.
9//! Piper's phoneme-duration noise is pinned to 0, so one render has one length.
10
11use std::fs;
12use std::io::{Read, Write};
13use std::path::{Path, PathBuf};
14use std::process::{Command, Stdio};
15use std::thread;
16use std::time::{Duration, Instant};
17
18use crate::speech::home;
19
20pub const DEFAULT_VOICE: &str = "en_US-ryan-high";
21
22pub const TIMEOUT: Duration = Duration::from_secs(120);
23
24/// A WAV with no samples is its 44-byte header; anything bigger is a usable render.
25pub const WAV_HEADER: u64 = 44;
26
27/// The folder under `voiceover/` that holds one render per cache key.
28pub const RENDER_DIR: &str = ".renders";
29
30#[derive(Debug, Clone, PartialEq)]
31pub struct Voice {
32 pub name: String,
33 pub language: Option<String>,
34 pub quality: Option<String>,
35 pub sample_rate: Option<u64>,
36 pub speakers: u64,
37 /// "female" or "male" from the name's tokens, else "unknown" (Piper's config has no gender).
38 pub gender: &'static str,
39}
40
41/// The gender a voice name carries: a `female` or `male` token (split on `-` and `_`),
42/// else "unknown". Matched by whole token, so "female" is never read as "male".
43pub fn gender_of(name: &str) -> &'static str {
44 let mut found = "unknown";
45 for token in name.split(['-', '_']).map(str::to_ascii_lowercase) {
46 match token.as_str() {
47 "female" => return "female",
48 "male" => found = "male",
49 _ => {}
50 }
51 }
52 found
53}
54
55pub fn voices_dir() -> PathBuf {
56 std::env::var_os("EDITH_PIPER_VOICES")
57 .map(PathBuf::from)
58 .unwrap_or_else(|| home().join(".local/share/piper-voices"))
59}
60
61/// The piper binary: `EDITH_PIPER` when set (it must be a file), else the venv's.
62pub fn piper_bin() -> Result<PathBuf, String> {
63 if let Some(p) = std::env::var_os("EDITH_PIPER") {
64 let p = PathBuf::from(p);
65 return if p.is_file() {
66 Ok(p)
67 } else {
68 Err(format!("EDITH_PIPER is set to {}, which is not a file", p.display()))
69 };
70 }
71 let p = home().join(".local/share/piper-venv/bin/piper");
72 if p.is_file() {
73 Ok(p)
74 } else {
75 Err(format!("piper is not installed at {}; set EDITH_PIPER to the binary", p.display()))
76 }
77}
78
79pub fn read_voice(name: &str, json_path: &Path) -> Voice {
80 let meta: Option<serde_json::Value> = fs::read_to_string(json_path).ok().and_then(|s| serde_json::from_str(&s).ok());
81 parse_voice(name, meta.as_ref())
82}
83
84/// A voice from its name and its parsed `.onnx.json` (None when the file is missing or
85/// unreadable). Some voices carry no `language.code`, `audio.quality` or `dataset`
86/// (tr_TR-eren-medium's config has only `espeak.voice: "tr"`), so each field falls back
87/// to the file name `<lang>_<REGION>-<name>-<quality>` before it is left empty. A
88/// field that is present but empty counts as missing.
89pub fn parse_voice(name: &str, meta: Option<&serde_json::Value>) -> Voice {
90 let text = |path: &str| {
91 meta.and_then(|v| v.pointer(path))
92 .and_then(serde_json::Value::as_str)
93 .map(str::trim)
94 .filter(|s| !s.is_empty())
95 .map(str::to_string)
96 };
97 let stem = name.split('-').next().filter(|s| s.contains('_')).map(str::to_string);
98 let name_quality = (name.matches('-').count() >= 2).then(|| name.rsplit('-').next().unwrap_or_default().to_string());
99 Voice {
100 name: name.to_string(),
101 language: text("/language/code").or(stem).or_else(|| text("/espeak/voice")),
102 quality: text("/audio/quality").or(name_quality),
103 sample_rate: meta.and_then(|v| v.pointer("/audio/sample_rate")).and_then(serde_json::Value::as_u64),
104 speakers: meta.and_then(|v| v.pointer("/num_speakers")).and_then(serde_json::Value::as_u64).unwrap_or(1),
105 gender: gender_of(name),
106 }
107}
108
109/// Every `<name>.onnx` in `dir`, with its `.onnx.json` when present, sorted by name.
110pub fn list_voices(dir: &Path) -> Result<Vec<Voice>, String> {
111 let entries = fs::read_dir(dir).map_err(|e| {
112 format!("cannot read the voices dir {}: {e}. Set EDITH_PIPER_VOICES, or install a Piper voice there", dir.display())
113 })?;
114 let mut voices: Vec<Voice> = entries
115 .filter_map(Result::ok)
116 .filter_map(|e| {
117 let file = e.file_name().to_string_lossy().into_owned();
118 let stem = file.strip_suffix(".onnx")?.to_string();
119 let json_path = dir.join(format!("{file}.json"));
120 Some(read_voice(&stem, &json_path))
121 })
122 .collect();
123 voices.sort_by(|a, b| a.name.cmp(&b.name));
124 Ok(voices)
125}
126
127/// en_US-ryan-high if present, else the first en_US voice, else the first voice.
128/// `voices` must be sorted by name, as `list_voices` returns it.
129pub fn default_voice(voices: &[Voice]) -> Option<&Voice> {
130 voices
131 .iter()
132 .find(|v| v.name == DEFAULT_VOICE)
133 .or_else(|| voices.iter().find(|v| v.name.starts_with("en_US-")))
134 .or_else(|| voices.first())
135}
136
137/// piper's `--length-scale` for a speed: twice as fast is half the length.
138pub fn length_scale(speed: f64) -> f64 {
139 1.0 / speed
140}
141
142pub fn fnv1a(bytes: &[u8]) -> u64 {
143 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
144 for b in bytes {
145 h ^= u64::from(*b);
146 h = h.wrapping_mul(0x0100_0000_01b3);
147 }
148 h
149}
150
151/// The hash of everything that changes the audio: text, voice, speed, pause and
152/// the model file. The output name is not part of it. Speed and pause are written
153/// at fixed precision so float noise cannot split one render into two files.
154pub fn cache_hash(text: &str, voice: &str, speed: f64, pause: f64, model: &Path) -> u32 {
155 let key = format!("v3|{text}|{voice}|{speed:.4}|{pause:.3}|{}", model.display());
156 (fnv1a(key.as_bytes()) & 0xffff_ffff) as u32
157}
158
159/// A lowercase ASCII slug of at most 40 characters, `voiceover` when nothing is left.
160pub fn slug(s: &str) -> String {
161 let mut out = String::new();
162 let mut dash = false;
163 for c in s.chars() {
164 if c.is_ascii_alphanumeric() {
165 out.push(c.to_ascii_lowercase());
166 dash = false;
167 } else if !dash && !out.is_empty() {
168 out.push('-');
169 dash = true;
170 }
171 }
172 out.truncate(40);
173 while out.ends_with('-') {
174 out.pop();
175 }
176 if out.is_empty() { "voiceover".to_string() } else { out }
177}
178
179/// `<name or slug of text>-<hash8>.wav`.
180pub fn wav_name(name: Option<&str>, text: &str, hash: u32) -> String {
181 let base = slug(name.unwrap_or(text));
182 format!("{base}-{hash:08x}.wav")
183}
184
185/// The last few non-empty lines of piper's stderr, for an error message.
186pub fn tail(log: &str) -> String {
187 let lines: Vec<&str> = log.lines().filter(|l| !l.trim().is_empty()).collect();
188 if lines.is_empty() {
189 return "no output".to_string();
190 }
191 lines[lines.len().saturating_sub(5)..].join(" | ")
192}
193
194/// Runs piper with `text` on stdin, stopping it after `TIMEOUT`.
195pub fn run_piper(bin: &Path, args: &[String], text: &str) -> Result<(), String> {
196 let mut child = Command::new(bin)
197 .args(args)
198 .stdin(Stdio::piped())
199 .stdout(Stdio::null())
200 .stderr(Stdio::piped())
201 .spawn()
202 .map_err(|e| format!("could not start piper ({}): {e}", bin.display()))?;
203 if let Some(mut stdin) = child.stdin.take() {
204 // Closing stdin (on drop) tells piper the text is complete. A write that fails
205 // means piper quit early, which its exit status reports.
206 let _ = stdin.write_all(text.as_bytes());
207 }
208 let mut stderr = child.stderr.take().ok_or("piper: no stderr pipe")?;
209 let reader = thread::spawn(move || {
210 let mut s = String::new();
211 let _ = stderr.read_to_string(&mut s);
212 s
213 });
214 let deadline = Instant::now() + TIMEOUT;
215 let status = loop {
216 match child.try_wait() {
217 Ok(Some(st)) => break st,
218 Ok(None) if Instant::now() >= deadline => {
219 let _ = child.kill();
220 let _ = child.wait();
221 return Err(format!("piper did not finish within {}s and was stopped", TIMEOUT.as_secs()));
222 }
223 Ok(None) => thread::sleep(Duration::from_millis(50)),
224 Err(e) => return Err(format!("waiting for piper: {e}")),
225 }
226 };
227 let log = reader.join().unwrap_or_default();
228 if status.success() {
229 Ok(())
230 } else {
231 Err(format!("piper failed ({status}): {}", tail(&log)))
232 }
233}
234
235/// Renders `text` to `out` through a `.part` file, so a failed run leaves no WAV behind.
236pub fn synth(bin: &Path, model: &Path, text: &str, speed: f64, pause: f64, out: &Path) -> Result<(), String> {
237 let part = out.with_extension("part");
238 let args: Vec<String> = [
239 "-m".to_string(),
240 model.display().to_string(),
241 "-f".to_string(),
242 part.display().to_string(),
243 "--length-scale".to_string(),
244 format!("{:.4}", length_scale(speed)),
245 // Duration noise off: the same text renders to the same length every time.
246 "--noise-w-scale".to_string(),
247 "0".to_string(),
248 "--sentence-silence".to_string(),
249 format!("{pause:.3}"),
250 ]
251 .into();
252 let result = run_piper(bin, &args, text).and_then(|()| {
253 let len = fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
254 if len <= WAV_HEADER {
255 return Err("piper wrote no audio".to_string());
256 }
257 // Piper's sentence silence goes between sentences only, so the last one gets its pause here.
258 pad_tail(&part, pause)?;
259 fs::rename(&part, out).map_err(|e| format!("could not save {}: {e}", out.display()))
260 });
261 if result.is_err() {
262 let _ = fs::remove_file(&part);
263 }
264 result
265}
266
267/// Appends `secs` of silence to a 16-bit PCM WAV that piper wrote, fixing its RIFF and data sizes.
268/// A no-op for a zero pause.
269pub fn pad_tail(path: &Path, secs: f64) -> Result<(), String> {
270 if secs <= 0.0 {
271 return Ok(());
272 }
273 let mut bytes = fs::read(path).map_err(|e| format!("could not read {}: {e}", path.display()))?;
274 let canonical = bytes.len() >= 44 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WAVE" && &bytes[36..40] == b"data";
275 if !canonical {
276 return Err("piper wrote a WAV this server cannot pad".to_string());
277 }
278 let channels = u64::from(u16::from_le_bytes([bytes[22], bytes[23]]));
279 let rate = u64::from(u32::from_le_bytes([bytes[24], bytes[25], bytes[26], bytes[27]]));
280 let bits = u16::from_le_bytes([bytes[34], bytes[35]]);
281 if bits != 16 || channels == 0 || rate == 0 {
282 return Err(format!("piper wrote {bits}-bit audio at {rate} Hz; only 16-bit PCM can take a pause"));
283 }
284 let extra = (secs * rate as f64).round() as u64 * channels * 2;
285 let data = (bytes.len() - 44) as u64 + extra;
286 let riff = (bytes.len() - 8) as u64 + extra;
287 if data > u64::from(u32::MAX) || riff > u64::from(u32::MAX) {
288 return Err("the voiceover is too long to write a WAV for".to_string());
289 }
290 bytes.resize(bytes.len() + extra as usize, 0);
291 bytes[4..8].copy_from_slice(&(riff as u32).to_le_bytes());
292 bytes[40..44].copy_from_slice(&(data as u32).to_le_bytes());
293 fs::write(path, bytes).map_err(|e| format!("could not write {}: {e}", path.display()))
294}
295
296/// The longest text a voiceover takes, in characters.
297pub const TEXT_LIMIT: usize = 5000;
298/// The speed range a voiceover takes (1.0 is the voice's own pace).
299pub const SPEED_MIN: f64 = 0.5;
300pub const SPEED_MAX: f64 = 2.0;
301/// The longest pause between sentences, in seconds.
302pub const PAUSE_MAX: f64 = 10.0;
303
304/// A voiceover on disk.
305#[derive(Debug, Clone, PartialEq)]
306pub struct Rendered {
307 /// The WAV: `<dir>/<name or slug of text>-<hash8>.wav`.
308 pub file: PathBuf,
309 pub voice: String,
310 /// The render was reused rather than synthesized.
311 pub cached: bool,
312}
313
314/// Speaks `text` with `voice` (the default voice when `None`) into `dir`, reusing an identical
315/// earlier render. Checked as the server checks it: text length, speed and pause ranges, the voice
316/// being installed.
317pub fn render(dir: &Path, text: &str, name: Option<&str>, voice: Option<&str>, speed: f64, pause: f64) -> Result<Rendered, String> {
318 if text.trim().is_empty() {
319 return Err("missing argument `text`: give the words to say".into());
320 }
321 let chars = text.chars().count();
322 if chars > TEXT_LIMIT {
323 return Err(format!("text is {chars} characters; the limit is {TEXT_LIMIT}: split it into several voiceovers"));
324 }
325 if !(SPEED_MIN..=SPEED_MAX).contains(&speed) {
326 return Err(format!("speed {speed} is outside {SPEED_MIN}..{SPEED_MAX}"));
327 }
328 if !(0.0..=PAUSE_MAX).contains(&pause) {
329 return Err(format!("pause {pause} is outside 0..{PAUSE_MAX} seconds"));
330 }
331 let vdir = voices_dir();
332 let voices = list_voices(&vdir)?;
333 let voice = match voice {
334 Some(want) => voices.iter().find(|v| v.name == want).ok_or_else(|| {
335 let names: Vec<&str> = voices.iter().map(|v| v.name.as_str()).collect();
336 format!("no voice `{want}` in {}; voices: {}", vdir.display(), names.join(", "))
337 })?,
338 None => default_voice(&voices).ok_or_else(|| format!("no voices in {}; install a Piper voice", vdir.display()))?,
339 };
340 let model = vdir.join(format!("{}.onnx", voice.name));
341 let hash = cache_hash(text, &voice.name, speed, pause, &model);
342 let renders = dir.join(RENDER_DIR);
343 let render = renders.join(format!("{hash:08x}.wav"));
344 let file = dir.join(wav_name(name, text, hash));
345 let cached = fs::metadata(&render).is_ok_and(|m| m.len() > WAV_HEADER);
346 if !cached {
347 let bin = piper_bin()?;
348 fs::create_dir_all(&renders).map_err(|e| format!("could not create {}: {e}", renders.display()))?;
349 synth(&bin, &model, text, speed, pause, &render)?;
350 }
351 if file != render {
352 // The named WAV is a copy of the render; the copy is refreshed when the render differs.
353 let same = fs::metadata(&file).is_ok_and(|m| m.len() == fs::metadata(&render).map_or(0, |r| r.len()));
354 if !same {
355 fs::create_dir_all(dir)
356 .and_then(|()| fs::copy(&render, &file).map(|_| ()))
357 .map_err(|e| format!("could not save {}: {e}", file.display()))?;
358 }
359 }
360 Ok(Rendered { file, voice: voice.name.clone(), cached })
361}