forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

speak.rs569 lines, 25.3 KiBHistoryRawDownload
1//! Speech tools: `voices` lists the local Piper voices, `voiceover` renders text to
2//! a WAV beside the project, imports it as a source and, when asked, places it on a
3//! lane as one undo step.
4//!
5//! Piper is an external binary (`EDITH_PIPER`, else `~/.local/share/piper-venv/bin/piper`)
6//! fed the text on stdin. A voice is a `<name>.onnx` file with a `<name>.onnx.json`
7//! beside it, read from `EDITH_PIPER_VOICES` or `~/.local/share/piper-voices`. Renders
8//! are cached by a hash of (text, voice, speed, pause, model) in `voiceover/.renders/`:
9//! a repeat reuses the render, and the named WAV beside the project is a copy of it.
10//! Piper's phoneme-duration noise is pinned to 0, so one render has one length.
11
12use std::path::Path;
13
14use serde_json::{Value, json};
15
16use engine::project::LaneKind;
17pub use engine::tts::{PAUSE_MAX, SPEED_MAX, SPEED_MIN, TEXT_LIMIT, Voice, default_voice, list_voices, voices_dir};
18
19use super::project::dirty;
20use crate::parse;
21use crate::server::{Entry, Reply, Server, Tool, opt_f64, opt_str};
22
23const VOICES_DOC: &str = "List the local Piper voices: name, language, quality, sample rate and speaker count. \
24The default voice is marked *: en_US-ryan-high when installed, else the first en_US voice, else the first one. \
25language filters by language code (en, en_US). Voices come from EDITH_PIPER_VOICES, or ~/.local/share/piper-voices.";
26
27const VOICEOVER_DOC: &str = "Speak text with a local Piper voice into <project dir>/voiceover/<name or slug of text>-<hash8>.wav, \
28import it as a source (src:N) and report its duration. Needs a project path (project_new or project_open): the WAV goes beside the .edith file even before project_save, and the reply then says the source is unsaved until project_save. \
29Renders are cached by (text, voice, speed, pause, model) in voiceover/.renders: the same call reuses the render, and a different name only copies it. Lengths are fixed (piper's duration noise is off); the waveform keeps piper's usual variation. \
30place {lane, at} places the voiceover on a lane at a time, as one undo step (the same place op as edit). \
31The lane must be an existing audio lane (A1..), and at a time in the project: both are checked before anything is rendered, and a refusal lists the audio lanes or the lane_add that makes one. Text is limited to 5000 characters; piper's stderr is reported on failure. \
32speed 0.5..2 sets piper's length_scale to 1/speed, but piper's length does not follow it exactly: measured on en_US-ryan-high, \
33speed 0.5 is about 1.7 times as long as speed 1, 0.85 about 1.10 times (not 1.18), 1.5 about 0.78 times and 2 about 0.62 times (not 0.5). \
34Judge the pace by ear, not by arithmetic. pause is seconds of silence after each sentence. \
35Requires piper (EDITH_PIPER, or ~/.local/share/piper-venv/bin/piper).";
36
37// ---- schemas --------------------------------------------------------------
38
39fn voices_schema() -> Value {
40 json!({
41 "type": "object",
42 "properties": {
43 "language": {"type": "string", "description": "Only voices whose language code starts with this, such as en or en_GB."}
44 },
45 "additionalProperties": false
46 })
47}
48
49fn voiceover_schema() -> Value {
50 json!({
51 "type": "object",
52 "properties": {
53 "text": {"type": "string", "maxLength": TEXT_LIMIT, "description": "What to say, up to 5000 characters."},
54 "voice": {"type": "string", "description": "A voice name from `voices`. Default en_US-ryan-high, else the first en_US voice."},
55 "speed": {"type": "number", "minimum": SPEED_MIN, "maximum": SPEED_MAX, "description": "Pace: 1 is normal, higher is faster (2 is about 1.6 times as fast as 1, not twice). Default 1."},
56 "pause": {"type": "number", "minimum": 0, "maximum": PAUSE_MAX, "description": "Seconds of silence after each sentence. Default 0."},
57 "place": {
58 "type": "object",
59 "description": "Place the voiceover on a lane, as one undo step.",
60 "properties": {
61 "lane": {"type": "string", "description": "An existing audio lane to place it on, such as A2. lane_add {kind: audio} makes one."},
62 "at": {"type": "string", "description": "Timeline time, such as 5s or 150f."}
63 },
64 "required": ["lane", "at"],
65 "additionalProperties": false
66 },
67 "name": {"type": "string", "description": "File name stem for the WAV. Default: a slug of the text."}
68 },
69 "required": ["text"],
70 "additionalProperties": false
71 })
72}
73
74pub fn tools() -> Vec<Tool> {
75 vec![
76 Tool { name: "voices", description: VOICES_DOC, schema: voices_schema, run: run_voices },
77 Tool { name: "voiceover", description: VOICEOVER_DOC, schema: voiceover_schema, run: run_voiceover },
78 ]
79}
80
81// ---- voices ---------------------------------------------------------------
82
83fn norm_lang(s: &str) -> String {
84 s.trim().to_ascii_lowercase().replace('-', "_")
85}
86
87fn language_matches(v: &Voice, want: &str) -> bool {
88 v.language.as_deref().is_some_and(|l| norm_lang(l).starts_with(&norm_lang(want)))
89}
90
91fn run_voices(_server: &mut Server, args: &Value) -> Reply {
92 let dir = voices_dir();
93 let voices = match list_voices(&dir) {
94 Ok(v) => v,
95 Err(e) => return Reply::err(e),
96 };
97 let filter = opt_str(args, "language");
98 let default = default_voice(&voices).map(|v| v.name.clone());
99 let shown: Vec<&Voice> = voices
100 .iter()
101 .filter(|v| filter.is_none_or(|f| language_matches(v, f)))
102 .collect();
103 if shown.is_empty() {
104 return Reply::err(match filter {
105 Some(f) => format!("no voice with language `{f}` in {}", dir.display()),
106 None => format!("no voices in {}; install a Piper voice (<name>.onnx with its .onnx.json)", dir.display()),
107 });
108 }
109 let lines: Vec<String> = shown
110 .iter()
111 .map(|v| {
112 let mark = if default.as_deref() == Some(v.name.as_str()) { "*" } else { " " };
113 format!(
114 "{mark} {} {} {} {} Hz {} speaker(s) {}",
115 v.name,
116 v.language.as_deref().unwrap_or("?"),
117 v.quality.as_deref().unwrap_or("?"),
118 v.sample_rate.map_or_else(|| "?".to_string(), |r| r.to_string()),
119 v.speakers,
120 v.gender
121 )
122 })
123 .collect();
124 let structured: Vec<Value> = shown
125 .iter()
126 .map(|v| json!({"name": v.name, "language": v.language, "quality": v.quality, "sample_rate": v.sample_rate, "speakers": v.speakers, "gender": v.gender}))
127 .collect();
128 Reply::ok(format!("{}\n\n* marks the default voice", lines.join("\n")))
129 .with(json!({"dir": dir.display().to_string(), "default": default, "voices": structured}))
130}
131
132// ---- voiceover ------------------------------------------------------------
133
134/// The voiceover's first clause: the WAV is a source now, and the project file names it
135/// only after a save, so a project with unsaved changes says so here.
136pub(super) fn imported_words(source: impl std::fmt::Display, unsaved: bool) -> String {
137 let mut words = format!("imported as a source (src:{source})");
138 if unsaved {
139 words.push_str(" (unsaved until project_save)");
140 }
141 words
142}
143
144/// `place {lane, at}`: both are needed, and both are passed to the edit op as written.
145fn place_arg(args: &Value) -> Result<Option<(String, String)>, String> {
146 let Some(p) = args.get("place").filter(|v| !v.is_null()) else {
147 return Ok(None);
148 };
149 let lane = p.get("lane").and_then(Value::as_str).ok_or("`place` needs a `lane`, such as A2")?;
150 let at = p.get("at").and_then(Value::as_str).ok_or("`place` needs an `at`, such as 5s")?;
151 Ok(Some((lane.to_string(), at.to_string())))
152}
153
154/// Checks a `place` target before anything is rendered: the lane must be an audio lane
155/// the timeline has, and `at` a time in this project. A refusal names the audio lanes
156/// that exist, or the `lane_add` that makes the missing one.
157pub(super) fn check_place(server: &Server, lane: &str, at: &str) -> Result<(), Reply> {
158 let s = server.session_ref()?;
159 let l = parse::lane(lane).map_err(Reply::err)?;
160 let audio: Vec<String> = s
161 .lanes()
162 .into_iter()
163 .filter(|x| x.kind == LaneKind::Audio)
164 .map(parse::lane_name)
165 .collect();
166 let have = if audio.is_empty() {
167 "the timeline has no audio lane".to_string()
168 } else {
169 format!("the audio lanes are {}", audio.join(", "))
170 };
171 if l.kind != LaneKind::Audio {
172 return Err(Reply::err(format!(
173 "voiceover goes on an audio lane (A1..), and {} is not one; {have}",
174 parse::lane_name(l)
175 )));
176 }
177 if !s.lanes().contains(&l) {
178 return Err(Reply::err(format!(
179 "lane {} is not on this timeline; {have}. Add one first with {{\"op\":\"lane_add\",\"kind\":\"audio\"}}",
180 parse::lane_name(l)
181 )));
182 }
183 parse::frame(&Value::String(at.to_string()), parse::session_fps(s), parse::session_end(s))
184 .map_err(|e| Reply::err(format!("`at`: {e}")))?;
185 Ok(())
186}
187
188/// The text cut to 40 characters for a ledger label, newlines shown as ` / `.
189fn short_text(text: &str) -> String {
190 let flat = text.replace('\n', " / ");
191 if flat.chars().count() <= 40 {
192 return flat;
193 }
194 let mut cut: String = flat.chars().take(39).collect();
195 cut.push('…');
196 cut
197}
198
199fn run_voiceover(server: &mut Server, args: &Value) -> Reply {
200 let text = match opt_str(args, "text") {
201 Some(t) if !t.trim().is_empty() => t,
202 _ => return Reply::err("missing argument `text`: give the words to say"),
203 };
204 let chars = text.chars().count();
205 if chars > TEXT_LIMIT {
206 return Reply::err(format!("text is {chars} characters; the limit is {TEXT_LIMIT}: split it into several voiceovers"));
207 }
208 let speed = match opt_f64(args, "speed") {
209 None => 1.0,
210 Some(v) if (SPEED_MIN..=SPEED_MAX).contains(&v) => v,
211 Some(v) => return Reply::err(format!("speed {v} is outside {SPEED_MIN}..{SPEED_MAX}")),
212 };
213 let pause = match opt_f64(args, "pause") {
214 None => 0.0,
215 Some(v) if (0.0..=PAUSE_MAX).contains(&v) => v,
216 Some(v) => return Reply::err(format!("pause {v} is outside 0..{PAUSE_MAX} seconds")),
217 };
218 let place = match place_arg(args) {
219 Ok(p) => p,
220 Err(e) => return Reply::err(e),
221 };
222 let name = opt_str(args, "name");
223
224 let Some(project) = server.path.clone() else {
225 return Reply::err("voiceover needs a project path to store its audio next to: open or start one with project_open or project_new {path:\"…\"} first");
226 };
227 if let Err(r) = server.session_ref() {
228 return r;
229 }
230 if let Some((lane, at)) = &place
231 && let Err(r) = check_place(server, lane, at)
232 {
233 return r;
234 }
235
236 let dir = project.parent().unwrap_or(Path::new(".")).join("voiceover");
237 let rendered = match engine::tts::render(&dir, text, name, opt_str(args, "voice"), speed, pause) {
238 Ok(r) => r,
239 Err(e) => return Reply::err(e),
240 };
241 let (file, cached, voice) = (rendered.file, rendered.cached, rendered.voice);
242
243 let start = match server.session_ref() {
244 Ok(s) => s.history_pushes(),
245 Err(r) => return r,
246 };
247 let source = {
248 let s = match server.session() {
249 Ok(s) => s,
250 Err(r) => return r,
251 };
252 match s.import(&file) {
253 Ok(n) => n,
254 Err(e) => return Reply::err(format!("{}: refused: {e}", file.display())),
255 }
256 };
257 // Counted by the engine's push count, so an import at the undo cap still lands
258 // on the ledger, as media_import does.
259 if let Some(s) = server.session.as_ref() {
260 let n = s.history_pushes().saturating_sub(start) as usize;
261 if n > 0 {
262 let label = format!("voiceover \"{}\" → src:{source}", short_text(text));
263 server.ledger.push(Entry::new(n, label));
264 server.history_lost_on_open = false;
265 server.redo_ledger.clear();
266 server.trim_ledger();
267 }
268 }
269
270 let file_name = file.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
271 let secs = engine::probe_media(&file).duration_secs.unwrap_or(0.0);
272 let unsaved = dirty(server);
273 let mut text_out = format!(
274 "{file_name} ({secs:.2}s) {}, voice {}, {}",
275 imported_words(source, unsaved),
276 voice,
277 if cached { "reused" } else { "synthesized" }
278 );
279
280 let mut placed = false;
281 if let Some((lane, at)) = place {
282 let ops = json!({
283 "ops": [{"op": "place", "source": source, "lane": lane, "at": at}],
284 "label": format!("voiceover {file_name}")
285 });
286 let r = super::edit::run_edit(server, &ops);
287 if r.is_error {
288 return Reply::err(format!("{text_out}\n{}", r.text));
289 }
290 placed = true;
291 text_out.push('\n');
292 text_out.push_str(&r.text);
293 }
294
295 Reply::ok(text_out).with(json!({
296 "source": source,
297 "path": file.display().to_string(),
298 "duration": secs,
299 "voice": voice,
300 "cached": cached,
301 "placed": placed,
302 }))
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308 use engine::tts::*;
309 use std::fs;
310 use crate::testutil::TestDir;
311
312 /// An empty scratch directory for this test, removed when the guard drops.
313 fn tmp(tag: &str) -> TestDir {
314 TestDir::new(&format!("speak-{tag}"))
315 }
316
317 fn call(srv: &mut Server, name: &str, args: Value) -> Reply {
318 let tool = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool is registered");
319 (tool.run)(srv, &args)
320 }
321
322 fn fake_voice(dir: &Path, name: &str, lang: &str, rate: u64) {
323 fs::write(dir.join(format!("{name}.onnx")), b"not a model").unwrap();
324 let cfg = json!({
325 "audio": {"sample_rate": rate, "quality": "high"},
326 "espeak": {"voice": "en-us"},
327 "language": {"code": lang},
328 "num_speakers": 1
329 });
330 fs::write(dir.join(format!("{name}.onnx.json")), cfg.to_string()).unwrap();
331 }
332
333 #[test]
334 fn lists_voices_from_a_dir_with_fake_configs() {
335 let dir = tmp("voices");
336 fake_voice(&dir, "en_US-ryan-high", "en_US", 22050);
337 fake_voice(&dir, "en_GB-alba-medium", "en_GB", 22050);
338 fs::write(dir.join("readme.txt"), "not a voice").unwrap();
339 fs::write(dir.join("en_US-broken.onnx"), "no json beside it").unwrap();
340
341 let voices = list_voices(&dir).unwrap();
342 let names: Vec<&str> = voices.iter().map(|v| v.name.as_str()).collect();
343 assert_eq!(names, ["en_GB-alba-medium", "en_US-broken", "en_US-ryan-high"]);
344 let ryan = voices.iter().find(|v| v.name == "en_US-ryan-high").unwrap();
345 assert_eq!(ryan.language.as_deref(), Some("en_US"));
346 assert_eq!(ryan.sample_rate, Some(22050));
347 assert_eq!(ryan.quality.as_deref(), Some("high"));
348 assert_eq!(ryan.speakers, 1);
349
350 assert_eq!(default_voice(&voices).unwrap().name, "en_US-ryan-high");
351 assert!(language_matches(ryan, "en"));
352 assert!(language_matches(ryan, "en_us"));
353 assert!(!language_matches(ryan, "en_GB"));
354 assert!(list_voices(&dir.join("missing")).is_err());
355 }
356
357 #[test]
358 fn a_config_without_language_or_quality_falls_back_to_the_name() {
359 // Shaped like tr_TR-eren-medium.onnx.json: no language.code, no audio.quality, no dataset.
360 let eren = json!({
361 "audio": {"sample_rate": 22050},
362 "espeak": {"voice": "tr"},
363 "num_speakers": 1,
364 "phoneme_type": "espeak"
365 });
366 let v = parse_voice("tr_TR-eren-medium", Some(&eren));
367 assert_eq!(v.language.as_deref(), Some("tr_TR"));
368 assert_eq!(v.quality.as_deref(), Some("medium"));
369 assert_eq!(v.sample_rate, Some(22050));
370 assert_eq!(v.speakers, 1);
371
372 // Fields the config gives win over the name.
373 let full = json!({"language": {"code": "en_GB"}, "audio": {"quality": "high", "sample_rate": 22050}});
374 let v = parse_voice("en_US-ryan-medium", Some(&full));
375 assert_eq!(v.language.as_deref(), Some("en_GB"));
376 assert_eq!(v.quality.as_deref(), Some("high"));
377
378 // Empty strings count as missing; a name with more dashes keeps its quality.
379 let blank = json!({"language": {"code": " "}, "audio": {"quality": ""}});
380 let v = parse_voice("en_US-libritts_r-medium", Some(&blank));
381 assert_eq!(v.language.as_deref(), Some("en_US"));
382 assert_eq!(v.quality.as_deref(), Some("medium"));
383
384 // No config at all: the name is the only source, and the speaker count is 1.
385 let bare = parse_voice("en_GB-alba-medium", None);
386 assert_eq!(bare.language.as_deref(), Some("en_GB"));
387 assert_eq!(bare.quality.as_deref(), Some("medium"));
388 assert_eq!(bare.sample_rate, None);
389 assert_eq!(bare.speakers, 1);
390
391 // A name with no language prefix falls back to espeak's voice.
392 let espeak_only = json!({"espeak": {"voice": "tr"}});
393 assert_eq!(parse_voice("voice", Some(&espeak_only)).language.as_deref(), Some("tr"));
394 }
395
396 #[test]
397 fn gender_comes_from_whole_name_tokens() {
398 assert_eq!(gender_of("en_US-amy-female-medium"), "female");
399 assert_eq!(gender_of("en_US-ryan-male-high"), "male");
400 // "female" contains "male": only the whole token counts.
401 assert_eq!(gender_of("en_US-female_only-medium"), "female");
402 assert_eq!(gender_of("en_US-ryan-high"), "unknown");
403 assert_eq!(gender_of("en_US-maleficent-high"), "unknown");
404 let v = parse_voice("en_GB-alba-female-medium", None);
405 assert_eq!(v.gender, "female");
406 }
407
408 #[test]
409 fn voiceover_says_when_its_source_is_unsaved() {
410 assert_eq!(imported_words(3, false), "imported as a source (src:3)");
411 assert_eq!(imported_words(3, true), "imported as a source (src:3) (unsaved until project_save)");
412 }
413
414 #[test]
415 fn default_voice_falls_back_to_first_en_us_then_first() {
416 let dir = tmp("fallback");
417 fake_voice(&dir, "en_GB-alba-medium", "en_GB", 22050);
418 fake_voice(&dir, "en_US-joe-medium", "en_US", 22050);
419 fake_voice(&dir, "en_US-amy-medium", "en_US", 22050);
420 let voices = list_voices(&dir).unwrap();
421 assert_eq!(default_voice(&voices).unwrap().name, "en_US-amy-medium");
422
423 let only_gb: Vec<Voice> = voices.into_iter().filter(|v| v.name.starts_with("en_GB")).collect();
424 assert_eq!(default_voice(&only_gb).unwrap().name, "en_GB-alba-medium");
425 }
426
427 #[test]
428 fn speed_maps_to_length_scale() {
429 assert!((length_scale(1.0) - 1.0).abs() < 1e-9);
430 assert!((length_scale(2.0) - 0.5).abs() < 1e-9);
431 assert!((length_scale(0.5) - 2.0).abs() < 1e-9);
432 }
433
434 #[test]
435 fn speed_docs_say_piper_length_is_not_linear_in_speed() {
436 // Measured: speed 2 renders about 0.62 times the length of speed 1, not 0.5, so no doc may promise 1/speed.
437 assert!(VOICEOVER_DOC.contains("not 0.5"), "the voiceover doc names the measured gap");
438 assert!(!VOICEOVER_DOC.contains("twice as fast"), "the voiceover doc does not promise a linear pace");
439 assert!(!voiceover_schema().to_string().contains("twice as fast"), "the speed parameter does not promise it either");
440 }
441
442 #[test]
443 fn names_are_slugs_with_a_hash_of_the_inputs() {
444 assert_eq!(slug("Hello, from edith!"), "hello-from-edith");
445 assert_eq!(slug(" "), "voiceover");
446 assert_eq!(slug("Intro Line!"), "intro-line");
447 assert!(slug(&"word ".repeat(30)).len() <= 40);
448
449 let model = Path::new("/voices/en_US-ryan-high.onnx");
450 let h = |s: f64, p: f64| cache_hash("Hello from edith.", "en_US-ryan-high", s, p, model);
451 let a = wav_name(None, "Hello from edith.", h(1.0, 0.0));
452 assert!(a.starts_with("hello-from-edith-"), "{a}");
453 assert!(a.ends_with(".wav"));
454 let hash = a.trim_end_matches(".wav").rsplit('-').next().unwrap();
455 assert_eq!(hash.len(), 8, "{a}");
456 assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
457
458 assert_eq!(a, wav_name(None, "Hello from edith.", h(1.0, 0.0)));
459 assert_ne!(a, wav_name(None, "Hello from edith.", h(1.5, 0.0)));
460 assert_ne!(a, wav_name(None, "Hello from edith.", h(1.0, 0.5)));
461 assert_ne!(a, wav_name(None, "Hello from edith.", cache_hash("Hello from edith.", "en_GB-alba-medium", 1.0, 0.0, Path::new("/voices/en_GB-alba-medium.onnx"))));
462 // The name changes the file name only, never the render's key.
463 assert_eq!(h(1.0, 0.0), cache_hash("Hello from edith.", "en_US-ryan-high", 1.0, 0.0, model));
464 assert!(wav_name(Some("Intro Line!"), "x", h(1.0, 0.0)).starts_with("intro-line-"));
465 }
466
467 #[test]
468 fn refuses_without_a_project_path() {
469 let mut srv = Server::new();
470 let r = call(&mut srv, "voiceover", json!({"text": "Hello from edith."}));
471 assert!(r.is_error);
472 assert!(r.text.contains("project_new"), "{}", r.text);
473 }
474
475 #[test]
476 fn refuses_long_text_and_bad_speed() {
477 let mut srv = Server::new();
478 let long = "a".repeat(TEXT_LIMIT + 1);
479 let r = call(&mut srv, "voiceover", json!({"text": long}));
480 assert!(r.is_error && r.text.contains("5000"), "{}", r.text);
481 let r = call(&mut srv, "voiceover", json!({"text": "hi", "speed": 3.0}));
482 assert!(r.is_error && r.text.contains("speed"), "{}", r.text);
483 }
484
485 fn piper_ready() -> bool {
486 if let Err(e) = piper_bin() {
487 eprintln!("skipping speak integration: {e}");
488 return false;
489 }
490 match list_voices(&voices_dir()).ok().and_then(|v| default_voice(&v).cloned()) {
491 Some(_) => true,
492 None => {
493 eprintln!("skipping speak integration: no Piper voice in {}", voices_dir().display());
494 false
495 }
496 }
497 }
498
499 #[test]
500 fn synthesizes_imports_and_caches_a_voiceover() {
501 if !piper_ready() {
502 return;
503 }
504 let dir = tmp("synth");
505 let mut srv = Server::new();
506 let proj = dir.join("hello.edith");
507 assert!(!call(&mut srv, "project_new", json!({"path": proj.display().to_string()})).is_error);
508
509 let r = call(&mut srv, "voiceover", json!({"text": "Hello from edith."}));
510 assert!(!r.is_error, "voiceover failed: {}", r.text);
511 let s = r.structured.as_ref().expect("structured reply");
512 assert_eq!(s["source"], json!(0), "{}", r.text);
513 let secs = s["duration"].as_f64().unwrap_or(0.0);
514 assert!(secs > 0.5, "duration {secs} in {}", r.text);
515 assert!(Path::new(s["path"].as_str().unwrap()).is_file());
516 assert_eq!(s["cached"], json!(false));
517 assert_eq!(s["placed"], json!(false));
518 assert!(srv.ledger.is_empty(), "import is not an undo step");
519
520 let again = call(&mut srv, "voiceover", json!({"text": "Hello from edith."}));
521 assert!(!again.is_error, "{}", again.text);
522 assert_eq!(again.structured.as_ref().unwrap()["cached"], json!(true));
523 }
524
525 /// A bad `place` is refused before anything is rendered: no WAV, no source, no ledger step.
526 #[test]
527 fn place_is_checked_before_anything_is_synthesized() {
528 let dir = tmp("place-check");
529 let mut srv = Server::new();
530 let proj = dir.join("check.edith");
531 assert!(!call(&mut srv, "project_new", json!({"path": proj.display().to_string()})).is_error);
532
533 let missing = call(&mut srv, "voiceover", json!({"text": "Hello from edith.", "place": {"lane": "A3", "at": "0s"}}));
534 assert!(missing.is_error);
535 assert!(missing.text.contains("A3") && missing.text.contains("lane_add"), "{}", missing.text);
536 assert!(missing.text.contains("the audio lanes are A1"), "a new project has A1: {}", missing.text);
537
538 let video = call(&mut srv, "voiceover", json!({"text": "Hello from edith.", "place": {"lane": "V1", "at": "0s"}}));
539 assert!(video.is_error && video.text.contains("audio lane"), "{}", video.text);
540
541 srv.session.as_mut().unwrap().add_lane(LaneKind::Audio);
542 let listed = call(&mut srv, "voiceover", json!({"text": "Hello from edith.", "place": {"lane": "a3", "at": "0s"}}));
543 assert!(listed.is_error);
544 assert!(listed.text.contains("the audio lanes are A1, A2"), "{}", listed.text);
545
546 let bad_at = call(&mut srv, "voiceover", json!({"text": "Hello from edith.", "place": {"lane": "A1", "at": "soon"}}));
547 assert!(bad_at.is_error && bad_at.text.contains("`at`"), "{}", bad_at.text);
548
549 assert!(!dir.join("voiceover").exists(), "no WAV was rendered for a refused place");
550 assert!(srv.ledger.is_empty());
551 assert!(srv.session.as_ref().unwrap().sources().is_empty(), "nothing was imported");
552 }
553
554 #[test]
555 fn place_on_a1_is_one_undo_step() {
556 if !piper_ready() {
557 return;
558 }
559 let dir = tmp("place");
560 let mut srv = Server::new();
561 let proj = dir.join("placed.edith");
562 assert!(!call(&mut srv, "project_new", json!({"path": proj.display().to_string()})).is_error);
563
564 let r = call(&mut srv, "voiceover", json!({"text": "Hello from edith.", "place": {"lane": "A1", "at": "0s"}}));
565 assert!(!r.is_error, "voiceover with place failed: {}", r.text);
566 assert_eq!(r.structured.as_ref().unwrap()["placed"], json!(true));
567 assert_eq!(srv.ledger.len(), 1, "one edit, one ledger entry");
568 }
569}