| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::fs; |
| 12 | use std::io::{Read, Write}; |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use std::process::{Command, Stdio}; |
| 15 | use std::thread; |
| 16 | use std::time::{Duration, Instant}; |
| 17 | |
| 18 | use crate::speech::home; |
| 19 | |
| 20 | pub const DEFAULT_VOICE: &str = "en_US-ryan-high"; |
| 21 | |
| 22 | pub const TIMEOUT: Duration = Duration::from_secs(120); |
| 23 | |
| 24 | |
| 25 | pub const WAV_HEADER: u64 = 44; |
| 26 | |
| 27 | |
| 28 | pub const RENDER_DIR: &str = ".renders"; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq)] |
| 31 | pub 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 | |
| 38 | pub gender: &'static str, |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | pub 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 | |
| 55 | pub 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 | |
| 62 | pub 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 | |
| 79 | pub 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 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | pub 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 | |
| 110 | pub 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 | |
| 128 | |
| 129 | pub 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 | |
| 138 | pub fn length_scale(speed: f64) -> f64 { |
| 139 | 1.0 / speed |
| 140 | } |
| 141 | |
| 142 | pub 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 | |
| 152 | |
| 153 | |
| 154 | pub 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 | |
| 160 | pub 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 | |
| 180 | pub 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 | |
| 186 | pub 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 | |
| 195 | pub 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 | |
| 205 | |
| 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 | |
| 236 | pub 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 | |
| 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 | |
| 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 | |
| 268 | |
| 269 | pub 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 | |
| 297 | pub const TEXT_LIMIT: usize = 5000; |
| 298 | |
| 299 | pub const SPEED_MIN: f64 = 0.5; |
| 300 | pub const SPEED_MAX: f64 = 2.0; |
| 301 | |
| 302 | pub const PAUSE_MAX: f64 = 10.0; |
| 303 | |
| 304 | |
| 305 | #[derive(Debug, Clone, PartialEq)] |
| 306 | pub struct Rendered { |
| 307 | |
| 308 | pub file: PathBuf, |
| 309 | pub voice: String, |
| 310 | |
| 311 | pub cached: bool, |
| 312 | } |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | pub 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 | |
| 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 | } |