forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

srt.rs131 lines, 4.9 KiBHistoryRawDownload
1//! SubRip (`.srt`).
2//!
3//! The format is a list of blocks separated by blank lines: an index, a timing
4//! line, then the text. In the wild the index is optional, wrong, or repeated;
5//! the fraction is a comma or a dot; the timing line trails coordinates
6//! (`X1:0 X2:640 …`) that nothing reads any more. So the *timing line* is what
7//! identifies a block here — a block without one is skipped and counted rather
8//! than taken as text of the block before it.
9
10use ec_core::{Error, Result};
11
12use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack};
13use crate::markup::{decode, parse_clock, parse_inline};
14
15/// Parse a SubRip document.
16///
17/// `Err` only when the bytes are not this format at all — text with no timing
18/// line anywhere in it. A file with some torn blocks parses to the blocks that
19/// are whole, with [`SubtitleTrack::skipped`] counting the rest.
20pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
21 let text = decode(bytes);
22 let mut track = SubtitleTrack::new().with_source(SourceFormat::Srt);
23 for block in blocks(&text) {
24 // The timing line is the anchor: everything before it is an index (or
25 // rubbish), everything after it is the cue's text.
26 let Some((at, (start_us, end_us))) = block
27 .iter()
28 .enumerate()
29 .find_map(|(i, line)| timing(line).map(|t| (i, t)))
30 else {
31 track.skipped += 1;
32 continue;
33 };
34 let body = block[at + 1..].join("\n");
35 track.cues.push(SubtitleCue {
36 start_us,
37 // A file that ends a cue before it starts says nothing about how
38 // long it is up; the cue is kept, with no duration rather than a
39 // negative one.
40 end_us: end_us.max(start_us),
41 style_ref: None,
42 positioning: None,
43 segments: parse_inline(body.trim_end(), false),
44 });
45 }
46 if track.cues.is_empty() && text.split_whitespace().next().is_some() {
47 return Err(Error::corrupt(
48 "no SubRip timing line in the whole document",
49 ));
50 }
51 Ok(track)
52}
53
54/// Blocks, split on blank lines, blank ones dropped.
55fn blocks(text: &str) -> impl Iterator<Item = Vec<&str>> {
56 let mut out: Vec<Vec<&str>> = Vec::new();
57 let mut current: Vec<&str> = Vec::new();
58 for line in text.lines() {
59 if line.trim().is_empty() {
60 if !current.is_empty() {
61 out.push(std::mem::take(&mut current));
62 }
63 } else {
64 current.push(line);
65 }
66 }
67 if !current.is_empty() {
68 out.push(current);
69 }
70 out.into_iter()
71}
72
73/// `00:00:01,000 --> 00:00:02,000` with anything after it ignored.
74pub(crate) fn timing(line: &str) -> Option<(i64, i64)> {
75 let (start, rest) = line.split_once("-->")?;
76 let end = rest.split_whitespace().next().unwrap_or_default();
77 Some((parse_clock(start)?, parse_clock(end)?))
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83 use crate::ir::plain_text;
84
85 #[test]
86 fn an_ordinary_file_parses() {
87 let doc = "1\n00:00:01,000 --> 00:00:02,500\nfirst line\nsecond line\n\n\
88 2\n00:00:03,000 --> 00:00:04,000\n<i>tilted</i>\n";
89 let track = parse(doc.as_bytes()).unwrap();
90 assert_eq!(track.source, Some(SourceFormat::Srt));
91 assert_eq!(track.cues.len(), 2);
92 assert_eq!(track.cues[0].start_us, 1_000_000);
93 assert_eq!(track.cues[0].end_us, 2_500_000);
94 assert_eq!(
95 plain_text(&track.cues[0].segments),
96 "first line\nsecond line"
97 );
98 assert_eq!(plain_text(&track.cues[1].segments), "tilted");
99 assert_eq!(track.skipped, 0);
100 }
101
102 #[test]
103 fn the_tolerances_a_real_file_needs() {
104 // BOM, CRLF, no indices, dotted fraction, trailing coordinates, an
105 // overlapping pair, and a block that is text with no timing at all.
106 let doc = b"\xef\xbb\xbf00:00:01.000 --> 00:00:04,000 X1:0 X2:640\r\none\r\n\r\n\
107 junk with no timing\r\n\r\n\
108 00:00:02,000 --> 00:00:03,000\r\ntwo\r\n";
109 let track = parse(doc).unwrap();
110 assert_eq!(track.cues.len(), 2);
111 assert_eq!(track.skipped, 1);
112 assert_eq!(track.cues[0].end_us, 4_000_000);
113 // Overlapping cues stay in file order, both of them.
114 assert_eq!(track.cues[1].start_us, 2_000_000);
115 assert_eq!(plain_text(&track.cues[1].segments), "two");
116 }
117
118 #[test]
119 fn a_backwards_pair_is_clamped_not_negative() {
120 let doc = "1\n00:00:05,000 --> 00:00:01,000\nback\n";
121 let cue = &parse(doc.as_bytes()).unwrap().cues[0];
122 assert_eq!((cue.start_us, cue.end_us), (5_000_000, 5_000_000));
123 }
124
125 #[test]
126 fn text_that_is_not_a_subtitle_file_is_refused_but_empty_is_not() {
127 assert!(parse(b"this is a text file\nwith no timings").is_err());
128 assert_eq!(parse(b"").unwrap().cues.len(), 0);
129 assert_eq!(parse(b"\n\n \n").unwrap().cues.len(), 0);
130 }
131}