edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! The creator tools card: Normalize, Captions, Fillers and Voiceover. The work is |
| 2 | //! [`crate::creator`]'s (the engine's, shared with the MCP server); this file is the |
| 3 | //! window's half -- the card's state, the background job the speech tools run on with its |
| 4 | //! progress and cancel, and the keys. |
| 5 | //! |
| 6 | //! Normalize is synchronous (it measures, sets gains and measures again, then it is done); |
| 7 | //! the three that listen or speak run off the render thread -- the sound is read where the |
| 8 | //! session is, the model runs on a thread, and the result is put on the timeline back here |
| 9 | //! as one undo step. |
| 10 | |
| 11 | use std::sync::Arc; |
| 12 | |
| 13 | use engine::speech::{self, Filler, Hear, Job, Spoken}; |
| 14 | |
| 15 | use crate::creator::{self, LANGUAGES, LUFS_RANGE, LUFS_STEP, PEAK_RANGE, PEAK_STEP, Said}; |
| 16 | use crate::player::text_field::FieldKey; |
| 17 | use crate::player::transcript; |
| 18 | use crate::ui::kit::{NumberEdit, scrub_value}; |
| 19 | use crate::*; |
| 20 | |
| 21 | /// The four tools the card holds, in the order its tabs are drawn. |
| 22 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 23 | pub(crate) enum Tool { |
| 24 | Normalize, |
| 25 | Captions, |
| 26 | Fillers, |
| 27 | Voiceover, |
| 28 | } |
| 29 | |
| 30 | impl Tool { |
| 31 | pub(crate) const ALL: [Tool; 4] = [Tool::Normalize, Tool::Captions, Tool::Fillers, Tool::Voiceover]; |
| 32 | |
| 33 | /// This tool's place in [`Tools::status`]. |
| 34 | pub(crate) fn slot(self) -> usize { |
| 35 | Tool::ALL.iter().position(|t| *t == self).unwrap_or(0) |
| 36 | } |
| 37 | |
| 38 | /// The tab's own name on the card: what each tool does, in plain words. |
| 39 | pub(crate) fn label(self) -> &'static str { |
| 40 | match self { |
| 41 | Tool::Normalize => "Normalize", |
| 42 | Tool::Captions => "Captions", |
| 43 | Tool::Fillers => "Filler words", |
| 44 | Tool::Voiceover => "Voiceover", |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// The two numbers Normalize takes, each a slider and a number field. |
| 50 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 51 | pub(crate) enum NumField { |
| 52 | Target, |
| 53 | Ceiling, |
| 54 | } |
| 55 | |
| 56 | impl NumField { |
| 57 | pub(crate) fn range(self) -> (f64, f64) { |
| 58 | match self { |
| 59 | NumField::Target => LUFS_RANGE, |
| 60 | NumField::Ceiling => PEAK_RANGE, |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// The grid a slider press or a typed value lands on. |
| 65 | pub(crate) fn step(self) -> f64 { |
| 66 | match self { |
| 67 | NumField::Target => LUFS_STEP, |
| 68 | NumField::Ceiling => PEAK_STEP, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Units a pixel of sideways drag moves the field by. |
| 73 | fn per_px(self) -> f64 { |
| 74 | match self { |
| 75 | NumField::Target => 0.25, |
| 76 | NumField::Ceiling => 0.05, |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// The text the field shows at rest. |
| 81 | pub(crate) fn shown(self, v: f64) -> String { |
| 82 | match self { |
| 83 | NumField::Target => format!("{v:.1}").replace('-', "\u{2212}"), |
| 84 | NumField::Ceiling => format!("{v:.1}").replace('-', "\u{2212}"), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn snap(self, v: f64) -> f64 { |
| 89 | let (lo, hi) = self.range(); |
| 90 | ((v / self.step()).round() * self.step()).clamp(lo, hi) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// A number field being scrubbed: where the press was and the value it started from. |
| 95 | #[derive(Clone, Copy, Debug)] |
| 96 | pub(crate) struct NumDrag { |
| 97 | pub(crate) field: NumField, |
| 98 | pub(crate) x0: f32, |
| 99 | pub(crate) v0: f64, |
| 100 | pub(crate) moved: bool, |
| 101 | } |
| 102 | |
| 103 | /// A speech or voiceover job in flight: what it is called on the card, and the shared state |
| 104 | /// its thread reports through and listens to. |
| 105 | pub(crate) struct Running { |
| 106 | pub(crate) what: &'static str, |
| 107 | pub(crate) job: Arc<Job>, |
| 108 | /// Which run this is, so a result that arrives after Cancel (or after the card was closed |
| 109 | /// and reopened) finds a different number and is dropped. |
| 110 | pub(crate) id: u64, |
| 111 | } |
| 112 | |
| 113 | /// The card's state. `Some` on `Player::tools` while it is up. |
| 114 | pub(crate) struct Tools { |
| 115 | pub(crate) tool: Tool, |
| 116 | // Normalize |
| 117 | pub(crate) lufs: f64, |
| 118 | pub(crate) ceiling: f64, |
| 119 | pub(crate) each: bool, |
| 120 | // Captions and Fillers |
| 121 | pub(crate) lang: usize, |
| 122 | pub(crate) hear: usize, |
| 123 | /// Listen to the sound again even though a transcript is there to read from. |
| 124 | pub(crate) relisten: bool, |
| 125 | // Fillers |
| 126 | pub(crate) found: Vec<(Filler, bool)>, |
| 127 | pub(crate) pick: usize, |
| 128 | // Voiceover |
| 129 | pub(crate) text: String, |
| 130 | pub(crate) typing: bool, |
| 131 | pub(crate) voice: usize, |
| 132 | /// What each tool's last run said, in the card's own words; each tab shows its own. |
| 133 | pub(crate) status: [Said; 4], |
| 134 | pub(crate) running: Option<Running>, |
| 135 | /// The tool the run in flight was started by: its status is the one the result writes. |
| 136 | pub(crate) run_tool: Tool, |
| 137 | /// The dropdown that is open, if any. |
| 138 | pub(crate) open: Option<Cycle>, |
| 139 | /// A Normalize number being typed (`typing` is set with it, so the keys come here). |
| 140 | pub(crate) num: Option<(NumField, NumberEdit)>, |
| 141 | pub(crate) drag: Option<NumDrag>, |
| 142 | /// A Normalize slider being dragged. |
| 143 | pub(crate) slide: Option<NumField>, |
| 144 | } |
| 145 | |
| 146 | impl Tools { |
| 147 | fn new(tool: Tool) -> Self { |
| 148 | Tools { |
| 149 | tool, |
| 150 | lufs: creator::LUFS_PRESETS[0].1, |
| 151 | ceiling: engine::normalize::TARGET_TRUE_PEAK, |
| 152 | each: false, |
| 153 | lang: 0, |
| 154 | hear: 0, |
| 155 | relisten: false, |
| 156 | found: Vec::new(), |
| 157 | pick: 0, |
| 158 | text: String::new(), |
| 159 | typing: false, |
| 160 | voice: 0, |
| 161 | status: Default::default(), |
| 162 | running: None, |
| 163 | run_tool: tool, |
| 164 | open: None, |
| 165 | num: None, |
| 166 | drag: None, |
| 167 | slide: None, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | pub(crate) fn said(&self, tool: Tool) -> &Said { |
| 172 | &self.status[tool.slot()] |
| 173 | } |
| 174 | |
| 175 | pub(crate) fn set_said(&mut self, tool: Tool, said: Said) { |
| 176 | self.status[tool.slot()] = said; |
| 177 | } |
| 178 | |
| 179 | /// The longest voiceover text the field takes: the engine's own limit. |
| 180 | pub(crate) const TEXT_CAP: usize = engine::tts::TEXT_LIMIT; |
| 181 | |
| 182 | /// One printable character into the voiceover text. |
| 183 | pub(crate) fn typed(&mut self, c: char) { |
| 184 | if !c.is_control() && self.text.chars().count() < Self::TEXT_CAP { |
| 185 | self.text.push(c); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// The tool a listen runs for: captions, or fillers. |
| 191 | fn tool_of(fillers: bool) -> Tool { |
| 192 | match fillers { |
| 193 | true => Tool::Fillers, |
| 194 | false => Tool::Captions, |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// `n` steps along a ring of `len`. |
| 199 | fn ring(at: usize, len: usize, steps: i32) -> usize { |
| 200 | match len { |
| 201 | 0 => 0, |
| 202 | _ => (at as i64 + i64::from(steps)).rem_euclid(len as i64) as usize, |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | impl Player { |
| 207 | /// Opens the card on `tool`. Nothing here is a clip's, so nothing is refused for want of a |
| 208 | /// selection; a missing timeline is. |
| 209 | pub(crate) fn open_tools(&mut self, tool: Tool, cx: &mut Context<Self>) { |
| 210 | if self.exporting().is_some() { |
| 211 | return; |
| 212 | } |
| 213 | if self.session.is_none() { |
| 214 | self.notify_user("No timeline — no file open".into()); |
| 215 | cx.notify(); |
| 216 | return; |
| 217 | } |
| 218 | // The card stays on its numbers across tools: Normalize's target is still there after a |
| 219 | // look at Captions. |
| 220 | let mut tools = self.tools.take().unwrap_or_else(|| Tools::new(tool)); |
| 221 | tools.tool = tool; |
| 222 | tools.typing = false; |
| 223 | // One card at a time -- `close_card`'s own rule. |
| 224 | self.close_other_cards(); |
| 225 | self.tools = Some(tools); |
| 226 | self.context_menu = None; |
| 227 | self.dock_src_active = false; |
| 228 | crate::ui::dock_stance::save(false); |
| 229 | cx.notify(); |
| 230 | } |
| 231 | |
| 232 | /// Cancels whatever the card has running and drops it. What `close_card` calls. |
| 233 | pub(crate) fn close_tools(&mut self) { |
| 234 | if let Some(tools) = self.tools.take() |
| 235 | && let Some(running) = tools.running |
| 236 | { |
| 237 | running.job.cancel.store(true, std::sync::atomic::Ordering::Relaxed); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// Switches the tab. A running job keeps running: its result lands on the card whichever |
| 242 | /// tab is showing. |
| 243 | pub(crate) fn tools_tab(&mut self, tool: Tool, cx: &mut Context<Self>) { |
| 244 | if let Some(t) = self.tools.as_mut() { |
| 245 | t.tool = tool; |
| 246 | t.typing = false; |
| 247 | t.num = None; |
| 248 | t.open = None; |
| 249 | } |
| 250 | cx.notify(); |
| 251 | } |
| 252 | |
| 253 | fn tools_mut(&mut self) -> Option<&mut Tools> { |
| 254 | self.tools.as_mut() |
| 255 | } |
| 256 | |
| 257 | /// A tool's result that worked: its card line, and the toast says the same. |
| 258 | pub(crate) fn tools_say(&mut self, tool: Tool, line: String) { |
| 259 | self.notify_user(line.clone().into()); |
| 260 | if let Some(t) = self.tools_mut() { |
| 261 | t.set_said(tool, Said::plain(line)); |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// A tool's result that did not work: the plain sentence on its card and in the toast, the |
| 266 | /// whole error in the card's tooltip. |
| 267 | pub(crate) fn tools_fail(&mut self, tool: Tool, why: &str) { |
| 268 | let said = creator::plain_error(why); |
| 269 | self.notify_user(said.line.clone().into()); |
| 270 | if let Some(t) = self.tools_mut() { |
| 271 | t.set_said(tool, said); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | // ---- normalize ---------------------------------------------------------------- |
| 276 | |
| 277 | pub(crate) fn tools_set_target(&mut self, lufs: f64, cx: &mut Context<Self>) { |
| 278 | self.tools_set_num(NumField::Target, lufs, cx); |
| 279 | } |
| 280 | |
| 281 | /// Writes one of Normalize's numbers, on its grid and inside its range. |
| 282 | pub(crate) fn tools_set_num(&mut self, field: NumField, v: f64, cx: &mut Context<Self>) { |
| 283 | if let Some(t) = self.tools_mut() { |
| 284 | let v = field.snap(v); |
| 285 | match field { |
| 286 | NumField::Target => t.lufs = v, |
| 287 | NumField::Ceiling => t.ceiling = v, |
| 288 | } |
| 289 | } |
| 290 | cx.notify(); |
| 291 | } |
| 292 | |
| 293 | /// A press or drag on a Normalize slider: the value `along` its track. |
| 294 | pub(crate) fn tools_slide(&mut self, field: NumField, along: f32, cx: &mut Context<Self>) { |
| 295 | let (lo, hi) = field.range(); |
| 296 | self.tools_set_num(field, lo + f64::from(along.clamp(0., 1.)) * (hi - lo), cx); |
| 297 | } |
| 298 | |
| 299 | fn num_value(&self, field: NumField) -> f64 { |
| 300 | self.tools.as_ref().map_or(0., |t| match field { |
| 301 | NumField::Target => t.lufs, |
| 302 | NumField::Ceiling => t.ceiling, |
| 303 | }) |
| 304 | } |
| 305 | |
| 306 | /// A press on a Normalize slider: the drag that follows keeps moving it. |
| 307 | pub(crate) fn begin_slide(&mut self, field: NumField) { |
| 308 | if let Some(t) = self.tools_mut() { |
| 309 | t.slide = Some(field); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// A press on a number field: a drag that follows scrubs it, a click without one types. |
| 314 | pub(crate) fn begin_num_drag(&mut self, field: NumField, x: f32) { |
| 315 | let v0 = self.num_value(field); |
| 316 | if let Some(t) = self.tools_mut() { |
| 317 | t.drag = Some(NumDrag { field, x0: x, v0, moved: false }); |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// The pointer moved with a number field pressed. |
| 322 | pub(crate) fn num_drag_move(&mut self, x: f32, fine: bool, cx: &mut Context<Self>) { |
| 323 | let Some(d) = self.tools.as_ref().and_then(|t| t.drag) else { |
| 324 | return; |
| 325 | }; |
| 326 | let dx = x - d.x0; |
| 327 | if !d.moved && dx.abs() < 3. { |
| 328 | return; |
| 329 | } |
| 330 | let (lo, hi) = d.field.range(); |
| 331 | let v = scrub_value(d.v0, dx, d.field.per_px(), fine, lo, hi); |
| 332 | if let Some(t) = self.tools_mut() { |
| 333 | t.drag = Some(NumDrag { moved: true, ..d }); |
| 334 | } |
| 335 | self.tools_set_num(d.field, v, cx); |
| 336 | } |
| 337 | |
| 338 | /// The button came up: a press that never moved opens the field for typing. |
| 339 | pub(crate) fn num_drag_end(&mut self, cx: &mut Context<Self>) { |
| 340 | if let Some(t) = self.tools_mut() |
| 341 | && t.slide.take().is_some() |
| 342 | { |
| 343 | cx.notify(); |
| 344 | return; |
| 345 | } |
| 346 | let Some(d) = self.tools.as_ref().and_then(|t| t.drag) else { |
| 347 | return; |
| 348 | }; |
| 349 | let shown = d.field.shown(self.num_value(d.field)).replace('\u{2212}', "-"); |
| 350 | if let Some(t) = self.tools_mut() { |
| 351 | t.drag = None; |
| 352 | if !d.moved { |
| 353 | t.num = Some((d.field, NumberEdit::begin(&shown))); |
| 354 | t.typing = true; |
| 355 | } |
| 356 | } |
| 357 | cx.notify(); |
| 358 | } |
| 359 | |
| 360 | pub(crate) fn tools_set_each(&mut self, each: bool, cx: &mut Context<Self>) { |
| 361 | if let Some(t) = self.tools_mut() { |
| 362 | t.each = each; |
| 363 | } |
| 364 | cx.notify(); |
| 365 | } |
| 366 | |
| 367 | /// Normalizes to the card's target. One undo step; the card says the level before and after. |
| 368 | pub(crate) fn run_normalize(&mut self, cx: &mut Context<Self>) { |
| 369 | let Some((each, lufs, ceiling)) = self.tools.as_ref().map(|t| (t.each, t.lufs, t.ceiling)) else { |
| 370 | return; |
| 371 | }; |
| 372 | let Some(session) = self.session.as_mut() else { |
| 373 | return; |
| 374 | }; |
| 375 | match creator::normalize(session, each, lufs, ceiling) { |
| 376 | Ok(report) => { |
| 377 | self.mark_dirty(); |
| 378 | self.tools_say(Tool::Normalize, creator::normalize_line(&report, each)); |
| 379 | } |
| 380 | Err(e) => self.tools_fail(Tool::Normalize, &format!("Not normalized: {e}")), |
| 381 | } |
| 382 | cx.notify(); |
| 383 | } |
| 384 | |
| 385 | // ---- ducking (the mix card's strips) ------------------------------------------- |
| 386 | |
| 387 | /// Ducks `lane` under `key` (the voice), or takes that duck off when it is already so. |
| 388 | pub(crate) fn toggle_duck(&mut self, lane: Lane, key: Lane, cx: &mut Context<Self>) { |
| 389 | let Some(session) = self.session.as_mut() else { |
| 390 | return; |
| 391 | }; |
| 392 | let on = session.lane_duck_list(lane).iter().any(|d| d.under == key.ord); |
| 393 | let done = match on { |
| 394 | true => creator::duck_off(session, lane, key), |
| 395 | false => creator::duck_under(session, lane, key), |
| 396 | }; |
| 397 | match done { |
| 398 | Ok(()) => self.mark_dirty(), |
| 399 | Err(e) => self.notify_user(format!("Not ducked — {e}").into()), |
| 400 | } |
| 401 | cx.notify(); |
| 402 | } |
| 403 | |
| 404 | /// Moves one number of the duck `lane` has under `key`. |
| 405 | pub(crate) fn step_duck( |
| 406 | &mut self, |
| 407 | lane: Lane, |
| 408 | key: Lane, |
| 409 | field: creator::DuckField, |
| 410 | steps: i32, |
| 411 | cx: &mut Context<Self>, |
| 412 | ) { |
| 413 | let Some(session) = self.session.as_mut() else { |
| 414 | return; |
| 415 | }; |
| 416 | match creator::duck_step(session, lane, key, field, steps) { |
| 417 | Ok(()) => self.mark_dirty(), |
| 418 | Err(e) => self.notify_user(format!("Duck unchanged — {e}").into()), |
| 419 | } |
| 420 | cx.notify(); |
| 421 | } |
| 422 | |
| 423 | // ---- captions and fillers (speech) ---------------------------------------------- |
| 424 | |
| 425 | /// The things the sound can be heard from, as the card's picker ring lists them. |
| 426 | pub(crate) fn tools_hears(&self) -> Vec<Hear> { |
| 427 | self.session.as_ref().map_or_else(Vec::new, creator::hear_choices) |
| 428 | } |
| 429 | |
| 430 | /// Opens a dropdown, or shuts it when it is the one open. |
| 431 | pub(crate) fn tools_toggle_drop(&mut self, what: Cycle, cx: &mut Context<Self>) { |
| 432 | if let Some(t) = self.tools_mut() { |
| 433 | t.open = if t.open == Some(what) { None } else { Some(what) }; |
| 434 | } |
| 435 | cx.notify(); |
| 436 | } |
| 437 | |
| 438 | /// Picks row `i` of a dropdown and shuts it. |
| 439 | pub(crate) fn tools_pick(&mut self, what: Cycle, i: usize, cx: &mut Context<Self>) { |
| 440 | if let Some(t) = self.tools_mut() { |
| 441 | match what { |
| 442 | Cycle::Language => t.lang = i, |
| 443 | Cycle::Hear => t.hear = i, |
| 444 | Cycle::Voice => t.voice = i, |
| 445 | } |
| 446 | t.open = None; |
| 447 | } |
| 448 | cx.notify(); |
| 449 | } |
| 450 | |
| 451 | /// Opens the folder voices are installed in, for a computer with none yet. |
| 452 | pub(crate) fn open_voices_folder(&mut self, cx: &mut Context<Self>) { |
| 453 | let dir = engine::tts::voices_dir(); |
| 454 | let _ = std::fs::create_dir_all(&dir); |
| 455 | match std::process::Command::new("xdg-open").arg(&dir).stdin(std::process::Stdio::null()).spawn() { |
| 456 | Ok(_) => {} |
| 457 | Err(_) => self.notify_user(format!("Voices go in {}", dir.display()).into()), |
| 458 | } |
| 459 | cx.notify(); |
| 460 | } |
| 461 | |
| 462 | /// The words the transcript already holds, when they still line up with the timeline: what |
| 463 | /// captions and fillers can be made from without listening again. |
| 464 | pub(crate) fn transcript_words(&self) -> Option<&Vec<Spoken>> { |
| 465 | self.transcript.words.as_ref().filter(|w| !w.is_empty() && !self.transcript.stale) |
| 466 | } |
| 467 | |
| 468 | /// Chooses between reading the transcript and listening to the sound again. |
| 469 | pub(crate) fn tools_set_relisten(&mut self, relisten: bool, cx: &mut Context<Self>) { |
| 470 | if let Some(t) = self.tools_mut() { |
| 471 | t.relisten = relisten; |
| 472 | t.open = None; |
| 473 | } |
| 474 | cx.notify(); |
| 475 | } |
| 476 | |
| 477 | /// Starts listening for captions (`fillers` false) or fillers (true). With a transcript to |
| 478 | /// read from (and no wish to listen again) the answer is instant; otherwise the sound is read |
| 479 | /// here and the model runs on a thread, with progress on the card and Cancel. |
| 480 | pub(crate) fn start_listening(&mut self, fillers: bool, cx: &mut Context<Self>) { |
| 481 | let Some(tools) = self.tools.as_ref() else { |
| 482 | return; |
| 483 | }; |
| 484 | if tools.running.is_some() { |
| 485 | return; |
| 486 | } |
| 487 | if !tools.relisten |
| 488 | && let Some(words) = self.transcript_words().cloned() |
| 489 | { |
| 490 | match fillers { |
| 491 | true => self.found_fillers(&words), |
| 492 | false => self.place_generated_captions(&words), |
| 493 | } |
| 494 | cx.notify(); |
| 495 | return; |
| 496 | } |
| 497 | let (lang, hear_at) = (tools.lang, tools.hear); |
| 498 | if let Err(why) = speech::stt_bin() { |
| 499 | return self.listen_fail(fillers, &why, cx); |
| 500 | } |
| 501 | let Some((model, device)) = transcript::speech_target(self.session.as_ref()) else { |
| 502 | return self.listen_fail(fillers, "No speech model is installed", cx); |
| 503 | }; |
| 504 | if let Err(why) = speech::available(device) { |
| 505 | return self.listen_fail(fillers, &why, cx); |
| 506 | } |
| 507 | let hears = self.tools_hears(); |
| 508 | let hear = hears.get(hear_at).copied().unwrap_or(Hear::Mix); |
| 509 | let lang = LANGUAGES[lang.min(LANGUAGES.len() - 1)].0; |
| 510 | let Some(session) = self.session.as_ref() else { |
| 511 | return; |
| 512 | }; |
| 513 | let heard = match speech::prepare(session, hear) { |
| 514 | Ok(h) => h, |
| 515 | Err(why) => return self.listen_fail(fillers, &why, cx), |
| 516 | }; |
| 517 | let job = Arc::new(Job::default()); |
| 518 | let id = self.tools_runs.wrapping_add(1); |
| 519 | self.tools_runs = id; |
| 520 | let what = if fillers { "Listening for fillers" } else { "Listening for captions" }; |
| 521 | if let Some(t) = self.tools_mut() { |
| 522 | let tool = tool_of(fillers); |
| 523 | t.running = Some(Running { what, job: job.clone(), id }); |
| 524 | t.run_tool = tool; |
| 525 | t.set_said(tool, Said::default()); |
| 526 | if fillers { |
| 527 | t.found.clear(); |
| 528 | } |
| 529 | } |
| 530 | let work = cx.background_executor().spawn({ |
| 531 | let job = job.clone(); |
| 532 | async move { speech::listen(heard, &model, device, lang, fillers, &job) } |
| 533 | }); |
| 534 | cx.spawn(async move |this, cx| { |
| 535 | let heard = work.await; |
| 536 | this.update(cx, |this, cx| this.finish_listening(id, fillers, heard, cx)).ok(); |
| 537 | }) |
| 538 | .detach(); |
| 539 | // The bar moves while the thread works: repaint until this run is over. |
| 540 | cx.spawn(async move |this, cx| { |
| 541 | loop { |
| 542 | cx.background_executor().timer(std::time::Duration::from_millis(200)).await; |
| 543 | let live = this |
| 544 | .update(cx, |this, cx| { |
| 545 | let live = this.tools.as_ref().and_then(|t| t.running.as_ref()).is_some_and(|r| r.id == id); |
| 546 | cx.notify(); |
| 547 | live |
| 548 | }) |
| 549 | .unwrap_or(false); |
| 550 | if !live { |
| 551 | break; |
| 552 | } |
| 553 | } |
| 554 | }) |
| 555 | .detach(); |
| 556 | cx.notify(); |
| 557 | } |
| 558 | |
| 559 | /// A listen that could not start: its sentence on the tool's card and in the toast. |
| 560 | fn listen_fail(&mut self, fillers: bool, why: &str, cx: &mut Context<Self>) { |
| 561 | self.tools_fail(tool_of(fillers), why); |
| 562 | cx.notify(); |
| 563 | } |
| 564 | |
| 565 | fn finish_listening(&mut self, id: u64, fillers: bool, heard: Result<Vec<Spoken>, String>, cx: &mut Context<Self>) { |
| 566 | // Cancelled, or the card went and came back: not this run's result any more. |
| 567 | if self.tools.as_ref().and_then(|t| t.running.as_ref()).is_none_or(|r| r.id != id) { |
| 568 | return; |
| 569 | } |
| 570 | if let Some(t) = self.tools_mut() { |
| 571 | t.running = None; |
| 572 | } |
| 573 | let words = match heard { |
| 574 | Ok(w) => w, |
| 575 | Err(e) if e == speech::CANCELLED => { |
| 576 | if let Some(t) = self.tools_mut() { |
| 577 | t.set_said(tool_of(fillers), Said::plain("Cancelled")); |
| 578 | } |
| 579 | cx.notify(); |
| 580 | return; |
| 581 | } |
| 582 | Err(e) => { |
| 583 | self.listen_fail(fillers, &e, cx); |
| 584 | return; |
| 585 | } |
| 586 | }; |
| 587 | match fillers { |
| 588 | true => self.found_fillers(&words), |
| 589 | false => self.place_generated_captions(&words), |
| 590 | } |
| 591 | cx.notify(); |
| 592 | } |
| 593 | |
| 594 | fn found_fillers(&mut self, words: &[Spoken]) { |
| 595 | let Some(session) = self.session.as_ref() else { |
| 596 | return; |
| 597 | }; |
| 598 | let found = creator::fillers_in(session, words); |
| 599 | if let Some(t) = self.tools_mut() { |
| 600 | let line = match found.len() { |
| 601 | 0 => "No filler words found".into(), |
| 602 | n => format!("{n} filler word{} found. Untick any to keep, then cut.", if n == 1 { "" } else { "s" }), |
| 603 | }; |
| 604 | t.set_said(Tool::Fillers, Said::plain(line)); |
| 605 | t.found = found.into_iter().map(|f| (f, true)).collect(); |
| 606 | t.pick = 0; |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | fn place_generated_captions(&mut self, words: &[Spoken]) { |
| 611 | let project = (!self.project_path.as_os_str().is_empty()).then(|| self.project_path.clone()); |
| 612 | let Some(session) = self.session.as_mut() else { |
| 613 | return; |
| 614 | }; |
| 615 | match creator::place_captions(session, words, project.as_deref()) { |
| 616 | Ok((n, lane, replaced)) => { |
| 617 | self.mark_dirty(); |
| 618 | let said = match replaced { |
| 619 | true => format!("Captions replaced ({n}) on {}.", lane.label()), |
| 620 | false => format!("{n} captions added on {}.", lane.label()), |
| 621 | }; |
| 622 | self.tools_say(Tool::Captions, said); |
| 623 | } |
| 624 | Err(e) => self.tools_fail(Tool::Captions, &format!("No captions: {e}")), |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | /// Cancels the run in flight. The thread stops at its next poll and the kill is the engine's. |
| 629 | pub(crate) fn cancel_tools_job(&mut self, cx: &mut Context<Self>) { |
| 630 | if let Some(t) = self.tools_mut() |
| 631 | && let Some(running) = t.running.take() |
| 632 | { |
| 633 | running.job.cancel.store(true, std::sync::atomic::Ordering::Relaxed); |
| 634 | let tool = t.run_tool; |
| 635 | t.set_said(tool, Said::plain("Cancelled")); |
| 636 | } |
| 637 | cx.notify(); |
| 638 | } |
| 639 | |
| 640 | // ---- fillers ------------------------------------------------------------------ |
| 641 | |
| 642 | pub(crate) fn toggle_filler(&mut self, i: usize, cx: &mut Context<Self>) { |
| 643 | if let Some(t) = self.tools_mut() |
| 644 | && let Some(row) = t.found.get_mut(i) |
| 645 | { |
| 646 | row.1 = !row.1; |
| 647 | t.pick = i; |
| 648 | } |
| 649 | cx.notify(); |
| 650 | } |
| 651 | |
| 652 | pub(crate) fn set_all_fillers(&mut self, on: bool, cx: &mut Context<Self>) { |
| 653 | if let Some(t) = self.tools_mut() { |
| 654 | t.found.iter_mut().for_each(|row| row.1 = on); |
| 655 | } |
| 656 | cx.notify(); |
| 657 | } |
| 658 | |
| 659 | /// Takes the playhead to filler `i`, for a listen before the cut. |
| 660 | pub(crate) fn seek_filler(&mut self, i: usize, cx: &mut Context<Self>) { |
| 661 | let Some(frame) = self.tools.as_ref().and_then(|t| t.found.get(i)).map(|(f, _)| f.start_f) else { |
| 662 | return; |
| 663 | }; |
| 664 | if let Some(t) = self.tools_mut() { |
| 665 | t.pick = i; |
| 666 | } |
| 667 | let at = f64::from(frame) / self.fps; |
| 668 | self.seek(at, cx); |
| 669 | } |
| 670 | |
| 671 | /// Cuts the ticked fillers out of every track, closing each hole. One undo step. |
| 672 | pub(crate) fn cut_ticked_fillers(&mut self, cx: &mut Context<Self>) { |
| 673 | let ticked: Vec<Filler> = self |
| 674 | .tools |
| 675 | .as_ref() |
| 676 | .map(|t| t.found.iter().filter(|(_, on)| *on).map(|(f, _)| f.clone()).collect()) |
| 677 | .unwrap_or_default(); |
| 678 | if ticked.is_empty() { |
| 679 | if let Some(t) = self.tools_mut() { |
| 680 | t.set_said(Tool::Fillers, Said::plain("Tick the filler words to cut first.")); |
| 681 | } |
| 682 | cx.notify(); |
| 683 | return; |
| 684 | } |
| 685 | let Some(session) = self.session.as_mut() else { |
| 686 | return; |
| 687 | }; |
| 688 | let before = session.timeline_duration(); |
| 689 | match creator::cut_fillers(session, &ticked) { |
| 690 | Ok(n) => { |
| 691 | let shorter = before - session.timeline_duration(); |
| 692 | self.selected.clear(); |
| 693 | self.reset_after_reseek(); |
| 694 | self.mark_dirty(); |
| 695 | if let Some(t) = self.tools_mut() { |
| 696 | t.found.clear(); |
| 697 | t.pick = 0; |
| 698 | } |
| 699 | let line = format!("Cut {n} filler word{}, {} shorter.", if n == 1 { "" } else { "s" }, secs_label(shorter)); |
| 700 | self.tools_say(Tool::Fillers, line); |
| 701 | } |
| 702 | Err(e) => self.tools_fail(Tool::Fillers, &format!("Nothing cut: {e}")), |
| 703 | } |
| 704 | cx.notify(); |
| 705 | } |
| 706 | |
| 707 | // ---- voiceover ---------------------------------------------------------------- |
| 708 | |
| 709 | pub(crate) fn tools_voices(&self) -> Vec<engine::tts::Voice> { |
| 710 | engine::tts::list_voices(&engine::tts::voices_dir()).unwrap_or_default() |
| 711 | } |
| 712 | |
| 713 | /// Speaks the card's text and places it at the playhead. The synthesis runs on a thread. |
| 714 | pub(crate) fn start_voiceover(&mut self, cx: &mut Context<Self>) { |
| 715 | let Some(tools) = self.tools.as_ref() else { |
| 716 | return; |
| 717 | }; |
| 718 | if tools.running.is_some() { |
| 719 | return; |
| 720 | } |
| 721 | let (text, voice_at) = (tools.text.clone(), tools.voice); |
| 722 | let voices = self.tools_voices(); |
| 723 | let voice = voices.get(voice_at).map(|v| v.name.clone()); |
| 724 | let dir = creator::voiceover_dir((!self.project_path.as_os_str().is_empty()).then_some(self.project_path.as_path())); |
| 725 | let at = self.session.as_ref().map_or(0.0, |s| s.now()); |
| 726 | let id = self.tools_runs.wrapping_add(1); |
| 727 | self.tools_runs = id; |
| 728 | let job = Arc::new(Job::default()); |
| 729 | if let Some(t) = self.tools_mut() { |
| 730 | t.typing = false; |
| 731 | t.running = Some(Running { what: "Speaking", job: job.clone(), id }); |
| 732 | t.run_tool = Tool::Voiceover; |
| 733 | t.set_said(Tool::Voiceover, Said::default()); |
| 734 | } |
| 735 | let work = cx.background_executor().spawn(async move { |
| 736 | let rendered = engine::tts::render(&dir, &text, None, voice.as_deref(), 1.0, 0.0)?; |
| 737 | // The window cannot hand a stop to piper from here: a cancelled run is simply not |
| 738 | // placed (checked on the way back). |
| 739 | Ok::<_, String>(rendered) |
| 740 | }); |
| 741 | cx.spawn(async move |this, cx| { |
| 742 | let rendered = work.await; |
| 743 | this.update(cx, |this, cx| this.finish_voiceover(id, at, rendered, cx)).ok(); |
| 744 | }) |
| 745 | .detach(); |
| 746 | cx.notify(); |
| 747 | } |
| 748 | |
| 749 | fn finish_voiceover(&mut self, id: u64, at: f64, rendered: Result<engine::tts::Rendered, String>, cx: &mut Context<Self>) { |
| 750 | if self.tools.as_ref().and_then(|t| t.running.as_ref()).is_none_or(|r| r.id != id) { |
| 751 | return; |
| 752 | } |
| 753 | if let Some(t) = self.tools_mut() { |
| 754 | t.running = None; |
| 755 | } |
| 756 | match rendered { |
| 757 | Ok(r) => match self.session.as_mut() { |
| 758 | Some(session) => match creator::place_voiceover(session, &r.file, at) { |
| 759 | Ok(lane) => { |
| 760 | self.mark_dirty(); |
| 761 | self.selected.clear(); |
| 762 | self.reset_after_reseek(); |
| 763 | let line = format!("Voiceover ({}) placed on {} at {}.", r.voice, lane.label(), creator::clock(at)); |
| 764 | self.tools_say(Tool::Voiceover, line); |
| 765 | } |
| 766 | Err(e) => self.tools_fail(Tool::Voiceover, &format!("Voiceover not placed: {e}")), |
| 767 | }, |
| 768 | None => return, |
| 769 | }, |
| 770 | Err(e) => self.tools_fail(Tool::Voiceover, &format!("No voiceover: {e}")), |
| 771 | } |
| 772 | cx.notify(); |
| 773 | } |
| 774 | |
| 775 | pub(crate) fn begin_voiceover_text(&mut self, cx: &mut Context<Self>) { |
| 776 | if let Some(t) = self.tools_mut() { |
| 777 | t.typing = true; |
| 778 | t.num = None; |
| 779 | t.open = None; |
| 780 | } |
| 781 | cx.notify(); |
| 782 | } |
| 783 | |
| 784 | /// The keyboard while the voiceover text is being typed (ahead of the palette and every |
| 785 | /// chord, as the marker field is): escape leaves the field, enter speaks it, the rest is |
| 786 | /// text. |
| 787 | pub(crate) fn tools_type_key( |
| 788 | &mut self, |
| 789 | key: &str, |
| 790 | ctrl: bool, |
| 791 | alt: bool, |
| 792 | key_char: Option<&str>, |
| 793 | cx: &mut Context<Self>, |
| 794 | ) { |
| 795 | if let Some((field, mut edit)) = self.tools.as_ref().and_then(|t| t.num.clone()) { |
| 796 | let done = edit.key(key, ctrl, alt, key_char); |
| 797 | let (lo, hi) = field.range(); |
| 798 | let typed = (done == FieldKey::Commit).then(|| edit.commit(lo, hi)).flatten(); |
| 799 | if let Some(v) = typed { |
| 800 | self.tools_set_num(field, v, cx); |
| 801 | } |
| 802 | if let Some(t) = self.tools_mut() { |
| 803 | match done { |
| 804 | FieldKey::Edited => t.num = Some((field, edit)), |
| 805 | FieldKey::Commit | FieldKey::Cancel => { |
| 806 | t.num = None; |
| 807 | t.typing = false; |
| 808 | } |
| 809 | } |
| 810 | } |
| 811 | cx.notify(); |
| 812 | return; |
| 813 | } |
| 814 | match key { |
| 815 | "escape" => { |
| 816 | if let Some(t) = self.tools_mut() { |
| 817 | t.typing = false; |
| 818 | } |
| 819 | } |
| 820 | "enter" => self.start_voiceover(cx), |
| 821 | "backspace" => { |
| 822 | if let Some(t) = self.tools_mut() { |
| 823 | t.text.pop(); |
| 824 | } |
| 825 | } |
| 826 | _ => { |
| 827 | if !ctrl |
| 828 | && !alt |
| 829 | && let Some(t) = self.tools_mut() |
| 830 | && let Some(chars) = key_char |
| 831 | { |
| 832 | chars.chars().for_each(|c| t.typed(c)); |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | cx.notify(); |
| 837 | } |
| 838 | |
| 839 | // ---- keys --------------------------------------------------------------------- |
| 840 | |
| 841 | /// The card's own keys while it is up and nothing is being typed: left and right switch |
| 842 | /// tab, enter runs the tool, escape cancels a running job or shuts an open list. `true` once the |
| 843 | /// card is up: it owns the strokes it does not answer, like every card. |
| 844 | pub(crate) fn tools_card_key(&mut self, key: &str, cx: &mut Context<Self>) -> bool { |
| 845 | let Some(tools) = self.tools.as_ref() else { |
| 846 | return false; |
| 847 | }; |
| 848 | let (tool, running) = (tools.tool, tools.running.is_some()); |
| 849 | match key { |
| 850 | "escape" if self.card_maximized => self.toggle_maximize(), |
| 851 | "escape" if running => self.cancel_tools_job(cx), |
| 852 | // A dropdown shuts first; past that there is nothing here to leave: the section |
| 853 | // stays open (its head folds it). |
| 854 | "escape" => { |
| 855 | if let Some(t) = self.tools_mut() { |
| 856 | t.open = None; |
| 857 | } |
| 858 | } |
| 859 | "left" | "right" => { |
| 860 | let at = Tool::ALL.iter().position(|t| *t == tool).unwrap_or(0); |
| 861 | let to = ring(at, Tool::ALL.len(), if key == "left" { -1 } else { 1 }); |
| 862 | self.tools_tab(Tool::ALL[to], cx); |
| 863 | } |
| 864 | "up" | "down" if tool == Tool::Fillers => { |
| 865 | let by = if key == "up" { -1 } else { 1 }; |
| 866 | if let Some(t) = self.tools_mut() { |
| 867 | t.pick = ring(t.pick, t.found.len(), by); |
| 868 | } |
| 869 | } |
| 870 | "space" if tool == Tool::Fillers => { |
| 871 | let i = self.tools.as_ref().map_or(0, |t| t.pick); |
| 872 | self.toggle_filler(i, cx); |
| 873 | } |
| 874 | "enter" if !running => match tool { |
| 875 | Tool::Normalize => self.run_normalize(cx), |
| 876 | Tool::Captions => self.start_listening(false, cx), |
| 877 | Tool::Fillers => match self.tools.as_ref().is_some_and(|t| !t.found.is_empty()) { |
| 878 | true => self.cut_ticked_fillers(cx), |
| 879 | false => self.start_listening(true, cx), |
| 880 | }, |
| 881 | Tool::Voiceover => self.begin_voiceover_text(cx), |
| 882 | }, |
| 883 | _ => {} |
| 884 | } |
| 885 | cx.notify(); |
| 886 | true |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | /// Which picker a cycle press moves. |
| 891 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 892 | pub(crate) enum Cycle { |
| 893 | Language, |
| 894 | Hear, |
| 895 | Voice, |
| 896 | } |