forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

markup.rs474 lines, 16.4 KiBHistoryRawDownload
1//! The angle-bracket markup SubRip and WebVTT share, plus the byte-level
2//! tolerances every text format here needs.
3//!
4//! Both formats carry a subset of HTML — `<i>`, `<b>`, `<u>`, `<s>`, `<font>`,
5//! and WebVTT's `<v Speaker>`, `<c.class>` and inline timestamps — written by a
6//! thousand tools with a thousand degrees of care. So the rule is that nothing
7//! here fails: an unclosed tag closes at the end of the cue, a stray `</i>`
8//! with nothing open is dropped, and a `<` that begins no tag at all is the
9//! character it looks like.
10
11use crate::ir::Segment;
12
13/// Bytes to text, the way a subtitle file has to be read: a UTF-8 or UTF-16 BOM
14/// consumed, invalid sequences replaced rather than refused, and CRLF (or a
15/// lone CR, which classic Mac tools still write) folded to LF so every parser
16/// after this sees one line ending.
17pub fn decode(bytes: &[u8]) -> String {
18 let text = if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
19 String::from_utf8_lossy(rest).into_owned()
20 } else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
21 utf16(rest, u16::from_le_bytes)
22 } else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
23 utf16(rest, u16::from_be_bytes)
24 } else {
25 String::from_utf8_lossy(bytes).into_owned()
26 };
27 if text.contains('\r') {
28 text.replace("\r\n", "\n").replace('\r', "\n")
29 } else {
30 text
31 }
32}
33
34fn utf16(bytes: &[u8], unit: fn([u8; 2]) -> u16) -> String {
35 let units: Vec<u16> = bytes.chunks_exact(2).map(|c| unit([c[0], c[1]])).collect();
36 String::from_utf16_lossy(&units)
37}
38
39/// `hh:mm:ss,mmm` in microseconds — the timing both text formats state, with
40/// every part they are written with in practice: comma or dot before the
41/// fraction, hours optional, a fraction of one to six digits, a leading minus
42/// on a file whose author shifted it too far.
43pub fn parse_clock(field: &str) -> Option<i64> {
44 let field = field.trim();
45 let (sign, field) = match field.strip_prefix('-') {
46 Some(rest) => (-1, rest),
47 None => (1, field),
48 };
49 let (clock, fraction) = match field.split_once([',', '.']) {
50 Some((clock, fraction)) => (clock, fraction),
51 None => (field, ""),
52 };
53 let mut parts = clock.split(':').rev();
54 let seconds: i64 = parts.next()?.trim().parse().ok()?;
55 let minutes: i64 = parts.next().map_or(Ok(0), |m| m.trim().parse()).ok()?;
56 let hours: i64 = parts.next().map_or(Ok(0), |h| h.trim().parse()).ok()?;
57 if parts.next().is_some() {
58 return None;
59 }
60 // A fraction is a fraction whatever its length: `.5` is half a second and
61 // `.500000` is the same instant.
62 let digits: String = fraction
63 .chars()
64 .take_while(char::is_ascii_digit)
65 .take(6)
66 .collect();
67 let micros = if digits.is_empty() {
68 0
69 } else {
70 let value: i64 = digits.parse().ok()?;
71 value * 10i64.pow(6 - digits.len() as u32)
72 };
73 Some(sign * ((hours * 3600 + minutes * 60 + seconds) * 1_000_000 + micros))
74}
75
76/// One cue body's markup as runs. `webvtt` turns on the two tags only WebVTT
77/// has — `<v>` and `<c>` — and the inline timestamps that go with them.
78pub(crate) fn parse_inline(body: &str, webvtt: bool) -> Vec<Segment> {
79 // A stack of open tags, each with the children collected inside it so far;
80 // the bottom frame is the cue itself and can never be popped.
81 let mut stack: Vec<(Option<Open>, Vec<Segment>)> = vec![(None, Vec::new())];
82 let mut text = String::new();
83 let mut rest = body;
84 while let Some(at) = rest.find('<') {
85 text.push_str(&unescape(&rest[..at]));
86 let after = &rest[at + 1..];
87 let Some(end) = after.find('>') else {
88 // No closing bracket anywhere: the rest of the cue is text.
89 text.push_str(&unescape(&rest[at..]));
90 rest = "";
91 break;
92 };
93 let tag = &after[..end];
94 rest = &after[end + 1..];
95 match classify(tag, webvtt) {
96 Tag::Text => {
97 text.push('<');
98 text.push_str(&unescape(tag));
99 text.push('>');
100 }
101 Tag::Timestamp(offset_us) => {
102 flush(&mut text, &mut stack);
103 push(&mut stack, Segment::Timestamp { offset_us });
104 }
105 Tag::Raw => {
106 flush(&mut text, &mut stack);
107 push(&mut stack, Segment::Raw(format!("<{tag}>")));
108 }
109 Tag::Open(open) => {
110 flush(&mut text, &mut stack);
111 stack.push((Some(open), Vec::new()));
112 }
113 Tag::Close(name) => {
114 flush(&mut text, &mut stack);
115 // Close the innermost frame with that name, and everything
116 // inside it: `<b><i></b>` closes both, which is what a browser
117 // does with the same bytes.
118 let found = stack
119 .iter()
120 .rposition(|(open, _)| open.as_ref().is_some_and(|o| o.name == name));
121 if let Some(depth) = found {
122 while stack.len() > depth {
123 close_top(&mut stack);
124 }
125 }
126 }
127 }
128 }
129 text.push_str(&unescape(rest));
130 flush(&mut text, &mut stack);
131 while stack.len() > 1 {
132 close_top(&mut stack);
133 }
134 stack
135 .pop()
136 .map(|(_, children)| children)
137 .unwrap_or_default()
138}
139
140/// An open tag: its name and the arguments the closing wrapper will need.
141struct Open {
142 name: String,
143 color: Option<(u8, u8, u8)>,
144 family: Option<String>,
145 size: Option<f32>,
146 annotation: String,
147}
148
149enum Tag {
150 Open(Open),
151 Close(String),
152 Timestamp(i64),
153 Raw,
154 /// Not a tag at all — a `<` that means `<`.
155 Text,
156}
157
158fn classify(tag: &str, webvtt: bool) -> Tag {
159 let trimmed = tag.trim();
160 if trimmed.is_empty() {
161 return Tag::Text;
162 }
163 if let Some(name) = trimmed.strip_prefix('/') {
164 let name = name.trim().to_ascii_lowercase();
165 let name = name.split(['.', ' ']).next().unwrap_or("").to_owned();
166 return Tag::Close(name);
167 }
168 // `<00:00:01.500>` is a cue timestamp, not an element.
169 if webvtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) {
170 return match parse_clock(trimmed) {
171 Some(offset_us) => Tag::Timestamp(offset_us),
172 None => Tag::Text,
173 };
174 }
175 let (head, attrs) = match trimmed.split_once(char::is_whitespace) {
176 Some((head, attrs)) => (head, attrs),
177 None => (trimmed, ""),
178 };
179 let (head, classes) = match head.split_once('.') {
180 Some((head, classes)) => (head, classes),
181 None => (head, ""),
182 };
183 let name = head.trim_end_matches('/').to_ascii_lowercase();
184 match name.as_str() {
185 "b" | "i" | "u" | "s" => Tag::Open(Open {
186 name,
187 color: None,
188 family: None,
189 size: None,
190 annotation: String::new(),
191 }),
192 "font" => Tag::Open(Open {
193 name,
194 color: attribute(attrs, "color").and_then(|v| parse_color(&v)),
195 family: attribute(attrs, "face"),
196 size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()),
197 annotation: String::new(),
198 }),
199 "v" | "c" if webvtt => Tag::Open(Open {
200 annotation: match name.as_str() {
201 "v" => attrs.trim().to_owned(),
202 _ => classes.replace('.', " "),
203 },
204 name,
205 color: None,
206 family: None,
207 size: None,
208 }),
209 _ => Tag::Raw,
210 }
211}
212
213/// `name="value"` / `name=value` out of a tag's attribute text.
214fn attribute(attrs: &str, name: &str) -> Option<String> {
215 let lower = attrs.to_ascii_lowercase();
216 let mut from = 0;
217 loop {
218 let at = lower[from..].find(name)? + from;
219 let after = attrs[at + name.len()..].trim_start();
220 match after.strip_prefix('=') {
221 Some(value) => {
222 let value = value.trim_start();
223 let quoted = value.strip_prefix(['"', '\'']);
224 return Some(match quoted {
225 Some(v) => v.split(['"', '\'']).next().unwrap_or(v).to_owned(),
226 None => value
227 .split_whitespace()
228 .next()
229 .unwrap_or_default()
230 .trim_end_matches('/')
231 .to_owned(),
232 });
233 }
234 None => from = at + name.len(),
235 }
236 }
237}
238
239/// `#rrggbb`, `#rgb`, or one of the sixteen names HTML has always had.
240fn parse_color(value: &str) -> Option<(u8, u8, u8)> {
241 let value = value.trim();
242 if let Some(hex) = value.strip_prefix('#') {
243 let digits: String = hex.chars().take_while(char::is_ascii_hexdigit).collect();
244 let byte = |s: &str| u8::from_str_radix(s, 16).ok();
245 return match digits.len() {
246 3 => {
247 let mut c = digits.chars().map(|c| byte(&format!("{c}{c}")));
248 Some((c.next()??, c.next()??, c.next()??))
249 }
250 6 | 8 => Some((
251 byte(&digits[0..2])?,
252 byte(&digits[2..4])?,
253 byte(&digits[4..6])?,
254 )),
255 _ => None,
256 };
257 }
258 let named = [
259 ("black", (0, 0, 0)),
260 ("silver", (192, 192, 192)),
261 ("gray", (128, 128, 128)),
262 ("grey", (128, 128, 128)),
263 ("white", (255, 255, 255)),
264 ("maroon", (128, 0, 0)),
265 ("red", (255, 0, 0)),
266 ("purple", (128, 0, 128)),
267 ("fuchsia", (255, 0, 255)),
268 ("green", (0, 128, 0)),
269 ("lime", (0, 255, 0)),
270 ("olive", (128, 128, 0)),
271 ("yellow", (255, 255, 0)),
272 ("navy", (0, 0, 128)),
273 ("blue", (0, 0, 255)),
274 ("teal", (0, 128, 128)),
275 ("aqua", (0, 255, 255)),
276 ("cyan", (0, 255, 255)),
277 ("magenta", (255, 0, 255)),
278 ];
279 let lower = value.to_ascii_lowercase();
280 named
281 .iter()
282 .find(|(name, _)| *name == lower)
283 .map(|(_, rgb)| *rgb)
284}
285
286/// The handful of entities subtitle text is written with, plus numeric ones.
287fn unescape(text: &str) -> String {
288 if !text.contains('&') {
289 return text.to_owned();
290 }
291 let mut out = String::with_capacity(text.len());
292 let mut rest = text;
293 while let Some(at) = rest.find('&') {
294 out.push_str(&rest[..at]);
295 let after = &rest[at + 1..];
296 let end = after.find(';').filter(|&e| e <= 10);
297 let Some(end) = end else {
298 out.push('&');
299 rest = after;
300 continue;
301 };
302 let name = &after[..end];
303 let replacement = match name.to_ascii_lowercase().as_str() {
304 "amp" => Some('&'),
305 "lt" => Some('<'),
306 "gt" => Some('>'),
307 "quot" => Some('"'),
308 "apos" => Some('\''),
309 "nbsp" => Some('\u{a0}'),
310 "lrm" => Some('\u{200e}'),
311 "rlm" => Some('\u{200f}'),
312 other => other
313 .strip_prefix('#')
314 .and_then(|n| match n.strip_prefix(['x', 'X']) {
315 Some(hex) => u32::from_str_radix(hex, 16).ok(),
316 None => n.parse().ok(),
317 })
318 .and_then(char::from_u32),
319 };
320 match replacement {
321 Some(c) => {
322 out.push(c);
323 rest = &after[end + 1..];
324 }
325 None => {
326 out.push('&');
327 rest = after;
328 }
329 }
330 }
331 out.push_str(rest);
332 out
333}
334
335fn flush(text: &mut String, stack: &mut [(Option<Open>, Vec<Segment>)]) {
336 if !text.is_empty() {
337 let taken = std::mem::take(text);
338 // A newline inside a cue body is a line break, not whitespace.
339 let mut lines = taken.split('\n');
340 if let Some(first) = lines.next()
341 && !first.is_empty()
342 {
343 stack
344 .last_mut()
345 .unwrap()
346 .1
347 .push(Segment::Text(first.into()));
348 }
349 for line in lines {
350 let children = &mut stack.last_mut().unwrap().1;
351 children.push(Segment::LineBreak);
352 if !line.is_empty() {
353 children.push(Segment::Text(line.into()));
354 }
355 }
356 }
357}
358
359fn push(stack: &mut [(Option<Open>, Vec<Segment>)], segment: Segment) {
360 stack.last_mut().unwrap().1.push(segment);
361}
362
363fn close_top(stack: &mut Vec<(Option<Open>, Vec<Segment>)>) {
364 let Some((open, children)) = stack.pop() else {
365 return;
366 };
367 let Some(open) = open else { return };
368 let parent = &mut stack.last_mut().unwrap().1;
369 match open.name.as_str() {
370 "b" => parent.push(Segment::Bold(children)),
371 "i" => parent.push(Segment::Italic(children)),
372 "u" => parent.push(Segment::Underline(children)),
373 "s" => parent.push(Segment::Strike(children)),
374 "v" => parent.push(Segment::Voice {
375 name: open.annotation,
376 children,
377 }),
378 "c" => parent.push(Segment::Class {
379 name: open.annotation,
380 children,
381 }),
382 // `<font>`: whichever of colour and face/size it stated. One that
383 // stated neither is a frame with nothing to say, so it is unwrapped
384 // rather than kept as an empty node.
385 _ => {
386 if let Some(rgb) = open.color {
387 parent.push(Segment::Color { rgb, children });
388 } else if open.family.is_some() || open.size.is_some() {
389 parent.push(Segment::Font {
390 family: open.family,
391 size: open.size,
392 children,
393 });
394 } else {
395 parent.extend(children);
396 }
397 }
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404 use crate::ir::plain_text;
405
406 #[test]
407 fn clocks_are_read_in_every_shape_a_file_writes_them() {
408 assert_eq!(parse_clock("00:00:01,500"), Some(1_500_000));
409 assert_eq!(parse_clock("00:00:01.5"), Some(1_500_000));
410 assert_eq!(parse_clock("1:02:03.250"), Some(3_723_250_000));
411 // Hours omitted, as WebVTT allows.
412 assert_eq!(parse_clock("02:03.000"), Some(123_000_000));
413 // Six digits and beyond.
414 assert_eq!(parse_clock("0:00:00.123456"), Some(123_456));
415 assert_eq!(parse_clock("0:00:00.1234569"), Some(123_456));
416 assert_eq!(parse_clock("-0:00:01.000"), Some(-1_000_000));
417 assert_eq!(parse_clock("not a time"), None);
418 assert_eq!(parse_clock("1:2:3:4.0"), None);
419 }
420
421 #[test]
422 fn decode_takes_the_bom_and_folds_the_line_endings() {
423 assert_eq!(decode(b"\xef\xbb\xbfa\r\nb\rc"), "a\nb\nc");
424 assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, b'i', 0]), "hi");
425 // Invalid UTF-8 is replaced, never refused.
426 assert_eq!(decode(b"a\xffb"), "a\u{fffd}b");
427 }
428
429 #[test]
430 fn markup_nests_and_forgives() {
431 let segments = parse_inline("<i>a</i> <b>b", false);
432 assert_eq!(plain_text(&segments), "a b");
433 assert!(matches!(segments[0], Segment::Italic(_)));
434 assert!(matches!(segments[2], Segment::Bold(_)));
435 // Mismatched close, stray close, and a `<` that is just a `<`.
436 assert_eq!(plain_text(&parse_inline("<b><i>x</b>y", false)), "xy");
437 assert_eq!(plain_text(&parse_inline("</i>plain", false)), "plain");
438 assert_eq!(plain_text(&parse_inline("a < b", false)), "a < b");
439 assert_eq!(
440 plain_text(&parse_inline("2 &lt; 3 &amp; 4", false)),
441 "2 < 3 & 4"
442 );
443 }
444
445 #[test]
446 fn webvtt_only_tags_are_off_for_srt() {
447 let vtt = parse_inline("<v Ann>hi</v>", true);
448 assert!(matches!(vtt[0], Segment::Voice { .. }));
449 assert_eq!(plain_text(&vtt), "hi");
450 let srt = parse_inline("<v Ann>hi", false);
451 assert_eq!(plain_text(&srt), "hi");
452 assert!(matches!(srt[0], Segment::Raw(_)));
453 }
454
455 #[test]
456 fn font_colour_is_read_by_hex_and_by_name() {
457 let segments = parse_inline("<font color=\"#ff0000\">red</font>", false);
458 assert!(matches!(
459 segments[0],
460 Segment::Color {
461 rgb: (255, 0, 0),
462 ..
463 }
464 ));
465 let named = parse_inline("<font color=lime>green</font>", false);
466 assert!(matches!(
467 named[0],
468 Segment::Color {
469 rgb: (0, 255, 0),
470 ..
471 }
472 ));
473 }
474}