forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB80ecf3dTahinli3 months ago230 commits

subtitle.rs344 lines, 13.5 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 `oxideav-subtitle` (SRT, WebVTT) and `oxideav-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//! What is *refused* is refused by name rather than by omission
18//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a
19//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of
20//! them opens with four rows that say so instead of opening with an empty list.
21
22use std::path::{Path, PathBuf};
23
24use oxideav_subtitle::ir::plain_text;
25
26/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds
27/// from the start of the media, which is the unit every parser here speaks.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct Cue {
30 pub start_us: i64,
31 pub end_us: i64,
32 /// Plain text, `\n` between the lines of a multi-line cue. The markup is
33 /// resolved and dropped: `<i>` from an SRT, `{\an8}` and `\N` from an ASS.
34 ///
35 /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate
36 /// and thrown away here, because nothing draws a cue yet. The upgrade path
37 /// is to keep `oxideav_core::Segment` beside this string -- the parsers
38 /// already hand it over -- and it belongs to whoever writes the renderer.
39 pub text: String,
40}
41
42/// A subtitle track: where it came from and what it says.
43#[derive(Clone, Debug)]
44pub struct SubtitleTrack {
45 /// The file it was read out of: a standalone subtitle file, or the media
46 /// file whose track number is below.
47 pub path: PathBuf,
48 /// Which track of `path`, for one embedded in a Matroska file. `None` when
49 /// `path` *is* the subtitle file.
50 pub track: Option<u64>,
51 /// What a list shows: a language, a muxer's name for the track, or the
52 /// file's own name for a standalone one.
53 pub label: String,
54 /// In start order. Empty when [`refused`](Self::refused) says why.
55 pub cues: Vec<Cue>,
56 /// Why this track has no cues, when it has none: a codec that is pictures
57 /// rather than text, a file that has gone missing since the project was
58 /// saved. `None` for one that parsed -- which a track with genuinely no
59 /// cues in it also is.
60 pub refused: Option<String>,
61}
62
63impl SubtitleTrack {
64 /// A track that is there and cannot be read, named and kept: a project
65 /// re-saved after one of these still lists it, which is the difference
66 /// between "your subtitles are missing" and losing them for good.
67 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {
68 Self {
69 path: path.to_path_buf(),
70 track,
71 label,
72 cues: Vec::new(),
73 refused: Some(why),
74 }
75 }
76}
77
78/// The one door a saved subtitle line comes back in through: a standalone file
79/// (`track` is `None`) or track `n` of a Matroska file.
80///
81/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is
82/// not there any more, a track number the file no longer has, a codec of
83/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name,
84/// because a project that opened yesterday has to open today -- a subtitle is
85/// not what a whole timeline should refuse over.
86pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack {
87 let Some(number) = track else {
88 return external(path);
89 };
90 let label = format!("track {number}");
91 let mut tracks = match of_matroska(path) {
92 Ok(tracks) => tracks,
93 Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()),
94 };
95 match tracks.iter().position(|t| t.track == Some(number)) {
96 Some(i) => tracks.swap_remove(i),
97 None => SubtitleTrack::refused(
98 path,
99 track,
100 label,
101 format!("no subtitle track {number} in {} any more", path.display()),
102 ),
103 }
104}
105
106/// A standalone subtitle file, parsed by its extension.
107fn external(path: &Path) -> SubtitleTrack {
108 let label = path
109 .file_name()
110 .map(|n| n.to_string_lossy().into_owned())
111 .unwrap_or_default();
112 match parse_file(path) {
113 Ok(cues) => SubtitleTrack {
114 path: path.to_path_buf(),
115 track: None,
116 label,
117 cues,
118 refused: None,
119 },
120 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),
121 }
122}
123
124/// Every subtitle track of a Matroska file, in file order -- the text ones with
125/// their cues, the bitmap ones refused by name (see the module docs).
126pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
127 Ok(crate::demux::matroska_subtitles(path)?
128 .into_iter()
129 .map(|t| {
130 let label = match (t.name.is_empty(), t.language.as_str()) {
131 (true, lang) => lang.to_owned(),
132 (false, "und") => t.name.clone(),
133 (false, lang) => format!("{lang} — {}", t.name),
134 };
135 match cues_of(&t) {
136 Ok(cues) => SubtitleTrack {
137 path: path.to_path_buf(),
138 track: Some(t.number),
139 label,
140 cues,
141 refused: None,
142 },
143 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),
144 }
145 })
146 .collect())
147}
148
149/// The cues of one Matroska subtitle track, or why it has none.
150///
151/// A Matroska text track carries the *timing* on the block and the *text* in
152/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is
153/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block
154/// with the `Start` and `End` fields cut out and the `[Script Info]` header
155/// filed away in `CodecPrivate`. Both are put back into the shape their parser
156/// reads -- rather than the markup being re-derived here -- which is also what
157/// makes an embedded track and the standalone file it was muxed from come back
158/// as the same cues.
159fn cues_of(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
160 let cues = match track.codec.as_str() {
161 "S_TEXT/UTF8" | "S_TEXT/ASCII" => track
162 .cues
163 .iter()
164 .map(|c| Cue {
165 start_us: c.start_us,
166 end_us: end_of(track, c),
167 text: srt_body(&String::from_utf8_lossy(&c.payload)),
168 })
169 .collect(),
170 "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?,
171 codec => {
172 return Err(format!(
173 "{codec} subtitles are pictures, not text — this track is listed, not read"
174 ));
175 }
176 };
177 Ok(cues)
178}
179
180/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes
181/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last.
182fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 {
183 /// How long a cue with nothing to say about it stays up: two seconds, a
184 /// read of one line.
185 const NO_DURATION_US: i64 = 2_000_000;
186 match cue.duration_us {
187 Some(d) => cue.start_us + d,
188 None => track
189 .cues
190 .iter()
191 .map(|c| c.start_us)
192 .find(|&s| s > cue.start_us)
193 .unwrap_or(cue.start_us + NO_DURATION_US),
194 }
195}
196
197/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the
198/// SRT parser, around a timing line this then throws away, because SRT markup
199/// is exactly what such a block holds and a second implementation of it here
200/// would be a second set of bugs.
201fn srt_body(text: &str) -> String {
202 let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end());
203 match oxideav_subtitle::srt::parse(doc.as_bytes()) {
204 Ok(track) => track
205 .cues
206 .first()
207 .map(|c| plain_text(&c.segments))
208 .unwrap_or_default(),
209 // The parser refuses nothing an SRT body can hold; if it ever does,
210 // the bytes themselves are a better answer than an empty cue.
211 Err(_) => text.trim_end().to_owned(),
212 }
213}
214
215/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate`
216/// with every block put back as a `Dialogue` line under it, parsed once as the
217/// `.ass` file it came from.
218fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
219 let mut doc = String::from_utf8_lossy(&track.private).into_owned();
220 if !doc.ends_with('\n') {
221 doc.push('\n');
222 }
223 for cue in &track.cues {
224 let fields = String::from_utf8_lossy(&cue.payload);
225 // `ReadOrder,Layer,<the Format fields from Style on>`: the two the
226 // block adds go, and the timing the block *is* takes their place. The
227 // field order is the one the header's `Format:` line declares, which
228 // is the order a demuxer strips them out of.
229 let mut rest = fields.trim_end().splitn(3, ',');
230 let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) {
231 (Some(r), Some(l), Some(t)) => (r, l, t),
232 _ => continue,
233 };
234 doc.push_str(&format!(
235 "Dialogue: {layer},{},{},{rest}\n",
236 timestamp(cue.start_us),
237 timestamp(end_of(track, cue))
238 ));
239 }
240 let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?;
241 // The timings above are centiseconds, which is all an ASS line can say;
242 // the blocks are microseconds. So the text comes from the parse and the
243 // timing from the block -- unless a line was dropped as unparsable, when
244 // the pairing is no longer sound and the parse answers for both.
245 let exact = parsed.cues.len() == track.cues.len();
246 Ok(parsed
247 .cues
248 .iter()
249 .enumerate()
250 .map(|(i, c)| Cue {
251 start_us: if exact {
252 track.cues[i].start_us
253 } else {
254 c.start_us
255 },
256 end_us: if exact {
257 end_of(track, &track.cues[i])
258 } else {
259 c.end_us
260 },
261 text: plain_text(&c.segments),
262 })
263 .collect())
264}
265
266/// Microseconds as ASS writes a time: `H:MM:SS.cc`.
267fn timestamp(us: i64) -> String {
268 let cs = (us.max(0) + 5_000) / 10_000;
269 format!(
270 "{}:{:02}:{:02}.{:02}",
271 cs / 360_000,
272 cs / 6_000 % 60,
273 cs / 100 % 60,
274 cs % 100
275 )
276}
277
278/// A standalone subtitle file, by extension: the formats this engine reads at
279/// all. Anything else is refused by name, as an unknown media file is.
280fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> {
281 let ext = path
282 .extension()
283 .map(|e| e.to_string_lossy().to_ascii_lowercase())
284 .unwrap_or_default();
285 // The extension before the read: a `.txt` is refused for what it is, not
286 // for whether it happens to be there.
287 type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>;
288 let parse: Parse = match ext.as_str() {
289 "srt" => oxideav_subtitle::srt::parse,
290 "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse,
291 "ass" | "ssa" => oxideav_ass::parse,
292 other => {
293 return Err(format!(
294 "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are"
295 )
296 .into());
297 }
298 };
299 let track = parse(&std::fs::read(path)?);
300 let track = track.map_err(|e| format!("{}: {e}", path.display()))?;
301 Ok(track
302 .cues
303 .iter()
304 .map(|c| Cue {
305 start_us: c.start_us,
306 end_us: c.end_us,
307 text: plain_text(&c.segments),
308 })
309 .collect())
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn ass_timestamps_are_written_the_way_ass_reads_them() {
318 assert_eq!(timestamp(0), "0:00:00.00");
319 assert_eq!(timestamp(500_000), "0:00:00.50");
320 assert_eq!(timestamp(3_250_000), "0:00:03.25");
321 // An hour, a minute and a second, and a negative time is not one.
322 assert_eq!(timestamp(3_661_000_000), "1:01:01.00");
323 assert_eq!(timestamp(-1), "0:00:00.00");
324 }
325
326 #[test]
327 fn srt_markup_is_resolved_not_carried() {
328 assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain");
329 assert_eq!(srt_body("two\nlines\n"), "two\nlines");
330 }
331
332 #[test]
333 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {
334 let err = parse_file(Path::new("/nonexistent/notes.txt"))
335 .unwrap_err()
336 .to_string();
337 assert!(err.contains("txt"), "{err}");
338 // ...and a `.srt` that is not there comes back as a track that says so
339 // rather than as no track at all, so a re-save does not lose it.
340 let gone = external(Path::new("/nonexistent/subs.srt"));
341 assert!(gone.refused.is_some());
342 assert_eq!(gone.label, "subs.srt");
343 }
344}