forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

edit_subs.rs2088 lines, 101.3 KiBHistoryRawDownload
1//! Caption ops for the batched `edit` verb, and the `captions` read tool.
2//!
3//! A caption lane (S1..) holds placements of subtitle-track windows. A whole
4//! track goes down as one placement covering all its cues, the same rule the GUI
5//! uses when a palette row is dropped on a lane ([`captions_place`]). The ops here
6//! follow the contract of `edit_fx`: [`apply`] answers its own op names, or `None`
7//! so the caller can offer the op to the next group.
8
9use engine::project::{Edge, Lane, LaneKind, SubClip};
10use engine::PlaybackSession;
11use serde_json::{json, Value};
12
13use super::edit_fx::Applied;
14use crate::parse;
15use crate::server::{opt_str, opt_u64, Reply, Server, Tool};
16
17const NO_PROJECT: &str = "no project open — call project_open or project_new first";
18
19/// The caption ops this module answers.
20pub const OPS: &[&str] = &["captions_place", "sub_move", "sub_trim", "sub_delete", "cue_text", "cue_add", "cue_replace", "cue_delete", "cue_time", "cue_merge", "cue_split", "captions_remove", "subtitles_lang"];
21
22/// Largest `captions` reply, in bytes of text.
23const CAPTIONS_CAP: usize = 4096;
24
25pub const CAPTIONS_DOC: &str = "List the cues on caption lanes (S1..) in timeline time, one line per cue: \
26\"<n>. track T cue C [S1@F] MM:SS.mmm–MM:SS.mmm text\". Use the track and cue numbers with the cue_text op (empty text removes the cue) or the cue_delete op. \
27[S1@F] is the placed caption that shows the cue: its address for sub_move, sub_trim and sub_delete (a cue split across placements is listed once per piece, each with its own address). \
28Only cues that a placed caption shows are listed; the footer lists every subtitle track, placed or not. \
29lane limits it to one caption lane; range {from, to} (times, as in the edit tool) limits it to a stretch of the timeline: from is inclusive, to is exclusive, so a cue that starts at to is not listed (and a cue that ends at from is not either). Seconds such as 1s are exact, not rounded to a frame. \
30Lists 40 cues a page: a long listing says which page it is and the next one to ask for (page). Each page is capped at about 4 KB; narrow with lane or range when it says more cues were cut.";
31
32/// The help for the `subtitles_lang` op, for the edit tool's op list (help.rs).
33pub const SUBTITLES_LANG_DOC: &str = "subtitles_lang {track, lang} — names the language of a subtitle track: lang is an ISO 639-2 code (fra, deu, eng) or a two-letter code or an English name (fr, French). It is what the track's MKV or mp4 export says the track is in; a track with none exports as und. One undo step. subtitles_import {path, lang?} sets it at import: when lang is left out it is guessed from the file name (talk.fr.srt, fra.srt, talk_en.srt, eng.srt), and otherwise left unset.";
34
35pub fn tools() -> Vec<Tool> {
36 vec![Tool { name: "captions", description: CAPTIONS_DOC, schema: captions_schema, run: run_captions }]
37}
38
39fn captions_schema() -> Value {
40 json!({
41 "type": "object",
42 "properties": {
43 "lane": { "type": "string", "description": "A caption lane, e.g. S1. Default: every caption lane." },
44 "page": { "type": "integer", "minimum": 1, "description": "Which page of 40 cues to list (default 1). A long listing says `next: captions {page:N}`." },
45 "range": {
46 "type": "object",
47 "description": "Only cues overlapping this stretch: from inclusive, to exclusive, e.g. {\"from\": \"0\", \"to\": \"end\"}.",
48 "properties": {
49 "from": { "type": "string" },
50 "to": { "type": "string" }
51 }
52 }
53 }
54 })
55}
56
57// ---- ops ------------------------------------------------------------------
58
59/// Applies one caption op if it is one of this module's. `None` for any other op name.
60pub fn apply(s: &mut PlaybackSession, op: &Value, fps: f64) -> Option<Result<Applied, String>> {
61 let name = op.get("op")?.as_str()?;
62 let end = parse::session_end(s);
63 let r = match name {
64 "captions_place" => op_captions_place(s, op, fps, end),
65 "sub_move" => op_sub_move(s, op, fps, end),
66 "sub_trim" => op_sub_trim(s, op, fps, end),
67 "sub_delete" => op_sub_delete(s, op, fps),
68 "cue_text" => op_cue_text(s, op),
69 "subtitles_lang" => op_subtitles_lang(s, op),
70 "cue_add" => op_cue_add(s, op, fps, end),
71 "cue_replace" => op_cue_replace(s, op),
72 "cue_delete" => op_cue_delete(s, op, fps, end),
73 "cue_time" => op_cue_time(s, op, fps, end),
74 "cue_merge" => op_cue_merge(s, op),
75 "cue_split" => op_cue_split(s, op, fps, end),
76 "captions_remove" => op_captions_remove(s, op),
77 _ => return None,
78 };
79 Some(r)
80}
81
82/// `captions_place {track, lane?, at?}`: the whole track as one placement from
83/// its first microsecond to its last cue, on `lane` (default S1, made if missing),
84/// at timeline frame `at` (default 0).
85fn op_captions_place(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
86 let track = track_arg(s, op)?;
87 let t = &s.subtitles()[track];
88 if let Some(why) = &t.refused {
89 return Err(format!("captions_place: subtitle track {track} could not be read: {why}"));
90 }
91 let cues = t.cues.len();
92 let end_us = t.cues.iter().map(|c| c.end_us).max().unwrap_or(0);
93 if cues == 0 || end_us <= 0 {
94 return Err(format!("captions_place: subtitle track {track} has no cues to place"));
95 }
96 let lane = match op.get("lane") {
97 None | Some(Value::Null) => Lane::new(LaneKind::Subtitle, 0),
98 Some(Value::String(t)) => parse::lane(t)?,
99 Some(_) => return Err("`lane` must be a caption lane name such as S1".into()),
100 };
101 if lane.kind != LaneKind::Subtitle {
102 return Err(format!(
103 "captions_place: {} is not a caption lane; captions go on S1.. (pictures and sound go on V/A lanes)",
104 parse::lane_name(lane)
105 ));
106 }
107 refuse_if_locked(s, "captions_place", &[lane])?;
108 let made = ensure_lane(s, lane)?;
109 let target = parse::lane_name(lane);
110 let below: Vec<&String> = made.iter().filter(|n| **n != target).collect();
111 let stray = match below.as_slice() {
112 [] => String::new(),
113 [one] => format!("; {one} was created empty, because {target} sits above it"),
114 many => format!(
115 "; {} were created empty, because {target} sits above them",
116 many.iter().map(|n| n.as_str()).collect::<Vec<_>>().join(", ")
117 ),
118 };
119 let at = opt_frame(op, "at", fps, end)?.unwrap_or(0);
120 // The window is whole frames: a track that ends between two frames would
121 // otherwise be stretched over the frames it occupies, and every cue would
122 // be shown late by the same fraction (a 4.750 s track on 143 frames showed
123 // its 0.500 s cue at 0.502 s). `whole_track` makes the window the frames' own length.
124 let sub = SubClip::whole_track(track, end_us, fps);
125 let frames = sub.frames;
126 s.place_sub(lane, at, sub).map_err(|e| {
127 let e = e.to_string();
128 let mut msg = format!("captions_place track {track}: {e}");
129 if e.contains("already covers") {
130 // The clash names the caption in the way by its start frame: say how to clear it.
131 let blocker = e
132 .split_once("at frame ")
133 .and_then(|(_, rest)| rest.split(|c: char| !c.is_ascii_digit()).next())
134 .unwrap_or("0");
135 let name = parse::lane_name(lane);
136 msg.push_str(&format!(
137 "; to make room: sub_delete {{clip:\"{name}@{blocker}\"}} removes that caption, \
138 sub_move {{clip:\"{name}@{blocker}\", to_lane:\"S2\"}} moves it to another caption lane, \
139 or captions_place {{track:{track}, lane:\"S2\"}} puts this track on another caption lane"
140 ));
141 }
142 msg
143 })?;
144 let cue_word = cue_count(cues);
145 Ok(Applied {
146 text: format!(
147 "captions_place track {track} ({cue_word}, {frames}f) → {} @{at}f{stray}",
148 parse::lane_name(lane)
149 ),
150 touched: vec![(lane, at)],
151 })
152}
153
154/// `sub_move {clip, to_lane?, at}`: moves a caption to another caption lane and/or frame.
155fn op_sub_move(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
156 let (lane, idx) = sub_arg(s, op)?;
157 let addr = sub_addr(s, lane, idx);
158 let before = s.sub_lane(lane)[idx];
159 let to = match op.get("to_lane") {
160 None | Some(Value::Null) => lane,
161 Some(Value::String(t)) => parse::lane(t)?,
162 Some(_) => return Err("`to_lane` must be a caption lane name such as S2".into()),
163 };
164 if to.kind != LaneKind::Subtitle || !s.subtitle_lanes().contains(&to) {
165 return Err(format!(
166 "sub_move {addr}: {} is not a caption lane here; the caption lanes are {}",
167 parse::lane_name(to),
168 lane_names(s)
169 ));
170 }
171 let mut locks = sub_group_lanes(s, lane, idx);
172 if !locks.contains(&to) {
173 locks.push(to);
174 }
175 refuse_if_locked(s, "sub_move", &locks)?;
176 let at = opt_frame(op, "at", fps, end)?.ok_or("missing `at`: give the frame to move the caption to")?;
177 s.move_sub(lane, idx, to, at)
178 .map_err(|e| format!("sub_move {addr} to {}@{at}f refused: {e}", parse::lane_name(to)))?;
179 // Read back by the window it shows: a move changes where it starts, not what it shows.
180 let touched: Vec<(Lane, u32)> = s
181 .sub_lane(to)
182 .iter()
183 .find(|c| c.track == before.track && c.in_us == before.in_us && c.out_us == before.out_us)
184 .map(|c| vec![(to, c.start)])
185 .unwrap_or_default();
186 let new = touched
187 .first()
188 .map(|&(l, st)| parse::addr(l, st))
189 .unwrap_or_else(|| format!("{}@{at}", parse::lane_name(to)));
190 Ok(Applied { text: format!("sub_move {addr} → {new}"), touched })
191}
192
193/// `sub_trim {clip, edge: in|out, to}`: moves one edge of a caption.
194fn op_sub_trim(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
195 let (lane, idx) = sub_arg(s, op)?;
196 let addr = sub_addr(s, lane, idx);
197 let (edge, side) = match op.get("edge").and_then(Value::as_str) {
198 Some("in") => (Edge::Start, "in"),
199 Some("out") => (Edge::End, "out"),
200 _ => return Err("`edge` must be \"in\" or \"out\"".into()),
201 };
202 let to = opt_frame(op, "to", fps, end)?.ok_or("missing `to`: give the frame the edge moves to")?;
203 refuse_if_locked(s, "sub_trim", &sub_group_lanes(s, lane, idx))?;
204 if let Err(e) = s.trim_sub(lane, idx, edge, to) {
205 let room = match s.trim_sub_room(lane, idx, edge) {
206 Some((lo, hi)) => format!(" (it can travel {lo}f–{hi}f)"),
207 None => String::new(),
208 };
209 return Err(format!("sub_trim {addr} {side} to {to}f refused: {e}{room}"));
210 }
211 let touched = s.sub_lane(lane).get(idx).map(|c| vec![(lane, c.start)]).unwrap_or_default();
212 Ok(Applied { text: format!("sub_trim {addr} {side} → {}", parse::tc(to, fps)), touched })
213}
214
215/// `sub_delete {clip}`: the Delete key on a caption. A lone caption is lifted
216/// (a gap is left); one in a group takes its group with it. A caption address
217/// names a whole placement, so a single cue inside one takes `cue_delete`.
218fn op_sub_delete(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
219 let (lane, idx) = match sub_arg(s, op) {
220 Ok(found) => found,
221 Err(e) if e.contains("is not a caption") => return Err(e),
222 Err(e) => return Err(format!("{e}{}", single_cue_hint(s, op, fps))),
223 };
224 let addr = sub_addr(s, lane, idx);
225 refuse_if_locked(s, "sub_delete", &sub_group_lanes(s, lane, idx))?;
226 if !s.delete_sub(lane, idx) {
227 return Err(format!("sub_delete {addr} refused: no such caption"));
228 }
229 Ok(Applied { text: format!("sub_delete {addr}"), touched: Vec::new() })
230}
231
232/// `captions_remove {track, force?}`: removes a caption track from the project, one undo step with
233/// the batch. A track with no placement on the timeline goes as it is. A track with placements is
234/// refused, naming them, unless `force:true`, which deletes those placements first (a placement in a
235/// group is refused: deleting it would delete its group's clips). The engine reindexes the other tracks.
236fn op_captions_remove(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
237 let track = track_arg(s, op)?;
238 let force = match op.get("force") {
239 None | Some(Value::Null) => false,
240 Some(Value::Bool(b)) => *b,
241 Some(_) => return Err("captions_remove: `force` must be true or false".into()),
242 };
243 let name = s.subtitles()[track].name.clone();
244 let placed: Vec<(Lane, usize)> = s
245 .subtitle_lanes()
246 .into_iter()
247 .flat_map(|l| {
248 s.sub_lane(l)
249 .iter()
250 .enumerate()
251 .filter(|(_, c)| c.track == track)
252 .map(move |(i, _)| (l, i))
253 .collect::<Vec<_>>()
254 })
255 .collect();
256 // Removing the track renumbers every track after it, so a locked lane holding one of those
257 // (or this track's own placements) would change what it shows.
258 let renumbered: Vec<Lane> = s
259 .subtitle_lanes()
260 .into_iter()
261 .filter(|&l| s.sub_lane(l).iter().any(|c| c.track >= track))
262 .collect();
263 refuse_if_locked(s, "captions_remove", &renumbered)?;
264 if !placed.is_empty() && !force {
265 let shown: Vec<String> = placed.iter().take(3).map(|&(l, i)| sub_addr(s, l, i)).collect();
266 return Err(format!(
267 "captions_remove refused: track {track} ({name}) has {} placement(s) on the timeline ({}{}); pass force:true to delete them with it, or sub_delete them first",
268 placed.len(),
269 shown.join(", "),
270 if placed.len() > shown.len() { ", …" } else { "" }
271 ));
272 }
273 if let Some(&(l, i)) = placed.iter().find(|&&(l, i)| s.sub_lane(l)[i].link.is_some()) {
274 return Err(format!(
275 "captions_remove refused: {} is grouped with clips; ungroup it first, since deleting it would delete its group",
276 sub_addr(s, l, i)
277 ));
278 }
279 // Each placement is deleted from the last down, so the indices still to go are unmoved.
280 let mut removed = 0usize;
281 for &(l, i) in placed.iter().rev() {
282 let addr = sub_addr(s, l, i);
283 if !s.delete_sub(l, i) {
284 return Err(format!("captions_remove refused: {addr} could not be deleted (its lane is locked?)"));
285 }
286 removed += 1;
287 }
288 s.remove_subtitles(track)
289 .map_err(|e| format!("captions_remove refused: {e}"))?;
290 let text = if removed == 0 {
291 format!("captions_remove track {track} ({name}) — removed")
292 } else {
293 format!("captions_remove track {track} ({name}) — removed with its {removed} placement(s)")
294 };
295 Ok(Applied { text, touched: Vec::new() })
296}
297
298/// The track and cue number an op names: `track` and `index`, the numbers captions lists.
299fn cue_arg(s: &PlaybackSession, op: &Value, name: &str) -> Result<(usize, usize), String> {
300 let track = track_arg(s, op)?;
301 let index = op
302 .get("index")
303 .and_then(Value::as_u64)
304 .ok_or("missing `index`: the cue number as captions lists it")? as usize;
305 let cues = s.subtitles()[track].cues.len();
306 if index >= cues {
307 return Err(format!("{name}: track {track} has {}; index {index} is not one of them", cue_count(cues)));
308 }
309 Ok((track, index))
310}
311
312/// The caption lane that shows cue `index` of `track`, to read timeline times through.
313fn cue_lane(s: &PlaybackSession, track: usize, index: usize) -> Option<Lane> {
314 s.subtitle_lanes()
315 .into_iter()
316 .find(|&l| s.sub_lane_cue_refs(l).iter().any(|&(_, _, t, c)| t == track && c == index))
317}
318
319/// `cue_time {track, index, at?, to?}`: moves one cue's start (`at`) and/or end (`to`), as timeline
320/// times (seconds exact). Give both to move or resize, one to trim that edge. The cue stays inside
321/// its neighbours and at least 0.1 s long. One undo step.
322fn op_cue_time(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
323 let (track, index) = cue_arg(s, op, "cue_time")?;
324 refuse_if_tracks_locked(s, "cue_time", &[track])?;
325 let at = range_end_us(op, "at", fps, end)?;
326 let to = range_end_us(op, "to", fps, end)?;
327 if at.is_none() && to.is_none() {
328 return Err("cue_time needs `at` (the new start), `to` (the new end), or both, as timeline times".into());
329 }
330 let lane = cue_lane(s, track, index)
331 .ok_or_else(|| format!("cue_time: no caption lane shows track {track} cue {index}; place the track first"))?;
332 let cue = &s.subtitles()[track].cues[index];
333 let (old_a, old_b) = (cue.start_us, cue.end_us);
334 let conv = |tl: i64| s.cue_track_us_at(lane, track, index, tl);
335 let a = at.and_then(conv).unwrap_or(old_a);
336 let b = to.and_then(conv).unwrap_or(old_b);
337 match s.set_cue_times(track, index, a, b) {
338 Ok(true) => Ok(Applied {
339 text: format!("cue_time track {track} cue {index} {} → {}", span_text(old_a, old_b), span_text(a, b)),
340 touched: Vec::new(),
341 }),
342 Ok(false) => Err(format!("cue_time: track {track} cue {index} is already there: nothing to change")),
343 Err(e) => Err(format!("cue_time: {e}")),
344 }
345}
346
347/// `cue_merge {track, index}`: joins a cue with the one after it into one cue. One undo step.
348fn op_cue_merge(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
349 let (track, index) = cue_arg(s, op, "cue_merge")?;
350 refuse_if_tracks_locked(s, "cue_merge", &[track])?;
351 s.merge_cue_next(track, index).map_err(|e| format!("cue_merge: {e}"))?;
352 let words = echo_words(&s.subtitles()[track].cues[index].text);
353 Ok(Applied { text: format!("cue_merge track {track} cue {index} + {} → \"{words}\"", index + 1), touched: Vec::new() })
354}
355
356/// `cue_split {track, index, at}`: divides one cue in two at timeline time `at`, the words shared
357/// at the word nearest the point. One undo step.
358fn op_cue_split(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
359 let (track, index) = cue_arg(s, op, "cue_split")?;
360 refuse_if_tracks_locked(s, "cue_split", &[track])?;
361 let at = range_end_us(op, "at", fps, end)?.ok_or("cue_split needs `at`: where to cut the cue, e.g. \"12s\"")?;
362 let lane = cue_lane(s, track, index)
363 .ok_or_else(|| format!("cue_split: no caption lane shows track {track} cue {index}; place the track first"))?;
364 let t = s.cue_track_us_at(lane, track, index, at).ok_or("cue_split: that cue is not shown")?;
365 let cue = &s.subtitles()[track].cues[index];
366 if !(cue.start_us < t && t < cue.end_us) {
367 return Err(format!(
368 "cue_split: {} is not inside the cue ({})",
369 clock_us(at),
370 span_text(cue.start_us, cue.end_us)
371 ));
372 }
373 if !s.split_cues_at(track, t) {
374 return Err("cue_split: the cue has no word to put on each side".into());
375 }
376 Ok(Applied { text: format!("cue_split track {track} cue {index} at {}", clock_us(at)), touched: Vec::new() })
377}
378
379/// `cue_text {track, index, text}`: retypes one cue of a subtitle track. Empty
380/// text removes the cue instead ([`remove_cue`]), since a blank cue is no cue.
381fn op_cue_text(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
382 let track = track_arg(s, op)?;
383 let index = op
384 .get("index")
385 .and_then(Value::as_u64)
386 .ok_or("missing `index`: the cue number as captions lists it")? as usize;
387 let raw = op.get("text").and_then(Value::as_str).ok_or("missing `text`: the new words for the cue")?;
388 // A literal backslash-n (two characters) is what a model types when it means a line break:
389 // read it as one, and say so in the reply, so the cue never keeps a stray `\n`.
390 let converted = raw.contains("\\n");
391 let text_owned = raw.replace("\\n", "\n");
392 let text = text_owned.as_str();
393 let cues = &s.subtitles()[track].cues;
394 let Some(cue) = cues.get(index) else {
395 return Err(format!(
396 "cue_text: track {track} has {}; index {index} is not one of them",
397 cue_count(cues.len())
398 ));
399 };
400 refuse_if_tracks_locked(s, "cue_text", &[track])?;
401 if text.is_empty() {
402 return remove_cue(s, track, index);
403 }
404 if cue.text == text {
405 return Err(format!("cue_text: track {track} cue {index} already reads that: nothing to change"));
406 }
407 if !s.set_cue_text(track, index, text) {
408 return Err(format!("cue_text: track {track} cue {index} refused the new text"));
409 }
410 let note = if converted { "; literal \\n read as a line break" } else { "" };
411 Ok(Applied {
412 text: format!("cue_text track {track} cue {index} → \"{}\"{note}", echo_words(text)),
413 touched: Vec::new(),
414 })
415}
416
417/// `subtitles_lang {track, lang}`: names a subtitle track's language, as an ISO 639-2 code. One
418/// undo step. Refused for a track that is not there, a language that is not one, or the language
419/// the track already has.
420fn op_subtitles_lang(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
421 let track = track_arg(s, op)?;
422 let raw = op
423 .get("lang")
424 .and_then(Value::as_str)
425 .ok_or("missing `lang`: the language as a code (fra, fr) or an English name (French)")?;
426 let code = engine::subtitle::language_code(raw).ok_or_else(|| {
427 format!("subtitles_lang: `{raw}` is not a language: give its code (fra or fr) or its English name (French)")
428 })?;
429 if s.subtitles()[track].language == code {
430 return Err(format!("subtitles_lang: track {track} is already {code}: nothing to change"));
431 }
432 if !s.set_subtitle_language(track, &code) {
433 return Err(format!("subtitles_lang: track {track} refused the language {code}"));
434 }
435 let name = engine::subtitle::language_name(&code).map(|n| format!(" ({n})")).unwrap_or_default();
436 Ok(Applied { text: format!("subtitles_lang track {track} → {code}{name}"), touched: Vec::new() })
437}
438
439/// `cue_add {track, at, to, text, overwrite?, track_clock?, extend?}`: adds a cue to a subtitle
440/// track. `at` and `to` are timeline times, as the edit tool takes them (seconds exact), mapped onto
441/// the track's own clock through the placement that shows it; `track_clock: true` takes them on the
442/// track's clock instead (the times its file gives its cues). The reply gives both clocks. The
443/// cue is kept in the project and saved with it. A cue that overlaps one already in the track is
444/// refused, unless `overwrite` is true, which replaces every cue it overlaps, as one undo step.
445/// A cue no placement shows is kept, and the reply says where it falls outside the captions;
446/// `extend: true` then lengthens the caption that ends nearest it so that it shows the cue.
447fn op_cue_add(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
448 let track = track_arg(s, op)?;
449 refuse_if_tracks_locked(s, "cue_add", &[track])?;
450 // Every placement of the track: (lane, index on the lane, start frame, frames, window in, out).
451 let mut placements: Vec<(Lane, usize, u32, u32, i64, i64)> = Vec::new();
452 for l in s.subtitle_lanes() {
453 for (idx, c) in s.sub_lane(l).iter().enumerate() {
454 if c.track == track {
455 placements.push((l, idx, c.start, c.frames, c.in_us, c.out_us));
456 }
457 }
458 }
459 // A track no caption lane shows has no place in the timeline: its cues are kept on the track's
460 // own clock, the timeline reads the same, and the reply says nothing shows until it is placed.
461 let track_clock = match op.get("track_clock") {
462 None | Some(Value::Null) => false,
463 Some(v) => v.as_bool().ok_or("cue_add: `track_clock` must be true or false")?,
464 };
465 let extend = match op.get("extend") {
466 None | Some(Value::Null) => false,
467 Some(v) => v.as_bool().ok_or("cue_add: `extend` must be true or false")?,
468 };
469 let at_raw = range_end_us(op, "at", fps, end)?.ok_or("cue_add needs `at`: the cue's start, e.g. \"31s\"")?;
470 let to_raw = range_end_us(op, "to", fps, end)?.ok_or("cue_add needs `to`: the cue's end, e.g. \"33s\"")?;
471 // The placement whose clock the times are read on: the last one that starts at or before `at`
472 // on that clock (a track may have several placements, each with its own window), else the first.
473 let clock = |p: &(Lane, usize, u32, u32, i64, i64)| if track_clock { p.4 } else { us_of_frame(p.2, fps) };
474 let chosen = placements
475 .iter()
476 .copied()
477 .filter(|p| clock(p) <= at_raw)
478 .max_by_key(|p| clock(p))
479 .or(placements.first().copied());
480 // That placement's map between the clocks: timeline = start + (track - in) * rate, the rate
481 // being its proportion (1.0 at unity), as the engine lays cues out. A track no placement shows
482 // has no map: its clock is the timeline's.
483 let (lane, idx, p0, p_in, rate) = match chosen {
484 Some((lane, idx, p_start, p_frames, p_in, p_out)) => {
485 let window = (p_out - p_in).max(1);
486 (Some(lane), idx, us_of_frame(p_start, fps), p_in, f64::from(p_frames) / fps * 1e6 / window as f64)
487 }
488 None => (None, 0, 0, 0, 1.0),
489 };
490 let to_timeline = |t: i64| p0 + ((t - p_in) as f64 * rate).round() as i64;
491 let to_track = |tl: i64| p_in + ((tl - p0) as f64 / rate).round() as i64;
492 let (at_tr, to_tr, at_tl, to_tl) = if track_clock {
493 (at_raw, to_raw, to_timeline(at_raw), to_timeline(to_raw))
494 } else {
495 (to_track(at_raw), to_track(to_raw), at_raw, to_raw)
496 };
497 if to_tr <= at_tr {
498 return Err(format!(
499 "cue_add: the cue's end {}s is not after its start {}s",
500 secs_of(to_raw),
501 secs_of(at_raw)
502 ));
503 }
504 let raw = op.get("text").and_then(Value::as_str).ok_or("missing `text`: the words for the new cue")?;
505 // A literal backslash-n (two characters) is what a model types when it means a line break:
506 // read it as one, and say so in the reply, so the cue never keeps a stray `\n`.
507 let converted = raw.contains("\\n");
508 let text_owned = raw.replace("\\n", "\n");
509 if text_owned.is_empty() {
510 return Err("cue_add needs `text`: the words for the new cue (empty adds nothing)".into());
511 }
512 let overwrite = match op.get("overwrite") {
513 None | Some(Value::Null) => false,
514 Some(v) => v.as_bool().ok_or("cue_add: `overwrite` must be true or false")?,
515 };
516 let before = s.subtitles()[track].cues.len();
517 let prior: Vec<(i64, i64, String)> = s.subtitles()[track].cues.iter().map(|c| (c.start_us, c.end_us, c.text.clone())).collect();
518 let index = s
519 .add_cue(track, at_tr, to_tr, &text_owned, overwrite)
520 .map_err(|e| format!("cue_add: {e}"))?;
521 let replaced = (before + 1).saturating_sub(s.subtitles()[track].cues.len());
522 let note = if converted { "; literal \\n read as a line break" } else { "" };
523 // Name the cues an overwrite removed: those of the prior list no longer present.
524 let now: Vec<(i64, i64, String)> = s.subtitles()[track].cues.iter().map(|c| (c.start_us, c.end_us, c.text.clone())).collect();
525 let gone: Vec<String> = prior
526 .iter()
527 .filter(|p| !now.contains(p))
528 .map(|(a, b, t)| format!("\"{}\" ({:.3}s–{:.3}s)", echo_words(t), secs_of(*a), secs_of(*b)))
529 .collect();
530 let cue_word = cues_word(replaced);
531 let swap = if replaced > 0 {
532 if gone.is_empty() {
533 format!("; replaced {replaced} overlapping {cue_word}")
534 } else {
535 format!("; replaced {replaced} overlapping {cue_word}: {}", gone.join(", "))
536 }
537 } else {
538 String::new()
539 };
540 // Shown by some placement of the track when it overlaps that placement's window.
541 let mut shown = placements.iter().any(|&(_, _, _, _, i, o)| at_tr < o && i < to_tr);
542 let lane_end = placements.iter().map(|&(_, _, st, fr, _, _)| us_of_frame(st + fr, fps)).max().unwrap_or(0);
543 let lane_start = placements.iter().map(|&(_, _, st, _, _, _)| us_of_frame(st, fps)).min().unwrap_or(0);
544 let mut ext = String::new();
545 let mut extend_failed = None;
546 // Lengthening the caption's end cannot bring in a cue that starts before the caption.
547 if let (false, true, Some(lane), true) = (shown, extend, lane, at_tl >= lane_start) {
548 // The caption that carries the cue is the one this clock reads: its out edge moves to the
549 // cue's end (the engine refuses one that would overlap the next caption of its lane).
550 let to_frame = (to_tl as f64 * fps / 1e6).ceil().max(0.0) as u32;
551 match s.trim_sub(lane, idx, Edge::End, to_frame) {
552 Ok(()) => {
553 let c = &s.sub_lane(lane)[idx];
554 shown = at_tr < c.out_us && c.in_us < to_tr;
555 ext = format!("; extended {}'s caption to {:.3}s", parse::lane_name(lane), secs_of(to_tl));
556 }
557 Err(e) => extend_failed = Some(e.to_string()),
558 }
559 }
560 let warn = if shown {
561 String::new()
562 } else if placements.is_empty() {
563 format!("; cue {index} is on track {track}, which no caption lane shows yet, so nothing shows until captions_place {{track:{track}}} puts it on a caption lane")
564 } else {
565 let lane_name = lane.map(parse::lane_name).unwrap_or_default();
566 if at_tl >= lane_end {
567 let fix = match extend_failed {
568 Some(e) => format!("extend refused: {e}"),
569 None => "extend:true lengthens the caption to cover it, or sub_trim/place".to_string(),
570 };
571 format!("; cue {index} is past {lane_name}'s end {:.1}s, so it won't show — {fix}", secs_of(lane_end))
572 } else {
573 format!(
574 "; cue {index} lies before {lane_name}'s start {:.1}s, so it won't show — move the cue to a time the caption covers, or sub_move the caption earlier",
575 secs_of(lane_start)
576 )
577 }
578 };
579 // The two clocks name the same span when they agree, so the second form is left out then.
580 let tl_text = span_text(at_tl, to_tl);
581 let tr_text = span_text(at_tr, to_tr);
582 let clocks = if tl_text == tr_text {
583 tl_text
584 } else if track_clock {
585 format!("{tr_text} track = {tl_text} timeline")
586 } else {
587 format!("{tl_text} timeline = {tr_text} track")
588 };
589 Ok(Applied {
590 text: format!(
591 "cue_add track {track} cue {index}: {clocks} → \"{}\"{swap}{note}{ext}{warn}",
592 echo_words(&text_owned)
593 ),
594 touched: Vec::new(),
595 })
596}
597
598/// Microseconds as seconds, for the replies.
599fn secs_of(us: i64) -> f64 {
600 us as f64 / 1e6
601}
602
603/// A span in seconds for the replies, `1.000s–2.000s`. A span that runs before zero (a track
604/// clock earlier than its start) is joined with "to", so no dash runs into a minus sign.
605fn span_text(from: i64, to: i64) -> String {
606 if from < 0 || to < 0 {
607 format!("{:.3}s to {:.3}s", secs_of(from), secs_of(to))
608 } else {
609 format!("{:.3}s–{:.3}s", secs_of(from), secs_of(to))
610 }
611}
612
613/// `cue_delete {track, index}` or `cue_delete {at, lane?}`: removes one caption cue from its
614/// subtitle track, as captions lists it. The track is what every placement of it shows, so
615/// the cue leaves all of them and nothing moves. `at` names the cue by the time it is shown
616/// at, on `lane` or on the first caption lane that shows one there.
617fn op_cue_delete(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Applied, String> {
618 if op.get("at").is_some_and(|v| !v.is_null()) {
619 let at = opt_frame(op, "at", fps, end)?.unwrap_or(0);
620 let lanes = match op.get("lane") {
621 None | Some(Value::Null) => s.subtitle_lanes(),
622 Some(Value::String(t)) => {
623 let lane = parse::lane(t)?;
624 if lane.kind != LaneKind::Subtitle || !s.subtitle_lanes().contains(&lane) {
625 return Err(format!(
626 "cue_delete: {t} is not a caption lane here; the caption lanes are {}",
627 lane_names(s)
628 ));
629 }
630 vec![lane]
631 }
632 Some(_) => return Err("`lane` must be a caption lane name such as S1".into()),
633 };
634 let Some((track, index, _, _)) = cue_shown_at(s, &lanes, us_of_frame(at, fps)) else {
635 return Err(format!("cue_delete: no caption cue is shown at {at}f; captions lists the cues and their times"));
636 };
637 refuse_if_tracks_locked(s, "cue_delete", &[track])?;
638 return remove_cue(s, track, index);
639 }
640 let track = track_arg(s, op)?;
641 let index = op
642 .get("index")
643 .and_then(Value::as_u64)
644 .ok_or("missing `index`: the cue number as captions lists it (or `at`, the time the cue is shown at)")?
645 as usize;
646 let cues = s.subtitles()[track].cues.len();
647 if index >= cues {
648 return Err(format!("cue_delete: track {track} has {}; index {index} is not one of them", cue_count(cues)));
649 }
650 refuse_if_tracks_locked(s, "cue_delete", &[track])?;
651 remove_cue(s, track, index)
652}
653
654/// Removes cue `index` of subtitle track `track` (both checked by the caller), and says what went.
655fn remove_cue(s: &mut PlaybackSession, track: usize, index: usize) -> Result<Applied, String> {
656 let cue = &s.subtitles()[track].cues[index];
657 let (start, stop, words) = (cue.start_us, cue.end_us, echo_words(&cue.text));
658 // The times are the timeline's, as captions lists them; the track's own clock follows in
659 // parentheses only when it reads differently.
660 let track_text = format!("{}–{}", clock_us(start), clock_us(stop));
661 let when = match cue_timeline_span(s, track, index) {
662 Some((a, b)) if format!("{}–{}", clock_us(a), clock_us(b)) != track_text => {
663 format!("{}–{} (track {track_text})", clock_us(a), clock_us(b))
664 }
665 Some(_) | None => track_text,
666 };
667 let placed: usize = s
668 .subtitle_lanes()
669 .into_iter()
670 .map(|l| s.sub_lane(l).iter().filter(|c| c.track == track).count())
671 .sum();
672 if !s.delete_cue(track, index) {
673 return Err(format!("cue_delete: track {track} cue {index} could not be removed"));
674 }
675 let gone = match placed {
676 0 => String::new(),
677 n => format!("; the track's {n} placement(s) no longer show it"),
678 };
679 Ok(Applied {
680 text: format!("cue_delete track {track} cue {index} {when} \"{words}\"{gone}"),
681 touched: Vec::new(),
682 })
683}
684
685/// The timeline span of cue `cue` of `track`, from first to last microsecond any placement of the
686/// track shows it at (as `sub_lane_cue_refs` clips it). `None` when no placement shows it.
687fn cue_timeline_span(s: &PlaybackSession, track: usize, cue: usize) -> Option<(i64, i64)> {
688 s.subtitle_lanes()
689 .into_iter()
690 .flat_map(|l| s.sub_lane_cue_refs(l))
691 .filter(|&(_, _, t, c)| t == track && c == cue)
692 .map(|(a, b, _, _)| (a, b))
693 .reduce(|(a0, b0), (a1, b1)| (a0.min(a1), b0.max(b1)))
694}
695
696/// The caption cue shown at `us` on the first of `lanes` that shows one there, as
697/// `(track, cue, start_us, end_us)`.
698fn cue_shown_at(s: &PlaybackSession, lanes: &[Lane], us: i64) -> Option<(usize, usize, i64, i64)> {
699 lanes
700 .iter()
701 .flat_map(|&lane| s.sub_lane_cue_refs(lane))
702 .filter(|&(a, b, _, _)| a <= us && us < b)
703 .min_by_key(|r| r.0)
704 .map(|(a, b, track, cue)| (track, cue, a, b))
705}
706
707/// What a `sub_delete` that names no placed caption adds to its error: the cue shown at
708/// the address's frame when there is one, with the op that removes just that cue.
709fn single_cue_hint(s: &PlaybackSession, op: &Value, fps: f64) -> String {
710 let generic = "; to remove a single caption cue use cue_delete {track, index} (captions lists each cue's track and index)";
711 let frame = op
712 .get("clip")
713 .and_then(Value::as_str)
714 .and_then(|a| a.split_once('@'))
715 .and_then(|(_, f)| f.trim().parse::<u32>().ok());
716 let Some(frame) = frame else {
717 return generic.to_string();
718 };
719 match cue_shown_at(s, &s.subtitle_lanes(), us_of_frame(frame, fps)) {
720 Some((track, cue, _, _)) => format!(
721 "; a caption cue is shown at {frame}f: cue_delete {{\"track\": {track}, \"index\": {cue}}} removes just that cue"
722 ),
723 None => generic.to_string(),
724 }
725}
726
727/// `cue_replace {track?, find, replace, case_sensitive?}`: replaces every occurrence of `find`
728/// in the cues of `track`, or of every subtitle track when `track` is omitted. Matching ignores
729/// case unless `case_sensitive` is true. The edit batch is one undo step.
730fn op_cue_replace(s: &mut PlaybackSession, op: &Value) -> Result<Applied, String> {
731 let find = op
732 .get("find")
733 .and_then(Value::as_str)
734 .filter(|f| !f.is_empty())
735 .ok_or("missing `find`: the text to look for in the cues")?;
736 let replace = op
737 .get("replace")
738 .and_then(Value::as_str)
739 .ok_or("missing `replace`: the text to put in its place (an empty string deletes it)")?;
740 let case_sensitive = op.get("case_sensitive").and_then(Value::as_bool).unwrap_or(false);
741 let tracks: Vec<usize> = match op.get("track") {
742 None | Some(Value::Null) => (0..s.subtitles().len()).collect(),
743 Some(_) => vec![track_arg(s, op)?],
744 };
745 // The new texts are worked out first, while the cues are only read.
746 let mut edits: Vec<(usize, usize, String)> = Vec::new();
747 let mut occurrences = 0usize;
748 for &t in &tracks {
749 for (i, cue) in s.subtitles()[t].cues.iter().enumerate() {
750 if let Some((new, n)) = replace_in(&cue.text, find, replace, case_sensitive) {
751 occurrences += n;
752 edits.push((t, i, new));
753 }
754 }
755 }
756 if edits.is_empty() {
757 return Err(format!("cue_replace: no cue reads \"{find}\"{}", if case_sensitive { " (case-sensitive)" } else { "" }));
758 }
759 let edited: Vec<usize> = edits.iter().map(|(t, _, _)| *t).collect();
760 refuse_if_tracks_locked(s, "cue_replace", &edited)?;
761 let changed = edits.iter().filter(|(t, i, new)| s.set_cue_text(*t, *i, new)).count();
762 if changed == 0 {
763 return Err(format!("cue_replace: none of the {} matching {} accepted the new text", edits.len(), cues_word(edits.len())));
764 }
765 Ok(Applied {
766 text: format!("cue_replace \"{find}\" → \"{replace}\": {occurrences} occurrence(s) in {changed} {}", cues_word(changed)),
767 touched: Vec::new(),
768 })
769}
770
771/// `text` with every match of `find` replaced, and how many there were; None when there is no match.
772fn replace_in(text: &str, find: &str, with: &str, case_sensitive: bool) -> Option<(String, usize)> {
773 let hay: Vec<char> = text.chars().collect();
774 let needle: Vec<char> = find.chars().collect();
775 let same = |a: char, b: char| {
776 a == b || (!case_sensitive && a.to_lowercase().eq(b.to_lowercase()))
777 };
778 let mut out = String::with_capacity(text.len());
779 let mut n = 0usize;
780 let mut i = 0usize;
781 while i < hay.len() {
782 if i + needle.len() <= hay.len() && needle.iter().enumerate().all(|(k, &c)| same(hay[i + k], c)) {
783 out.push_str(with);
784 i += needle.len();
785 n += 1;
786 } else {
787 out.push(hay[i]);
788 i += 1;
789 }
790 }
791 (n > 0).then_some((out, n))
792}
793
794// ---- captions (read) ------------------------------------------------------
795
796/// Cues per `captions` page: a page is what one reply lists, and `page` takes the next.
797const CAPTIONS_PAGE: usize = 40;
798
799/// One cue a `captions` listing can show: its lane, its track and cue, the stretch it covers
800/// (microseconds), the placement that shows it, and which part of a cut cue it is.
801struct Listed {
802 lane: Lane,
803 track: usize,
804 cue: usize,
805 a: i64,
806 b: i64,
807 at: String,
808 part: Option<(usize, usize)>,
809}
810
811fn run_captions(srv: &mut Server, args: &Value) -> Reply {
812 let Some(s) = srv.session.as_ref() else {
813 return Reply::err(NO_PROJECT);
814 };
815 let fps = parse::session_fps(s);
816 let end = parse::session_end(s);
817 let lanes = match captions_lanes(s, args) {
818 Ok(l) => l,
819 Err(e) => return Reply::err(e),
820 };
821 let range = match range_us(args, fps, end) {
822 Ok(r) => r,
823 Err(e) => return Reply::err(e),
824 };
825
826 if s.subtitle_lanes().is_empty() {
827 return Reply::ok(format!(
828 "no caption lanes on this timeline. subtitles_import {{path}} loads a track; captions_place {{track}} puts it on S1.{}",
829 track_footer(s)
830 ));
831 }
832
833 // Every listed cue in lane order, before paging, so the page count and part numbers are the
834 // same whichever page is asked for.
835 // Headline counts are distinct cues, not pieces: a cue a cut split across placements is one cue.
836 // The cues outside every placement are counted over every track, as the footer counts them.
837 let unplaced = unplaced_cue_count(s);
838 let range_label = range.map(|(from, to)| {
839 let open_end = match args.get("range").and_then(|r| r.get("to")) {
840 None | Some(Value::Null) => true,
841 Some(Value::String(t)) => t.trim() == "end",
842 Some(_) => false,
843 };
844 format!("{}–{}", clock_us(from), if open_end { "end".to_string() } else { clock_us(to) })
845 });
846 let mut heads: Vec<String> = Vec::new();
847 let mut all: Vec<Listed> = Vec::new();
848 for lane in lanes {
849 let refs = s.sub_lane_cue_refs(lane);
850 let total = distinct_cues(refs.iter().map(|&(_, _, t, c)| (t, c)));
851 let inside: Vec<_> = refs
852 .into_iter()
853 .filter(|&(a, b, _, _)| range.is_none_or(|(from, to)| a < to && b > from))
854 .collect();
855 heads.push(match &range_label {
856 Some(label) => {
857 let in_range = distinct_cues(inside.iter().map(|&(_, _, t, c)| (t, c)));
858 let more = if unplaced > 0 { format!(", {unplaced} more outside every placement") } else { String::new() };
859 format!(
860 "{}: {in_range} {} in {label} ({total} cues placed{more})",
861 parse::lane_name(lane),
862 cues_word(in_range)
863 )
864 }
865 None => format!("{} {}", parse::lane_name(lane), cue_count(total)),
866 });
867 for &(a, b, track, cue) in &inside {
868 // The placement that shows this piece of the cue: the address sub_move and friends take.
869 let mid = (a + b) / 2;
870 let at = s
871 .sub_lane(lane)
872 .iter()
873 .find(|c| c.track == track && us_of_frame(c.start, fps) <= mid && mid < us_of_frame(c.end(), fps))
874 .map(|c| parse::addr(lane, c.start))
875 .unwrap_or_default();
876 all.push(Listed { lane, track, cue, a, b, at, part: None });
877 }
878 }
879 // A cue a cut split across placements is listed once per piece: each row says which part
880 // it is, so no two rows read as the same cue.
881 let mut counts: Vec<((usize, usize), usize)> = Vec::new();
882 for l in &all {
883 match counts.iter_mut().find(|(k, _)| *k == (l.track, l.cue)) {
884 Some(c) => c.1 += 1,
885 None => counts.push(((l.track, l.cue), 1)),
886 }
887 }
888 let mut seen: Vec<((usize, usize), usize)> = Vec::new();
889 for l in all.iter_mut() {
890 let of = counts.iter().find(|(k, _)| *k == (l.track, l.cue)).map_or(1, |c| c.1);
891 if of > 1 {
892 let k = match seen.iter_mut().find(|(key, _)| *key == (l.track, l.cue)) {
893 Some(c) => {
894 c.1 += 1;
895 c.1
896 }
897 None => {
898 seen.push(((l.track, l.cue), 1));
899 1
900 }
901 };
902 l.part = Some((k, of));
903 }
904 }
905 let total = all.len();
906 let pages = total.div_ceil(CAPTIONS_PAGE).max(1);
907 let page = match opt_u64(args, "page") {
908 None => 1,
909 Some(p) if p >= 1 && (p as usize) <= pages => p as usize,
910 Some(p) => return Reply::err(format!("captions: page {p} is past the last page ({pages}); pages run 1 to {pages}")),
911 };
912 let first = (page - 1) * CAPTIONS_PAGE;
913 let last = (first + CAPTIONS_PAGE).min(total);
914
915 let mut text = format!("{}\n", heads.join(", "));
916 if pages > 1 {
917 let next = if page < pages { format!("; next: captions {{page:{}}}", page + 1) } else { String::new() };
918 text.push_str(&format!(
919 "page {page} of {pages} (cues {}–{last} of {total}){next}\n",
920 first + 1
921 ));
922 }
923 let mut rows = Vec::new();
924 let mut cut = 0usize;
925 for (n, l) in all[first..last].iter().enumerate() {
926 let body = s
927 .subtitles()
928 .get(l.track)
929 .and_then(|t| t.cues.get(l.cue))
930 .map(|c| c.text.replace('\n', " / "))
931 .unwrap_or_default();
932 let part = l.part.map_or_else(String::new, |(k, of)| format!(" (part {k}/{of})"));
933 let line = format!(
934 " {}. track {} cue {}{part} [{}] {}–{} {body}\n",
935 first + n + 1,
936 l.track,
937 l.cue,
938 l.at,
939 clock_us(l.a),
940 clock_us(l.b)
941 );
942 if text.len() + line.len() > CAPTIONS_CAP {
943 cut = last - first - n;
944 break;
945 }
946 text.push_str(&line);
947 rows.push(json!({
948 "lane": parse::lane_name(l.lane),
949 "track": l.track,
950 "cue": l.cue,
951 "address": l.at,
952 "start_us": l.a,
953 "end_us": l.b,
954 "text": body,
955 }));
956 }
957 if cut > 0 {
958 text.push_str(&format!(
959 "… {cut} more {} on this page cut at 4 KB; narrow with lane or range\n",
960 cues_word(cut)
961 ));
962 }
963 text.push_str(&track_footer(s));
964 let next = (page < pages).then_some(page + 1);
965 Reply::ok(text.trim_end().to_string()).with(json!({ "cues": rows, "page": page, "pages": pages, "next": next }))
966}
967
968fn captions_lanes(s: &PlaybackSession, args: &Value) -> Result<Vec<Lane>, String> {
969 match opt_str(args, "lane") {
970 None => Ok(s.subtitle_lanes()),
971 Some(t) => {
972 let lane = parse::lane(t)?;
973 if lane.kind != LaneKind::Subtitle || !s.subtitle_lanes().contains(&lane) {
974 return Err(format!(
975 "{t} is not a caption lane here; the caption lanes are {}",
976 lane_names(s)
977 ));
978 }
979 Ok(vec![lane])
980 }
981 }
982}
983
984/// The `range` argument as microseconds `[from, to)` of timeline time, or `None`.
985fn range_us(args: &Value, fps: f64, end: u32) -> Result<Option<(i64, i64)>, String> {
986 let r = match args.get("range") {
987 None | Some(Value::Null) => return Ok(None),
988 Some(r) => r,
989 };
990 if !r.is_object() {
991 return Err("argument `range` must be an object such as {\"from\": \"0\", \"to\": \"end\"}".into());
992 }
993 let from = range_end_us(r, "from", fps, end)?.unwrap_or(0);
994 let to = range_end_us(r, "to", fps, end)?.unwrap_or_else(|| us_of_frame(end, fps));
995 if to < from {
996 return Err(format!(
997 "argument `range`: it ends at {}, before it starts at {}",
998 clock_us(to),
999 clock_us(from)
1000 ));
1001 }
1002 Ok(Some((from, to)))
1003}
1004
1005/// One end of a `range` as microseconds. Seconds (`"1s"`, `1.0`) are taken exactly, so
1006/// a cue at 1.000 s is not moved by a frame rounding; other forms go through a frame.
1007fn range_end_us(r: &Value, key: &str, fps: f64, end: u32) -> Result<Option<i64>, String> {
1008 let secs = match r.get(key) {
1009 Some(Value::Number(n)) => n.as_f64(),
1010 Some(Value::String(s)) if s.trim().ends_with('s') && !s.contains(':') => {
1011 s.trim().trim_end_matches('s').trim().parse::<f64>().ok()
1012 }
1013 _ => None,
1014 };
1015 if let Some(secs) = secs.filter(|v| v.is_finite()) {
1016 return Ok(Some((secs * 1e6).round() as i64));
1017 }
1018 Ok(opt_frame(r, key, fps, end)?.map(|f| us_of_frame(f, fps)))
1019}
1020
1021/// One line per subtitle track, so a cue not yet on a lane can still be targeted.
1022/// The cues some placement shows, per track: a cue a ripple or a trim pushed out of every
1023/// placement is still in the track, and the footer says so rather than counting it as placed.
1024fn shown_cues(s: &PlaybackSession) -> Vec<std::collections::BTreeSet<usize>> {
1025 let mut shown: Vec<std::collections::BTreeSet<usize>> = vec![Default::default(); s.subtitles().len()];
1026 for l in s.subtitle_lanes() {
1027 for (_, _, track, cue) in s.sub_lane_cue_refs(l) {
1028 if let Some(set) = shown.get_mut(track) {
1029 set.insert(cue);
1030 }
1031 }
1032 }
1033 shown
1034}
1035
1036/// Cues in the tracks that no placement shows, over every track.
1037fn unplaced_cue_count(s: &PlaybackSession) -> usize {
1038 let shown = shown_cues(s);
1039 s.subtitles()
1040 .iter()
1041 .enumerate()
1042 .map(|(i, t)| (0..t.cues.len()).filter(|c| !shown[i].contains(c)).count())
1043 .sum()
1044}
1045
1046/// How many different cues the `(track, cue)` pairs name.
1047fn distinct_cues(cues: impl Iterator<Item = (usize, usize)>) -> usize {
1048 cues.collect::<std::collections::BTreeSet<_>>().len()
1049}
1050
1051fn track_footer(s: &PlaybackSession) -> String {
1052 let tracks = s.subtitles();
1053 if tracks.is_empty() {
1054 return String::new();
1055 }
1056 let shown = shown_cues(s);
1057 let mut out = String::from("\ntracks:");
1058 for (i, t) in tracks.iter().enumerate() {
1059 let placed = shown[i].len();
1060 let unplaced: Vec<usize> = (0..t.cues.len()).filter(|c| !shown[i].contains(c)).collect();
1061 let state = match &t.refused {
1062 Some(why) => format!("refused: {why}"),
1063 None if t.cues.is_empty() => "0 cues".to_string(),
1064 None if unplaced.is_empty() => format!("{}, all placed", cue_count(t.cues.len())),
1065 None => format!("{}, {placed} placed ({})", cue_count(t.cues.len()), unplaced_why(&unplaced)),
1066 };
1067 let label = if t.label.is_empty() { String::new() } else { format!(" {}", t.label) };
1068 out.push_str(&format!("\n track {i}{label} · {state}"));
1069 }
1070 out
1071}
1072
1073// ---- helpers --------------------------------------------------------------
1074
1075/// `cue` or `cues`, by the count.
1076fn cues_word(n: usize) -> &'static str {
1077 if n == 1 { "cue" } else { "cues" }
1078}
1079
1080/// A count of cues, `1 cue` or `9 cues`.
1081fn cue_count(n: usize) -> String {
1082 format!("{n} {}", cues_word(n))
1083}
1084
1085/// Why some cues are not placed, named by their index as captions lists them: three at most.
1086fn unplaced_why(cues: &[usize]) -> String {
1087 let named: Vec<String> = cues.iter().take(3).map(usize::to_string).collect();
1088 let more = if cues.len() > 3 { ", …" } else { "" };
1089 let verb = if cues.len() == 1 { "is" } else { "are" };
1090 format!("{} {}{more} {verb} outside every placement", cues_word(cues.len()), named.join(", "))
1091}
1092
1093/// Cue words as a reply echoes them: line breaks shown as " / ", cut to 60 characters.
1094fn echo_words(text: &str) -> String {
1095 const MAX: usize = 60;
1096 let flat = text.replace('\n', " / ");
1097 match flat.char_indices().nth(MAX) {
1098 Some((cut, _)) => format!("{}…", &flat[..cut]),
1099 None => flat,
1100 }
1101}
1102
1103/// The subtitle track named by `track`, checked to exist.
1104fn track_arg(s: &PlaybackSession, op: &Value) -> Result<usize, String> {
1105 let track = op
1106 .get("track")
1107 .and_then(Value::as_u64)
1108 .ok_or("missing `track`: the subtitle track number, as captions and subtitles_import list it")?
1109 as usize;
1110 let count = s.subtitles().len();
1111 if track >= count {
1112 return Err(if count == 0 {
1113 "there is no subtitle track on this timeline; subtitles_import {path} adds one".to_string()
1114 } else {
1115 format!("subtitle track {track} is not on this timeline: the tracks are 0 to {}", count - 1)
1116 });
1117 }
1118 Ok(track)
1119}
1120
1121/// A caption address (`S1@0` or `S1#0`) resolved to its lane and index. Refuses media clips.
1122fn sub_arg(s: &PlaybackSession, op: &Value) -> Result<(Lane, usize), String> {
1123 let addr = op
1124 .get("clip")
1125 .and_then(Value::as_str)
1126 .ok_or("missing `clip`: give a caption address such as S1@0")?;
1127 let (lane, idx) = match super::edit::clip_addr(s, addr) {
1128 Ok(found) => found,
1129 Err(e) => return Err(caption_addr_hint(s, addr, e)),
1130 };
1131 if lane.kind != LaneKind::Subtitle {
1132 return Err(format!("{addr} is not a caption: caption ops take S-lane addresses such as S1@0"));
1133 }
1134 Ok((lane, idx))
1135}
1136
1137/// What a caption address that starts no placement adds to its error. A cue's own start frame is
1138/// the usual wrong guess (captions lists cues, not placements): when a placement covers that frame,
1139/// the error names it, so the next call can use it. Other addresses keep the generic error.
1140fn caption_addr_hint(s: &PlaybackSession, addr: &str, generic: String) -> String {
1141 let Some((lane_name, frame)) = addr.split_once('@') else {
1142 return generic;
1143 };
1144 let (Ok(lane), Ok(frame)) = (parse::lane(lane_name.trim()), frame.trim().parse::<u32>()) else {
1145 return generic;
1146 };
1147 if lane.kind != LaneKind::Subtitle {
1148 return generic;
1149 }
1150 let covering = s.sub_lane(lane).iter().find(|c| c.start <= frame && frame < c.end());
1151 match covering {
1152 Some(c) => format!(
1153 "no caption starts at {addr}; the caption placed at {frame}f is {} (spans {}–{}). Address it by that: sub_move {{\"clip\": \"{}\", ...}}. captions lists each cue with its address in [brackets]",
1154 parse::addr(lane, c.start),
1155 c.start,
1156 c.end(),
1157 parse::addr(lane, c.start)
1158 ),
1159 None => format!("{generic}; captions lists each cue with its address in [brackets], which is the address sub_move takes"),
1160 }
1161}
1162
1163fn sub_addr(s: &PlaybackSession, lane: Lane, idx: usize) -> String {
1164 match s.sub_lane(lane).get(idx) {
1165 Some(c) => parse::addr(lane, c.start),
1166 None => format!("{}#{idx}", parse::lane_name(lane)),
1167 }
1168}
1169
1170/// Makes caption lane `lane` exist, adding caption lanes up to it. Each add is one undo step.
1171/// Returns the names of the lanes it added, `lane` last. The engine adds lanes in order, so
1172/// S2 cannot be made without S1 under it: those lanes come back here for the reply to name.
1173fn ensure_lane(s: &mut PlaybackSession, lane: Lane) -> Result<Vec<String>, String> {
1174 let mut added: Vec<String> = Vec::new();
1175 while !s.subtitle_lanes().contains(&lane) {
1176 if added.len() > lane.ord {
1177 return Err(format!(
1178 "{} could not be made; the caption lanes are {}",
1179 parse::lane_name(lane),
1180 lane_names(s)
1181 ));
1182 }
1183 let made = s.add_lane(LaneKind::Subtitle);
1184 added.push(parse::lane_name(made));
1185 }
1186 Ok(added)
1187}
1188
1189/// Refuses a caption op that would change any of `lanes` while one is locked, naming the lock:
1190/// `<op> refused: lane S1 is locked: ...`. Nothing is changed when it refuses.
1191fn refuse_if_locked(s: &PlaybackSession, op: &str, lanes: &[Lane]) -> Result<(), String> {
1192 super::edit::check_unlocked(s, lanes).map_err(|e| format!("{op} refused: {e}"))
1193}
1194
1195/// Refuses a cue op on any of `tracks` while a locked caption lane shows one of them: a cue
1196/// change reaches every placement of its track, so each such lane counts.
1197fn refuse_if_tracks_locked(s: &PlaybackSession, op: &str, tracks: &[usize]) -> Result<(), String> {
1198 let showing: Vec<Lane> = s
1199 .subtitle_lanes()
1200 .into_iter()
1201 .filter(|&l| s.sub_lane(l).iter().any(|c| tracks.contains(&c.track)))
1202 .collect();
1203 refuse_if_locked(s, op, &showing)
1204}
1205
1206/// The lanes a caption op reaches besides its own: the lanes of its group, which move, trim or
1207/// go with it. `[lane]` alone when the caption is not grouped.
1208fn sub_group_lanes(s: &PlaybackSession, lane: Lane, idx: usize) -> Vec<Lane> {
1209 let mut out = vec![lane];
1210 let Some(link) = s.sub_lane(lane).get(idx).and_then(|c| c.link) else {
1211 return out;
1212 };
1213 for l in s.lanes().into_iter().chain(s.subtitle_lanes()) {
1214 let linked = if l.kind == LaneKind::Subtitle {
1215 s.sub_lane(l).iter().any(|c| c.link == Some(link))
1216 } else {
1217 s.lane_clips(l).iter().any(|c| c.link == Some(link))
1218 };
1219 if linked && !out.contains(&l) {
1220 out.push(l);
1221 }
1222 }
1223 out
1224}
1225
1226fn lane_names(s: &PlaybackSession) -> String {
1227 let names: Vec<String> = s.subtitle_lanes().into_iter().map(parse::lane_name).collect();
1228 if names.is_empty() {
1229 "none".to_string()
1230 } else {
1231 names.join(", ")
1232 }
1233}
1234
1235/// A frame argument: a time in any form the edit tool takes, or absent.
1236fn opt_frame(op: &Value, key: &str, fps: f64, end: u32) -> Result<Option<u32>, String> {
1237 match op.get(key) {
1238 None | Some(Value::Null) => Ok(None),
1239 Some(v) => parse::frame(v, fps, end).map(Some).map_err(|e| format!("`{key}`: {e}")),
1240 }
1241}
1242
1243fn us_of_frame(frame: u32, fps: f64) -> i64 {
1244 (f64::from(frame) / fps * 1e6).round() as i64
1245}
1246
1247/// `MM:SS.mmm`, or `H:MM:SS.mmm` from an hour on.
1248fn clock_us(us: i64) -> String {
1249 let ms = (us.max(0) as f64 / 1000.0).round() as u64;
1250 let h = ms / 3_600_000;
1251 let m = (ms / 60_000) % 60;
1252 let s = (ms / 1000) % 60;
1253 let milli = ms % 1000;
1254 if h > 0 {
1255 format!("{h}:{m:02}:{s:02}.{milli:03}")
1256 } else {
1257 format!("{m:02}:{s:02}.{milli:03}")
1258 }
1259}
1260
1261#[cfg(test)]
1262mod tests {
1263 use super::*;
1264 use std::path::Path;
1265
1266 fn open() -> Server {
1267 engine::ao::set_silent_output();
1268 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
1269 Server { session: Some(PlaybackSession::open(p).expect("open test asset")), ..Server::default() }
1270 }
1271
1272 fn srt() -> String {
1273 Path::new(env!("CARGO_MANIFEST_DIR"))
1274 .join("../engine/tests/data/test_subs.srt")
1275 .to_string_lossy()
1276 .into_owned()
1277 }
1278
1279 fn ed(srv: &mut Server, ops: Value) -> Reply {
1280 crate::tools::edit::run_edit(srv, &json!({ "ops": ops }))
1281 }
1282
1283 fn list(srv: &mut Server, args: Value) -> Reply {
1284 run_captions(srv, &args)
1285 }
1286
1287 /// Imports the test track and places it on S1 at 0; returns the placement's frames.
1288 fn placed(srv: &mut Server) -> u32 {
1289 let r = ed(srv, json!([{ "op": "subtitles_import", "path": srt() }]));
1290 assert!(!r.is_error, "{}", r.text);
1291 let r = ed(srv, json!([{ "op": "captions_place", "track": 0 }]));
1292 assert!(!r.is_error, "{}", r.text);
1293 srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].frames
1294 }
1295
1296 /// `subtitles_lang` names a track's language as a code or a name, refuses a
1297 /// language it cannot read and the one a track already has, and is one undo step.
1298 #[test]
1299 fn subtitles_lang_names_a_track_and_one_undo_takes_it_back() {
1300 let mut srv = open();
1301 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": srt() }]));
1302 assert!(!r.is_error, "{}", r.text);
1303 let r = ed(&mut srv, json!([{ "op": "subtitles_lang", "track": 0, "lang": "fr" }]));
1304 assert!(!r.is_error && r.text.contains("subtitles_lang track 0 → fra (French)"), "{}", r.text);
1305 assert_eq!(srv.session.as_ref().unwrap().subtitles()[0].language, "fra");
1306 let r = ed(&mut srv, json!([{ "op": "subtitles_lang", "track": 0, "lang": "French" }]));
1307 assert!(r.is_error && r.text.contains("already fra"), "{}", r.text);
1308 let r = ed(&mut srv, json!([{ "op": "subtitles_lang", "track": 0, "lang": "klingon" }]));
1309 assert!(r.is_error && r.text.contains("not a language"), "{}", r.text);
1310 let r = ed(&mut srv, json!([{ "op": "subtitles_lang", "track": 4, "lang": "deu" }]));
1311 assert!(r.is_error, "{}", r.text);
1312 let r = run_tool(&mut srv, "undo", json!({}));
1313 assert!(!r.is_error, "{}", r.text);
1314 assert_eq!(srv.session.as_ref().unwrap().subtitles()[0].language, "", "one undo takes it back");
1315 }
1316
1317 #[test]
1318 fn captions_place_lists_and_cue_text_retypes() {
1319 let mut srv = open();
1320 placed(&mut srv);
1321 let r = list(&mut srv, json!({}));
1322 assert!(!r.is_error, "{}", r.text);
1323 assert!(r.text.contains("S1 3 cues"), "{}", r.text);
1324 assert!(r.text.contains("track 0 cue 0"), "{}", r.text);
1325 assert!(r.text.contains("first line"), "{}", r.text);
1326
1327 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": "Hello there" }]));
1328 assert!(!r.is_error, "{}", r.text);
1329 let r = list(&mut srv, json!({ "lane": "S1" }));
1330 assert!(r.text.contains("Hello there"), "{}", r.text);
1331 assert!(!r.text.contains("first line"), "{}", r.text);
1332
1333 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": "Hello there" }]));
1334 assert!(r.is_error);
1335 assert!(r.text.contains("already reads that"), "{}", r.text);
1336 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 9, "text": "x" }]));
1337 assert!(r.is_error && r.text.contains("index 9 is not one of them"), "{}", r.text);
1338 }
1339
1340 /// `cue_add` puts a cue in the gap between two cues, replies with its index and times, and is
1341 /// one undo step; an overlap is refused unless `overwrite`, which replaces what it covers.
1342 #[test]
1343 fn cue_add_places_a_cue_in_a_gap_and_refuses_an_overlap() {
1344 // A track no caption lane shows takes the cue too, and the reply says nothing shows yet.
1345 let mut unplaced = open();
1346 let r = ed(&mut unplaced, json!([{ "op": "subtitles_import", "path": srt() }]));
1347 assert!(!r.is_error, "{}", r.text);
1348 let r = ed(&mut unplaced, json!([{ "op": "cue_add", "track": 0, "at": "1.6s", "to": "1.9s", "text": "x" }]));
1349 assert!(!r.is_error && r.text.contains("nothing shows until captions_place {track:0}"), "{}", r.text);
1350 assert_eq!(unplaced.session.as_ref().unwrap().subtitles()[0].cues.len(), 4, "the cue is kept on the track");
1351
1352 let mut srv = open();
1353 placed(&mut srv);
1354 let steps = srv.ledger.len();
1355 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.6s", "to": "1.9s", "track_clock": true, "text": "Added\\nline" }]));
1356 assert!(!r.is_error, "{}", r.text);
1357 // Placed at 0, the track's clock and the timeline agree: one span, no second form.
1358 assert!(r.text.contains("cue_add track 0 cue 1: 1.600s–1.900s → \"Added / line\""), "{}", r.text);
1359 assert!(!r.text.contains("track ="), "{}", r.text);
1360 assert!(r.text.contains("Added / line"), "{}", r.text);
1361 assert_eq!(srv.ledger.len(), steps + 1, "one batch is one undo step");
1362 let cues = srv.session.as_ref().unwrap().subtitles()[0].cues.clone();
1363 assert_eq!(cues.len(), 4, "three file cues and the added one");
1364 assert_eq!((cues[1].start_us, cues[1].end_us, cues[1].text.as_str()), (1_600_000, 1_900_000, "Added\nline"));
1365
1366 // Over the first cue (0.5 s to 1.5 s): refused, and nothing changes.
1367 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.0s", "to": "1.7s", "text": "Clash" }]));
1368 assert!(r.is_error && r.text.contains("overlaps"), "{}", r.text);
1369 assert_eq!(srv.session.as_ref().unwrap().subtitles()[0].cues.len(), 4, "a refusal changes nothing");
1370
1371 // With overwrite it replaces the two cues it covers, in one step.
1372 let steps = srv.ledger.len();
1373 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.0s", "to": "1.7s", "text": "Over", "overwrite": true }]));
1374 assert!(!r.is_error, "{}", r.text);
1375 assert!(r.text.contains("replaced 2 overlapping cues"), "{}", r.text);
1376 assert_eq!(srv.ledger.len(), steps + 1, "the replacing add is one undo step");
1377 let texts: Vec<String> = srv.session.as_ref().unwrap().subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
1378 assert_eq!(texts, ["Over", "second line\nwith a break", "third line"], "{texts:?}");
1379
1380 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 9, "at": "1s", "to": "2s", "text": "x" }]));
1381 assert!(r.is_error && r.text.contains("track 9"), "{}", r.text);
1382 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "2s", "to": "1s", "text": "x" }]));
1383 assert!(r.is_error && r.text.contains("not after"), "{}", r.text);
1384 }
1385
1386 /// A batch that imports a track and then fails is rolled back with the import.
1387 #[test]
1388 fn a_failed_batch_takes_its_subtitle_import_back() {
1389 let mut srv = open();
1390 let r = ed(
1391 &mut srv,
1392 json!([
1393 { "op": "subtitles_import", "path": srt() },
1394 { "op": "captions_place", "track": 5 }
1395 ]),
1396 );
1397 assert!(r.is_error, "{}", r.text);
1398 assert!(srv.session.as_ref().unwrap().subtitles().is_empty(), "the import was rolled back: {}", r.text);
1399 }
1400
1401 /// A timeline time maps onto the track's clock through the placement, the track-clock flag
1402 /// takes the track's own times, and a cue no placement shows says where it falls.
1403 #[test]
1404 fn cue_add_maps_timeline_times_and_warns_outside_the_caption() {
1405 let mut srv = open();
1406 placed(&mut srv);
1407 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "31s", "to": "32s", "text": "Late" }]));
1408 assert!(!r.is_error && r.text.contains("won't show"), "{}", r.text);
1409 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.6s", "to": "1.9s", "track_clock": true, "text": "Track" }]));
1410 assert!(!r.is_error, "{}", r.text);
1411 assert!(r.text.contains("1.600s–1.900s → \"Track\""), "{}", r.text);
1412 assert!(!r.text.contains("won't show"), "{}", r.text);
1413 }
1414
1415 /// Imports the test track and places it on S1 at `at`, as `captions_place` takes it.
1416 fn placed_at(srv: &mut Server, at: &str) {
1417 let r = ed(srv, json!([{ "op": "subtitles_import", "path": srt() }]));
1418 assert!(!r.is_error, "{}", r.text);
1419 let r = ed(srv, json!([{ "op": "captions_place", "track": 0, "at": at }]));
1420 assert!(!r.is_error, "{}", r.text);
1421 }
1422
1423 /// On a placement that starts at 4 s, a cue_delete reply names the timeline span, with the
1424 /// track's own clock in parentheses because it reads differently; placed at 0 it names one span.
1425 #[test]
1426 fn cue_delete_names_the_timeline_span_and_the_track_clock_only_when_it_differs() {
1427 let mut srv = open();
1428 placed_at(&mut srv, "4s");
1429 let r = ed(&mut srv, json!([{ "op": "cue_delete", "track": 0, "index": 0 }]));
1430 assert!(!r.is_error, "{}", r.text);
1431 assert!(r.text.contains("cue_delete track 0 cue 0 00:04.500–00:05.500 (track 00:00.500–00:01.500)"), "{}", r.text);
1432
1433 let mut srv = open();
1434 placed(&mut srv);
1435 let r = ed(&mut srv, json!([{ "op": "cue_delete", "track": 0, "index": 1 }]));
1436 assert!(!r.is_error, "{}", r.text);
1437 assert!(r.text.contains("cue_delete track 0 cue 1 00:02.000–00:03.250 \"second line"), "{}", r.text);
1438 assert!(!r.text.contains("(track"), "{}", r.text);
1439 }
1440
1441 /// A cue before an offset placement's start is accepted with a warning, its reply has no
1442 /// doubled minus, and both spans read with "to" where the track clock is below zero.
1443 #[test]
1444 fn cue_add_before_an_offset_placement_warns_and_never_prints_a_double_minus() {
1445 let mut srv = open();
1446 placed_at(&mut srv, "4s");
1447 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "0s", "to": "1s", "text": "Early" }]));
1448 assert!(!r.is_error, "{}", r.text);
1449 assert!(r.text.contains("0.000s–1.000s timeline = -4.000s to -3.000s track"), "{}", r.text);
1450 assert!(r.text.contains("lies before S1's start 4.0s, so it won't show"), "{}", r.text);
1451 assert!(!r.text.contains("--") && !r.text.contains("–-"), "{}", r.text);
1452 assert_eq!(srv.session.as_ref().unwrap().subtitles()[0].cues.len(), 4, "the cue is kept");
1453 }
1454
1455 /// A cue whose two clocks read the same span names that span once.
1456 #[test]
1457 fn cue_add_names_one_span_when_the_clocks_agree() {
1458 let mut srv = open();
1459 placed(&mut srv);
1460 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "8s", "to": "9s", "text": "Nine" }]));
1461 assert!(!r.is_error, "{}", r.text);
1462 assert!(r.text.contains("cue_add track 0 cue 3: 8.000s–9.000s → \"Nine\""), "{}", r.text);
1463 assert!(!r.text.contains("timeline ="), "{}", r.text);
1464 }
1465
1466 /// A caption whose trim left its out edge at 4 s shows the cue that crosses it as 3.000–4.000,
1467 /// the same span the export writes, and the cue after the trim is not shown.
1468 #[test]
1469 fn a_cue_crossing_a_trimmed_out_edge_is_listed_clipped() {
1470 let dir = crate::testutil::TestDir::new("sub-trim-out");
1471 let path = dir.path().join("cues.srt");
1472 std::fs::write(&path, "1\n00:00:00,500 --> 00:00:02,000\nAlpha line\n\n2\n00:00:03,000 --> 00:00:04,500\nBravo line\n\n3\n00:00:05,000 --> 00:00:07,000\nCharlie line\n").expect("write");
1473 let mut srv = open();
1474 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": path.to_string_lossy() }]));
1475 assert!(!r.is_error, "{}", r.text);
1476 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0 }]));
1477 assert!(!r.is_error, "{}", r.text);
1478 let r = ed(&mut srv, json!([{ "op": "sub_trim", "clip": "S1@0", "edge": "out", "to": "4s" }]));
1479 assert!(!r.is_error, "{}", r.text);
1480 let r = list(&mut srv, json!({}));
1481 assert!(r.text.contains("track 0 cue 1 [S1@0] 00:03.000–00:04.000 Bravo line"), "{}", r.text);
1482 assert!(!r.text.contains("00:04.500"), "{}", r.text);
1483 assert!(r.text.contains("cue 2 is outside every placement"), "{}", r.text);
1484 }
1485
1486 /// A cue past the caption's end says where the caption ends (its own lane's end, not the first
1487 /// placement's), and `extend` lengthens the caption so the cue shows.
1488 #[test]
1489 fn cue_add_past_the_end_names_the_lane_end_and_extend_shows_it() {
1490 let mut srv = open();
1491 let fps = 30.0;
1492 placed(&mut srv);
1493 let end = {
1494 let s = srv.session.as_ref().unwrap();
1495 let c = &s.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0];
1496 (c.start + c.frames) as f64 / fps
1497 };
1498 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "20s", "to": "21s", "text": "Late", "track_clock": true }]));
1499 assert!(!r.is_error, "{}", r.text);
1500 assert!(r.text.contains(&format!("past S1's end {end:.1}s, so it won't show")), "{}", r.text);
1501 assert!(r.text.contains("extend:true"), "{}", r.text);
1502 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "22s", "to": "23s", "text": "Later", "track_clock": true, "extend": true }]));
1503 assert!(!r.is_error, "{}", r.text);
1504 assert!(r.text.contains("extended S1's caption to") && !r.text.contains("won't show"), "{}", r.text);
1505 let c = &srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0))[0];
1506 assert!(c.start + c.frames > (end * fps) as u32, "the caption now runs past its old end: {}", r.text);
1507 let r = list(&mut srv, json!({}));
1508 assert!(r.text.contains("Later"), "{}", r.text);
1509 }
1510
1511 /// The captions footer counts the cues of a track and how many a placement shows: a cue no
1512 /// placement shows is not counted as placed.
1513 #[test]
1514 fn captions_footer_says_how_many_cues_are_placed() {
1515 let mut srv = open();
1516 placed(&mut srv);
1517 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "31s", "to": "32s", "text": "Late" }]));
1518 assert!(!r.is_error, "{}", r.text);
1519 let r = list(&mut srv, json!({}));
1520 assert!(r.text.contains("track 0 explainer.captions.srt") || r.text.contains("· 4 cues, 3 placed"), "{}", r.text);
1521 assert!(r.text.contains("· 4 cues, 3 placed"), "{}", r.text);
1522 // The cue no placement shows is named by its index, as captions lists it.
1523 assert!(r.text.contains("4 cues, 3 placed (cue 3 is outside every placement)"), "{}", r.text);
1524 }
1525
1526 /// A range headline names the cues in the range, then the cues placed and the cues outside every
1527 /// placement, so the counts add up: a range past the placements says 0 in range, not "0 of 17".
1528 #[test]
1529 fn captions_range_headline_says_cues_in_range_placed_and_outside() {
1530 let mut srv = open();
1531 placed(&mut srv);
1532 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "31s", "to": "32s", "text": "Late" }]));
1533 assert!(!r.is_error, "{}", r.text);
1534 let r = run_tool(&mut srv, "captions", json!({"range": {"from": "30s", "to": "40s"}}));
1535 assert!(
1536 r.text.starts_with("S1: 0 cues in 00:30.000–00:40.000 (3 cues placed, 1 more outside every placement)"),
1537 "{}",
1538 r.text
1539 );
1540 let r = run_tool(&mut srv, "captions", json!({"range": {"from": "0s", "to": "40s"}}));
1541 assert!(
1542 r.text.starts_with("S1: 3 cues in 00:00.000–00:40.000 (3 cues placed, 1 more outside every placement)"),
1543 "{}",
1544 r.text
1545 );
1546 // A range that runs to the end says so, rather than the clock time of the end.
1547 let r = run_tool(&mut srv, "captions", json!({"range": {"from": "0s", "to": "end"}}));
1548 assert!(r.text.starts_with("S1: ") && r.text.contains("–end (3 cues placed"), "{}", r.text);
1549 // Without a range the heading is the lane's placed count, as before.
1550 let r = run_tool(&mut srv, "captions", json!({}));
1551 assert!(r.text.starts_with("S1 3 cues"), "{}", r.text);
1552 }
1553
1554 /// A track that ends between two frames is placed onto whole frames, and each cue is still shown
1555 /// at its own time: a 4.750 s track on 143 frames used to show its 0.500 s cue at 0.502 s.
1556 #[test]
1557 fn cues_show_at_their_own_times_when_the_track_ends_between_frames() {
1558 let dir = std::env::temp_dir().join(format!("edith_f17_subs_{}", std::process::id()));
1559 std::fs::create_dir_all(&dir).expect("temp dir");
1560 let path = dir.join("off_frame.srt");
1561 std::fs::write(
1562 &path,
1563 "1\n00:00:00,500 --> 00:00:01,500\nfirst\n\n\
1564 2\n00:00:02,000 --> 00:00:03,250\nsecond\n\n\
1565 3\n00:00:04,000 --> 00:00:04,750\nthird\n",
1566 )
1567 .expect("write");
1568 let mut srv = open();
1569 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": path.to_string_lossy() }]));
1570 assert!(!r.is_error, "{}", r.text);
1571 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0 }]));
1572 assert!(!r.is_error, "{}", r.text);
1573 let r = list(&mut srv, json!({}));
1574 for shown in ["00:00.500–00:01.500", "00:02.000–00:03.250", "00:04.000–00:04.750"] {
1575 assert!(r.text.contains(shown), "{shown} missing:\n{}", r.text);
1576 }
1577 let _ = std::fs::remove_dir_all(&dir);
1578 }
1579
1580 /// An added cue is on its track, so a placed caption shows it, and a save and reopen keep it.
1581 #[test]
1582 fn an_added_cue_shows_on_the_caption_lane_and_survives_a_reopen() {
1583 let mut srv = open();
1584 placed(&mut srv);
1585 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.6s", "to": "1.9s", "text": "Added" }]));
1586 assert!(!r.is_error, "{}", r.text);
1587 let r = list(&mut srv, json!({}));
1588 assert!(r.text.contains("S1 4 cues"), "{}", r.text);
1589 assert!(r.text.contains("Added"), "{}", r.text);
1590
1591 let dir = crate::testutil::TestDir::new("cue-add-reopen");
1592 let path = dir.path().join("proj.edith");
1593 srv.path = Some(path.clone());
1594 let r = run_tool(&mut srv, "project_save", json!({}));
1595 assert!(!r.is_error, "{}", r.text);
1596 let mut fresh = Server::default();
1597 let r = run_tool(&mut fresh, "project_open", json!({ "path": path.display().to_string() }));
1598 assert!(!r.is_error, "{}", r.text);
1599 let r = list(&mut fresh, json!({}));
1600 assert!(r.text.contains("S1 4 cues"), "{}", r.text);
1601 assert!(r.text.contains("Added"), "{}", r.text);
1602 }
1603
1604 #[test]
1605 fn cue_replace_rewrites_every_match_in_one_undo_step() {
1606 let mut srv = open();
1607 placed(&mut srv);
1608 let steps = srv.ledger.len();
1609 let r = ed(&mut srv, json!([{ "op": "cue_replace", "find": "LINE", "replace": "row" }]));
1610 assert!(!r.is_error, "{}", r.text);
1611 assert!(r.text.contains("occurrence(s) in"), "{}", r.text);
1612 assert_eq!(srv.ledger.len(), steps + 1, "one batch is one undo step");
1613 let r = list(&mut srv, json!({}));
1614 assert!(r.text.contains("first row"), "{}", r.text);
1615 assert!(!r.text.to_lowercase().contains("first line"), "{}", r.text);
1616
1617 // Case-sensitive matching leaves the lower-case word alone.
1618 let r = ed(&mut srv, json!([{ "op": "cue_replace", "track": 0, "find": "LINE", "replace": "x", "case_sensitive": true }]));
1619 assert!(r.is_error && r.text.contains("no cue reads"), "{}", r.text);
1620 let r = ed(&mut srv, json!([{ "op": "cue_replace", "track": 0, "find": "zzz-absent", "replace": "x" }]));
1621 assert!(r.is_error && r.text.contains("no cue reads"), "{}", r.text);
1622 let r = ed(&mut srv, json!([{ "op": "cue_replace", "track": 9, "find": "a", "replace": "b" }]));
1623 assert!(r.is_error, "{}", r.text);
1624 }
1625
1626 /// Runs a registered tool by name, as the server would.
1627 fn run_tool(srv: &mut Server, name: &str, args: Value) -> Reply {
1628 let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("registered tool");
1629 (t.run)(srv, &args)
1630 }
1631
1632 /// A long track is listed 40 cues a page, each page saying where the next one is; a page past
1633 /// the last is refused by name.
1634 #[test]
1635 fn captions_pages_forty_cues_and_says_where_the_next_page_is() {
1636 let mut srv = open();
1637 let dir = crate::testutil::TestDir::new("captions-pages");
1638 let path = dir.path().join("many.srt");
1639 let mut body = String::new();
1640 for i in 0..90u32 {
1641 let (a, b) = (i * 100, i * 100 + 90);
1642 body.push_str(&format!("{}\n{:02}:{:02}:{:02},{:03} --> {:02}:{:02}:{:02},{:03}\ncue {i}\n\n", i + 1, a / 3_600_000, a / 60_000 % 60, a / 1000 % 60, a % 1000, b / 3_600_000, b / 60_000 % 60, b / 1000 % 60, b % 1000));
1643 }
1644 std::fs::write(&path, body).unwrap();
1645 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": path.display().to_string() }]));
1646 assert!(!r.is_error, "{}", r.text);
1647 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0 }]));
1648 assert!(!r.is_error, "{}", r.text);
1649
1650 let r = list(&mut srv, json!({}));
1651 assert!(!r.is_error, "{}", r.text);
1652 assert!(r.text.contains("page 1 of 3 (cues 1–40 of 90); next: captions {page:2}"), "{}", r.text);
1653 assert_eq!(cue_rows(&r.text), 40, "{}", r.text);
1654 assert!(r.text.contains(" 1. track 0 cue 0 "), "{}", r.text);
1655 let r2 = list(&mut srv, json!({"page": 2}));
1656 assert!(r2.text.contains("page 2 of 3 (cues 41–80 of 90); next: captions {page:3}"), "{}", r2.text);
1657 assert!(r2.text.contains(" 41. track 0 cue 40 "), "{}", r2.text);
1658 let r3 = list(&mut srv, json!({"page": 3}));
1659 assert!(r3.text.contains("page 3 of 3 (cues 81–90 of 90)") && !r3.text.contains("next:"), "{}", r3.text);
1660 assert_eq!(cue_rows(&r3.text), 10, "{}", r3.text);
1661 assert_eq!(r3.structured.as_ref().unwrap()["next"], serde_json::Value::Null);
1662 let past = list(&mut srv, json!({"page": 4}));
1663 assert!(past.is_error && past.text.contains("past the last page (3)"), "{}", past.text);
1664 assert!(list(&mut srv, json!({"page": 0})).is_error);
1665 }
1666
1667 /// The cue rows of a captions listing (" n. track T cue C ..."), not its header or footer.
1668 /// Each listed cue names the placement sub_move takes, and a cue's own start frame, which
1669 /// starts no placement, is refused by naming the placement that covers it.
1670 #[test]
1671 fn captions_list_the_address_sub_move_takes_for_each_cue() {
1672 let mut srv = open();
1673 placed(&mut srv);
1674 let fps = parse::session_fps(srv.session.as_ref().unwrap());
1675 let r = list(&mut srv, json!({}));
1676 assert!(!r.is_error, "{}", r.text);
1677 assert_eq!(r.text.matches("[S1@0]").count(), cue_rows(&r.text), "{}", r.text);
1678 let rows = r.structured.as_ref().and_then(|v| v["cues"].as_array()).expect("cues");
1679 assert!(rows.iter().all(|c| c["address"] == "S1@0"), "{rows:?}");
1680 // The second cue starts at 2 s, inside the placement at 0: that frame is no placement start.
1681 let frame = (2.0 * fps).round() as u32;
1682 let r = ed(&mut srv, json!([{ "op": "sub_move", "clip": format!("S1@{frame}"), "at": "30s" }]));
1683 assert!(r.is_error, "{}", r.text);
1684 assert!(r.text.contains("is S1@0"), "{}", r.text);
1685 assert!(r.text.contains("in [brackets]"), "{}", r.text);
1686 // The address the listing gives moves the placement.
1687 let r = ed(&mut srv, json!([{ "op": "sub_move", "clip": "S1@0", "at": "30s" }]));
1688 assert!(!r.is_error, "{}", r.text);
1689 }
1690
1691 fn cue_rows(text: &str) -> usize {
1692 text.lines()
1693 .filter(|l| l.starts_with(' ') && l.trim_start().starts_with(|c: char| c.is_ascii_digit()))
1694 .count()
1695 }
1696
1697 #[test]
1698 fn cue_text_turns_a_literal_backslash_n_into_a_line_break_and_says_so() {
1699 let mut srv = open();
1700 placed(&mut srv);
1701 // Two characters, backslash then n, as a model types a line break.
1702 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 1, "text": "Line one\\nline two" }]));
1703 assert!(!r.is_error, "{}", r.text);
1704 assert!(r.text.contains("literal \\n read as a line break"), "{}", r.text);
1705 assert!(r.text.contains("\"Line one / line two\""), "{}", r.text);
1706 let kept = srv.session.as_ref().unwrap().subtitles()[0].cues[1].text.clone();
1707 assert_eq!(kept, "Line one\nline two", "a real newline is stored, not two characters");
1708 // A real newline needs no note.
1709 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": "Plain" }]));
1710 assert!(!r.text.contains("literal"), "{}", r.text);
1711 }
1712
1713 #[test]
1714 fn captions_place_clash_says_how_to_clear_the_caption_in_the_way() {
1715 let mut srv = open();
1716 placed(&mut srv);
1717 // The track already sits on S1 from frame 0: placing it there again clashes.
1718 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0 }]));
1719 assert!(r.is_error, "{}", r.text);
1720 assert!(r.text.contains("already covers"), "{}", r.text);
1721 assert!(r.text.contains("sub_delete {clip:\"S1@0\"}"), "{}", r.text);
1722 assert!(r.text.contains("sub_move {clip:\"S1@0\", to_lane:\"S2\"}"), "{}", r.text);
1723 }
1724
1725 #[test]
1726 fn cue_text_reply_echoes_the_new_words() {
1727 let mut srv = open();
1728 placed(&mut srv);
1729 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 1, "text": "Line one\nline two" }]));
1730 assert!(!r.is_error, "{}", r.text);
1731 assert!(r.text.contains("cue_text track 0 cue 1 → \"Line one / line two\""), "{}", r.text);
1732
1733 let long = "x".repeat(100);
1734 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": long }]));
1735 assert!(!r.is_error, "{}", r.text);
1736 assert!(r.text.contains(&format!("\"{}…\"", "x".repeat(60))), "{}", r.text);
1737 assert!(!r.text.contains(&"x".repeat(61)), "the echo stops at 60 characters: {}", r.text);
1738 }
1739
1740 /// A cut over a whole caption removes it from the listing, the header count
1741 /// agrees with the rows, and the reopened project lists the same. A ripple
1742 /// delete (remove_time) over the same span is the same cut.
1743 #[test]
1744 fn a_cut_over_a_whole_caption_leaves_no_copy_and_the_count_agrees() {
1745 let mut srv = open();
1746 placed(&mut srv);
1747 let fps = parse::session_fps(srv.session.as_ref().unwrap());
1748 // Cue 2 ("second line") runs 2.000 s to 3.250 s: cut the frames it covers.
1749 let from = (2.0 * fps).round() as u32;
1750 let to = (3.25 * fps).ceil() as u32;
1751 let r = ed(&mut srv, json!([{ "op": "cut_regions", "regions": [[format!("{from}f"), format!("{to}f")]] }]));
1752 assert!(!r.is_error, "{}", r.text);
1753 let r = list(&mut srv, json!({}));
1754 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1755 assert_eq!(cue_rows(&r.text), 2, "header and rows agree: {}", r.text);
1756 assert!(!r.text.contains("second line"), "{}", r.text);
1757
1758 // The same cut as a ripple delete of that span.
1759 let mut rip = open();
1760 placed(&mut rip);
1761 let r = ed(&mut rip, json!([{ "op": "remove_time", "at": format!("{from}f"), "duration": format!("{}f", to - from) }]));
1762 assert!(!r.is_error, "{}", r.text);
1763 let r = list(&mut rip, json!({}));
1764 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1765 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1766
1767 // Saved and reopened: the same two cues, and no copy of the cut one.
1768 let dir = crate::testutil::TestDir::new("cut-whole-caption");
1769 let path = dir.path().join("proj.edith");
1770 srv.path = Some(path.clone());
1771 let r = run_tool(&mut srv, "project_save", json!({}));
1772 assert!(!r.is_error, "{}", r.text);
1773 let mut fresh = Server::default();
1774 let r = run_tool(&mut fresh, "project_open", json!({ "path": path.display().to_string() }));
1775 assert!(!r.is_error, "{}", r.text);
1776 let r = list(&mut fresh, json!({}));
1777 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1778 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1779 assert!(!r.text.contains("second line"), "{}", r.text);
1780 }
1781
1782 /// `cue_delete {track, index}` removes one cue from the listing, names it in
1783 /// the reply, and the removal (with a retype after it) survives a save and reopen.
1784 #[test]
1785 fn cue_delete_removes_one_cue_and_survives_a_reopen() {
1786 let mut srv = open();
1787 placed(&mut srv);
1788 let r = ed(&mut srv, json!([{ "op": "cue_delete", "track": 0, "index": 1 }]));
1789 assert!(!r.is_error, "{}", r.text);
1790 assert!(r.text.contains("cue_delete track 0 cue 1"), "{}", r.text);
1791 assert!(r.text.contains("second line"), "the reply names what went: {}", r.text);
1792 let r = list(&mut srv, json!({}));
1793 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1794 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1795 assert!(!r.text.contains("second line"), "{}", r.text);
1796 assert!(r.text.contains("track 0 cue 1"), "the cue after it moved up one: {}", r.text);
1797
1798 // A retype of the cue that moved up is kept under its file index.
1799 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 1, "text": "Third one" }]));
1800 assert!(!r.is_error, "{}", r.text);
1801
1802 let dir = crate::testutil::TestDir::new("cue-delete");
1803 let path = dir.path().join("proj.edith");
1804 srv.path = Some(path.clone());
1805 let r = run_tool(&mut srv, "project_save", json!({}));
1806 assert!(!r.is_error, "{}", r.text);
1807 let mut fresh = Server::default();
1808 let r = run_tool(&mut fresh, "project_open", json!({ "path": path.display().to_string() }));
1809 assert!(!r.is_error, "{}", r.text);
1810 let r = list(&mut fresh, json!({}));
1811 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1812 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1813 assert!(!r.text.contains("second line"), "the removed cue stays gone: {}", r.text);
1814 assert!(r.text.contains("Third one"), "the retype came back: {}", r.text);
1815 assert!(!r.text.contains("third line"), "{}", r.text);
1816 }
1817
1818 /// Empty `cue_text` removes the cue rather than leaving a blank one.
1819 #[test]
1820 fn cue_text_with_no_words_removes_the_cue() {
1821 let mut srv = open();
1822 placed(&mut srv);
1823 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": "" }]));
1824 assert!(!r.is_error, "{}", r.text);
1825 assert!(r.text.contains("cue_delete track 0 cue 0"), "{}", r.text);
1826 let r = list(&mut srv, json!({}));
1827 assert!(r.text.contains("S1 2 cues"), "{}", r.text);
1828 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1829 assert!(!r.text.contains("first line"), "{}", r.text);
1830 let r = ed(&mut srv, json!([{ "op": "cue_delete", "track": 0, "index": 5 }]));
1831 assert!(r.is_error && r.text.contains("index 5 is not one of them"), "{}", r.text);
1832 }
1833
1834 /// `cue_delete {at}` takes the cue shown at that time; `sub_delete` on a time
1835 /// inside a placed cue says so and names the cue_delete that removes just it.
1836 #[test]
1837 fn cue_delete_by_time_and_the_sub_delete_hint() {
1838 let mut srv = open();
1839 placed(&mut srv);
1840 let fps = parse::session_fps(srv.session.as_ref().unwrap());
1841 // "second line" runs 2.000 s to 3.250 s; 2.5 s is inside it.
1842 let frame = (2.5 * fps).round() as u32;
1843
1844 let r = ed(&mut srv, json!([{ "op": "sub_delete", "clip": format!("S1@{frame}") }]));
1845 assert!(r.is_error, "{}", r.text);
1846 assert!(r.text.contains("cue_delete") && r.text.contains("\"index\": 1"), "{}", r.text);
1847 assert_eq!(srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0)).len(), 1);
1848
1849 let r = ed(&mut srv, json!([{ "op": "cue_delete", "at": format!("{frame}f") }]));
1850 assert!(!r.is_error, "{}", r.text);
1851 assert!(r.text.contains("second line"), "{}", r.text);
1852 let r = list(&mut srv, json!({}));
1853 assert_eq!(cue_rows(&r.text), 2, "{}", r.text);
1854 assert!(!r.text.contains("second line"), "{}", r.text);
1855
1856 let r = ed(&mut srv, json!([{ "op": "cue_delete", "at": "2.5s", "lane": "S2" }]));
1857 assert!(r.is_error && r.text.contains("is not a caption lane here"), "{}", r.text);
1858 }
1859
1860 /// A cut that leaves a sliver of a cue under four frames at its edge shows no
1861 /// sliver: the cue's tail is still a cue, and the cue is listed once.
1862 #[test]
1863 fn a_cut_edge_sliver_is_not_a_cue() {
1864 let mut srv = open();
1865 placed(&mut srv);
1866 let fps = parse::session_fps(srv.session.as_ref().unwrap());
1867 // "second line" runs 2.000 s to 3.250 s: cutting 2.1 s to 2.9 s leaves 0.1 s at its head.
1868 let from = (2.1 * fps).round() as u32;
1869 let to = (2.9 * fps).round() as u32;
1870 let r = ed(&mut srv, json!([{ "op": "cut_regions", "regions": [[format!("{from}f"), format!("{to}f")]] }]));
1871 assert!(!r.is_error, "{}", r.text);
1872 let r = list(&mut srv, json!({}));
1873 assert_eq!(cue_rows(&r.text), 3, "the head sliver is no cue: {}", r.text);
1874 // Cues split at the cut: the words inside it ("with") and the 0.1 s head ("second line") are gone; "a break" survives.
1875 assert!(!r.text.contains("second line"), "the head sliver's words are gone: {}", r.text);
1876 assert!(!r.text.contains("with"), "the words inside the cut are gone: {}", r.text);
1877 assert!(r.text.contains("a break"), "the tail after the cut stays: {}", r.text);
1878 }
1879
1880 #[test]
1881 fn replace_in_counts_and_respects_case() {
1882 assert_eq!(replace_in("a Cat, a cat", "cat", "dog", false), Some(("a dog, a dog".into(), 2)));
1883 assert_eq!(replace_in("a Cat, a cat", "cat", "dog", true), Some(("a Cat, a dog".into(), 1)));
1884 assert_eq!(replace_in("aaaa", "aa", "b", true), Some(("bb".into(), 2)));
1885 assert_eq!(replace_in("nothing", "zz", "b", false), None);
1886 assert_eq!(replace_in("Édith LUFS", "édith", "Edith", false), Some(("Edith LUFS".into(), 1)));
1887 }
1888
1889 #[test]
1890 fn captions_place_refuses_overlap_and_makes_missing_lanes() {
1891 let mut srv = open();
1892 placed(&mut srv);
1893 let depth = srv.session.as_ref().unwrap().undo_depth();
1894 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "at": "0f" }]));
1895 assert!(r.is_error, "{}", r.text);
1896 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth, "a refused placement changes nothing");
1897
1898 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S3", "at": "1s" }]));
1899 assert!(!r.is_error, "{}", r.text);
1900 let lanes = srv.session.as_ref().unwrap().subtitle_lanes();
1901 assert_eq!(lanes.len(), 3, "S2 and S3 were made alongside S1");
1902 }
1903
1904 #[test]
1905 fn sub_move_trim_delete_on_a_placed_track() {
1906 let mut srv = open();
1907 let frames = placed(&mut srv);
1908
1909 let r = ed(&mut srv, json!([{ "op": "sub_move", "clip": "S1@0", "at": "10s" }]));
1910 assert!(!r.is_error, "{}", r.text);
1911 let s = srv.session.as_ref().unwrap();
1912 let start = s.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].start;
1913 assert!(start > 0, "moved away from 0");
1914 assert!(r.text.contains(&format!("S1@{start}")), "{}", r.text);
1915
1916 let to = format!("S1@{start}");
1917 let half = frames / 2;
1918 let r = ed(&mut srv, json!([{ "op": "sub_trim", "clip": to, "edge": "out", "to": format!("{}f", start + half) }]));
1919 assert!(!r.is_error, "{}", r.text);
1920 assert_eq!(srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].frames, half);
1921
1922 let r = ed(&mut srv, json!([{ "op": "sub_delete", "clip": to }]));
1923 assert!(!r.is_error, "{}", r.text);
1924 assert!(srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0)).is_empty());
1925 }
1926
1927 #[test]
1928 fn caption_ops_refuse_media_clips_and_missing_lanes() {
1929 let mut srv = open();
1930 placed(&mut srv);
1931 let r = ed(&mut srv, json!([{ "op": "sub_delete", "clip": "V1@0" }]));
1932 assert!(r.is_error && r.text.contains("is not a caption"), "{}", r.text);
1933 let r = ed(&mut srv, json!([{ "op": "sub_move", "clip": "S1@0", "to_lane": "S9", "at": "2s" }]));
1934 assert!(r.is_error && r.text.contains("S9 is not a caption lane"), "{}", r.text);
1935 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 5 }]));
1936 assert!(r.is_error && r.text.contains("is not on this timeline"), "{}", r.text);
1937 }
1938
1939 #[test]
1940 fn captions_lists_nothing_helpfully_without_lanes() {
1941 let mut srv = open();
1942 let r = list(&mut srv, json!({}));
1943 assert!(!r.is_error);
1944 assert!(r.text.contains("no caption lanes"), "{}", r.text);
1945 }
1946
1947 /// Timeline frames a track's window covers, at least one. The GUI's rule for a dropped row.
1948 /// Test-only: nothing in the tool calls it any more.
1949 fn frames_of_us(us: i64, fps: f64) -> u32 {
1950 match fps.is_finite() && fps > 0.0 {
1951 true => ((us as f64) * fps / 1e6).round().clamp(1.0, f64::from(u32::MAX)) as u32,
1952 false => 1,
1953 }
1954 }
1955
1956 #[test]
1957 fn frames_of_us_rounds_and_never_zero() {
1958 assert_eq!(frames_of_us(1_000_000, 25.0), 25);
1959 assert_eq!(frames_of_us(1, 25.0), 1);
1960 assert_eq!(frames_of_us(5, 0.0), 1);
1961 }
1962
1963 #[test]
1964 fn clock_is_minutes_and_millis() {
1965 assert_eq!(clock_us(1_200_000), "00:01.200");
1966 assert_eq!(clock_us(3_723_500_000), "1:02:03.500");
1967 }
1968
1969 /// An overwrite names the cue it replaces, and a remove_time over captions names the cue it trims.
1970 #[test]
1971 fn overwrite_and_a_cut_over_captions_name_the_cues() {
1972 let mut srv = open();
1973 placed(&mut srv);
1974 // Over the first file cue (0.5 s to 1.5 s): the overwrite says which cue it replaced.
1975 let r = ed(&mut srv, json!([{ "op": "cue_add", "track": 0, "at": "1.0s", "to": "1.7s", "text": "Over", "overwrite": true }]));
1976 assert!(!r.is_error, "{}", r.text);
1977 assert!(r.text.contains("replaced") && r.text.contains("\"first line") && r.text.contains("0.500s–1.500s"), "{}", r.text);
1978 // Cutting 1.0 s to 1.5 s trims the "Over" cue (1.0 s to 1.7 s) at its edge, and the reply names it.
1979 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1.0s", "duration": "0.5s" }]));
1980 assert!(!r.is_error, "{}", r.text);
1981 assert!(
1982 r.text.contains("caption cue(s) trimmed: S1 cue 1 'Over' → 'Over' (was 1.000s–1.700s, now 1.000s–1.200s)"),
1983 "{}",
1984 r.text
1985 );
1986 }
1987
1988 #[test]
1989 fn captions_remove_takes_an_unplaced_track_and_refuses_a_placed_one_until_forced() {
1990 let mut srv = open();
1991 placed(&mut srv);
1992 // A second, unplaced track, from a file of its own.
1993 let dir = std::env::temp_dir().join(format!("edith_r14_{}", std::process::id()));
1994 std::fs::create_dir_all(&dir).unwrap();
1995 let second = dir.join("second.srt");
1996 std::fs::write(&second, "1\n00:00:00,500 --> 00:00:01,000\nother track\n").unwrap();
1997 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": second.to_string_lossy() }]));
1998 assert!(!r.is_error, "{}", r.text);
1999 let r = ed(&mut srv, json!([{ "op": "captions_remove", "track": 1 }]));
2000 assert!(!r.is_error && r.text.contains("removed"), "{}", r.text);
2001 assert_eq!(srv.session.as_ref().unwrap().subtitles().len(), 1, "track 1 is gone");
2002 // The placed track 0 is refused, naming its placement, and nothing changes.
2003 let before = srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0)).len();
2004 let r = ed(&mut srv, json!([{ "op": "captions_remove", "track": 0 }]));
2005 assert!(r.is_error && r.text.contains("1 placement(s) on the timeline (S1@0)") && r.text.contains("force:true"), "{}", r.text);
2006 assert_eq!(srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0)).len(), before);
2007 // With force:true the placement goes with the track, as one step that undo gives back.
2008 let depth = srv.session.as_ref().unwrap().undo_depth();
2009 let r = ed(&mut srv, json!([{ "op": "captions_remove", "track": 0, "force": true }]));
2010 assert!(!r.is_error && r.text.contains("with its 1 placement(s)"), "{}", r.text);
2011 assert!(srv.session.as_ref().unwrap().subtitles().is_empty());
2012 assert!(srv.session.as_ref().unwrap().undo_depth() > depth);
2013 let r = run_tool(&mut srv, "undo", json!({}));
2014 assert!(!r.is_error, "{}", r.text);
2015 assert_eq!(srv.session.as_ref().unwrap().subtitles().len(), 1, "undo brings the track back");
2016 assert_eq!(srv.session.as_ref().unwrap().sub_lane(Lane::new(LaneKind::Subtitle, 0)).len(), before);
2017 let _ = std::fs::remove_dir_all(&dir);
2018 }
2019
2020 /// A locked caption lane is never changed: every caption op that would change it refuses,
2021 /// names the lock, and leaves the history and the cues as they were. Unlocking lets them work.
2022 #[test]
2023 fn a_locked_caption_lane_refuses_every_caption_op() {
2024 let mut srv = open();
2025 placed(&mut srv);
2026 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "S1", "locked": true }]));
2027 assert!(!r.is_error, "{}", r.text);
2028 let depth = srv.session.as_ref().unwrap().undo_depth();
2029 let cues_before: Vec<String> = srv.session.as_ref().unwrap().subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
2030 let cases = [
2031 json!({ "op": "sub_move", "clip": "S1@0", "at": "3s" }),
2032 json!({ "op": "sub_trim", "clip": "S1@0", "edge": "out", "to": "2s" }),
2033 json!({ "op": "sub_delete", "clip": "S1@0" }),
2034 json!({ "op": "captions_place", "track": 0, "lane": "S1", "at": "5s" }),
2035 json!({ "op": "cue_text", "track": 0, "index": 0, "text": "changed" }),
2036 json!({ "op": "cue_text", "track": 0, "index": 0, "text": "" }),
2037 json!({ "op": "cue_delete", "track": 0, "index": 0 }),
2038 json!({ "op": "cue_delete", "at": "1s" }),
2039 json!({ "op": "cue_replace", "find": "a", "replace": "b" }),
2040 json!({ "op": "cue_add", "track": 0, "at": "10s", "to": "11s", "text": "new" }),
2041 json!({ "op": "captions_remove", "track": 0 }),
2042 ];
2043 for case in cases {
2044 let name = case["op"].as_str().unwrap().to_string();
2045 let r = ed(&mut srv, json!([case]));
2046 assert!(r.is_error && r.text.contains("lane S1 is locked"), "{name} must refuse on the lock: {}", r.text);
2047 }
2048 let s = srv.session.as_ref().unwrap();
2049 assert_eq!(s.undo_depth(), depth, "refused ops leave no history");
2050 assert_eq!(s.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect::<Vec<_>>(), cues_before, "refused ops change no cue");
2051 assert_eq!(s.sub_lane(Lane::new(LaneKind::Subtitle, 0)).len(), 1, "the placement is where it was");
2052
2053 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "S1", "locked": false }]));
2054 assert!(!r.is_error, "{}", r.text);
2055 let r = ed(&mut srv, json!([{ "op": "cue_text", "track": 0, "index": 0, "text": "changed" }]));
2056 assert!(!r.is_error, "unlocked, the cue edit goes through: {}", r.text);
2057 }
2058
2059 /// A move onto a locked caption lane is refused naming that lane, and the caption stays put.
2060 #[test]
2061 fn a_move_onto_a_locked_caption_lane_is_refused() {
2062 let mut srv = open();
2063 placed(&mut srv);
2064 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S2", "at": "0f" }]));
2065 assert!(!r.is_error, "{}", r.text);
2066 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "S2", "locked": true }]));
2067 assert!(!r.is_error, "{}", r.text);
2068 let depth = srv.session.as_ref().unwrap().undo_depth();
2069 let r = ed(&mut srv, json!([{ "op": "sub_move", "clip": "S1@0", "to_lane": "S2", "at": "1s" }]));
2070 assert!(r.is_error && r.text.contains("lane S2 is locked"), "{}", r.text);
2071 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
2072 }
2073
2074 /// captions_place on S2 with no S1 makes S1 first (the engine adds lanes in order), and the
2075 /// reply says that S1 was made empty rather than leaving it unexplained.
2076 #[test]
2077 fn captions_place_on_s2_says_the_empty_s1_it_made() {
2078 let mut srv = open();
2079 let r = ed(&mut srv, json!([{ "op": "subtitles_import", "path": srt() }]));
2080 assert!(!r.is_error, "{}", r.text);
2081 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S2" }]));
2082 assert!(!r.is_error, "{}", r.text);
2083 assert!(r.text.contains("S1 was created empty, because S2 sits above it"), "{}", r.text);
2084 assert_eq!(srv.session.as_ref().unwrap().subtitle_lanes().len(), 2);
2085 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S1" }]));
2086 assert!(!r.is_error && !r.text.contains("created empty"), "{}", r.text);
2087 }
2088}