forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

creator.rs466 lines, 18.1 KiBHistoryRawDownload
1//! The creator tools the MCP server had first and the window now shares: loudness
2//! normalizing, ducking, captions from speech, filler removal and a voiceover from text.
3//!
4//! Everything here takes the session and says what happened; none of it touches the
5//! window, so the same calls are what the tests drive. The work is the engine's
6//! ([`engine::normalize`], [`engine::speech`], [`engine::tts`], [`engine::duck`]) -- the
7//! MCP tools call those very functions, so a mix normalized from either door lands on the
8//! same numbers.
9
10use std::path::{Path, PathBuf};
11
12use engine::PlaybackSession;
13use engine::duck::{self, Duck};
14use engine::normalize::{self, Report, Scope};
15use engine::project::{Lane, LaneKind};
16use engine::speech::{self, Filler, Hear, Spoken};
17
18/// The loudness targets the Normalize card offers, in LUFS: online video, streaming speech
19/// and broadcast (EBU R128). The first is the default.
20pub(crate) const LUFS_PRESETS: [(&str, f64); 3] = normalize::PRESETS;
21
22/// How far the target and the ceiling move per press, in LU and dB.
23pub(crate) const LUFS_STEP: f64 = 1.0;
24pub(crate) const PEAK_STEP: f64 = 0.5;
25/// The target's and the ceiling's ranges, as the engine takes them.
26pub(crate) const LUFS_RANGE: (f64, f64) = (-40.0, -5.0);
27pub(crate) const PEAK_RANGE: (f64, f64) = (-9.0, 0.0);
28
29/// The languages the captions and fillers cards offer; `auto` lets Whisper decide.
30pub(crate) const LANGUAGES: [(&str, &str); 12] = [
31 ("auto", "Auto"),
32 ("en", "English"),
33 ("es", "Spanish"),
34 ("fr", "French"),
35 ("de", "German"),
36 ("it", "Italian"),
37 ("pt", "Portuguese"),
38 ("nl", "Dutch"),
39 ("tr", "Turkish"),
40 ("ru", "Russian"),
41 ("ja", "Japanese"),
42 ("zh", "Chinese"),
43];
44
45/// How the cards name a speech model: by what it is for. `tiny` is the quick one, `base` the
46/// middle, `small` the careful one; a model with no such name keeps its own, capitalised.
47pub(crate) fn model_label(model: &str) -> String {
48 match model {
49 "tiny" => "Fast".to_string(),
50 "base" => "Balanced".to_string(),
51 "small" => "Accurate".to_string(),
52 other => {
53 let mut c = other.chars();
54 c.next().map_or_else(String::new, |f| f.to_uppercase().chain(c).collect())
55 }
56 }
57}
58
59// ---- normalize ----------------------------------------------------------------------
60
61/// A minus sign the way the cards print it: U+2212, never a hyphen.
62pub(crate) fn minus(s: String) -> String {
63 s.replace('-', "\u{2212}")
64}
65
66/// A level for the card: one decimal, `silent` for no energy.
67pub(crate) fn lufs_text(x: f64) -> String {
68 if x.is_finite() {
69 minus(format!("{x:.1}"))
70 } else {
71 "silent".to_string()
72 }
73}
74
75/// `m:ss` for a time in seconds, or `h:mm:ss` past an hour: the plain clock the cards show.
76pub(crate) fn clock(secs: f64) -> String {
77 let whole = secs.max(0.0).round() as u64;
78 let (h, m, s) = (whole / 3600, whole / 60 % 60, whole % 60);
79 match h {
80 0 => format!("{m}:{s:02}"),
81 _ => format!("{h}:{m:02}:{s:02}"),
82 }
83}
84
85/// What a tool says on its card and in the toast: one plain sentence, and for an error that was
86/// cut short the whole text (the card's tooltip). `offline` marks the sentence a Relink answers.
87#[derive(Clone, Debug, Default)]
88pub(crate) struct Said {
89 pub(crate) line: String,
90 pub(crate) detail: Option<String>,
91 pub(crate) offline: bool,
92}
93
94impl Said {
95 pub(crate) fn plain(line: impl Into<String>) -> Self {
96 Said { line: line.into(), ..Said::default() }
97 }
98}
99
100/// The number the engine gives when sources are offline: `7` in "... 7 source(s) offline ...".
101fn offline_count(e: &str) -> Option<usize> {
102 let at = e.find(" source(s) offline")?;
103 e[..at].rsplit(|c: char| !c.is_ascii_digit()).next()?.parse().ok()
104}
105
106/// An error in the cards' words. A refusal for offline sources becomes a count and a sentence the
107/// Relink button answers; anything else keeps its first sentence, with the rest in the tooltip.
108pub(crate) fn plain_error(e: &str) -> Said {
109 if let Some(n) = offline_count(e) {
110 let line = match n {
111 1 => "1 file is offline. Relink it in Media.".to_string(),
112 n => format!("{n} files are offline. Relink them in Media."),
113 };
114 return Said { line, detail: Some(e.to_string()), offline: true };
115 }
116 let first = e.split(". ").next().unwrap_or(e).split(';').next().unwrap_or(e).trim();
117 let first = match first.chars().next() {
118 Some(c) => c.to_uppercase().chain(first.chars().skip(1)).collect::<String>(),
119 None => String::new(),
120 };
121 let detail = (first.len() != e.trim().len()).then(|| e.to_string());
122 Said { line: first, detail, offline: false }
123}
124
125/// The audio tracks a normalize reaches: unmuted, with clips on them.
126pub(crate) fn normalizable_lanes(session: &PlaybackSession) -> Vec<Lane> {
127 normalize::mix_lanes(session)
128}
129
130/// Normalizes the whole mix, or each track on its own, to `lufs` with the true peak held
131/// under `true_peak` dBTP. One undo step.
132pub(crate) fn normalize(
133 session: &mut PlaybackSession,
134 each: bool,
135 lufs: f64,
136 true_peak: f64,
137) -> Result<Report, String> {
138 let scope = match each {
139 true => Scope::Each(normalizable_lanes(session)),
140 false => Scope::Mix,
141 };
142 normalize::normalize(session, &scope, lufs, true_peak)
143}
144
145/// Joins names as a sentence reads: `A1, A2 and A3`.
146fn join_names(names: &[String]) -> String {
147 match names {
148 [] => String::new(),
149 [one] => one.clone(),
150 [init @ .., last] => format!("{} and {last}", init.join(", ")),
151 }
152}
153
154/// What a normalize says on the card and in the toast: where the level landed, and what held it
155/// short of the target if something did.
156pub(crate) fn normalize_line(report: &Report, each: bool) -> String {
157 let names: Vec<String> = report.lanes.iter().map(|l| l.lane.label()).collect();
158 let (subject, verb) = match (each, names.as_slice()) {
159 (true, lanes) if lanes.len() > 1 => (join_names(lanes), "are each"),
160 (true, [one]) => (one.clone(), "is"),
161 // The whole mix says which tracks it moved, so a one-track mix still names the track.
162 (_, []) => ("The whole mix".to_string(), "is"),
163 (_, lanes) => (format!("The whole mix ({})", join_names(lanes)), "is"),
164 };
165 let (before, after) = (report.before.integrated_lufs, report.after.integrated_lufs);
166 let target = minus(format!("{:.0}", report.lufs));
167 let head = match (before - after).abs() < 0.05 && before.is_finite() {
168 true => format!("Already at {} LUFS.", lufs_text(after)),
169 false => format!("{subject} {verb} now {} LUFS.", lufs_text(after)),
170 };
171 let tail = match (report.reached, report.peak_held) {
172 (true, _) => String::new(),
173 (false, true) => format!(
174 " The {} dB peak limit stops it from getting louder, so it can't reach {target} LUFS.",
175 lufs_text(report.true_peak)
176 ),
177 (false, false) => format!(" It is short of the {target} LUFS target."),
178 };
179 format!("{head}{tail}")
180}
181
182// ---- ducking ------------------------------------------------------------------------
183
184/// The depth a new duck starts at, in dB: the MCP tool's default.
185pub(crate) const DUCK_DEPTH_DEFAULT: f32 = -12.0;
186/// One press of a duck stepper: a dB of depth, ten ms of attack, fifty of release.
187pub(crate) const DUCK_DEPTH_STEP: f32 = 1.0;
188pub(crate) const DUCK_ATTACK_STEP: f32 = 10.0;
189pub(crate) const DUCK_RELEASE_STEP: f32 = 50.0;
190
191/// Which of a duck's numbers a stepper moves.
192#[derive(Clone, Copy, PartialEq, Eq, Debug)]
193pub(crate) enum DuckField {
194 Depth,
195 Attack,
196 Release,
197}
198
199/// Ducks `lane` under `key` (the voice), keeping the numbers a duck under that key already
200/// has. A duck under a different key is added beside it, as the MCP `duck` op does.
201pub(crate) fn duck_under(session: &mut PlaybackSession, lane: Lane, key: Lane) -> Result<(), String> {
202 check_duck(session, lane, key)?;
203 let duck = session
204 .lane_duck_list(lane)
205 .into_iter()
206 .find(|d| d.under == key.ord)
207 .unwrap_or_else(|| Duck::new(key.ord, DUCK_DEPTH_DEFAULT));
208 set_duck(session, lane, duck)
209}
210
211/// Moves one number of the duck `lane` has under `key` by `steps` presses.
212pub(crate) fn duck_step(
213 session: &mut PlaybackSession,
214 lane: Lane,
215 key: Lane,
216 field: DuckField,
217 steps: i32,
218) -> Result<(), String> {
219 let mut duck = session
220 .lane_duck_list(lane)
221 .into_iter()
222 .find(|d| d.under == key.ord)
223 .ok_or_else(|| format!("{} is not ducked under {}", lane.label(), key.label()))?;
224 let by = steps as f32;
225 match field {
226 DuckField::Depth => {
227 duck.depth_db = (duck.depth_db + by * DUCK_DEPTH_STEP).clamp(duck::MIN_DEPTH_DB, duck::MAX_DEPTH_DB)
228 }
229 DuckField::Attack => {
230 duck.attack_ms = (duck.attack_ms + by * DUCK_ATTACK_STEP).clamp(duck::MIN_TIME_MS, duck::MAX_ATTACK_MS)
231 }
232 DuckField::Release => {
233 duck.release_ms =
234 (duck.release_ms + by * DUCK_RELEASE_STEP).clamp(duck::MIN_TIME_MS, duck::MAX_RELEASE_MS)
235 }
236 }
237 set_duck(session, lane, duck)
238}
239
240/// Takes the duck `lane` has under `key` off, keeping its others.
241pub(crate) fn duck_off(session: &mut PlaybackSession, lane: Lane, key: Lane) -> Result<(), String> {
242 if session.lane_locked(lane) {
243 return Err(format!("{} is locked", lane.label()));
244 }
245 match session.clear_lane_duck(lane, key.ord) {
246 true => Ok(()),
247 false => Err(format!("{} is not ducked under {}", lane.label(), key.label())),
248 }
249}
250
251fn check_duck(session: &PlaybackSession, lane: Lane, key: Lane) -> Result<(), String> {
252 if lane.kind != LaneKind::Audio || key.kind != LaneKind::Audio {
253 return Err("only an audio track ducks, and only under another audio track".into());
254 }
255 if lane == key {
256 return Err(format!("{} cannot duck under itself", lane.label()));
257 }
258 if session.lane_locked(lane) {
259 return Err(format!("{} is locked", lane.label()));
260 }
261 Ok(())
262}
263
264fn set_duck(session: &mut PlaybackSession, lane: Lane, duck: Duck) -> Result<(), String> {
265 let duck = duck.clamped().ok_or("a duck takes finite numbers")?;
266 // Already so: no second undo step for a press that changed nothing.
267 if session.lane_duck_list(lane).contains(&duck) {
268 return Ok(());
269 }
270 match session.set_lane_duck(lane, Some(duck)) {
271 true => Ok(()),
272 false => Err(format!("{} could not take that duck", lane.label())),
273 }
274}
275
276// ---- captions and fillers -----------------------------------------------------------
277
278/// What to listen to for captions and fillers: the whole mix, or one audio track.
279pub(crate) fn hear_choices(session: &PlaybackSession) -> Vec<Hear> {
280 std::iter::once(Hear::Mix)
281 .chain(
282 session
283 .lanes()
284 .into_iter()
285 .filter(|l| l.kind == LaneKind::Audio && !session.lane_clips(*l).is_empty())
286 .map(Hear::Lane),
287 )
288 .collect()
289}
290
291/// How the card names a [`Hear`].
292pub(crate) fn hear_label(hear: Hear) -> String {
293 match hear {
294 Hear::Mix => "Whole mix".to_string(),
295 Hear::Lane(l) => l.label(),
296 }
297}
298
299/// The caption lane new captions go on: the first with nothing on it, else the next one
300/// (made when they are placed).
301pub(crate) fn caption_lane(session: &PlaybackSession) -> Lane {
302 let lanes = session.subtitle_lanes();
303 lanes
304 .iter()
305 .copied()
306 .find(|l| session.sub_lane(*l).is_empty() && !session.lane_locked(*l))
307 .unwrap_or_else(|| Lane::new(LaneKind::Subtitle, lanes.len()))
308}
309
310/// Where the caption file of a generated track is kept: beside the project when it has a
311/// path, else in the editor's cache; never over a file that is there.
312pub(crate) fn caption_file(project: Option<&Path>) -> PathBuf {
313 let (dir, stem) = match project {
314 Some(p) => (
315 p.parent().map(Path::to_path_buf).unwrap_or_default(),
316 p.file_stem().map_or_else(|| "project".to_string(), |s| s.to_string_lossy().into_owned()),
317 ),
318 None => (speech::home().join(".cache/edith/captions"), format!("captions-{}", std::process::id())),
319 };
320 let mut path = dir.join(format!("{stem}.captions.srt"));
321 let mut n = 2;
322 while path.exists() {
323 path = dir.join(format!("{stem}.captions-{n}.srt"));
324 n += 1;
325 }
326 path
327}
328
329/// Cuts `words` into caption cues and puts them on the next free caption lane, as one undo
330/// step. Returns how many cues and the lane they are on.
331/// Puts the transcript's captions on the caption lane, as one undo step. Captions made by an
332/// earlier run are replaced in place (their lane is cleared first), so a second run never stacks
333/// a second copy. Returns the cue count, the lane, and whether an earlier run was replaced.
334pub(crate) fn place_captions(
335 session: &mut PlaybackSession,
336 words: &[Spoken],
337 project: Option<&Path>,
338) -> Result<(usize, Lane, bool), String> {
339 let fps = session.meta().frame_rate;
340 let cues = speech::captions(words, fps);
341 if cues.is_empty() {
342 return Err("no speech to caption: the transcript has no words".into());
343 }
344 let earlier = generated_caption_lane(session);
345 if let Some(lane) = earlier
346 && session.lane_locked(lane)
347 {
348 return Err(format!("{} is locked: unlock it to replace its captions", lane.label()));
349 }
350 let lane = earlier.unwrap_or_else(|| caption_lane(session));
351 let pushed = session.history_pushes();
352 // One batch: the clearing and the new track are a single undo step (the engine's own
353 // batch nests inside this one).
354 session.begin_batch();
355 if earlier.is_some() {
356 clear_generated_captions(session, lane);
357 }
358 let placed = speech::place_captions(session, &cues, lane, &caption_file(project));
359 session.end_batch();
360 if let Err(e) = placed {
361 // A failed attempt leaves nothing behind: take back what it pushed.
362 for _ in pushed..session.history_pushes() {
363 if !session.undo() {
364 break;
365 }
366 }
367 session.clear_redo();
368 return Err(e);
369 }
370 Ok((cues.len(), lane, earlier.is_some()))
371}
372
373/// Whether a subtitle track is a caption track this editor generated (its file is named for
374/// the project and `.captions`, see [`caption_file`]).
375fn is_generated_caption(track: &engine::subtitle::SubtitleTrack) -> bool {
376 track.path.file_name().is_some_and(|n| n.to_string_lossy().contains(".captions"))
377}
378
379/// The first subtitle lane that holds generated captions, if any.
380fn generated_caption_lane(session: &PlaybackSession) -> Option<Lane> {
381 let tracks = session.subtitles();
382 session
383 .subtitle_lanes()
384 .into_iter()
385 .find(|&l| session.sub_lane(l).iter().any(|c| tracks.get(c.track).is_some_and(is_generated_caption)))
386}
387
388/// Takes every caption off `lane` and drops the generated tracks they came from, when nothing
389/// else places them. Inside the caller's batch.
390fn clear_generated_captions(session: &mut PlaybackSession, lane: Lane) {
391 let mut tracks: Vec<usize> = session.sub_lane(lane).iter().map(|c| c.track).collect();
392 while !session.sub_lane(lane).is_empty() {
393 if !session.delete_sub(lane, 0) {
394 break;
395 }
396 }
397 tracks.sort_unstable();
398 tracks.dedup();
399 // Highest first, so each removal leaves the lower indices where they are.
400 for t in tracks.into_iter().rev() {
401 if session.subtitles().get(t).is_some_and(is_generated_caption) {
402 let _ = session.remove_subtitles(t);
403 }
404 }
405}
406
407/// The fillers among `words`, with the padding a cut takes either side (a few frames, never
408/// into the next word).
409pub(crate) fn fillers_in(session: &PlaybackSession, words: &[Spoken]) -> Vec<Filler> {
410 let fps = session.meta().frame_rate;
411 let end = (session.timeline_duration() * fps).round() as u32;
412 let pad = (0.06 * fps).round() as u32;
413 speech::find_fillers(words, pad, end)
414}
415
416/// Cuts the picked fillers out of every track, closing each hole, as one undo step.
417pub(crate) fn cut_fillers(session: &mut PlaybackSession, fillers: &[Filler]) -> Result<usize, String> {
418 cut_fillers_regions(session, fillers).map(|_| fillers.len())
419}
420
421/// [`cut_fillers`], returning the regions cut (`(start, length)` frames) so a transcript can
422/// follow the edit.
423pub(crate) fn cut_fillers_regions(session: &mut PlaybackSession, fillers: &[Filler]) -> Result<Vec<(u32, u32)>, String> {
424 let lanes = session.lanes();
425 speech::cut_fillers(session, fillers, &lanes)
426}
427
428// ---- voiceover ----------------------------------------------------------------------
429
430/// The folder a voiceover is written to: `voiceover/` beside the project, or the editor's
431/// cache when the project has no path yet.
432pub(crate) fn voiceover_dir(project: Option<&Path>) -> PathBuf {
433 match project.and_then(Path::parent) {
434 Some(dir) => dir.join("voiceover"),
435 None => speech::home().join(".cache/edith/voiceover"),
436 }
437}
438
439/// Takes the voiceover `file` in as a source and puts it at `at_secs` on the first audio
440/// track with room for it (a new track when none has), as one undo step. Returns the lane.
441pub(crate) fn place_voiceover(session: &mut PlaybackSession, file: &Path, at_secs: f64) -> Result<Lane, String> {
442 let secs = engine::probe_media(file).duration_secs.unwrap_or(0.0);
443 let fps = session.meta().frame_rate;
444 let (from, to) = ((at_secs * fps).round() as u32, ((at_secs + secs) * fps).ceil() as u32);
445 let free = |l: &Lane| {
446 l.kind == LaneKind::Audio
447 && !session.lane_locked(*l)
448 && session.lane_clips(*l).iter().all(|c| c.end() <= from || c.start >= to)
449 };
450 let found = session.lanes().into_iter().find(free);
451 session.begin_batch();
452 let placed = (|| {
453 let lane = match found {
454 Some(l) => l,
455 None => session.add_lane(LaneKind::Audio),
456 };
457 session.import(file).map_err(|e| format!("{}: refused: {e}", file.display()))?;
458 match session.place_stream_at(at_secs, file, 0, Some(lane)) {
459 Ok(true) => Ok(lane),
460 Ok(false) => Err(format!("the voiceover did not place at {at_secs:.2} s")),
461 Err(e) => Err(e.to_string()),
462 }
463 })();
464 session.end_batch();
465 placed
466}