forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

webvtt.rs174 lines, 6.4 KiBHistoryRawDownload
1//! WebVTT (`.vtt`).
2//!
3//! SubRip's shape with a `WEBVTT` header, optional cue identifiers, cue
4//! settings after the timing line, and two tags of its own (`<v Speaker>`,
5//! `<c.class>`) plus inline timestamps. `NOTE`, `STYLE` and `REGION` blocks
6//! are read past: they say nothing about *when* anything is on screen, which
7//! is what this IR carries.
8
9use ec_core::{Error, Result};
10
11use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign};
12use crate::markup::{decode, parse_inline};
13use crate::srt::timing;
14
15/// Parse a WebVTT document.
16///
17/// The `WEBVTT` signature is *expected*, not required — a file missing it but
18/// full of cues is a file of cues. `Err` is for text with no timing line
19/// anywhere, exactly as in [`crate::srt::parse`].
20pub fn parse(bytes: &[u8]) -> Result<SubtitleTrack> {
21 let text = decode(bytes);
22 let mut track = SubtitleTrack::new().with_source(SourceFormat::WebVtt);
23 let mut blocks = text.split("\n\n").peekable();
24 if let Some(first) = blocks.peek()
25 && let Some(header) = first.trim_start().strip_prefix("WEBVTT")
26 {
27 let header = header.trim();
28 if !header.is_empty() {
29 track
30 .metadata
31 .push(("header".to_owned(), header.to_owned()));
32 }
33 track.extradata = first.trim_start().as_bytes().to_vec();
34 blocks.next();
35 }
36 for block in blocks {
37 let lines: Vec<&str> = block.lines().filter(|l| !l.trim().is_empty()).collect();
38 let Some(first) = lines.first() else { continue };
39 // Blocks that are not cues, by their first word.
40 let keyword = first.split_whitespace().next().unwrap_or_default();
41 if matches!(keyword, "NOTE" | "STYLE" | "REGION") {
42 continue;
43 }
44 let Some((at, (start_us, end_us))) = lines
45 .iter()
46 .enumerate()
47 .find_map(|(i, line)| timing(line).map(|t| (i, t)))
48 else {
49 track.skipped += 1;
50 continue;
51 };
52 // Anything before the timing line is the cue identifier, which names
53 // the cue for styling and says nothing about its timing or its text.
54 let body = lines[at + 1..].join("\n");
55 track.cues.push(SubtitleCue {
56 start_us,
57 end_us: end_us.max(start_us),
58 style_ref: None,
59 positioning: settings(lines[at]),
60 segments: parse_inline(body.trim_end(), true),
61 });
62 }
63 if track.cues.is_empty() && text.split_whitespace().next().is_some() {
64 return Err(Error::corrupt(
65 "no WebVTT timing line in the whole document",
66 ));
67 }
68 Ok(track)
69}
70
71/// The `align:`, `position:`, `line:` and `size:` settings after a timing line.
72/// `None` when the line carries none of them.
73fn settings(line: &str) -> Option<CuePosition> {
74 let after = line.split_once("-->")?.1;
75 // The end timestamp first, then the settings.
76 let mut position = CuePosition::default();
77 let mut any = false;
78 for setting in after.split_whitespace().skip(1) {
79 let Some((key, value)) = setting.split_once(':') else {
80 continue;
81 };
82 // `position:10%,line-left` — the alignment suffix is not the number.
83 let number = || {
84 value
85 .split(',')
86 .next()
87 .unwrap_or_default()
88 .trim_end_matches('%')
89 .parse::<f32>()
90 .ok()
91 };
92 match key {
93 "align" => {
94 position.align = match value {
95 "start" => TextAlign::Start,
96 "center" | "middle" => TextAlign::Center,
97 "end" => TextAlign::End,
98 "left" => TextAlign::Left,
99 "right" => TextAlign::Right,
100 _ => continue,
101 };
102 any = true;
103 }
104 "position" => {
105 position.x = number();
106 any |= position.x.is_some();
107 }
108 // A `line` without a `%` is a line *number*, not a percentage;
109 // it is carried as given, which is what the renderer will need.
110 "line" => {
111 position.y = number();
112 any |= position.y.is_some();
113 }
114 "size" => {
115 position.size = number();
116 any |= position.size.is_some();
117 }
118 _ => {}
119 }
120 }
121 any.then_some(position)
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use crate::ir::{Segment, plain_text};
128
129 #[test]
130 fn header_identifiers_notes_and_settings() {
131 let doc = "WEBVTT - a title\n\n\
132 NOTE this block says nothing\n\n\
133 cue-1\n00:00:01.000 --> 00:00:02.000 align:center position:40% line:90%\n\
134 <v Ann>hello</v>\n\n\
135 00:01:00.000 --> 00:01:02.000\nplain\n";
136 let track = parse(doc.as_bytes()).unwrap();
137 assert_eq!(track.source, Some(SourceFormat::WebVtt));
138 assert_eq!(
139 track.metadata,
140 vec![("header".to_owned(), "- a title".to_owned())]
141 );
142 assert_eq!(track.cues.len(), 2);
143 let first = &track.cues[0];
144 assert_eq!((first.start_us, first.end_us), (1_000_000, 2_000_000));
145 let position = first.positioning.unwrap();
146 assert_eq!(position.align, TextAlign::Center);
147 assert_eq!((position.x, position.y), (Some(40.0), Some(90.0)));
148 assert_eq!(plain_text(&first.segments), "hello");
149 assert!(matches!(first.segments[0], Segment::Voice { .. }));
150 assert_eq!(track.cues[1].positioning, None);
151 assert_eq!(track.cues[1].start_us, 60_000_000);
152 }
153
154 #[test]
155 fn inline_timestamps_and_classes_are_runs_not_words() {
156 let doc = "WEBVTT\n\n00:00:00.000 --> 00:00:09.000\n\
157 <c.loud>shout</c><00:00:03.000>then quiet\n";
158 let cue = &parse(doc.as_bytes()).unwrap().cues[0];
159 assert_eq!(plain_text(&cue.segments), "shoutthen quiet");
160 assert!(cue.segments.iter().any(|s| matches!(
161 s,
162 Segment::Timestamp {
163 offset_us: 3_000_000
164 }
165 )));
166 }
167
168 #[test]
169 fn a_file_without_the_signature_still_parses_and_prose_does_not() {
170 let track = parse(b"00:00:01.000 --> 00:00:02.000\nhi\n").unwrap();
171 assert_eq!(track.cues.len(), 1);
172 assert!(parse(b"WEBVTT\n\nNOTE just a note\n\nnot a cue block").is_err());
173 }
174}