forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

subtitle.rs527 lines, 22.2 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//! 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//! `oxideav-sub-image`, 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::path::{Path, PathBuf};
30use std::sync::Arc;
31
32use oxideav_subtitle::ir::plain_text;
33
34/// One line of subtitle: on screen from `start_us` to `end_us`, microseconds
35/// from the start of the media, which is the unit every parser here speaks.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Cue {
38 pub start_us: i64,
39 pub end_us: i64,
40 /// Plain text, `\n` between the lines of a multi-line cue. The markup is
41 /// resolved and dropped: `<i>` from an SRT, `{\an8}` and `\N` from an ASS.
42 ///
43 /// ponytail: bold/italic/colour and ASS positioning are parsed by the crate
44 /// and thrown away here, because nothing draws a cue yet. The upgrade path
45 /// is to keep `oxideav_core::Segment` beside this string -- the parsers
46 /// already hand it over -- and it belongs to whoever writes the renderer.
47 pub text: String,
48 /// The picture this cue *is*, for a track that is pictures rather than
49 /// lines. `None` for every text cue -- an `.srt`, a `.vtt`, an `.ass`, an
50 /// `S_TEXT/*` track -- and `Some` for every cue of a PGS one, which then
51 /// has no [`text`](Self::text) at all.
52 ///
53 /// Shared rather than owned: [`crate::export::timeline_cues`] copies a whole
54 /// track's cues, per repaint, and a display set is tens of kilobytes.
55 pub image: Option<Arc<CueImage>>,
56}
57
58/// A cue that is a picture: one PGS display set, kept the way the Matroska
59/// block held it -- run-length and palettised, tens of kilobytes -- and turned
60/// into pixels only when something is about to draw it ([`Self::rgba`]).
61///
62/// Kept encoded because decoded is enormous: this film's canvas is 8 MB of
63/// RGBA and its four PGS tracks carry about eleven thousand display sets
64/// between them, so a track that decoded itself at import would cost gigabytes
65/// where it now costs the thirty megabytes the file already spends on it.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct CueImage {
68 /// The canvas the disc composed against: 1920x1080 for a BluRay, whatever
69 /// the film's own frame was cropped to. The whole canvas is the picture --
70 /// transparent everywhere the cue does not paint -- so a caller lays it
71 /// over the film rather than placing it.
72 pub width: u32,
73 pub height: u32,
74 /// The display set: `type`, big-endian size, body, segment after segment,
75 /// which is the shape a Matroska block holds PGS in.
76 set: Vec<u8>,
77}
78
79impl CueImage {
80 /// The picture: straight (not premultiplied) RGBA, `width * height * 4`
81 /// bytes, transparent wherever the cue paints nothing. `None` for a display
82 /// set the decoder will not have, which is a corrupt block.
83 ///
84 /// Decoded on the spot: the run-length walk and one canvas-sized buffer,
85 /// which is a thing to do when the cue on screen changes and not sixty
86 /// times a second. A caller that draws these keeps the answer for as long
87 /// as the cue is up.
88 pub fn rgba(&self) -> Option<Vec<u8>> {
89 use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase};
90 let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID));
91 let mut decoder = oxideav_sub_image::pgs::make_decoder(&params).ok()?;
92 // The decoder reads a `.sup`'s framing and a Matroska block is the same
93 // segments with the `PG` magic and the timestamps taken off, so they go
94 // back on. The times themselves are the block's and are already on the
95 // `Cue`, so they are written as nothing.
96 let mut sup = Vec::with_capacity(self.set.len() + 64);
97 // Up to and including the `END` that closes the first display set which
98 // composes an object, and no further: a block is normally one set, but
99 // a muxer that packs a composition and the erase after it into one would
100 // otherwise leave the *erase* as the last word and decode to an empty
101 // canvas -- the cue drawn as nothing at all.
102 let mut shows = false;
103 for (kind, body) in segments(&self.set)? {
104 sup.extend_from_slice(b"PG");
105 sup.extend_from_slice(&[0; 8]);
106 sup.push(kind);
107 sup.extend_from_slice(&(body.len() as u16).to_be_bytes());
108 sup.extend_from_slice(body);
109 match kind {
110 oxideav_sub_image::pgs::SEG_PCS => {
111 shows = body.get(10).is_some_and(|&n| n > 0);
112 }
113 oxideav_sub_image::pgs::SEG_END if shows => break,
114 _ => {}
115 }
116 }
117 decoder
118 .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))
119 .ok()?;
120 match decoder.receive_frame().ok()? {
121 Frame::Video(frame) => Some(frame.planes.into_iter().next()?.data),
122 _ => None,
123 }
124 }
125}
126
127/// The segments of a display set as a Matroska block holds them: a type byte, a
128/// big-endian size, that many bytes of body, and again until the block is out.
129/// `None` for bytes that do not walk -- a truncated or mislabelled block.
130fn segments(set: &[u8]) -> Option<Vec<(u8, &[u8])>> {
131 let mut out = Vec::new();
132 let mut at = 0;
133 while at < set.len() {
134 let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize;
135 out.push((set[at], set.get(at + 3..at + 3 + size)?));
136 at += 3 + size;
137 }
138 Some(out)
139}
140
141/// A subtitle track: where it came from and what it says.
142#[derive(Clone, Debug)]
143pub struct SubtitleTrack {
144 /// The file it was read out of: a standalone subtitle file, or the media
145 /// file whose track number is below.
146 pub path: PathBuf,
147 /// Which track of `path`, for one embedded in a Matroska file. `None` when
148 /// `path` *is* the subtitle file.
149 pub track: Option<u64>,
150 /// What a list shows: a language, a muxer's name for the track, or the
151 /// file's own name for a standalone one.
152 pub label: String,
153 /// In start order. Empty when [`refused`](Self::refused) says why.
154 pub cues: Vec<Cue>,
155 /// This track is pictures rather than text (`S_HDMV/PGS`). Not a refusal:
156 /// it is drawn over the picture like any other track, and what it cannot do
157 /// is be *written* as text -- an SRT carries none of it.
158 ///
159 /// Read off the codec id at every open rather than off the cues, because a
160 /// PGS track whose display sets are all erases -- or one with no cues at
161 /// all -- is still a track of pictures, and calling it text would have an
162 /// export promise to write words it does not have.
163 pub bitmap: bool,
164 /// Why this track has no cues, when it has none: a codec that is pictures
165 /// rather than text, a file that has gone missing since the project was
166 /// saved. `None` for one that parsed -- which a track with genuinely no
167 /// cues in it also is.
168 pub refused: Option<String>,
169}
170
171impl SubtitleTrack {
172 /// A track that is there and cannot be read, named and kept: a project
173 /// re-saved after one of these still lists it, which is the difference
174 /// between "your subtitles are missing" and losing them for good.
175 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {
176 Self {
177 path: path.to_path_buf(),
178 track,
179 label,
180 cues: Vec::new(),
181 bitmap: false,
182 refused: Some(why),
183 }
184 }
185
186 /// Whether this track's cues are pictures rather than lines -- a PGS track
187 /// off a remux. What it decides is where words are the only answer: an
188 /// export writes a *text* track and cannot carry these
189 /// ([`crate::export::planned_subtitles`] says so out loud).
190 pub fn is_bitmap(&self) -> bool {
191 self.bitmap
192 }
193}
194
195/// The one door a saved subtitle line comes back in through: a standalone file
196/// (`track` is `None`) or track `n` of a Matroska file.
197///
198/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is
199/// not there any more, a track number the file no longer has, a codec of
200/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name,
201/// because a project that opened yesterday has to open today -- a subtitle is
202/// not what a whole timeline should refuse over.
203pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack {
204 let Some(number) = track else {
205 return external(path);
206 };
207 let label = format!("track {number}");
208 let mut tracks = match of_matroska(path) {
209 Ok(tracks) => tracks,
210 Err(why) => return SubtitleTrack::refused(path, track, label, why.to_string()),
211 };
212 match tracks.iter().position(|t| t.track == Some(number)) {
213 Some(i) => tracks.swap_remove(i),
214 None => SubtitleTrack::refused(
215 path,
216 track,
217 label,
218 format!("no subtitle track {number} in {} any more", path.display()),
219 ),
220 }
221}
222
223/// A standalone subtitle file, parsed by its extension.
224fn external(path: &Path) -> SubtitleTrack {
225 let label = path
226 .file_name()
227 .map(|n| n.to_string_lossy().into_owned())
228 .unwrap_or_default();
229 match parse_file(path) {
230 Ok(cues) => SubtitleTrack {
231 path: path.to_path_buf(),
232 track: None,
233 label,
234 cues,
235 // Every format `parse_file` reads is text.
236 bitmap: false,
237 refused: None,
238 },
239 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),
240 }
241}
242
243/// Every subtitle track of a Matroska file, in file order -- the text ones with
244/// their cues, the bitmap ones refused by name (see the module docs).
245pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
246 Ok(crate::demux::matroska_subtitles(path)?
247 .into_iter()
248 .map(|mut t| {
249 let label = match (t.name.is_empty(), t.language.as_str()) {
250 (true, lang) => lang.to_owned(),
251 (false, "und") => t.name.clone(),
252 (false, lang) => format!("{lang} — {}", t.name),
253 };
254 let bitmap = t.codec == crate::demux::PGS;
255 match cues_of(&mut t) {
256 Ok(cues) => SubtitleTrack {
257 path: path.to_path_buf(),
258 track: Some(t.number),
259 label,
260 cues,
261 bitmap,
262 refused: None,
263 },
264 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),
265 }
266 })
267 .collect())
268}
269
270/// The cues of one Matroska subtitle track, or why it has none.
271///
272/// A Matroska text track carries the *timing* on the block and the *text* in
273/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is
274/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block
275/// with the `Start` and `End` fields cut out and the `[Script Info]` header
276/// filed away in `CodecPrivate`. Both are put back into the shape their parser
277/// reads -- rather than the markup being re-derived here -- which is also what
278/// makes an embedded track and the standalone file it was muxed from come back
279/// as the same cues.
280///
281/// A PGS track is neither: its blocks are pictures, and they are moved out of
282/// `track` rather than copied ([`pgs_cues`]) -- thirty megabytes a track is not
283/// a thing to hold twice.
284fn cues_of(track: &mut crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
285 // A track compressed or encrypted with something the demuxer cannot undo is
286 // refused in those words: the row stays, and it says why.
287 if let Some(why) = &track.unsupported {
288 return Err(why.clone());
289 }
290 let cues = match track.codec.as_str() {
291 "S_TEXT/UTF8" | "S_TEXT/ASCII" => track
292 .cues
293 .iter()
294 .map(|c| Cue {
295 start_us: c.start_us,
296 end_us: end_of(track, c),
297 text: srt_body(&String::from_utf8_lossy(&c.payload)),
298 image: None,
299 })
300 .collect(),
301 "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?,
302 crate::demux::PGS => pgs_cues(track),
303 codec => {
304 return Err(format!(
305 "{codec} subtitles are pictures, not text — this track is listed, not read"
306 ));
307 }
308 };
309 Ok(cues)
310}
311
312/// The cues of an `S_HDMV/PGS` track: one display set per block, and a display
313/// set is a picture the disc composes onto its own canvas.
314///
315/// Only the blocks that compose *something* are cues. The other half of them
316/// are the disc's "take it off again" -- a composition with no object on it --
317/// and they are what says when the picture before them goes away, which is why
318/// they are walked and not skipped. A muxer writes `BlockDuration` zero for all
319/// of them, so [`end_of`] is what pairs the two.
320fn pgs_cues(track: &mut crate::demux::MkvSubtitle) -> Vec<Cue> {
321 // Before the blocks are emptied: `end_of` reads the ones after this one.
322 let ends: Vec<i64> = track.cues.iter().map(|c| end_of(track, c)).collect();
323 track
324 .cues
325 .iter_mut()
326 .zip(ends)
327 .filter_map(|(block, end_us)| {
328 let (width, height) = pgs_canvas(&block.payload)?;
329 Some(Cue {
330 start_us: block.start_us,
331 end_us,
332 text: String::new(),
333 image: Some(Arc::new(CueImage {
334 width,
335 height,
336 set: std::mem::take(&mut block.payload),
337 })),
338 })
339 })
340 .collect()
341}
342
343/// The canvas of a display set that paints something -- its `PCS` says how big
344/// the disc's picture is, and how many objects are composed onto it.
345///
346/// `None` when nothing is composed, which is the disc clearing the screen, and
347/// `None` for bytes that are not a display set at all.
348fn pgs_canvas(set: &[u8]) -> Option<(u32, u32)> {
349 /// `PresentationCompositionSegment`, which every display set opens with.
350 const PCS: u8 = 0x16;
351 let (_, pcs) = segments(set)?.into_iter().find(|&(kind, _)| kind == PCS)?;
352 // Width and height, then the frame rate, the composition number and state,
353 // the palette-update flag and the palette id -- and then how many objects
354 // this composition puts on the canvas.
355 let width = u16::from_be_bytes([*pcs.first()?, *pcs.get(1)?]);
356 let height = u16::from_be_bytes([*pcs.get(2)?, *pcs.get(3)?]);
357 (*pcs.get(10)? > 0).then_some((u32::from(width), u32::from(height)))
358}
359
360/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes
361/// none, and for the PGS block that writes a zero, which says the same thing --
362/// when the next one arrives, and [`NO_DURATION_US`] for the last.
363fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 {
364 /// How long a cue with nothing to say about it stays up: two seconds, a
365 /// read of one line.
366 const NO_DURATION_US: i64 = 2_000_000;
367 match cue.duration_us.filter(|&d| d > 0) {
368 Some(d) => cue.start_us + d,
369 None => track
370 .cues
371 .iter()
372 .map(|c| c.start_us)
373 .find(|&s| s > cue.start_us)
374 .unwrap_or(cue.start_us + NO_DURATION_US),
375 }
376}
377
378/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the
379/// SRT parser, around a timing line this then throws away, because SRT markup
380/// is exactly what such a block holds and a second implementation of it here
381/// would be a second set of bugs.
382fn srt_body(text: &str) -> String {
383 let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end());
384 match oxideav_subtitle::srt::parse(doc.as_bytes()) {
385 Ok(track) => track
386 .cues
387 .first()
388 .map(|c| plain_text(&c.segments))
389 .unwrap_or_default(),
390 // The parser refuses nothing an SRT body can hold; if it ever does,
391 // the bytes themselves are a better answer than an empty cue.
392 Err(_) => text.trim_end().to_owned(),
393 }
394}
395
396/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate`
397/// with every block put back as a `Dialogue` line under it, parsed once as the
398/// `.ass` file it came from.
399fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
400 let mut doc = String::from_utf8_lossy(&track.private).into_owned();
401 if !doc.ends_with('\n') {
402 doc.push('\n');
403 }
404 for cue in &track.cues {
405 let fields = String::from_utf8_lossy(&cue.payload);
406 // `ReadOrder,Layer,<the Format fields from Style on>`: the two the
407 // block adds go, and the timing the block *is* takes their place. The
408 // field order is the one the header's `Format:` line declares, which
409 // is the order a demuxer strips them out of.
410 let mut rest = fields.trim_end().splitn(3, ',');
411 let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) {
412 (Some(r), Some(l), Some(t)) => (r, l, t),
413 _ => continue,
414 };
415 doc.push_str(&format!(
416 "Dialogue: {layer},{},{},{rest}\n",
417 timestamp(cue.start_us),
418 timestamp(end_of(track, cue))
419 ));
420 }
421 let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?;
422 // The timings above are centiseconds, which is all an ASS line can say;
423 // the blocks are microseconds. So the text comes from the parse and the
424 // timing from the block -- unless a line was dropped as unparsable, when
425 // the pairing is no longer sound and the parse answers for both.
426 let exact = parsed.cues.len() == track.cues.len();
427 Ok(parsed
428 .cues
429 .iter()
430 .enumerate()
431 .map(|(i, c)| Cue {
432 start_us: if exact {
433 track.cues[i].start_us
434 } else {
435 c.start_us
436 },
437 end_us: if exact {
438 end_of(track, &track.cues[i])
439 } else {
440 c.end_us
441 },
442 text: plain_text(&c.segments),
443 image: None,
444 })
445 .collect())
446}
447
448/// Microseconds as ASS writes a time: `H:MM:SS.cc`.
449fn timestamp(us: i64) -> String {
450 let cs = (us.max(0) + 5_000) / 10_000;
451 format!(
452 "{}:{:02}:{:02}.{:02}",
453 cs / 360_000,
454 cs / 6_000 % 60,
455 cs / 100 % 60,
456 cs % 100
457 )
458}
459
460/// A standalone subtitle file, by extension: the formats this engine reads at
461/// all. Anything else is refused by name, as an unknown media file is.
462fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> {
463 let ext = path
464 .extension()
465 .map(|e| e.to_string_lossy().to_ascii_lowercase())
466 .unwrap_or_default();
467 // The extension before the read: a `.txt` is refused for what it is, not
468 // for whether it happens to be there.
469 type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>;
470 let parse: Parse = match ext.as_str() {
471 "srt" => oxideav_subtitle::srt::parse,
472 "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse,
473 "ass" | "ssa" => oxideav_ass::parse,
474 other => {
475 return Err(format!(
476 "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are"
477 )
478 .into());
479 }
480 };
481 let track = parse(&std::fs::read(path)?);
482 let track = track.map_err(|e| format!("{}: {e}", path.display()))?;
483 Ok(track
484 .cues
485 .iter()
486 .map(|c| Cue {
487 start_us: c.start_us,
488 end_us: c.end_us,
489 text: plain_text(&c.segments),
490 image: None,
491 })
492 .collect())
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn ass_timestamps_are_written_the_way_ass_reads_them() {
501 assert_eq!(timestamp(0), "0:00:00.00");
502 assert_eq!(timestamp(500_000), "0:00:00.50");
503 assert_eq!(timestamp(3_250_000), "0:00:03.25");
504 // An hour, a minute and a second, and a negative time is not one.
505 assert_eq!(timestamp(3_661_000_000), "1:01:01.00");
506 assert_eq!(timestamp(-1), "0:00:00.00");
507 }
508
509 #[test]
510 fn srt_markup_is_resolved_not_carried() {
511 assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain");
512 assert_eq!(srt_body("two\nlines\n"), "two\nlines");
513 }
514
515 #[test]
516 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {
517 let err = parse_file(Path::new("/nonexistent/notes.txt"))
518 .unwrap_err()
519 .to_string();
520 assert!(err.contains("txt"), "{err}");
521 // ...and a `.srt` that is not there comes back as a track that says so
522 // rather than as no track at all, so a re-save does not lose it.
523 let gone = external(Path::new("/nonexistent/subs.srt"));
524 assert!(gone.refused.is_some());
525 assert_eq!(gone.label, "subs.srt");
526 }
527}