forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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