forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

subtitle.rs705 lines, 30.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 `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::collections::HashMap;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32
33use oxideav_subtitle::ir::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 `oxideav_core::Segment` beside this string -- the parsers
47 /// already hand it 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}
58
59/// A cue that is a picture: one PGS display set, kept the way the Matroska
60/// block held it -- run-length and palettised, tens of kilobytes -- and turned
61/// into pixels only when something is about to draw it ([`Self::rgba`]).
62///
63/// Kept encoded because decoded is enormous: this film's canvas is 8 MB of
64/// RGBA and its four PGS tracks carry about eleven thousand display sets
65/// between them, so a track that decoded itself at import would cost gigabytes
66/// where it now costs the thirty megabytes the file already spends on it.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct CueImage {
69 /// The canvas the disc composed against: 1920x1080 for a BluRay, whatever
70 /// the film's own frame was cropped to. The whole canvas is the picture --
71 /// transparent everywhere the cue does not paint -- so a caller lays it
72 /// over the film rather than placing it.
73 pub width: u32,
74 pub height: u32,
75 /// The display set: `type`, big-endian size, body, segment after segment,
76 /// which is the shape a Matroska block holds PGS in.
77 set: Vec<u8>,
78}
79
80impl CueImage {
81 /// The picture: straight (not premultiplied) RGBA, `width * height * 4`
82 /// bytes, transparent wherever the cue paints nothing. `None` for a display
83 /// set the decoder will not have, which is a corrupt block.
84 ///
85 /// Decoded on the spot: the run-length walk and one canvas-sized buffer,
86 /// which is a thing to do when the cue on screen changes and not sixty
87 /// times a second. A caller that draws these keeps the answer for as long
88 /// as the cue is up.
89 pub fn rgba(&self) -> Option<Vec<u8>> {
90 use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase};
91 let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID));
92 let mut decoder = oxideav_sub_image::pgs::make_decoder(&params).ok()?;
93 // The decoder reads a `.sup`'s framing and a Matroska block is the same
94 // segments with the `PG` magic and the timestamps taken off, so they go
95 // back on. The times themselves are the block's and are already on the
96 // `Cue`, so they are written as nothing.
97 let mut sup = Vec::with_capacity(self.set.len() + 64);
98 // Up to and including the `END` that closes the first display set which
99 // composes an object, and no further: a block is normally one set, but
100 // a muxer that packs a composition and the erase after it into one would
101 // otherwise leave the *erase* as the last word and decode to an empty
102 // canvas -- the cue drawn as nothing at all.
103 let mut shows = false;
104 for (kind, body) in segments(&self.set)? {
105 sup.extend_from_slice(b"PG");
106 sup.extend_from_slice(&[0; 8]);
107 sup.push(kind);
108 sup.extend_from_slice(&(body.len() as u16).to_be_bytes());
109 sup.extend_from_slice(body);
110 match kind {
111 oxideav_sub_image::pgs::SEG_PCS => {
112 shows = body.get(10).is_some_and(|&n| n > 0);
113 }
114 oxideav_sub_image::pgs::SEG_END if shows => break,
115 _ => {}
116 }
117 }
118 decoder
119 .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))
120 .ok()?;
121 match decoder.receive_frame().ok()? {
122 Frame::Video(frame) => Some(frame.planes.into_iter().next()?.data),
123 _ => None,
124 }
125 }
126}
127
128/// The segments of a display set as a Matroska block holds them: a type byte, a
129/// big-endian size, that many bytes of body, and again until the block is out.
130/// `None` for bytes that do not walk -- a truncated or mislabelled block.
131fn segments(set: &[u8]) -> Option<Vec<(u8, &[u8])>> {
132 let mut out = Vec::new();
133 let mut at = 0;
134 while at < set.len() {
135 let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize;
136 out.push((set[at], set.get(at + 3..at + 3 + size)?));
137 at += 3 + size;
138 }
139 Some(out)
140}
141
142/// A subtitle track: where it came from and what it says.
143#[derive(Clone, Debug)]
144pub struct SubtitleTrack {
145 /// The file it was read out of: a standalone subtitle file, or the media
146 /// file whose track number is below.
147 pub path: PathBuf,
148 /// Which track of `path`, for one embedded in a Matroska file. `None` when
149 /// `path` *is* the subtitle file.
150 pub track: Option<u64>,
151 /// What language the track is in, as the container states it (`eng`, `fra`,
152 /// `und` for a file that says nothing -- which is what both demuxers hand
153 /// over rather than an empty string). Empty only for a standalone file,
154 /// which states no language at all.
155 ///
156 /// Kept apart from [`name`](Self::name) because a container keeps them
157 /// apart: an export writes `TRACK_LANGUAGE` and `TRACK_NAME` as two fields
158 /// ([`crate::mux::SubParams`]), and a French track whose language is folded
159 /// into its title leaves as an English one.
160 pub language: String,
161 /// What the track is *called* beside its language (`Signs`, `Forced`), or
162 /// the file's own name for a standalone one. Empty where it has none.
163 pub name: String,
164 /// What a list shows: the [`language`](Self::language), the
165 /// [`name`](Self::name), or the pair ([`label_of`]) -- flattened here
166 /// because a row shows one string, and derived from the two rather than
167 /// being what they are derived from.
168 pub label: String,
169 /// In start order. Empty when [`refused`](Self::refused) says why.
170 pub cues: Vec<Cue>,
171 /// This track is pictures rather than text (`S_HDMV/PGS`). Not a refusal:
172 /// it is drawn over the picture like any other track, and what it cannot do
173 /// is be *written* as text -- an SRT carries none of it.
174 ///
175 /// Read off the codec id at every open rather than off the cues, because a
176 /// PGS track whose display sets are all erases -- or one with no cues at
177 /// all -- is still a track of pictures, and calling it text would have an
178 /// export promise to write words it does not have.
179 pub bitmap: bool,
180 /// Why this track has no cues, when it has none: a codec that is pictures
181 /// rather than text, a file that has gone missing since the project was
182 /// saved. `None` for one that parsed -- which a track with genuinely no
183 /// cues in it also is.
184 pub refused: Option<String>,
185}
186
187impl SubtitleTrack {
188 /// A track that is there and cannot be read, named and kept: a project
189 /// re-saved after one of these still lists it, which is the difference
190 /// between "your subtitles are missing" and losing them for good.
191 ///
192 /// No language and no name: what is refused is never *written* (an export
193 /// drops it before the muxer, [`crate::export::planned_subtitles`]), and the
194 /// row it leaves behind shows the `label` it was refused under.
195 fn refused(path: &Path, track: Option<u64>, label: String, why: String) -> Self {
196 Self {
197 path: path.to_path_buf(),
198 track,
199 language: String::new(),
200 name: String::new(),
201 label,
202 cues: Vec::new(),
203 bitmap: false,
204 refused: Some(why),
205 }
206 }
207
208 /// Whether this track's cues are pictures rather than lines -- a PGS track
209 /// off a remux. What it decides is where words are the only answer: an
210 /// export writes a *text* track and cannot carry these
211 /// ([`crate::export::planned_subtitles`] says so out loud).
212 pub fn is_bitmap(&self) -> bool {
213 self.bitmap
214 }
215}
216
217/// The one door a saved subtitle line comes back in through: a standalone file
218/// (`track` is `None`) or track `n` of a media file, Matroska or mp4
219/// ([`of_media`]).
220///
221/// Never an error, whatever is wrong: a deleted `.srt`, a media file that is
222/// not there any more, a track number the file no longer has, a codec of
223/// pictures. All of them come back [`refused`](SubtitleTrack::refused) by name,
224/// because a project that opened yesterday has to open today -- a subtitle is
225/// not what a whole timeline should refuse over.
226pub fn open(path: &Path, track: Option<u64>) -> SubtitleTrack {
227 let mut one = open_all(std::slice::from_ref(&(path.to_path_buf(), track)));
228 one.remove(0)
229}
230
231/// Every saved subtitle line of a project at once, back in the order they were
232/// saved in -- which is the order they are picked by, so it is the row order
233/// this hands back whatever it had to read.
234///
235/// The reason this exists beside [`open`]: a Matroska file is walked whole to
236/// reach *one* of its tracks, and a film whose project names thirty-five of them
237/// was thirty-five walks of a 25 GB file -- seven seconds with the window
238/// stopped, since a project opens on the UI thread. Each distinct file is walked
239/// once here and every row that named it is picked out of that one walk.
240pub fn open_all(rows: &[(PathBuf, Option<u64>)]) -> Vec<SubtitleTrack> {
241 // Keyed by path, so a second row naming the same file finds the walk rather
242 // than doing it again. The whole walk is kept until the last row is served:
243 // it is the tracks nobody asked for that are dropped at the end.
244 //
245 // corner-cut: a track is *moved* out of its walk, so two rows naming the same
246 // file and the same track leave the second refused by name rather than
247 // holding the cues twice. No project edith saves has one -- a row is added
248 // by (file, track) and only once ([`crate::Project::add_subtitles`]) -- and
249 // a hand-written `.edith` with a doubled row still opens, with that row
250 // saying so. Clone the picked track instead if that ever has to hold.
251 let mut walked: HashMap<&Path, crate::Result<Vec<SubtitleTrack>>> = HashMap::new();
252 rows.iter()
253 .map(|(path, track)| {
254 let Some(number) = *track else {
255 return external(path);
256 };
257 let label = format!("track {number}");
258 let tracks = walked
259 .entry(path.as_path())
260 .or_insert_with(|| of_media(path));
261 let tracks = match tracks {
262 Ok(tracks) => tracks,
263 Err(why) => return SubtitleTrack::refused(path, *track, label, why.to_string()),
264 };
265 match tracks.iter().position(|t| t.track == Some(number)) {
266 Some(i) => tracks.swap_remove(i),
267 None => SubtitleTrack::refused(
268 path,
269 *track,
270 label,
271 format!("no subtitle track {number} in {} any more", path.display()),
272 ),
273 }
274 })
275 .collect()
276}
277
278/// A standalone subtitle file, parsed by its extension.
279fn external(path: &Path) -> SubtitleTrack {
280 let label = path
281 .file_name()
282 .map(|n| n.to_string_lossy().into_owned())
283 .unwrap_or_default();
284 match parse_file(path) {
285 Ok(cues) => SubtitleTrack {
286 path: path.to_path_buf(),
287 track: None,
288 // A file beside the media states no language of its own -- and its
289 // name is the only thing it does state, which is what an export
290 // writes it as.
291 language: String::new(),
292 name: label.clone(),
293 label,
294 cues,
295 // Every format `parse_file` reads is text.
296 bitmap: false,
297 refused: None,
298 },
299 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),
300 }
301}
302
303/// Every subtitle track *inside* a media file, whichever container it is: a
304/// Matroska's ([`of_matroska`]) or an mp4's timed text ([`of_mp4`]).
305///
306/// The one door for it, so a project row, an import and an export's read-back
307/// cannot disagree about what a file carries -- and so an mp4 this project
308/// wrote comes back into it, which is the whole reason the mp4 reader exists:
309/// mp4 is the default export format, and a file edith writes and cannot open
310/// is not a round trip.
311pub fn of_media(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
312 match crate::demux::is_matroska(path) {
313 true => of_matroska(path),
314 false => of_mp4(path),
315 }
316}
317
318/// Every timed-text (`tx3g`) subtitle track of an mp4, in track order, with its
319/// cues -- the mp4 twin of [`of_matroska`].
320///
321/// A `tx3g` track is *continuous*: it states one sample per instant of the film
322/// and the stretches with nothing on screen are samples of no text, so those are
323/// dropped here rather than kept as cues with an empty line
324/// ([`crate::demux::Mp4TextSample::payload`]). What is left is the cues, timed
325/// on the file's own clock, and a track whose samples are all empty comes back
326/// with none rather than with one per instant.
327///
328/// Never a bitmap: an mp4 carries no PGS track this reads, so the refusal
329/// [`of_matroska`] has for one has no counterpart here.
330pub fn of_mp4(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
331 Ok(crate::demux::mp4_subtitles(path)?
332 .into_iter()
333 .map(|t| SubtitleTrack {
334 path: path.to_path_buf(),
335 track: Some(t.number),
336 label: label_of(&t.language, &t.name),
337 language: t.language,
338 name: t.name,
339 cues: t.samples.iter().filter_map(tx3g_cue).collect(),
340 bitmap: false,
341 refused: None,
342 })
343 .collect())
344}
345
346/// One `tx3g` sample as a cue, or `None` for the sample that is not one: the
347/// empty one that says nothing is on screen between here and the next line, and
348/// the truncated one whose declared length runs past its own bytes.
349fn tx3g_cue(sample: &crate::demux::Mp4TextSample) -> Option<Cue> {
350 let len = usize::from(u16::from_be_bytes([
351 *sample.payload.first()?,
352 *sample.payload.get(1)?,
353 ]));
354 let text = String::from_utf8_lossy(sample.payload.get(2..2 + len)?);
355 (!text.is_empty()).then(|| Cue {
356 start_us: sample.start_us,
357 end_us: sample.end_us,
358 text: text.into_owned(),
359 image: None,
360 })
361}
362
363/// What a list row shows for a track a container declares: the language, the
364/// muxer's title, or the pair.
365///
366/// A row shows one string, so the two are flattened for it -- and *only* for it.
367/// Both are kept on the track beside this
368/// ([`SubtitleTrack::language`], [`SubtitleTrack::name`]), so an export writes
369/// the container's own two fields rather than guessing them back out of this
370/// string, which is what used to leave every French track marked English.
371fn label_of(language: &str, name: &str) -> String {
372 match (name.is_empty(), language) {
373 (true, lang) => lang.to_owned(),
374 (false, "und") => name.to_owned(),
375 (false, lang) => format!("{lang} — {name}"),
376 }
377}
378
379/// Every subtitle track of a Matroska file, in file order -- the text ones with
380/// their cues, the bitmap ones refused by name (see the module docs).
381pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
382 Ok(crate::demux::matroska_subtitles(path)?
383 .into_iter()
384 .map(|mut t| {
385 let label = label_of(&t.language, &t.name);
386 let bitmap = t.codec == crate::demux::PGS;
387 match cues_of(&mut t) {
388 Ok(cues) => SubtitleTrack {
389 path: path.to_path_buf(),
390 track: Some(t.number),
391 language: t.language,
392 name: t.name,
393 label,
394 cues,
395 bitmap,
396 refused: None,
397 },
398 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),
399 }
400 })
401 .collect())
402}
403
404/// The cues of one Matroska subtitle track, or why it has none.
405///
406/// A Matroska text track carries the *timing* on the block and the *text* in
407/// it, so neither codec is parsed as its own file would be: `S_TEXT/UTF8` is
408/// one SRT cue's body per block, `S_TEXT/ASS` is one `Dialogue` line per block
409/// with the `Start` and `End` fields cut out and the `[Script Info]` header
410/// filed away in `CodecPrivate`. Both are put back into the shape their parser
411/// reads -- rather than the markup being re-derived here -- which is also what
412/// makes an embedded track and the standalone file it was muxed from come back
413/// as the same cues.
414///
415/// A PGS track is neither: its blocks are pictures, and they are moved out of
416/// `track` rather than copied ([`pgs_cues`]) -- thirty megabytes a track is not
417/// a thing to hold twice.
418fn cues_of(track: &mut crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
419 // A track compressed or encrypted with something the demuxer cannot undo is
420 // refused in those words: the row stays, and it says why.
421 if let Some(why) = &track.unsupported {
422 return Err(why.clone());
423 }
424 let cues = match track.codec.as_str() {
425 "S_TEXT/UTF8" | "S_TEXT/ASCII" => track
426 .cues
427 .iter()
428 .map(|c| Cue {
429 start_us: c.start_us,
430 end_us: end_of(track, c),
431 text: srt_body(&String::from_utf8_lossy(&c.payload)),
432 image: None,
433 })
434 .collect(),
435 "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?,
436 crate::demux::PGS => pgs_cues(track),
437 codec => {
438 return Err(format!(
439 "{codec} subtitles are pictures, not text — this track is listed, not read"
440 ));
441 }
442 };
443 Ok(cues)
444}
445
446/// The cues of an `S_HDMV/PGS` track: one display set per block, and a display
447/// set is a picture the disc composes onto its own canvas.
448///
449/// Only the blocks that compose *something* are cues. The other half of them
450/// are the disc's "take it off again" -- a composition with no object on it --
451/// and they are what says when the picture before them goes away, which is why
452/// they are walked and not skipped. A muxer writes `BlockDuration` zero for all
453/// of them, so [`end_of`] is what pairs the two.
454fn pgs_cues(track: &mut crate::demux::MkvSubtitle) -> Vec<Cue> {
455 // Before the blocks are emptied: `end_of` reads the ones after this one.
456 let ends: Vec<i64> = track.cues.iter().map(|c| end_of(track, c)).collect();
457 track
458 .cues
459 .iter_mut()
460 .zip(ends)
461 .filter_map(|(block, end_us)| {
462 let (width, height) = pgs_canvas(&block.payload)?;
463 Some(Cue {
464 start_us: block.start_us,
465 end_us,
466 text: String::new(),
467 image: Some(Arc::new(CueImage {
468 width,
469 height,
470 set: std::mem::take(&mut block.payload),
471 })),
472 })
473 })
474 .collect()
475}
476
477/// The canvas of a display set that paints something -- its `PCS` says how big
478/// the disc's picture is, and how many objects are composed onto it.
479///
480/// `None` when nothing is composed, which is the disc clearing the screen, and
481/// `None` for bytes that are not a display set at all.
482fn pgs_canvas(set: &[u8]) -> Option<(u32, u32)> {
483 /// `PresentationCompositionSegment`, which every display set opens with.
484 const PCS: u8 = 0x16;
485 let (_, pcs) = segments(set)?.into_iter().find(|&(kind, _)| kind == PCS)?;
486 // Width and height, then the frame rate, the composition number and state,
487 // the palette-update flag and the palette id -- and then how many objects
488 // this composition puts on the canvas.
489 let width = u16::from_be_bytes([*pcs.first()?, *pcs.get(1)?]);
490 let height = u16::from_be_bytes([*pcs.get(2)?, *pcs.get(3)?]);
491 (*pcs.get(10)? > 0).then_some((u32::from(width), u32::from(height)))
492}
493
494/// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes
495/// none, and for the PGS block that writes a zero, which says the same thing --
496/// when the next one arrives, and [`NO_DURATION_US`] for the last.
497fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 {
498 /// How long a cue with nothing to say about it stays up: two seconds, a
499 /// read of one line.
500 const NO_DURATION_US: i64 = 2_000_000;
501 match cue.duration_us.filter(|&d| d > 0) {
502 Some(d) => cue.start_us + d,
503 None => track
504 .cues
505 .iter()
506 .map(|c| c.start_us)
507 .find(|&s| s > cue.start_us)
508 .unwrap_or(cue.start_us + NO_DURATION_US),
509 }
510}
511
512/// The text of one `S_TEXT/UTF8` block with its markup resolved: through the
513/// SRT parser, around a timing line this then throws away, because SRT markup
514/// is exactly what such a block holds and a second implementation of it here
515/// would be a second set of bugs.
516fn srt_body(text: &str) -> String {
517 let doc = format!("1\n00:00:00,000 --> 00:00:01,000\n{}\n", text.trim_end());
518 match oxideav_subtitle::srt::parse(doc.as_bytes()) {
519 Ok(track) => track
520 .cues
521 .first()
522 .map(|c| plain_text(&c.segments))
523 .unwrap_or_default(),
524 // The parser refuses nothing an SRT body can hold; if it ever does,
525 // the bytes themselves are a better answer than an empty cue.
526 Err(_) => text.trim_end().to_owned(),
527 }
528}
529
530/// The cues of an `S_TEXT/ASS` track: the script header out of `CodecPrivate`
531/// with every block put back as a `Dialogue` line under it, parsed once as the
532/// `.ass` file it came from.
533fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
534 let mut doc = String::from_utf8_lossy(&track.private).into_owned();
535 if !doc.ends_with('\n') {
536 doc.push('\n');
537 }
538 for cue in &track.cues {
539 let fields = String::from_utf8_lossy(&cue.payload);
540 // `ReadOrder,Layer,<the Format fields from Style on>`: the two the
541 // block adds go, and the timing the block *is* takes their place. The
542 // field order is the one the header's `Format:` line declares, which
543 // is the order a demuxer strips them out of.
544 let mut rest = fields.trim_end().splitn(3, ',');
545 let (_read_order, layer, rest) = match (rest.next(), rest.next(), rest.next()) {
546 (Some(r), Some(l), Some(t)) => (r, l, t),
547 _ => continue,
548 };
549 doc.push_str(&format!(
550 "Dialogue: {layer},{},{},{rest}\n",
551 timestamp(cue.start_us),
552 timestamp(end_of(track, cue))
553 ));
554 }
555 let parsed = oxideav_ass::parse(doc.as_bytes()).map_err(|e| e.to_string())?;
556 // The timings above are centiseconds, which is all an ASS line can say;
557 // the blocks are microseconds. So the text comes from the parse and the
558 // timing from the block -- unless a line was dropped as unparsable, when
559 // the pairing is no longer sound and the parse answers for both.
560 let exact = parsed.cues.len() == track.cues.len();
561 Ok(parsed
562 .cues
563 .iter()
564 .enumerate()
565 .map(|(i, c)| Cue {
566 start_us: if exact {
567 track.cues[i].start_us
568 } else {
569 c.start_us
570 },
571 end_us: if exact {
572 end_of(track, &track.cues[i])
573 } else {
574 c.end_us
575 },
576 text: plain_text(&c.segments),
577 image: None,
578 })
579 .collect())
580}
581
582/// Microseconds as ASS writes a time: `H:MM:SS.cc`.
583fn timestamp(us: i64) -> String {
584 let cs = (us.max(0) + 5_000) / 10_000;
585 format!(
586 "{}:{:02}:{:02}.{:02}",
587 cs / 360_000,
588 cs / 6_000 % 60,
589 cs / 100 % 60,
590 cs % 100
591 )
592}
593
594/// A standalone subtitle file, by extension: the formats this engine reads at
595/// all. Anything else is refused by name, as an unknown media file is.
596fn parse_file(path: &Path) -> crate::Result<Vec<Cue>> {
597 let ext = path
598 .extension()
599 .map(|e| e.to_string_lossy().to_ascii_lowercase())
600 .unwrap_or_default();
601 // The extension before the read: a `.txt` is refused for what it is, not
602 // for whether it happens to be there.
603 type Parse = fn(&[u8]) -> oxideav_core::Result<oxideav_subtitle::ir::SubtitleTrack>;
604 let parse: Parse = match ext.as_str() {
605 "srt" => oxideav_subtitle::srt::parse,
606 "vtt" | "webvtt" => oxideav_subtitle::webvtt::parse,
607 "ass" | "ssa" => oxideav_ass::parse,
608 other => {
609 // What is *genuinely* accepted, all of it: the subtitle files this
610 // parses and the containers [`of_media`] walks for the tracks
611 // inside them (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`, `.mp4`,
612 // `.m4v`, `.mov`). The old sentence named the four text formats
613 // alone and so refused a `.mks` this very binary reads.
614 return Err(format!(
615 "{other:?} is not a subtitle format this reads — .srt, .vtt, .ass and .ssa are, \
616 as are the subtitle tracks inside a Matroska or an mp4"
617 )
618 .into());
619 }
620 };
621 let track = parse(&std::fs::read(path)?);
622 let track = track.map_err(|e| format!("{}: {e}", path.display()))?;
623 Ok(track
624 .cues
625 .iter()
626 .map(|c| Cue {
627 start_us: c.start_us,
628 end_us: c.end_us,
629 text: plain_text(&c.segments),
630 image: None,
631 })
632 .collect())
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638
639 #[test]
640 fn ass_timestamps_are_written_the_way_ass_reads_them() {
641 assert_eq!(timestamp(0), "0:00:00.00");
642 assert_eq!(timestamp(500_000), "0:00:00.50");
643 assert_eq!(timestamp(3_250_000), "0:00:03.25");
644 // An hour, a minute and a second, and a negative time is not one.
645 assert_eq!(timestamp(3_661_000_000), "1:01:01.00");
646 assert_eq!(timestamp(-1), "0:00:00.00");
647 }
648
649 #[test]
650 fn srt_markup_is_resolved_not_carried() {
651 assert_eq!(srt_body("<i>tilted</i> and plain"), "tilted and plain");
652 assert_eq!(srt_body("two\nlines\n"), "two\nlines");
653 }
654
655 /// The sample that is not a cue: a `tx3g` track states one sample per
656 /// instant, so the stretches with nothing on screen are samples of no text
657 /// -- a track of nothing but those is a track with no cues, not one blank
658 /// cue per instant.
659 #[test]
660 fn an_empty_timed_text_sample_is_not_a_cue() {
661 let sample = |payload: Vec<u8>| crate::demux::Mp4TextSample {
662 start_us: 500_000,
663 end_us: 1_500_000,
664 payload,
665 };
666 let mut text = vec![0, 5];
667 text.extend_from_slice(b"lines");
668 let cue = tx3g_cue(&sample(text)).expect("a sample with words is a cue");
669 assert_eq!(
670 (cue.start_us, cue.end_us, &cue.text[..]),
671 (500_000, 1_500_000, "lines")
672 );
673 // The empty sample, the one an export writes between two cues and past
674 // the last of them...
675 assert!(tx3g_cue(&sample(vec![0, 0])).is_none());
676 // ...and the bytes that are not a sample: a length past the payload,
677 // and no length at all.
678 assert!(tx3g_cue(&sample(vec![0, 9, b'h', b'i'])).is_none());
679 assert!(tx3g_cue(&sample(Vec::new())).is_none());
680 }
681
682 /// What a row shows, and what an export has to split back apart: the pair a
683 /// container states, flattened the one way both readers flatten it.
684 #[test]
685 fn a_label_is_the_language_the_title_or_the_two() {
686 assert_eq!(label_of("eng", ""), "eng");
687 assert_eq!(label_of("fra", "Signs"), "fra — Signs");
688 // An undetermined language is no language: the title stands alone.
689 assert_eq!(label_of("und", "Commentary"), "Commentary");
690 assert_eq!(label_of("und", ""), "und");
691 }
692
693 #[test]
694 fn an_unknown_extension_is_refused_by_name_and_a_missing_file_is_kept() {
695 let err = parse_file(Path::new("/nonexistent/notes.txt"))
696 .unwrap_err()
697 .to_string();
698 assert!(err.contains("txt"), "{err}");
699 // ...and a `.srt` that is not there comes back as a track that says so
700 // rather than as no track at all, so a re-save does not lose it.
701 let gone = external(Path::new("/nonexistent/subs.srt"));
702 assert!(gone.refused.is_some());
703 assert_eq!(gone.label, "subs.srt");
704 }
705}