forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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