forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

subtitle.rs2131 lines, 88.7 KiBHistoryRawDownload
1//! Subtitles: a list of cues with a time on them, out of a file beside the
2//! media (`.srt`, `.vtt`, `.ass`) or out of a track inside it.
3//!
4//! One model for both, because a timeline cannot care which it was: a
5//! [`SubtitleTrack`] is where it came from -- a path, and the Matroska track
6//! number when it is one of several inside that path -- plus the [`Cue`]s. That
7//! pair is also all a `.edith` writes ([`crate::edith`]): the cues are read
8//! back out of the file on the way in, exactly as a clip's *pictures* are, so a
9//! project file stays an edit list and not a copy of the subtitles.
10//!
11//! Parsing is `ec-subs` (SRT, WebVTT) and `ec-ass` (ASS/SSA) --
12//! the markup, the override tags and the encoding quirks of a dozen dialects
13//! are not this project's to re-derive. What comes back here is plain text: the
14//! renderer is a later thing, and a cue nobody can draw yet is still a cue that
15//! has to be listed, timed and saved.
16//!
17//! A cue is not always words. `S_HDMV/PGS` off a BluRay remux is *pictures* --
18//! run-length bitmaps the disc composed against its own frame -- and one of
19//! those is a [`Cue`] with a [`CueImage`] on it and no text. The decoding is
20//! `ec-pgs`, for the reason above. Everything downstream carries the
21//! picture the way it carries the string: [`crate::export::timeline_cues`] maps
22//! it onto the timeline, a front-end draws it over the film.
23//!
24//! What is still *refused* is refused by name rather than by omission
25//! ([`SubtitleTrack::refused`]): VobSub off a DVD is a picture format nothing
26//! here reads, and a file carrying one opens with a row that says so instead of
27//! opening with an empty list.
28
29use std::collections::HashMap;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32
33use ec_subs::plain_text;
34
35/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds
36/// from the start of the media, which is the unit every parser here speaks.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Cue {
39 pub start_us: i64,
40 pub end_us: i64,
41 /// Plain text, `\n` between the lines of a multi-line cue. The markup is
42 /// resolved and dropped: `<i>` from an SRT, `{\an8}` and `\N` from an ASS.
43 ///
44 /// corner-cut: bold/italic/colour and ASS positioning are parsed by the crate
45 /// and thrown away here, because nothing draws a cue yet. The upgrade path
46 /// is to keep `ec_subs::Segment` runs beside this string -- the parsers
47 /// already hand them over -- and it belongs to whoever writes the renderer.
48 pub text: String,
49 /// The picture this cue *is*, for a track that is pictures rather than
50 /// lines. `None` for every text cue -- an `.srt`, a `.vtt`, an `.ass`, an
51 /// `S_TEXT/*` track -- and `Some` for every cue of a PGS one, which then
52 /// has no [`text`](Self::text) at all.
53 ///
54 /// Shared rather than owned: [`crate::export::timeline_cues`] copies a whole
55 /// track's cues, per repaint, and a display set is tens of kilobytes.
56 pub image: Option<Arc<CueImage>>,
57 /// When each word of [`text`](Self::text) is spoken, `(start_us, end_us, word)` on the same
58 /// clock as the cue, one entry per whitespace-separated word. Empty for a cue from a file
59 /// (an SRT has no word times) and for one whose words were retyped: use
60 /// [`Self::real_words`], which checks them against the text, never the field.
61 pub words: Vec<(i64, i64, String)>,
62 /// The karaoke syllables of an ASS cue, on the same clock as the cue. Empty for every other
63 /// cue; use [`Self::real_karaoke`], which checks them against the text, never the field.
64 pub karaoke: Vec<Syllable>,
65}
66
67/// One karaoke beat of an ASS cue (`\k`, `\kf`, `\ko`): the text it sings and how it is lit.
68/// Not stored in a project: it is read again from the imported file, with the cue.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Syllable {
71 /// Where the beat is lit from and to, microseconds on the cue's clock.
72 pub start_us: i64,
73 pub end_us: i64,
74 /// Which non-whitespace character of the cue's text the syllable starts at, and the
75 /// characters it covers (`text`, whitespace dropped). Counting only the letters keeps the
76 /// place when the line wrapping re-flows the spaces.
77 pub from: usize,
78 pub text: String,
79 pub mode: ec_subs::KaraokeMode,
80 /// The colour before the syllable is sung (`\2c`, else the style's secondary).
81 pub unsung: [u8; 3],
82 /// The colour once sung: an enclosing colour override, else `None` for the text's own.
83 pub sung: Option<[u8; 3]>,
84}
85
86/// The unsung colour of a style that names no secondary, libass's default.
87const DEFAULT_SECONDARY: [u8; 3] = [255, 0, 0];
88
89/// The syllables of `cue`'s body, grouped by their `(start, length)` as the parser documents.
90fn syllables(cue: &ec_subs::SubtitleCue, track: &ec_subs::SubtitleTrack) -> Vec<Syllable> {
91 struct Walk {
92 out: Vec<Syllable>,
93 seen: usize,
94 base: i64,
95 style: [u8; 3],
96 /// The `(start_cs, cs)` of the syllable the last piece belonged to.
97 last: Option<(u32, u32)>,
98 }
99 fn walk(segs: &[ec_subs::Segment], colour: Option<[u8; 3]>, beat: Option<(u32, u32, ec_subs::KaraokeMode, [u8; 3])>, w: &mut Walk) {
100 use ec_subs::Segment as S;
101 for seg in segs {
102 match seg {
103 S::Text(t) => {
104 let letters: String = t.chars().filter(|c| !c.is_whitespace()).collect();
105 if letters.is_empty() {
106 continue;
107 }
108 let n = letters.chars().count();
109 if let Some((start_cs, cs, mode, unsung)) = beat {
110 match w.out.last_mut() {
111 Some(l) if w.last == Some((start_cs, cs)) => l.text.push_str(&letters),
112 _ => w.out.push(Syllable {
113 start_us: w.base + i64::from(start_cs) * 10_000,
114 end_us: w.base + i64::from(start_cs + cs) * 10_000,
115 from: w.seen,
116 text: letters,
117 mode,
118 unsung,
119 sung: colour,
120 }),
121 }
122 w.last = Some((start_cs, cs));
123 }
124 w.seen += n;
125 }
126 S::Karaoke { cs, start_cs, mode, secondary, children } => {
127 let unsung = secondary.map_or(w.style, |(r, g, b)| [r, g, b]);
128 walk(children, colour, Some((*start_cs, *cs, *mode, unsung)), w);
129 }
130 S::Color { rgb, children } => walk(children, Some([rgb.0, rgb.1, rgb.2]), beat, w),
131 S::Bold(c) | S::Italic(c) | S::Underline(c) | S::Strike(c) => walk(c, colour, beat, w),
132 S::Font { children, .. } | S::Voice { children, .. } | S::Class { children, .. } => walk(children, colour, beat, w),
133 S::LineBreak | S::Timestamp { .. } | S::Raw(_) => {}
134 }
135 }
136 }
137 let style = cue
138 .style_ref
139 .as_deref()
140 .and_then(|n| track.style(n))
141 .and_then(|s| s.secondary_color)
142 .map_or(DEFAULT_SECONDARY, |(r, g, b, _)| [r, g, b]);
143 let mut w = Walk { out: Vec::new(), seen: 0, base: cue.start_us, style, last: None };
144 walk(&cue.segments, None, None, &mut w);
145 w.out
146}
147
148/// `syllables` moved with the cue they belong to, as [`map_words`] moves words: the cue's `[a, b]`
149/// became `[from, to]` on the timeline, and a syllable that starts at or past `b` is dropped.
150pub fn map_karaoke(syl: &[Syllable], (a, b): (i64, i64), (from, to): (i64, i64)) -> Vec<Syllable> {
151 let scale = if b > a { (to - from) as f64 / (b - a) as f64 } else { 1.0 };
152 let onto = |t: i64| from + ((t.clamp(a, b) - a) as f64 * scale).round() as i64;
153 syl.iter()
154 .filter(|s| b <= a || s.start_us < b)
155 .map(|s| Syllable { start_us: onto(s.start_us), end_us: onto(s.end_us), ..s.clone() })
156 .collect()
157}
158
159impl Cue {
160 /// The karaoke syllables, when they still describe the text: each one's letters are the
161 /// letters of the text at its place (a retyped cue has lost its karaoke).
162 pub fn real_karaoke(&self) -> Option<&[Syllable]> {
163 let letters: Vec<char> = self.text.chars().filter(|c| !c.is_whitespace()).collect();
164 let ok = !self.karaoke.is_empty()
165 && self.karaoke.iter().all(|s| {
166 let n = s.text.chars().count();
167 letters.get(s.from..s.from + n).is_some_and(|l| l.iter().copied().eq(s.text.chars()))
168 });
169 ok.then_some(&self.karaoke[..])
170 }
171}
172
173impl Cue {
174 /// The word times, when they still describe the text: the same words in the same order
175 /// (case aside, since a caption may capitalise a sentence start after it is timed).
176 pub fn real_words(&self) -> Option<&[(i64, i64, String)]> {
177 let mut text = self.text.split_whitespace();
178 let ok = !self.words.is_empty()
179 && self.words.iter().all(|w| text.next().is_some_and(|t| t.to_lowercase() == w.2.to_lowercase()))
180 && text.next().is_none();
181 ok.then_some(&self.words[..])
182 }
183}
184
185/// `words` moved with the cue they belong to: the cue's `[a, b]` in its own clock became
186/// `[from, to]` on the timeline (a linear map, as a placement or a speed change is), and the
187/// words before `a` are held at its edge; a word that starts at or past `b` -- the cue was cut
188/// there, by a range end or a trim -- is dropped, and the last word kept ends no later than `to`.
189pub fn map_words(
190 words: &[(i64, i64, String)],
191 (a, b): (i64, i64),
192 (from, to): (i64, i64),
193) -> Vec<(i64, i64, String)> {
194 let scale = if b > a { (to - from) as f64 / (b - a) as f64 } else { 1.0 };
195 let onto = |t: i64| from + ((t.clamp(a, b) - a) as f64 * scale).round() as i64;
196 words
197 .iter()
198 .filter(|(s, _, _)| b <= a || *s < b)
199 .map(|(s, e, w)| (onto(*s), onto(*e), w.clone()))
200 .collect()
201}
202
203/// A cue that is a picture: one PGS display set, kept the way the Matroska
204/// block held it -- run-length and palettised, tens of kilobytes -- and turned
205/// into pixels only when something is about to draw it ([`Self::rgba`]).
206///
207/// Kept encoded because decoded is enormous: this film's canvas is 8 MB of
208/// RGBA and its four PGS tracks carry about eleven thousand display sets
209/// between them, so a track that decoded itself at import would cost gigabytes
210/// where it now costs the thirty megabytes the file already spends on it.
211#[derive(Clone, Debug, PartialEq, Eq)]
212pub struct CueImage {
213 /// The canvas the disc composed against: 1920x1080 for a BluRay, whatever
214 /// the film's own frame was cropped to. The whole canvas is the picture --
215 /// transparent everywhere the cue does not paint -- so a caller lays it
216 /// over the film rather than placing it.
217 pub width: u32,
218 pub height: u32,
219 set: Source,
220}
221
222/// What a [`CueImage`] keeps until something draws it.
223#[derive(Clone, Debug, PartialEq, Eq)]
224enum Source {
225 /// A PGS display set: `type`, big-endian size, body, segment after segment,
226 /// which is the shape a Matroska block holds PGS in.
227 Pgs(Vec<u8>),
228 /// A DVD subpicture unit, with the `.idx` text (palette, size) of its track.
229 Dvd { idx: Arc<Vec<u8>>, unit: Vec<u8> },
230 /// A DVB display set (PES payload or Matroska block).
231 Dvb(Vec<u8>),
232}
233
234impl CueImage {
235 /// The picture: straight (not premultiplied) RGBA, `width * height * 4`
236 /// bytes, transparent wherever the cue paints nothing. `None` for a display
237 /// set the decoder will not have, which is a corrupt block.
238 ///
239 /// Decoded on the spot: the run-length walk and one canvas-sized buffer,
240 /// which is a thing to do when the cue on screen changes and not sixty
241 /// times a second. A caller that draws these keeps the answer for as long
242 /// as the cue is up.
243 pub fn rgba(&self) -> Option<Vec<u8>> {
244 let set = match &self.set {
245 Source::Pgs(set) => set,
246 Source::Dvd { idx, unit } => {
247 let mut decoder = ec_dvdsub::DvdSubDecoder::new(Some(idx.as_slice()).filter(|i| !i.is_empty()));
248 decoder.push_unit(unit, None).ok()?;
249 return frame_rgba(decoder.take_cue()?.frame);
250 }
251 Source::Dvb(set) => {
252 let mut decoder = ec_dvbsub::DvbSubDecoder::new();
253 // A damaged segment is dropped by the decoder; what it did draw is kept.
254 let _ = decoder.push_pes(set);
255 return frame_rgba(decoder.take_cue()?.frame);
256 }
257 };
258 // The decoder reads a `.sup`'s framing and a Matroska block is the same
259 // segments with the `PG` magic and the timestamps taken off, so they go
260 // back on. The times themselves are the block's and are already on the
261 // `Cue`, so they are written as nothing.
262 let mut sup = Vec::with_capacity(set.len() + 64);
263 // Up to and including the `END` that closes the first display set which
264 // composes an object, and no further: a block is normally one set, but
265 // a muxer that packs a composition and the erase after it into one would
266 // otherwise leave the *erase* as the last word and decode to an empty
267 // canvas -- the cue drawn as nothing at all.
268 let mut shows = false;
269 for (kind, body) in segments(set)? {
270 sup.extend_from_slice(b"PG");
271 sup.extend_from_slice(&[0; 8]);
272 sup.push(kind);
273 sup.extend_from_slice(&(body.len() as u16).to_be_bytes());
274 sup.extend_from_slice(body);
275 match kind {
276 ec_pgs::SEG_PCS => {
277 shows = body.get(10).is_some_and(|&n| n > 0);
278 }
279 ec_pgs::SEG_END if shows => break,
280 _ => {}
281 }
282 }
283 // One decoder per display set: the block carries its own epoch, so there
284 // is no state from an earlier cue to carry in. The first frame out is the
285 // one the set composes -- the segments past it were cut above.
286 let mut decoder = ec_pgs::PgsDecoder::new();
287 decoder.push(&sup).ok()?;
288 let frame = decoder.take_frame()?;
289 Some(frame.planes.into_iter().next()?.data.to_vec())
290 }
291}
292
293/// The pixels of a decoded subtitle frame: its one RGBA plane.
294fn frame_rgba(frame: ec_core::frame::VideoFrame) -> Option<Vec<u8>> {
295 Some(frame.planes.into_iter().next()?.data.to_vec())
296}
297
298/// The segments of a display set as a Matroska block holds them: a type byte, a
299/// big-endian size, that many bytes of body, and again until the block is out.
300/// `None` for bytes that do not walk -- a truncated or mislabelled block.
301fn segments(set: &[u8]) -> Option<Vec<(u8, &[u8])>> {
302 let mut out = Vec::new();
303 let mut at = 0;
304 while at < set.len() {
305 let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize;
306 out.push((set[at], set.get(at + 3..at + 3 + size)?));
307 at += 3 + size;
308 }
309 Some(out)
310}
311
312/// A subtitle track: where it came from and what it says.
313///
314/// `PartialEq` because it is one of the things an edit can change and therefore
315/// one of the things an undo has to bring back exactly
316/// ([`crate::Project::parts`], the sweep's round-trip).
317#[derive(Clone, Debug, PartialEq, Eq)]
318pub struct SubtitleTrack {
319 /// The file it was read out of: a standalone subtitle file, or the media
320 /// file whose track number is below.
321 pub path: PathBuf,
322 /// Which track of `path`, for one embedded in a Matroska file. `None` when
323 /// `path` *is* the subtitle file.
324 pub track: Option<u64>,
325 /// What language the track is in, as the container states it (`eng`, `fra`,
326 /// `und` for a file that says nothing -- which is what both demuxers hand
327 /// over rather than an empty string). Empty for a standalone file until an
328 /// import or a retype names one ([`set_language`](crate::Project::set_subtitle_language));
329 /// an export writes empty as `und`. A retype on an embedded track replaces
330 /// the container's own, and the project file carries it (`sublang` lines).
331 ///
332 /// Kept apart from [`name`](Self::name) because a container keeps them
333 /// apart: an export writes `TRACK_LANGUAGE` and `TRACK_NAME` as two fields
334 /// ([`crate::mux::SubParams`]), and a French track whose language is folded
335 /// into its title leaves as an English one.
336 pub language: String,
337 /// What the track is *called* beside its language (`Signs`, `Forced`). Empty
338 /// where it has none -- a standalone file has none, its file name is only
339 /// what [`label`](Self::label) shows.
340 pub name: String,
341 /// What a list shows: the [`language`](Self::language), the
342 /// [`name`](Self::name), or the pair ([`label_of`]) -- flattened here
343 /// because a row shows one string, and derived from the two rather than
344 /// being what they are derived from.
345 pub label: String,
346 /// In start order. Empty when [`refused`](Self::refused) says why.
347 pub cues: Vec<Cue>,
348 /// This track is pictures rather than text (`S_HDMV/PGS`). Not a refusal:
349 /// it is drawn over the picture like any other track, and what it cannot do
350 /// is be *written* as text -- an SRT carries none of it.
351 ///
352 /// Read off the codec id at every open rather than off the cues, because a
353 /// PGS track whose display sets are all erases -- or one with no cues at
354 /// all -- is still a track of pictures, and calling it text would have an
355 /// export promise to write words it does not have.
356 pub bitmap: bool,
357 /// Why this track has no cues, when it has none: a codec that is pictures
358 /// rather than text, a file that has gone missing since the project was
359 /// saved. `None` for one that parsed -- which a track with genuinely no
360 /// cues in it also is.
361 pub refused: Option<String>,
362}
363
364impl SubtitleTrack {
365 /// A track that is there and cannot be read, named and kept: a project
366 /// re-saved after one of these still lists it, which is the difference
367 /// between "your subtitles are missing" and losing them for good.
368 ///
369 /// No language and no name: what is refused is never *written* (an export
370 /// drops it before the muxer, [`crate::export::planned_subtitles`]), and the
371 /// row it leaves behind shows the `label` it was refused under.
372 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {
373 Self {
374 path: path.to_path_buf(),
375 track,
376 language: String::new(),
377 name: String::new(),
378 label,
379 cues: Vec::new(),
380 bitmap: false,
381 refused: Some(why),
382 }
383 }
384
385 /// Whether this track's cues are pictures rather than lines -- a PGS track
386 /// off a remux. What it decides is where words are the only answer: an
387 /// export writes a *text* track and cannot carry these
388 /// ([`crate::export::planned_subtitles`] says so out loud).
389 pub fn is_bitmap(&self) -> bool {
390 self.bitmap
391 }
392}
393
394/// The one door a saved subtitle line comes back in through: a standalone file
395/// (`track` is `None`) or track `n` of a media file, Matroska or mp4
396/// ([`of_media`]).
397///
398/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is
399/// not there any more, a track number the file no longer has, a codec of
400/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name,
401/// because a project that opened yesterday has to open today -- a subtitle is
402/// not what a whole timeline should refuse over.
403pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack {
404 let mut one = open_all(std::slice::from_ref(&(path.to_path_buf(), track)));
405 one.remove(0)
406}
407
408/// Every saved subtitle line of a project at once, back in the order they were
409/// saved in -- which is the order they are picked by, so it is the row order
410/// this hands back whatever it had to read.
411///
412/// The reason this exists beside [`open`]: a Matroska file is walked whole to
413/// reach *one* of its tracks, and a film whose project names thirty-five of them
414/// was thirty-five walks of a 25 GB file -- seven seconds with the window
415/// stopped, since a project opens on the UI thread. Each distinct file is walked
416/// once here and every row that named it is picked out of that one walk.
417pub fn open_all(rows: &[(PathBuf, Option<u64>)]) -> Vec<SubtitleTrack> {
418 // Keyed by path, so a second row naming the same file finds the walk rather
419 // than doing it again. The whole walk is kept until the last row is served:
420 // it is the tracks nobody asked for that are dropped at the end.
421 //
422 // corner-cut: a track is *moved* out of its walk, so two rows naming the same
423 // file and the same track leave the second refused by name rather than
424 // holding the cues twice. No project edith saves has one -- a row is added
425 // by (file, track) and only once ([`crate::Project::add_subtitles`]) -- and
426 // a hand-written `.edith` with a doubled row still opens, with that row
427 // saying so. Clone the picked track instead if that ever has to hold.
428 let mut walked: HashMap<&Path, crate::Result<Vec<SubtitleTrack>>> = HashMap::new();
429 // The files with a caption row: the only ones whose picture is read for captions.
430 let wants_captions: std::collections::HashSet<&Path> = rows
431 .iter()
432 .filter(|(_, t)| t.is_some_and(crate::demux::captions::is_caption_track))
433 .map(|(p, _)| p.as_path())
434 .collect();
435 rows.iter()
436 .map(|(path, track)| {
437 let Some(number) = *track else {
438 return external(path);
439 };
440 let label = format!("track {number}");
441 let tracks = walked
442 .entry(path.as_path())
443 .or_insert_with(|| of_media_with(path, wants_captions.contains(path.as_path())));
444 let tracks = match tracks {
445 Ok(tracks) => tracks,
446 Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()),
447 };
448 match tracks.iter().position(|t| t.track == Some(number)) {
449 Some(i) => tracks.swap_remove(i),
450 None => SubtitleTrack::refused(
451 path,
452 *track,
453 label,
454 format!("no subtitle track {number} in {} any more", path.display()),
455 ),
456 }
457 })
458 .collect()
459}
460
461/// A standalone subtitle file, parsed by its extension.
462fn external(path: &Path) -> SubtitleTrack {
463 let label = path
464 .file_name()
465 .map(|n| n.to_string_lossy().into_owned())
466 .unwrap_or_default();
467 match parse_file(path) {
468 Ok(cues) => SubtitleTrack {
469 bitmap: cues.iter().any(|c| c.image.is_some()),
470 path: path.to_path_buf(),
471 track: None,
472 // A file beside the media states no language of its own: it is set
473 // by an import ([`guess_language`]) or by a retype, and empty until
474 // then, which an export writes as `und`. Its file name is not a
475 // title: an export titles it with its language's name or not at all.
476 language: String::new(),
477 name: String::new(),
478 label,
479 cues,
480 refused: None,
481 },
482 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),
483 }
484}
485
486/// The languages a file name can name, as `(ISO 639-1, ISO 639-2, the 639-2
487/// bibliographic code when it differs, English name)`. Only the common ones, and
488/// no two-letter word that would be a name in a file name (`is`, `no`, `to`).
489const LANGUAGES: &[(&str, &str, &str, &str)] = &[
490 ("en", "eng", "eng", "English"),
491 ("fr", "fra", "fre", "French"),
492 ("de", "deu", "ger", "German"),
493 ("es", "spa", "spa", "Spanish"),
494 ("it", "ita", "ita", "Italian"),
495 ("pt", "por", "por", "Portuguese"),
496 ("nl", "nld", "dut", "Dutch"),
497 ("sv", "swe", "swe", "Swedish"),
498 ("da", "dan", "dan", "Danish"),
499 ("nb", "nob", "nob", "Norwegian"),
500 ("fi", "fin", "fin", "Finnish"),
501 ("pl", "pol", "pol", "Polish"),
502 ("cs", "ces", "cze", "Czech"),
503 ("sk", "slk", "slo", "Slovak"),
504 ("hu", "hun", "hun", "Hungarian"),
505 ("ro", "ron", "rum", "Romanian"),
506 ("bg", "bul", "bul", "Bulgarian"),
507 ("el", "ell", "gre", "Greek"),
508 ("tr", "tur", "tur", "Turkish"),
509 ("ru", "rus", "rus", "Russian"),
510 ("uk", "ukr", "ukr", "Ukrainian"),
511 ("ar", "ara", "ara", "Arabic"),
512 ("he", "heb", "heb", "Hebrew"),
513 ("hi", "hin", "hin", "Hindi"),
514 ("ja", "jpn", "jpn", "Japanese"),
515 ("ko", "kor", "kor", "Korean"),
516 ("zh", "zho", "chi", "Chinese"),
517 ("th", "tha", "tha", "Thai"),
518 ("vi", "vie", "vie", "Vietnamese"),
519 ("id", "ind", "ind", "Indonesian"),
520 ("ms", "msa", "may", "Malay"),
521 ("fa", "fas", "per", "Persian"),
522 ("ca", "cat", "cat", "Catalan"),
523 ("hr", "hrv", "hrv", "Croatian"),
524 ("sr", "srp", "srp", "Serbian"),
525 ("sl", "slv", "slv", "Slovenian"),
526 ("et", "est", "est", "Estonian"),
527 ("lv", "lav", "lav", "Latvian"),
528 ("lt", "lit", "lit", "Lithuanian"),
529];
530
531/// The ISO 639-2 code a file name's language token names, when it names one
532/// (`fr` and `fra` are both French, `fre` is French too).
533fn code_of_token(token: &str) -> Option<&'static str> {
534 let token = token.to_ascii_lowercase();
535 LANGUAGES
536 .iter()
537 .find(|(two, three, bib, _)| match token.len() {
538 2 => *two == token,
539 3 => *three == token || *bib == token,
540 _ => false,
541 })
542 .map(|(_, three, _, _)| *three)
543}
544
545/// The language a subtitle file's name says it is, as the ISO 639-2 code an
546/// import sets: the last token of the name that is a language (`talk.fr.srt`,
547/// `talk.fra.srt`, `fra.srt`, `talk_en.srt`, `eng.srt` are French, French,
548/// French, English, English). `None` when no token of the name is one -- the
549/// track is then left unset, not guessed.
550pub fn guess_language(path: &Path) -> Option<&'static str> {
551 let stem = path.file_stem()?.to_str()?;
552 stem.rsplit(['.', '_', '-', ' '])
553 .find_map(code_of_token)
554}
555
556/// The ISO 639-2 code a person typed for a language: a 639-1 two-letter code
557/// (`fr`), an English name (`French`), or a three-letter code as it is written
558/// (`fra`, `und`), which is taken as it is. `None` for anything else.
559pub fn language_code(input: &str) -> Option<String> {
560 let input = input.trim().to_ascii_lowercase();
561 match input.len() {
562 2 => LANGUAGES
563 .iter()
564 .find(|(two, _, _, _)| *two == input)
565 .map(|(_, three, _, _)| three.to_string()),
566 3 if input.bytes().all(|b| b.is_ascii_lowercase()) => {
567 Some(code_of_token(&input).map_or_else(|| input.clone(), str::to_string))
568 }
569 _ => LANGUAGES
570 .iter()
571 .find(|(_, _, _, name)| name.eq_ignore_ascii_case(&input))
572 .map(|(_, three, _, _)| three.to_string()),
573 }
574}
575
576/// The English name of an ISO 639-2 code, as an export titles its track
577/// (`fra` is `French`). `None` for a code the list does not name.
578pub fn language_name(code: &str) -> Option<&'static str> {
579 let code = code.to_ascii_lowercase();
580 LANGUAGES
581 .iter()
582 .find(|(_, three, bib, _)| *three == code || *bib == code)
583 .map(|(_, _, _, name)| *name)
584}
585
586/// The language an import gives a track: the `lang` a person typed, or else the
587/// one the file name says, with where it came from for the reply (`as given`,
588/// `from the file name`). `None` when neither names one. Refused, with the words
589/// to say so, for a `lang` that is not a language.
590pub fn import_language(path: &Path, lang: Option<&str>) -> Result<Option<(String, &'static str)>, String> {
591 match lang {
592 Some(raw) => language_code(raw)
593 .map(|code| Some((code, "as given")))
594 .ok_or_else(|| format!("`{raw}` is not a language: give its code (fra or fr) or its English name (French)")),
595 None => Ok(guess_language(path).map(|code| (code.to_string(), "from the file name"))),
596 }
597}
598
599/// Names the language of `track` (an ISO 639-2 code, or empty for unset) and
600/// keeps its row's label in step: an embedded track's label shows its language,
601/// and a standalone file's label is its file name, which does not change.
602pub fn set_language(track: &mut SubtitleTrack, code: &str) {
603 track.language = code.to_string();
604 if track.track.is_some() && track.refused.is_none() {
605 track.label = label_of(&track.language, &track.name);
606 }
607}
608
609/// Every subtitle track *inside* a media file, whichever container it is: a
610/// Matroska's ([`of_matroska`]) or an mp4's timed text ([`of_mp4`]).
611///
612/// The one door for it, so a project row, an import and an export's read-back
613/// cannot disagree about what a file carries -- and so an mp4 this project
614/// wrote comes back into it, which is the whole reason the mp4 reader exists:
615/// mp4 is the default export format, and a file edith writes and cannot open
616/// is not a round trip.
617pub fn of_media(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
618 of_media_with(path, true)
619}
620
621/// [`of_media`], with the embedded closed captions ([`of_captions`]) listed after the container's
622/// own tracks only when `captions` says so: they cost a read of every picture packet, so a
623/// project re-open asks for them only for a file that has a caption row.
624fn of_media_with(path: &Path, captions: bool) -> crate::Result<Vec<SubtitleTrack>> {
625 let mut tracks = match crate::demux::is_matroska(path) {
626 true => of_matroska(path),
627 false if crate::demux::is_mpeg_system(path) => of_mpegts(path),
628 false => of_mp4(path),
629 }?;
630 if captions {
631 tracks.extend(of_captions(path));
632 }
633 Ok(tracks)
634}
635
636/// The CEA-608 (CC1-CC4) and CEA-708 (service 1) captions carried inside the picture of `path`
637/// (H.264/HEVC SEI, MPEG-2 user data), one track per channel that has cues, named `CC1 (608)` or
638/// `Service 1 (708)`. Timed on the picture's own clock. Found by one cached read of every
639/// picture packet ([`crate::demux::captions`]); empty for a file without captions.
640pub fn of_captions(path: &Path) -> Vec<SubtitleTrack> {
641 crate::demux::captions::tracks(path)
642 .iter()
643 .map(|t| SubtitleTrack {
644 path: path.to_path_buf(),
645 track: Some(t.number),
646 language: "und".to_string(),
647 name: t.name.clone(),
648 label: label_of("und", &t.name),
649 cues: t
650 .cues
651 .iter()
652 .map(|c| Cue {
653 start_us: c.cue.start_us,
654 end_us: c.cue.end_us,
655 text: plain_text(&c.cue.segments),
656 image: None,
657 words: Vec::new(),
658 karaoke: Vec::new(),
659 })
660 .collect(),
661 bitmap: false,
662 refused: None,
663 })
664 .collect()
665}
666
667/// Every PGS subtitle track of an MPEG transport stream (an AVCHD or Blu-ray `.m2ts`), in
668/// PMT order: the same display sets a Matroska file carries, so they are read the same way
669/// ([`pgs_cues`]). `track` is the demuxer's stream index.
670pub fn of_mpegts(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
671 Ok(crate::demux::ts::subtitles(path)?
672 .into_iter()
673 .map(|mut t| {
674 let label = label_of(&t.language, &t.name);
675 let cues = match t.codec.as_str() {
676 crate::demux::VOBSUB => dvd_cues(&mut t),
677 crate::demux::DVBSUB => dvb_cues(&mut t),
678 _ => pgs_cues(&mut t),
679 };
680 SubtitleTrack {
681 path: path.to_path_buf(),
682 track: Some(t.number),
683 language: t.language,
684 name: t.name,
685 label,
686 cues,
687 bitmap: true,
688 refused: None,
689 }
690 })
691 .collect())
692}
693
694/// Every timed-text (`tx3g`) subtitle track of an mp4, in track order, with its
695/// cues -- the mp4 twin of [`of_matroska`].
696///
697/// A `tx3g` track is *continuous*: it states one sample per instant of the film
698/// and the stretches with nothing on screen are samples of no text, so those are
699/// dropped here rather than kept as cues with an empty line
700/// ([`crate::demux::Mp4TextSample::payload`]). What is left is the cues, timed
701/// on the file's own clock, and a track whose samples are all empty comes back
702/// with none rather than with one per instant.
703///
704/// Never a bitmap: an mp4 carries no PGS track this reads, so the refusal
705/// [`of_matroska`] has for one has no counterpart here.
706pub fn of_mp4(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
707 Ok(crate::demux::mp4_subtitles(path)?
708 .into_iter()
709 .map(|t| SubtitleTrack {
710 path: path.to_path_buf(),
711 track: Some(t.number),
712 label: label_of(&t.language, &t.name),
713 language: t.language,
714 name: t.name,
715 cues: t.samples.iter().filter_map(tx3g_cue).collect(),
716 bitmap: false,
717 refused: None,
718 })
719 .collect())
720}
721
722/// One `tx3g` sample as a cue, or `None` for the sample that is not one: the
723/// empty one that says nothing is on screen between here and the next line, and
724/// the truncated one whose declared length runs past its own bytes.
725fn tx3g_cue(sample: &crate::demux::Mp4TextSample) -> Option<Cue> {
726 let len = usize::from(u16::from_be_bytes([
727 *sample.payload.first()?,
728 *sample.payload.get(1)?,
729 ]));
730 let text = String::from_utf8_lossy(sample.payload.get(2..2 + len)?);
731 (!text.is_empty()).then(|| Cue {
732 start_us: sample.start_us,
733 end_us: sample.end_us,
734 text: text.into_owned(),
735 image: None,
736 words: Vec::new(),
737 karaoke: Vec::new(),
738 })
739}
740
741/// What a list row shows for a track a container declares: the language, the
742/// muxer's title, or the pair.
743///
744/// A row shows one string, so the two are flattened for it -- and *only* for it.
745/// Both are kept on the track beside this
746/// ([`SubtitleTrack::language`], [`SubtitleTrack::name`]), so an export writes
747/// the container's own two fields rather than guessing them back out of this
748/// string, which is what used to leave every French track marked English.
749fn label_of(language: &str, name: &str) -> String {
750 match (name.is_empty(), language) {
751 (true, lang) => lang.to_owned(),
752 (false, "und") => name.to_owned(),
753 (false, lang) => format!("{lang} — {name}"),
754 }
755}
756
757/// Every subtitle track of a Matroska file, in file order -- the text ones with
758/// their cues, the bitmap ones refused by name (see the module docs).
759pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
760 Ok(crate::demux::matroska_subtitles(path)?
761 .into_iter()
762 .map(|mut t| {
763 let label = label_of(&t.language, &t.name);
764 let bitmap = matches!(t.codec.as_str(), crate::demux::PGS | crate::demux::VOBSUB | crate::demux::DVBSUB);
765 match cues_of(&mut t) {
766 Ok(cues) => SubtitleTrack {
767 path: path.to_path_buf(),
768 track: Some(t.number),
769 language: t.language,
770 name: t.name,
771 label,
772 cues,
773 bitmap,
774 refused: None,
775 },
776 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),
777 }
778 })
779 .collect())
780}
781
782/// The cues of one Matroska subtitle track, or why it has none.
783///
784/// A Matroska text track carries the *timing* on the block and the *text* in
785/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is
786/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block
787/// with the `Start` and `End` fields cut out and the `[Script Info]` header
788/// filed away in `CodecPrivate`. Both are put back into the shape their parser
789/// reads -- rather than the markup being re-derived here -- which is also what
790/// makes an embedded track and the standalone file it was muxed from come back
791/// as the same cues.
792///
793/// A PGS track is neither: its blocks are pictures, and they are moved out of
794/// `track` rather than copied ([`pgs_cues`]) -- thirty megabytes a track is not
795/// a thing to hold twice.
796fn cues_of(track: &mut crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
797 // A track compressed or encrypted with something the demuxer cannot undo is
798 // refused in those words: the row stays, and it says why.
799 if let Some(why) = &track.unsupported {
800 return Err(why.clone());
801 }
802 let cues = match track.codec.as_str() {
803 "S_TEXT/UTF8" | "S_TEXT/ASCII" => text_cues(track, srt_body),
804 // WebVTT in Matroska is `D_WEBVTT/<kind>` (ffmpeg and mkvmerge both
805 // write it so); the older `S_TEXT/WEBVTT` is the same payload.
806 "D_WEBVTT/SUBTITLES"
807 | "D_WEBVTT/CAPTIONS"
808 | "D_WEBVTT/DESCRIPTIONS"
809 | "D_WEBVTT/METADATA"
810 | "S_TEXT/WEBVTT" => text_cues(track, webvtt_body),
811 "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?,
812 crate::demux::PGS => pgs_cues(track),
813 crate::demux::VOBSUB => dvd_cues(track),
814 crate::demux::DVBSUB => dvb_cues(track),
815 codec => {
816 return Err(format!(
817 "{codec} subtitles are pictures, not text — this track is listed, not read"
818 ));
819 }
820 };
821 Ok(cues)
822}
823
824/// The cues of an `S_HDMV/PGS` track: one display set per block, and a display
825/// set is a picture the disc composes onto its own canvas.
826///
827/// Only the blocks that compose *something* are cues. The other half of them
828/// are the disc's "take it off again" -- a composition with no object on it --
829/// and they are what says when the picture before them goes away, which is why
830/// they are walked and not skipped. A muxer writes `BlockDuration` zero for all
831/// of them, so [`end_of`] is what pairs the two.
832fn pgs_cues(track: &mut crate::demux::MkvSubtitle) -> Vec<Cue> {
833 // Before the blocks are emptied: `end_of` reads the ones after this one.
834 let ends: Vec<i64> = track.cues.iter().map(|c| end_of(track, c)).collect();
835 track
836 .cues
837 .iter_mut()
838 .zip(ends)
839 .filter_map(|(block, end_us)| {
840 let (width, height) = pgs_canvas(&block.payload)?;
841 Some(Cue {
842 start_us: block.start_us,
843 end_us,
844 text: String::new(),
845 words: Vec::new(),
846 karaoke: Vec::new(),
847 image: Some(Arc::new(CueImage {
848 width,
849 height,
850 set: Source::Pgs(std::mem::take(&mut block.payload)),
851 })),
852 })
853 })
854 .collect()
855}
856
857/// How long a bitmap cue with no stated end stays up: two seconds.
858const NO_END_US: i64 = 2_000_000;
859
860/// Gives every cue whose end is unstated the start of the next cue (or two seconds
861/// for the last), and never lets a stated end run past the next cue's start.
862fn settle(spans: &mut [(i64, Option<i64>)]) {
863 for i in 0..spans.len() {
864 let next = spans.get(i + 1).map(|n| n.0);
865 let (start, end) = spans[i];
866 let end = match (end, next) {
867 (Some(e), Some(n)) => e.min(n.max(start)),
868 (Some(e), None) => e,
869 (None, Some(n)) => n,
870 (None, None) => start + NO_END_US,
871 };
872 spans[i].1 = Some(end);
873 }
874}
875
876/// The cues of an `S_VOBSUB` track (or a `.idx`/`.sub` pair): one subpicture unit per
877/// block, which carries its own delay and end after the block's time. The `.idx` text
878/// is the palette and canvas.
879fn dvd_cues(track: &mut crate::demux::MkvSubtitle) -> Vec<Cue> {
880 let units = std::mem::take(&mut track.cues)
881 .into_iter()
882 .map(|b| (b.start_us, b.duration_us.filter(|&d| d > 0), b.payload))
883 .collect();
884 dvd_units(units, std::mem::take(&mut track.private))
885}
886
887/// [`dvd_cues`] on `(time in microseconds, stated duration, unit)` triples.
888fn dvd_units(units: Vec<(i64, Option<i64>, Vec<u8>)>, idx: Vec<u8>) -> Vec<Cue> {
889 let parsed = ec_dvdsub::parse_idx(&idx);
890 let palette = parsed.palette.unwrap_or(ec_dvdsub::DEFAULT_PALETTE);
891 let canvas = parsed.size.unwrap_or((720, 576));
892 let idx = Arc::new(idx);
893 let us = |t: i64| t * 1_000_000 / 90_000;
894 let mut spans = Vec::new();
895 let mut made = Vec::new();
896 for (at, duration, unit) in units {
897 let Ok(cue) = ec_dvdsub::decode_spu(&unit, &palette, canvas) else {
898 continue;
899 };
900 let start = at + us(cue.start_90k);
901 let end = cue.end_90k.map(|e| at + us(e)).or(duration.map(|d| at + d));
902 spans.push((start, end));
903 made.push((cue.frame.width, cue.frame.height, unit));
904 }
905 settle(&mut spans);
906 spans
907 .into_iter()
908 .zip(made)
909 .map(|((start_us, end), (width, height, unit))| Cue {
910 start_us,
911 end_us: end.unwrap_or(start_us + NO_END_US),
912 text: String::new(),
913 words: Vec::new(),
914 karaoke: Vec::new(),
915 image: Some(Arc::new(CueImage {
916 width,
917 height,
918 set: Source::Dvd { idx: idx.clone(), unit },
919 })),
920 })
921 .collect()
922}
923
924/// The cues of an `S_DVBSUB` track (or a transport stream's DVB PID): one display set
925/// per block. A set with no regions is the clear that ends the one before it; a set
926/// states how long it stays up (`timeout`), cut short by the next set.
927fn dvb_cues(track: &mut crate::demux::MkvSubtitle) -> Vec<Cue> {
928 // (start, end, canvas, empty, set)
929 let mut sets = Vec::new();
930 for block in std::mem::take(&mut track.cues) {
931 let mut decoder = ec_dvbsub::DvbSubDecoder::new();
932 let _ = decoder.push_pes(&block.payload);
933 let Some(cue) = decoder.take_cue() else {
934 continue;
935 };
936 let stated = block
937 .duration_us
938 .filter(|&d| d > 0)
939 .or((cue.timeout_ms > 0).then(|| i64::from(cue.timeout_ms) * 1000));
940 sets.push((
941 block.start_us,
942 stated.map(|d| block.start_us + d),
943 (cue.frame.width, cue.frame.height),
944 cue.empty,
945 block.payload,
946 ));
947 }
948 let mut spans: Vec<(i64, Option<i64>)> = sets.iter().map(|s| (s.0, s.1)).collect();
949 settle(&mut spans);
950 spans
951 .into_iter()
952 .zip(sets)
953 .filter(|(_, s)| !s.3)
954 .map(|((start_us, end), (_, _, (width, height), _, set))| Cue {
955 start_us,
956 end_us: end.unwrap_or(start_us + NO_END_US),
957 text: String::new(),
958 words: Vec::new(),
959 karaoke: Vec::new(),
960 image: Some(Arc::new(CueImage {
961 width,
962 height,
963 set: Source::Dvb(set),
964 })),
965 })
966 .collect()
967}
968
969/// The canvas of a display set that paints something -- its `PCS` says how big
970/// the disc's picture is, and how many objects are composed onto it.
971///
972/// `None` when nothing is composed, which is the disc clearing the screen, and
973/// `None` for bytes that are not a display set at all.
974fn pgs_canvas(set: &[u8]) -> Option<(u32, u32)> {
975 /// `PresentationCompositionSegment`, which every display set opens with.
976 const PCS: u8 = 0x16;
977 let (_, pcs) = segments(set)?.into_iter().find(|&(kind, _)| kind == PCS)?;
978 // Width and height, then the frame rate, the composition number and state,
979 // the palette-update flag and the palette id -- and then how many objects
980 // this composition puts on the canvas.
981 let width = u16::from_be_bytes([*pcs.first()?, *pcs.get(1)?]);
982 let height = u16::from_be_bytes([*pcs.get(2)?, *pcs.get(3)?]);
983 (*pcs.get(10)? > 0).then_some((u32::from(width), u32::from(height)))
984}
985
986/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes
987/// none, and for the PGS block that writes a zero, which says the same thing --
988/// when the next one arrives, and [`NO_DURATION_US`] for the last.
989fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 {
990 /// How long a cue with nothing to say about it stays up: two seconds, a
991 /// read of one line.
992 const NO_DURATION_US: i64 = 2_000_000;
993 match cue.duration_us.filter(|&d| d > 0) {
994 Some(d) => cue.start_us + d,
995 None => track
996 .cues
997 .iter()
998 .map(|c| c.start_us)
999 .find(|&s| s > cue.start_us)
1000 .unwrap_or(cue.start_us + NO_DURATION_US),
1001 }
1002}
1003
1004/// The cues of a Matroska text track whose blocks are one cue body each: the
1005/// timing is the block's, and `body` resolves the markup of one block's text.
1006fn text_cues(
1007 track: &crate::demux::MkvSubtitle,
1008 body: fn(&str) -> String,
1009) -> Vec<Cue> {
1010 track
1011 .cues
1012 .iter()
1013 .map(|c| Cue {
1014 start_us: c.start_us,
1015 end_us: end_of(track, c),
1016 text: body(&String::from_utf8_lossy(&c.payload)),
1017 image: None,
1018 words: Vec::new(),
1019 karaoke: Vec::new(),
1020 })
1021 .collect()
1022}
1023
1024/// The text of one WebVTT block with its markup resolved: the WebVTT parser
1025/// reads a one-cue file built around it, the same way [`srt_body`] does for an
1026/// SRT block. The block's own timing wins, so the timing line here is a
1027/// placeholder that is thrown away.
1028fn webvtt_body(text: &str) -> String {
1029 // The block's bytes can open with blank lines (the cue identifier slot), and
1030 // a blank line would end the timing block before the text.
1031 let doc = format!(
1032 "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\n{}\n",
1033 text.trim_matches(['\n', '\r']).trim_end()
1034 );
1035 match ec_subs::webvtt::parse(doc.as_bytes()) {
1036 Ok(track) => track
1037 .cues
1038 .first()
1039 .map(|c| plain_text(&c.segments))
1040 .unwrap_or_default(),
1041 Err(_) => text.trim_end().to_owned(),
1042 }
1043}
1044
1045/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the
1046/// SRT parser, around a timing line this then throws away, because SRT markup
1047/// is exactly what such a block holds and a second implementation of it here
1048/// would be a second set of bugs.
1049fn srt_body(text: &str) -> String {
1050 let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end());
1051 match ec_subs::srt::parse(doc.as_bytes()) {
1052 Ok(track) => track
1053 .cues
1054 .first()
1055 .map(|c| plain_text(&c.segments))
1056 .unwrap_or_default(),
1057 // The parser refuses nothing an SRT body can hold; if it ever does,
1058 // the bytes themselves are a better answer than an empty cue.
1059 Err(_) => text.trim_end().to_owned(),
1060 }
1061}
1062
1063/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate`
1064/// with every block put back as a `Dialogue` line under it, parsed once as the
1065/// `.ass` file it came from.
1066fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
1067 let mut doc = String::from_utf8_lossy(&track.private).into_owned();
1068 if !doc.ends_with('\n') {
1069 doc.push('\n');
1070 }
1071 for cue in &track.cues {
1072 let fields = String::from_utf8_lossy(&cue.payload);
1073 // `ReadOrder,Layer,<the Format fields from Style on>`: the two the
1074 // block adds go, and the timing the block *is* takes their place. The
1075 // field order is the one the header's `Format:` line declares, which
1076 // is the order a demuxer strips them out of.
1077 let mut rest = fields.trim_end().splitn(3, ',');
1078 let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) {
1079 (Some(r), Some(l), Some(t)) => (r, l, t),
1080 _ => continue,
1081 };
1082 doc.push_str(&format!(
1083 "Dialogue: {layer},{},{},{rest}\n",
1084 timestamp(cue.start_us),
1085 timestamp(end_of(track, cue))
1086 ));
1087 }
1088 let parsed = ec_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?;
1089 // The timings above are centiseconds, which is all an ASS line can say;
1090 // the blocks are microseconds. So the text comes from the parse and the
1091 // timing from the block -- unless a line was dropped as unparsable, when
1092 // the pairing is no longer sound and the parse answers for both.
1093 let exact = parsed.cues.len() == track.cues.len();
1094 Ok(parsed
1095 .cues
1096 .iter()
1097 .enumerate()
1098 .map(|(i, c)| {
1099 let start_us = if exact { track.cues[i].start_us } else { c.start_us };
1100 // The syllables are timed from the line's own start, which the block may differ from.
1101 let mut karaoke = syllables(c, &parsed);
1102 for s in &mut karaoke {
1103 s.start_us += start_us - c.start_us;
1104 s.end_us += start_us - c.start_us;
1105 }
1106 Cue {
1107 start_us,
1108 end_us: if exact {
1109 end_of(track, &track.cues[i])
1110 } else {
1111 c.end_us
1112 },
1113 text: plain_text(&c.segments),
1114 image: None,
1115 words: Vec::new(),
1116 karaoke,
1117 }
1118 })
1119 .collect())
1120}
1121
1122/// Microseconds as ASS writes a time: `H:MM:SS.cc`.
1123fn timestamp(us: i64) -> String {
1124 let cs = (us.max(0) + 5_000) / 10_000;
1125 format!(
1126 "{}:{:02}:{:02}.{:02}",
1127 cs / 360_000,
1128 cs / 6_000 % 60,
1129 cs / 100 % 60,
1130 cs % 100
1131 )
1132}
1133
1134/// A standalone subtitle file, by extension: the formats this engine reads at
1135/// all. Anything else is refused by name, as an unknown media file is.
1136fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> {
1137 Ok(read_file(path)?.0)
1138}
1139
1140/// The cues of a VobSub pair: `name.idx` (palette, canvas) beside `name.sub` (the
1141/// subpicture units in an MPEG program stream). Either file may be the one named.
1142fn vobsub_file_cues(path: &Path) -> crate::Result<Vec<Cue>> {
1143 let (idx_path, sub_path) = (path.with_extension("idx"), path.with_extension("sub"));
1144 let (Ok(idx), Ok(sub)) = (std::fs::read(&idx_path), std::fs::read(&sub_path)) else {
1145 return Err(format!(
1146 "a VobSub subtitle is a pair, {} and {}, and one of them is missing or unreadable",
1147 idx_path.display(),
1148 sub_path.display()
1149 )
1150 .into());
1151 };
1152 // The first subpicture stream of the program (substream 0x20); `stream` is its index.
1153 let units = ec_dvdsub::sub_file_units(&sub, 0)
1154 .into_iter()
1155 .map(|(unit, pts_90k)| (pts_90k * 1_000_000 / 90_000, None, unit))
1156 .collect();
1157 let cues = dvd_units(units, idx);
1158 if cues.is_empty() {
1159 return Err(format!("no subtitle pictures in {}", sub_path.display()).into());
1160 }
1161 Ok(cues)
1162}
1163
1164/// The lines of a text subtitle file that were not imported, each with its
1165/// line number and why (`line 34: end before start`). Empty for a file that
1166/// read whole, and for an ASS script, whose cues have no such lines to skip.
1167pub fn skipped_cues(path: &Path) -> Vec<String> {
1168 read_file(path).map(|(_, skipped)| skipped).unwrap_or_default()
1169}
1170
1171/// The cues of a text subtitle file, and the timing lines that were not made
1172/// into one. See [`timing_lines`] for why the file is read twice.
1173fn read_file(path: &Path) -> crate::Result<(Vec<Cue>, Vec<String>)> {
1174 let ext = path
1175 .extension()
1176 .map(|e| e.to_string_lossy().to_ascii_lowercase())
1177 .unwrap_or_default();
1178 if matches!(ext.as_str(), "idx" | "sub") {
1179 return Ok((vobsub_file_cues(path)?, Vec::new()));
1180 }
1181 // The extension before the read: a `.txt` is refused for what it is, not
1182 // for whether it happens to be there.
1183 type Parse = fn(&[u8]) -> ec_core::Result<ec_subs::SubtitleTrack>;
1184 let parse: Parse = match ext.as_str() {
1185 "srt" => ec_subs::srt::parse,
1186 "vtt" | "webvtt" => ec_subs::webvtt::parse,
1187 "ass" | "ssa" => ec_ass::parse,
1188 other => {
1189 // What is *genuinely* accepted, all of it: the subtitle files this
1190 // parses and the containers [`of_media`] walks for the tracks
1191 // inside them (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`, `.mp4`,
1192 // `.m4v`, `.mov`). The old sentence named the four text formats
1193 // alone and so refused a `.mks` this very binary reads.
1194 return Err(format!(
1195 "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are, \
1196 as are the subtitle tracks inside a Matroska or an mp4"
1197 )
1198 .into());
1199 }
1200 };
1201 let vtt = matches!(ext.as_str(), "vtt" | "webvtt");
1202 let ass = matches!(ext.as_str(), "ass" | "ssa");
1203 let bytes = std::fs::read(path)?;
1204 let marked;
1205 let input: &[u8] = if ass {
1206 &bytes
1207 } else {
1208 marked = mark_breaks(&bytes);
1209 &marked
1210 };
1211 let track = parse(input);
1212 let track = track.map_err(|e| format!("{}: {e}", path.display()))?;
1213 let cue_of = |c: &ec_subs::SubtitleCue| {
1214 // ec-subs strips the markup and resolves the character references in
1215 // one pass, so a `&lt;` written in a WebVTT file is text, not a tag,
1216 // and is not decoded a second time here.
1217 let text = plain_text(&c.segments).replace(char::from(BREAK_MARK), "\n");
1218 Cue {
1219 start_us: c.start_us,
1220 end_us: c.end_us,
1221 text,
1222 image: None,
1223 words: Vec::new(),
1224 karaoke: syllables(c, &track),
1225 }
1226 };
1227 if ass {
1228 return Ok((track.cues.iter().map(cue_of).collect(), Vec::new()));
1229 }
1230 // The parser keeps a cue whose end is before its start and drops one whose
1231 // timing it cannot read, both without a word. Each timing line is matched
1232 // to the parser's next cue: a line it is a cue for is kept or, if its
1233 // timing is wrong, named as skipped; a line with no cue is named too.
1234 let text = String::from_utf8_lossy(&bytes);
1235 let text = text.trim_start_matches('\u{feff}');
1236 let mut kept = Vec::new();
1237 let mut skipped = Vec::new();
1238 let mut next = 0;
1239 for line in timing_lines(text, vtt) {
1240 let matched = match (line.span, track.cues.get(next)) {
1241 // ec-subs clamps a backwards pair to a zero-length cue, so the
1242 // cue to match is the clamped one; the line is still skipped.
1243 (Some((s, e)), Some(c)) if (c.start_us, c.end_us) == (s, e.max(s)) => {
1244 next += 1;
1245 true
1246 }
1247 _ => false,
1248 };
1249 match line.why {
1250 Some(why) => skipped.push(format!("line {}: {why}", line.line)),
1251 None if matched => kept.push(cue_of(&track.cues[next - 1])),
1252 None => skipped.push(format!("line {}: the parser did not read this cue", line.line)),
1253 }
1254 }
1255 // A cue no timing line claimed is kept as the parser gave it.
1256 kept.extend(track.cues[next..].iter().map(cue_of));
1257 kept.sort_by_key(|c| c.start_us);
1258 Ok((kept, skipped))
1259}
1260
1261/// The byte a `<br>` line break is marked with on its way through the parser,
1262/// which drops the tag and the break with it. A control character, so no cue's
1263/// own text carries one; `cue_of` turns it back into a newline.
1264const BREAK_MARK: u8 = 0x01;
1265
1266/// The file's bytes with each `<br>`, `<br/>` or `<br />` replaced by
1267/// [`BREAK_MARK`]. A byte-level pass, so a timing line is untouched and its
1268/// line number still counts.
1269fn mark_breaks(bytes: &[u8]) -> Vec<u8> {
1270 let mut out = Vec::with_capacity(bytes.len());
1271 let mut at = 0;
1272 while at < bytes.len() {
1273 if bytes[at] == b'<' {
1274 // The tag's own name, with its case, spaces and slash set aside.
1275 if let Some(close) = bytes[at..].iter().take(9).position(|&b| b == b'>') {
1276 let name: Vec<u8> = bytes[at + 1..at + close]
1277 .iter()
1278 .filter(|b| !b.is_ascii_whitespace() && **b != b'/')
1279 .map(u8::to_ascii_lowercase)
1280 .collect();
1281 if name == b"br" {
1282 out.push(BREAK_MARK);
1283 at += close + 1;
1284 continue;
1285 }
1286 }
1287 }
1288 out.push(bytes[at]);
1289 at += 1;
1290 }
1291 out
1292}
1293
1294/// One timing line of a text subtitle file, `start --> end`: where it is, and
1295/// either the span it gives or why it gives none.
1296struct TimingLine {
1297 /// Its number in the file, from 1.
1298 line: usize,
1299 /// Its start and end in microseconds, when both are timestamps.
1300 span: Option<(i64, i64)>,
1301 /// Why the cue it begins is not imported, when it is not: an end before
1302 /// its start, or a time that is not one.
1303 why: Option<String>,
1304}
1305
1306/// Every timing line of an SRT or WebVTT text, and every cue block that has
1307/// none, in file order. The parser reads the same lines itself, but drops a cue
1308/// it cannot time without a word and keeps one that runs backwards, so the reply
1309/// needs them read again here.
1310///
1311/// A line counts when its left side is a time-like run (a digit, then a `:`),
1312/// so a cue whose words happen to hold an arrow is not one. A time-like pair
1313/// with a wrong arrow (`->`) is named too, and so is a block that opens like a
1314/// cue (see below) and holds no timing line at all.
1315fn timing_lines(text: &str, vtt: bool) -> Vec<TimingLine> {
1316 // The blocks of the file: what runs between blank lines, each with the
1317 // number and text of its lines.
1318 let mut blocks: Vec<Vec<(usize, &str)>> = vec![Vec::new()];
1319 for (at, line) in text.lines().enumerate() {
1320 if line.trim().is_empty() {
1321 blocks.push(Vec::new());
1322 } else if let Some(block) = blocks.last_mut() {
1323 block.push((at + 1, line));
1324 }
1325 }
1326 let mut out = Vec::new();
1327 for block in blocks.iter().filter(|b| !b.is_empty()) {
1328 let mut timed = false;
1329 for &(n, line) in block {
1330 if let Some(t) = cue_timing(n, line) {
1331 timed = true;
1332 out.push(t);
1333 } else if !line.contains("-->") && is_bad_arrow(line) {
1334 timed = true;
1335 let why = "timing arrow must be -->".to_string();
1336 out.push(TimingLine { line: n, span: None, why: Some(why) });
1337 }
1338 }
1339 // A block that opens like a cue but has no timing line is named by its
1340 // first line. In SRT that is an index number; in WebVTT, any block that
1341 // is not the header, a NOTE, a STYLE or a REGION.
1342 let (first_no, first) = block[0];
1343 let first = first.trim();
1344 let opens = if vtt {
1345 !matches!(first.split_whitespace().next(), Some("WEBVTT" | "NOTE" | "STYLE" | "REGION"))
1346 } else {
1347 first.bytes().all(|b| b.is_ascii_digit())
1348 };
1349 if !timed && opens {
1350 let why = "cue has no timing line".to_string();
1351 out.push(TimingLine { line: first_no, span: None, why: Some(why) });
1352 }
1353 }
1354 out.sort_by_key(|t| t.line);
1355 out
1356}
1357
1358/// The timing line on one line of text, when it is one: `start --> end`, with
1359/// a time-like start. `None` for any other line.
1360fn cue_timing(line_no: usize, line: &str) -> Option<TimingLine> {
1361 let (start, rest) = line.split_once("-->")?;
1362 let start = start.trim();
1363 if !start.starts_with(|c: char| c.is_ascii_digit()) || !start.contains(':') {
1364 return None;
1365 }
1366 // A WebVTT cue setting (`align:start`) follows the end time.
1367 let end = rest.split_whitespace().next().unwrap_or("");
1368 let (from, to) = (clock_us(start), clock_us(end));
1369 let (span, why) = match (from, to) {
1370 (Some(s), Some(e)) if e < s => (Some((s, e)), Some("end before start".to_string())),
1371 (Some(s), Some(e)) if e == s => {
1372 (Some((s, e)), Some("start and end are the same time".to_string()))
1373 }
1374 (Some(s), Some(e)) => (Some((s, e)), None),
1375 (None, _) => (None, Some(format!("start time `{start}` is not a timestamp"))),
1376 (Some(_), None) => (None, Some(format!("end time `{end}` is not a timestamp"))),
1377 };
1378 Some(TimingLine { line: line_no, span, why })
1379}
1380
1381/// Whether a line without `-->` reads as a timing line with a wrong arrow: a
1382/// time-like run, then one or more dashes and a `>`, then a time-like run
1383/// (`00:00:02,000 -> 00:00:03,000`).
1384fn is_bad_arrow(line: &str) -> bool {
1385 let Some(gt) = line.find('>') else {
1386 return false;
1387 };
1388 let before = &line[..gt];
1389 let head = before.trim_end_matches('-');
1390 if head.len() == before.len() {
1391 return false;
1392 }
1393 let (start, end) = (head.trim(), &line[gt + 1..]);
1394 start.starts_with(|c: char| c.is_ascii_digit()) && start.contains(':') && end.contains(':')
1395}
1396
1397/// A subtitle timestamp, `[H:]MM:SS` then `.` or `,` and up to three digits of
1398/// fraction, as microseconds. `None` for anything else, including minutes or
1399/// seconds of sixty and more.
1400fn clock_us(text: &str) -> Option<i64> {
1401 let (hms, frac) = text.split_once(['.', ','])?;
1402 if frac.is_empty() || frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
1403 return None;
1404 }
1405 let parts: Vec<&str> = hms.split(':').collect();
1406 if !(2..=3).contains(&parts.len()) {
1407 return None;
1408 }
1409 let mut secs: i64 = 0;
1410 for (k, part) in parts.iter().enumerate() {
1411 if part.is_empty() || part.len() > 9 || !part.bytes().all(|b| b.is_ascii_digit()) {
1412 return None;
1413 }
1414 let v: i64 = part.parse().ok()?;
1415 // Only the hours are unbounded; minutes and seconds are below sixty.
1416 if k > 0 && v >= 60 {
1417 return None;
1418 }
1419 secs = secs * 60 + v;
1420 }
1421 let millis: i64 = format!("{frac:0<3}").parse().ok()?;
1422 Some((secs * 1000 + millis) * 1000)
1423}
1424
1425/// One cue as a writer states it: whole milliseconds, and lines that are
1426/// neither empty nor carry a stray carriage return. Shared by [`write_srt`] and
1427/// [`write_vtt`] so the two cannot disagree about which cues exist.
1428///
1429/// Picture cues are dropped (a text file cannot carry them), as are cues with
1430/// no words and cues whose millisecond span is empty or negative once rounded.
1431/// Negative starts are clamped to zero; the result is sorted by start.
1432fn written_cues(cues: &[Cue]) -> Vec<(i64, i64, Vec<String>)> {
1433 let mut out: Vec<(i64, i64, Vec<String>)> = cues
1434 .iter()
1435 .filter(|c| c.image.is_none())
1436 .filter_map(|c| {
1437 let start = ms_of(c.start_us.max(0));
1438 let end = ms_of(c.end_us.max(0));
1439 if end <= start {
1440 return None;
1441 }
1442 let lines: Vec<String> = c
1443 .text
1444 .lines()
1445 .map(|l| l.trim_end().to_owned())
1446 .filter(|l| !l.is_empty())
1447 .collect();
1448 (!lines.is_empty()).then_some((start, end, lines))
1449 })
1450 .collect();
1451 out.sort_by_key(|&(start, end, _)| (start, end));
1452 out
1453}
1454
1455/// Microseconds to whole milliseconds, rounding half up. The input is never
1456/// negative here: [`written_cues`] clamps first.
1457fn ms_of(us: i64) -> i64 {
1458 (us + 500) / 1000
1459}
1460
1461/// `HH:MM:SS<sep>mmm`, where `sep` is `,` for SRT and `.` for WebVTT.
1462fn clock(ms: i64, sep: char) -> String {
1463 format!(
1464 "{:02}:{:02}:{:02}{sep}{:03}",
1465 ms / 3_600_000,
1466 ms / 60_000 % 60,
1467 ms / 1000 % 60,
1468 ms % 1000
1469 )
1470}
1471
1472/// The cues as a SubRip file: numbered from 1, in start order, `HH:MM:SS,mmm`
1473/// times, lines as the cue has them. SRT has no escaping, so the text goes out
1474/// as it is. Picture cues and empty cues are left out (see [`written_cues`]).
1475pub fn write_srt(cues: &[Cue]) -> String {
1476 let mut out = String::new();
1477 for (i, (start, end, lines)) in written_cues(cues).iter().enumerate() {
1478 out.push_str(&format!(
1479 "{}\n{} --> {}\n",
1480 i + 1,
1481 clock(*start, ','),
1482 clock(*end, ',')
1483 ));
1484 for line in lines {
1485 out.push_str(line);
1486 out.push('\n');
1487 }
1488 out.push('\n');
1489 }
1490 out
1491}
1492
1493/// The cues as a WebVTT file: the `WEBVTT` header, then numbered cues in start
1494/// order with `HH:MM:SS.mmm` times. Cue text is escaped as WebVTT reads it:
1495/// `&` becomes `&amp;`, `<` becomes `&lt;` and `>` becomes `&gt;`. Escaping `>`
1496/// is also what keeps a `-->` in the words from reading as a timing line.
1497/// Picture cues and empty cues are left out (see [`written_cues`]).
1498pub fn write_vtt(cues: &[Cue]) -> String {
1499 let mut out = String::from("WEBVTT\n\n");
1500 for (i, (start, end, lines)) in written_cues(cues).iter().enumerate() {
1501 out.push_str(&format!(
1502 "{}\n{} --> {}\n",
1503 i + 1,
1504 clock(*start, '.'),
1505 clock(*end, '.')
1506 ));
1507 for line in lines {
1508 out.push_str(&escape_vtt(line));
1509 out.push('\n');
1510 }
1511 out.push('\n');
1512 }
1513 out
1514}
1515
1516/// The three characters WebVTT cue text cannot carry as they are.
1517fn escape_vtt(text: &str) -> String {
1518 text.replace('&', "&amp;")
1519 .replace('<', "&lt;")
1520 .replace('>', "&gt;")
1521}
1522
1523/// Save cues to `path`, as SRT for `.srt` and WebVTT for `.vtt` (any case). The
1524/// extension is checked before anything is written, so a `.txt` is refused and
1525/// leaves nothing behind.
1526///
1527/// Written through `<path>.part` and a rename, as [`crate::edith::save`] does:
1528/// the bytes are fsynced before the name exists, the directory after, and a
1529/// failed write removes the part file.
1530pub fn save_cues(path: &Path, cues: &[Cue]) -> crate::Result<()> {
1531 let ext = path
1532 .extension()
1533 .map(|e| e.to_string_lossy().to_ascii_lowercase())
1534 .unwrap_or_default();
1535 let text = match ext.as_str() {
1536 "srt" => write_srt(cues),
1537 "vtt" => write_vtt(cues),
1538 other => {
1539 return Err(format!(
1540 "{other:?} is not a caption format this writes -- .srt and .vtt are"
1541 )
1542 .into());
1543 }
1544 };
1545 let dir = path
1546 .parent()
1547 .filter(|p| !p.as_os_str().is_empty())
1548 .unwrap_or(Path::new("."));
1549 let mut part = path.to_path_buf().into_os_string();
1550 part.push(".part");
1551 let part = PathBuf::from(part);
1552 let result = std::fs::File::create(&part)
1553 .and_then(|mut f| {
1554 use std::io::Write;
1555 f.write_all(text.as_bytes())?;
1556 f.sync_all()
1557 })
1558 .and_then(|()| std::fs::rename(&part, path))
1559 .and_then(|()| std::fs::File::open(dir)?.sync_all());
1560 if result.is_err() {
1561 let _ = std::fs::remove_file(&part);
1562 }
1563 result.map_err(Into::into)
1564}
1565
1566/// Group timed words into caption cues. `words` is `(start_us, end_us, word)`,
1567/// sorted by start here whatever order it arrives in; words that are empty
1568/// after trimming are skipped.
1569///
1570/// A cue is closed before a word that would take it past any of these:
1571/// - a pause longer than `gap_secs` since the previous word ended;
1572/// - `max_secs` from the cue's first word to this word's end;
1573/// - two lines of `max_chars` each: the words joined with spaces may not exceed
1574/// `2 * max_chars` characters.
1575///
1576/// A cue is also closed after a word that ends a sentence (`.`, `!`, `?`, `…`,
1577/// optionally followed by closing quotes or brackets). A cue of more than
1578/// `max_chars` characters is split over two lines at the word boundary that
1579/// makes the longer line shortest, so the lines come out as close to even as the
1580/// words allow. Text is the lines joined with `\n`; no picture.
1581///
1582/// A single word longer than the limits is still a cue of its own rather than
1583/// being dropped or cut.
1584pub fn cues_from_words(
1585 words: &[(i64, i64, String)],
1586 max_chars: usize,
1587 max_secs: f64,
1588 gap_secs: f64,
1589) -> Vec<Cue> {
1590 let mut sorted: Vec<&(i64, i64, String)> =
1591 words.iter().filter(|w| !w.2.trim().is_empty()).collect();
1592 sorted.sort_by_key(|w| w.0);
1593 let max_us = (max_secs * 1e6) as i64;
1594 let gap_us = (gap_secs * 1e6) as i64;
1595 let joined_len = |cur: &[&(i64, i64, String)]| -> usize {
1596 cur.iter()
1597 .map(|w| w.2.trim().chars().count())
1598 .sum::<usize>()
1599 + cur.len().saturating_sub(1)
1600 };
1601 let mut out = Vec::new();
1602 let mut cur: Vec<&(i64, i64, String)> = Vec::new();
1603 for &word in &sorted {
1604 if let Some(&last) = cur.last() {
1605 let pause = word.0 - last.1 > gap_us;
1606 let too_long = word.1 - cur[0].0 > max_us;
1607 let too_wide = joined_len(&cur) + 1 + word.2.trim().chars().count() > 2 * max_chars;
1608 if pause || too_long || too_wide {
1609 out.push(words_cue(&cur, max_chars));
1610 cur.clear();
1611 }
1612 }
1613 cur.push(word);
1614 if ends_sentence(&word.2) {
1615 out.push(words_cue(&cur, max_chars));
1616 cur.clear();
1617 }
1618 }
1619 if !cur.is_empty() {
1620 out.push(words_cue(&cur, max_chars));
1621 }
1622 out
1623}
1624
1625/// One cue out of its words: timed from the first word's start to the last
1626/// word's end, text laid out over at most two lines.
1627fn words_cue(cur: &[&(i64, i64, String)], max_chars: usize) -> Cue {
1628 let words: Vec<&str> = cur.iter().map(|w| w.2.trim()).collect();
1629 let len = |ws: &[&str]| {
1630 ws.iter().map(|w| w.chars().count()).sum::<usize>() + ws.len().saturating_sub(1)
1631 };
1632 let total = len(&words);
1633 let text = if total <= max_chars || words.len() < 2 {
1634 words.join(" ")
1635 } else {
1636 // The split that keeps the longer of the two lines shortest; ties go to
1637 // the one nearest the middle.
1638 let middle = total as i64 / 2;
1639 let mut best: Option<(usize, (usize, i64))> = None;
1640 for k in 1..words.len() {
1641 let (a, b) = (len(&words[..k]), len(&words[k..]));
1642 let score = (a.max(b), (a as i64 - middle).abs());
1643 if best.is_none_or(|(_, s)| score < s) {
1644 best = Some((k, score));
1645 }
1646 }
1647 let k = best.map_or(1, |(k, _)| k);
1648 format!("{}\n{}", words[..k].join(" "), words[k..].join(" "))
1649 };
1650 let start = cur[0].0;
1651 let end = cur.last().map_or(start, |w| w.1).max(start);
1652 Cue {
1653 start_us: start,
1654 end_us: end,
1655 text,
1656 image: None,
1657 words: Vec::new(),
1658 karaoke: Vec::new(),
1659 }
1660}
1661
1662/// Whether a word closes a sentence: final `.`, `!`, `?` or `…`, looking past
1663/// closing quotes and brackets.
1664fn ends_sentence(word: &str) -> bool {
1665 word.trim_end_matches(['"', '\'', ')', ']', '”', '’'])
1666 .ends_with(['.', '!', '?', '…'])
1667}
1668
1669/// The decoding path checked against a snapshot of the oxideav one it replaced.
1670#[cfg(test)]
1671mod parity;
1672
1673#[cfg(test)]
1674mod tests {
1675 use super::*;
1676
1677 #[test]
1678 fn ass_timestamps_are_written_the_way_ass_reads_them() {
1679 assert_eq!(timestamp(0), "0:00:00.00");
1680 assert_eq!(timestamp(500_000), "0:00:00.50");
1681 assert_eq!(timestamp(3_250_000), "0:00:03.25");
1682 // An hour, a minute and a second, and a negative time is not one.
1683 assert_eq!(timestamp(3_661_000_000), "1:01:01.00");
1684 assert_eq!(timestamp(-1), "0:00:00.00");
1685 }
1686
1687 #[test]
1688 fn srt_markup_is_resolved_not_carried() {
1689 assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain");
1690 assert_eq!(srt_body("two\nlines\n"), "two\nlines");
1691 }
1692
1693 /// The sample that is not a cue: a `tx3g` track states one sample per
1694 /// instant, so the stretches with nothing on screen are samples of no text
1695 /// -- a track of nothing but those is a track with no cues, not one blank
1696 /// cue per instant.
1697 #[test]
1698 fn an_empty_timed_text_sample_is_not_a_cue() {
1699 let sample = |payload: Vec<u8>| crate::demux::Mp4TextSample {
1700 start_us: 500_000,
1701 end_us: 1_500_000,
1702 payload,
1703 };
1704 let mut text = vec![0, 5];
1705 text.extend_from_slice(b"lines");
1706 let cue = tx3g_cue(&sample(text)).expect("a sample with words is a cue");
1707 assert_eq!(
1708 (cue.start_us, cue.end_us, &cue.text[..]),
1709 (500_000, 1_500_000, "lines")
1710 );
1711 // The empty sample, the one an export writes between two cues and past
1712 // the last of them...
1713 assert!(tx3g_cue(&sample(vec![0, 0])).is_none());
1714 // ...and the bytes that are not a sample: a length past the payload,
1715 // and no length at all.
1716 assert!(tx3g_cue(&sample(vec![0, 9, b'h', b'i'])).is_none());
1717 assert!(tx3g_cue(&sample(Vec::new())).is_none());
1718 }
1719
1720 /// An ASS script's text is UTF-8 whether or not it starts with a BOM: the
1721 /// parser this reads it with would read each byte as Latin-1 otherwise.
1722 /// `\h` is still a hard space, and nothing else is touched.
1723 #[test]
1724 fn ass_text_is_read_as_utf8_with_or_without_a_bom() {
1725 let dir = crate::scratch::Scratch::dir("subtitle_ass_utf8");
1726 let body = "[Script Info]\nScriptType: v4.00+\n\n[Events]\n\
1727 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
1728 Dialogue: 0,0:00:00.00,0:00:02.00,Default,,0,0,0,,{\\b1}Kalın{\\b0} ve ş Ğ 🎵\n\
1729 Dialogue: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,Alt\\hkesme\n";
1730 for (name, bytes) in [
1731 ("plain.ass", body.as_bytes().to_vec()),
1732 ("bom.ass", [&[0xEF, 0xBB, 0xBF][..], body.as_bytes()].concat()),
1733 ] {
1734 let path = dir.join(name);
1735 std::fs::write(&path, bytes).expect("write");
1736 let cues = parse_file(&path).expect("parse");
1737 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
1738 assert_eq!(texts, ["Kalın ve ş Ğ 🎵", "Alt\u{a0}kesme"], "{name}");
1739 }
1740 }
1741
1742 /// A cue the parser would silently drop or keep backwards is named by its
1743 /// line, kept out of the track, and the cues around it are read as before.
1744 #[test]
1745 fn a_bad_timing_line_is_skipped_and_named_with_its_line() {
1746 let dir = crate::scratch::Scratch::dir("subtitle_bad_timing");
1747 let path = dir.join("bad.srt");
1748 let body = "1\n00:00:01,000 --> 00:00:02,000\nOne\n\n\
1749 2\n00:00:03,000 --> 00:00:04,000\nTwo\n\n\
1750 3\n00:00:09,000 --> 00:00:0x,500\nBad digit\n\n\
1751 4\n00:00:08,500 --> 00:00:08,000\nReversed\n\n\
1752 5\n00:00:06,000 --> 00:00:07,000\nFive\n";
1753 std::fs::write(&path, body).expect("write");
1754 let (cues, skipped) = read_file(&path).expect("read");
1755 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
1756 assert_eq!(texts, ["One", "Two", "Five"]);
1757 assert_eq!(
1758 skipped,
1759 [
1760 "line 10: end time `00:00:0x,500` is not a timestamp",
1761 "line 14: end before start",
1762 ]
1763 );
1764 assert_eq!(skipped_cues(&path), skipped);
1765 }
1766
1767 /// A timing line with a `->` for its arrow is named by its line, and a cue
1768 /// block with no timing line at all is named by its first line. Neither
1769 /// adds a cue, and the cues around them are read as before.
1770 #[test]
1771 fn a_wrong_arrow_and_a_cue_without_timing_are_named_by_line() {
1772 let dir = crate::scratch::Scratch::dir("subtitle_arrow_no_timing");
1773 let path = dir.join("malformed.srt");
1774 let body = "1\n00:00:01,000 --> 00:00:02,000\nOne\n\n\
1775 2\n00:00:02,000 -> 00:00:03,000\nArrow\n\n\
1776 3\n00:00:04,000 --> 00:00:05,000\nThree\n\n\
1777 4\nNo timing here\nstill text\n\n\
1778 5\n00:00:06,000 --> 00:00:07,000\nFive\n";
1779 std::fs::write(&path, body).expect("write");
1780 let (cues, skipped) = read_file(&path).expect("read");
1781 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
1782 assert_eq!(texts, ["One", "Three", "Five"]);
1783 assert_eq!(
1784 skipped,
1785 [
1786 "line 6: timing arrow must be -->",
1787 "line 13: cue has no timing line",
1788 ]
1789 );
1790 assert_eq!(skipped_cues(&path), skipped);
1791
1792 let vtt = dir.join("malformed.vtt");
1793 let body = "WEBVTT\n\nNOTE a comment\nmore\n\nintro\n00:00.000 --> 00:01.000\nHi\n\n\
1794 lost\nno timing\n\nSTYLE\n::cue { color: red }\n";
1795 std::fs::write(&vtt, body).expect("write");
1796 let (cues, skipped) = read_file(&vtt).expect("read");
1797 assert_eq!(cues.len(), 1);
1798 assert_eq!(skipped, ["line 10: cue has no timing line"]);
1799 }
1800
1801 /// A file that reads whole names nothing: a cue text may hold a number or
1802 /// a NOTE line of its own, and a WebVTT header, NOTE, STYLE and REGION
1803 /// block is not a cue.
1804 #[test]
1805 fn a_valid_file_names_nothing() {
1806 let dir = crate::scratch::Scratch::dir("subtitle_valid_names_nothing");
1807 let srt = dir.join("valid.srt");
1808 let body = "1\n00:00:01,000 --> 00:00:02,000\nIn the year\n2024\n\n\
1809 2\n00:00:03,000 --> 00:00:04,000\nSecond\n";
1810 std::fs::write(&srt, body).expect("write");
1811 let (cues, skipped) = read_file(&srt).expect("read");
1812 assert_eq!(cues.len(), 2);
1813 assert!(skipped.is_empty(), "{skipped:?}");
1814
1815 let vtt = dir.join("valid.vtt");
1816 let body = "WEBVTT\n\nNOTE a comment\nmore\n\nREGION\nid:r1\n\n\
1817 intro\n00:00.000 --> 00:01.000 align:start\nHi\n\n\
1818 00:01.000 --> 00:02.000\nNOTE is text here\n";
1819 std::fs::write(&vtt, body).expect("write");
1820 let (cues, skipped) = read_file(&vtt).expect("read");
1821 assert_eq!(cues.len(), 2);
1822 assert!(skipped.is_empty(), "{skipped:?}");
1823 }
1824
1825 /// `<br>` is a line break in a WebVTT cue, in any of its spellings, and the
1826 /// other tags still go. A break at a line's end is one more than the
1827 /// line's own, as a browser shows it, and it does not end the cue.
1828 #[test]
1829 fn a_br_tag_is_a_line_break_in_a_cue() {
1830 let dir = crate::scratch::Scratch::dir("subtitle_br_tag");
1831 let path = dir.join("breaks.vtt");
1832 let body = "WEBVTT\n\n00:00.000 --> 00:01.500\nTwo lines<br>second <i>it</i>\n\n\
1833 00:01.500 --> 00:03.000\nthree<br/>four<BR />five<br>\nsix\n\n\
1834 00:03.000 --> 00:04.000\nPlain\n";
1835 std::fs::write(&path, body).expect("write");
1836 let texts: Vec<String> = read_file(&path).expect("read").0.into_iter().map(|c| c.text).collect();
1837 assert_eq!(texts, ["Two lines\nsecond it", "three\nfour\nfive\n\nsix", "Plain"]);
1838 // An SRT cue has the same break.
1839 let srt = dir.join("breaks.srt");
1840 std::fs::write(&srt, "1\n00:00:00,000 --> 00:00:01,000\nA<br>B\n").expect("write");
1841 assert_eq!(read_file(&srt).expect("read").0[0].text, "A\nB");
1842 }
1843
1844 /// The timestamps a subtitle file writes: hours optional, `.` or `,` before
1845 /// up to three fraction digits, and minutes and seconds below sixty.
1846 #[test]
1847 fn subtitle_clocks_read_the_forms_files_write() {
1848 assert_eq!(clock_us("00:01.500"), Some(1_500_000));
1849 assert_eq!(clock_us("1:02:03,5"), Some(3_723_500_000));
1850 assert_eq!(clock_us("00:00:00,000"), Some(0));
1851 assert_eq!(clock_us("00:60:00,000"), None);
1852 assert_eq!(clock_us("00:00:0x,500"), None);
1853 assert_eq!(clock_us("00:00:01"), None);
1854 assert_eq!(clock_us("00:00:01,"), None);
1855 }
1856
1857 /// What a row shows, and what an export has to split back apart: the pair a
1858 /// container states, flattened the one way both readers flatten it.
1859 #[test]
1860 fn a_label_is_the_language_the_title_or_the_two() {
1861 assert_eq!(label_of("eng", ""), "eng");
1862 assert_eq!(label_of("fra", "Signs"), "fra — Signs");
1863 // An undetermined language is no language: the title stands alone.
1864 assert_eq!(label_of("und", "Commentary"), "Commentary");
1865 assert_eq!(label_of("und", ""), "und");
1866 }
1867
1868 /// The language a file name names, from its last token that is one: the
1869 /// two-letter and three-letter codes, and a name with none names nothing.
1870 #[test]
1871 fn a_file_name_names_its_language_or_nothing() {
1872 for (name, code) in [
1873 ("talk.fr.srt", "fra"),
1874 ("talk.fra.srt", "fra"),
1875 ("fra.srt", "fra"),
1876 ("talk_en.srt", "eng"),
1877 ("eng.srt", "eng"),
1878 ("talk.de.forced.srt", "deu"),
1879 ("talk_fre.srt", "fra"),
1880 ("/media/talk.en-US.srt", "eng"),
1881 ] {
1882 assert_eq!(guess_language(Path::new(name)), Some(code), "{name}");
1883 }
1884 for name in ["talk.srt", "the_end.srt", "talk_is.srt", "talk.no.srt"] {
1885 assert_eq!(guess_language(Path::new(name)), None, "{name} names no language");
1886 }
1887 }
1888
1889 /// What a person may type for a language, and the name an export titles it by.
1890 #[test]
1891 fn a_typed_language_is_an_iso_639_2_code() {
1892 assert_eq!(language_code("fr").as_deref(), Some("fra"));
1893 assert_eq!(language_code(" French ").as_deref(), Some("fra"));
1894 assert_eq!(language_code("ENG").as_deref(), Some("eng"));
1895 assert_eq!(language_code("fre").as_deref(), Some("fra"));
1896 assert_eq!(language_code("und").as_deref(), Some("und"));
1897 assert_eq!(language_code("zz9"), None);
1898 assert_eq!(language_code("x"), None);
1899 assert_eq!(language_name("fra"), Some("French"));
1900 assert_eq!(language_name("und"), None);
1901 }
1902
1903 /// A standalone file is untitled: its name is its label, not its title, and a
1904 /// retype names its language. An embedded track's label follows its language.
1905 #[test]
1906 fn an_import_takes_the_given_language_or_the_file_names() {
1907 let path = Path::new("/media/talk.fr.srt");
1908 assert_eq!(import_language(path, None), Ok(Some(("fra".to_string(), "from the file name"))));
1909 assert_eq!(import_language(path, Some("eng")), Ok(Some(("eng".to_string(), "as given"))));
1910 assert_eq!(import_language(Path::new("/media/talk.srt"), None), Ok(None));
1911 assert!(import_language(path, Some("klingon")).unwrap_err().contains("not a language"));
1912 }
1913
1914 #[test]
1915 fn a_retype_relabels_an_embedded_track_and_never_titles_a_file() {
1916 let mut file = external(Path::new("/nonexistent/subs.srt"));
1917 assert_eq!(file.name, "");
1918 assert_eq!(file.label, "subs.srt");
1919 set_language(&mut file, "fra");
1920 assert_eq!((file.language.as_str(), file.label.as_str()), ("fra", "subs.srt"));
1921
1922 let mut embedded = SubtitleTrack {
1923 path: PathBuf::from("/media/a.mkv"),
1924 track: Some(3),
1925 language: "eng".into(),
1926 name: "Signs".into(),
1927 label: "eng — Signs".into(),
1928 cues: Vec::new(),
1929 bitmap: false,
1930 refused: None,
1931 };
1932 set_language(&mut embedded, "fra");
1933 assert_eq!(embedded.label, "fra — Signs");
1934 }
1935
1936 #[test]
1937 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {
1938 let err = parse_file(Path::new("/nonexistent/notes.txt"))
1939 .unwrap_err()
1940 .to_string();
1941 assert!(err.contains("txt"), "{err}");
1942 // ...and a `.srt` that is not there comes back as a track that says so
1943 // rather than as no track at all, so a re-save does not lose it.
1944 let gone = external(Path::new("/nonexistent/subs.srt"));
1945 assert!(gone.refused.is_some());
1946 assert_eq!(gone.label, "subs.srt");
1947 }
1948
1949 fn cue(start_ms: i64, end_ms: i64, text: &str) -> Cue {
1950 Cue {
1951 start_us: start_ms * 1000,
1952 end_us: end_ms * 1000,
1953 text: text.to_owned(),
1954 image: None,
1955 words: Vec::new(),
1956 karaoke: Vec::new(),
1957 }
1958 }
1959
1960 #[test]
1961 fn srt_is_numbered_timed_and_sorted() {
1962 let cues = [cue(2_000, 3_500, "second"), cue(0, 1_250, "first\nlined")];
1963 assert_eq!(
1964 write_srt(&cues),
1965 "1\n00:00:00,000 --> 00:00:01,250\nfirst\nlined\n\n\
1966 2\n00:00:02,000 --> 00:00:03,500\nsecond\n\n"
1967 );
1968 }
1969
1970 #[test]
1971 fn srt_roundtrips_through_the_parser() {
1972 let dir = crate::scratch::Scratch::dir("subtitle_write_srt");
1973 let path = dir.join("out.srt");
1974 let cues = [
1975 cue(500, 2_250, "hello there"),
1976 cue(3_661_004, 3_662_000, "an hour, and a line\nunder it"),
1977 ];
1978 save_cues(&path, &cues).expect("save");
1979 let back = parse_file(&path).expect("parse");
1980 assert_eq!(back.len(), 2);
1981 for (got, want) in back.iter().zip(&cues) {
1982 assert_eq!(got.start_us / 1000, want.start_us / 1000);
1983 assert_eq!(got.end_us / 1000, want.end_us / 1000);
1984 assert_eq!(got.text, want.text);
1985 }
1986 assert!(!dir.join("out.srt.part").exists());
1987 }
1988
1989 #[test]
1990 fn vtt_has_its_header_and_dotted_times() {
1991 let out = write_vtt(&[cue(1_000, 2_000, "hi")]);
1992 assert_eq!(out, "WEBVTT\n\n1\n00:00:01.000 --> 00:00:02.000\nhi\n\n");
1993 assert_eq!(write_vtt(&[]), "WEBVTT\n\n");
1994 }
1995
1996 #[test]
1997 fn vtt_escapes_what_it_must_and_roundtrips() {
1998 let text = "tom & jerry <i>x</i> --> done";
1999 let out = write_vtt(&[cue(0, 1_000, text)]);
2000 assert!(
2001 out.contains("tom &amp; jerry &lt;i&gt;x&lt;/i&gt; --&gt; done\n"),
2002 "{out}"
2003 );
2004 // Only the timing line carries `-->`.
2005 assert_eq!(out.matches("-->").count(), 1, "{out}");
2006 // The file still parses as one cue with its timing, and the text reads
2007 // back as it was written: `&`, `<`, `>` and `-->` included.
2008 let dir = crate::scratch::Scratch::dir("subtitle_write_vtt");
2009 let path = dir.join("out.vtt");
2010 save_cues(&path, &[cue(0, 1_000, text)]).expect("save");
2011 let back = parse_file(&path).expect("parse");
2012 assert_eq!(back.len(), 1);
2013 assert_eq!((back[0].start_us, back[0].end_us), (0, 1_000_000));
2014 assert_eq!(back[0].text, text);
2015
2016 // One pass only: `&amp;lt;` is the text `&lt;`, and a reference the
2017 // decoder does not know is kept as written.
2018 let raw = dir.join("raw.vtt");
2019 std::fs::write(
2020 &raw,
2021 "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\n\
2022 A &amp;lt; B &#x3C; C &#62; D&nbsp;E &bogus; F\n\n",
2023 )
2024 .expect("write");
2025 let back = parse_file(&raw).expect("parse");
2026 assert_eq!(back[0].text, "A &lt; B < C > D\u{a0}E &bogus; F");
2027 }
2028
2029 #[test]
2030 fn writers_drop_pictures_and_empty_or_backwards_cues() {
2031 let picture = Cue {
2032 start_us: 0,
2033 end_us: 1_000_000,
2034 text: String::new(),
2035 image: Some(Arc::new(CueImage {
2036 width: 1,
2037 height: 1,
2038 set: Source::Pgs(Vec::new()),
2039 })),
2040 words: Vec::new(),
2041 karaoke: Vec::new(),
2042 };
2043 let cues = [
2044 picture,
2045 cue(0, 1_000, " "),
2046 cue(5_000, 4_000, "backwards"),
2047 cue(6_000, 6_000, "instant"),
2048 cue(-500, 1_000, "clamped"),
2049 ];
2050 assert_eq!(
2051 write_srt(&cues),
2052 "1\n00:00:00,000 --> 00:00:01,000\nclamped\n\n"
2053 );
2054 }
2055
2056 #[test]
2057 fn save_refuses_other_extensions_and_leaves_nothing() {
2058 let dir = crate::scratch::Scratch::dir("subtitle_write_refuse");
2059 let path = dir.join("out.txt");
2060 assert!(save_cues(&path, &[cue(0, 1_000, "x")]).is_err());
2061 assert!(!path.exists());
2062 assert!(!dir.join("out.txt.part").exists());
2063 }
2064
2065 fn word(start_ms: i64, end_ms: i64, w: &str) -> (i64, i64, String) {
2066 (start_ms * 1000, end_ms * 1000, w.to_owned())
2067 }
2068
2069 #[test]
2070 fn words_split_on_a_pause() {
2071 let words = [
2072 word(0, 300, "one"),
2073 word(350, 600, "two"),
2074 word(2_000, 2_300, "three"),
2075 ];
2076 let cues = cues_from_words(&words, 42, 10.0, 0.5);
2077 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
2078 assert_eq!(texts, ["one two", "three"]);
2079 assert_eq!((cues[1].start_us, cues[1].end_us), (2_000_000, 2_300_000));
2080 }
2081
2082 #[test]
2083 fn words_split_on_length_and_on_duration() {
2084 // Four words of 4 letters: 19 characters joined. With max_chars 9 the
2085 // cue holds at most 2 * 9 = 18, so the fourth word starts a new cue; the
2086 // first three are 14 characters, over one line, so they split 2 + 1.
2087 let words = [
2088 word(0, 100, "aaaa"),
2089 word(100, 200, "bbbb"),
2090 word(200, 300, "cccc"),
2091 word(300, 400, "dddd"),
2092 ];
2093 let cues = cues_from_words(&words, 9, 10.0, 5.0);
2094 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
2095 assert_eq!(texts, ["aaaa bbbb\ncccc", "dddd"]);
2096 // Duration: a cue may run 1 s from its first word's start.
2097 let timed = [
2098 word(0, 400, "a"),
2099 word(400, 800, "b"),
2100 word(800, 1_200, "c"),
2101 ];
2102 let cues = cues_from_words(&timed, 100, 1.0, 5.0);
2103 assert_eq!(cues.len(), 2);
2104 assert_eq!(cues[0].text, "a b");
2105 assert_eq!(cues[1].text, "c");
2106 }
2107
2108 #[test]
2109 fn words_split_on_sentence_end_and_lay_out_two_lines() {
2110 let words = [
2111 word(0, 100, "Hello"),
2112 word(100, 200, "there."),
2113 word(200, 300, "\"Again?\""),
2114 word(300, 400, "Yes"),
2115 ];
2116 let cues = cues_from_words(&words, 42, 10.0, 5.0);
2117 let texts: Vec<&str> = cues.iter().map(|c| c.text.as_str()).collect();
2118 assert_eq!(texts, ["Hello there.", "\"Again?\"", "Yes"]);
2119
2120 // Over one line's worth: split near the middle, at a word boundary.
2121 let long = [
2122 word(0, 100, "alpha"),
2123 word(100, 200, "bravo"),
2124 word(200, 300, "charlie"),
2125 word(300, 400, "delta"),
2126 ];
2127 let cues = cues_from_words(&long, 13, 10.0, 5.0);
2128 assert_eq!(cues.len(), 1);
2129 assert_eq!(cues[0].text, "alpha bravo\ncharlie delta");
2130 }
2131}