servo_webvtt/lib.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::marker::PhantomData;
6use std::mem;
7
8use html5ever::buffer_queue::{BufferQueue, SetResult};
9use html5ever::tendril::StrTendril;
10use markup5ever::small_char_set;
11
12mod collectors;
13pub mod cue;
14
15use collectors::collect_webvtt_cue_timings_and_settings;
16
17use crate::cue::settings::WebVttCue;
18
19#[derive(Debug, PartialEq)]
20pub enum WebVttParserError {
21 InvalidHeader,
22}
23
24impl std::fmt::Display for WebVttParserError {
25 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 match self {
27 WebVttParserError::InvalidHeader => write!(formatter, "Invalid WebVTT header in file"),
28 }
29 }
30}
31
32#[derive(Clone, Copy, Default, PartialEq)]
33enum ParserState {
34 #[default]
35 FileTag,
36 WhitespaceAfterFileTag,
37 BeforeNewlineAfterFileTag,
38 BeforeHeader,
39 InBlockLoop,
40 AfterBlockLoop,
41 Region,
42 Finished,
43}
44
45pub trait WebVttParserSink<Context> {
46 fn consume_cue(&self, cx: &mut Context, cue: WebVttCue);
47}
48
49#[derive(Default)]
50pub struct IncrementalWebVTTParser<Context, Sink: WebVttParserSink<Context>> {
51 phantom: PhantomData<Context>,
52 pub sink: Sink,
53 buffer: BufferQueue,
54
55 // Checkpoint values
56 seen_cue: bool,
57 seen_eof: bool,
58 seen_arrow: bool,
59
60 // State values
61 in_header: bool,
62 line_count: u32,
63 state: ParserState,
64
65 // Storage values
66 current_line_in_block: StrTendril,
67 current_buffer_in_block: String,
68 lines_from_previous_position: StrTendril,
69
70 current_cue_in_block: Option<WebVttCue>,
71}
72
73pub type ParserUpdate = Result<(), WebVttParserError>;
74
75impl<Context, Sink> IncrementalWebVTTParser<Context, Sink>
76where
77 Sink: WebVttParserSink<Context>,
78{
79 /// <https://w3c.github.io/webvtt/#webvtt-parser-algorithm>
80 pub fn new(sink: Sink) -> Self {
81 Self {
82 sink,
83 phantom: Default::default(),
84 buffer: Default::default(),
85 seen_cue: Default::default(),
86 seen_eof: Default::default(),
87 seen_arrow: Default::default(),
88 in_header: Default::default(),
89 line_count: Default::default(),
90 state: Default::default(),
91 current_line_in_block: Default::default(),
92 current_buffer_in_block: Default::default(),
93 current_cue_in_block: Default::default(),
94 lines_from_previous_position: Default::default(),
95 }
96 }
97
98 pub fn end(&mut self, cx: &mut Context) -> ParserUpdate {
99 self.seen_eof = true;
100 self.step(cx)
101 }
102
103 pub fn parse_sync(&mut self, cx: &mut Context, input: &str) -> ParserUpdate {
104 self.seen_eof = true;
105 self.parse(cx, input)
106 }
107
108 /// <https://w3c.github.io/webvtt/#webvtt-parser-algorithm>
109 pub fn parse(&mut self, cx: &mut Context, input: &str) -> ParserUpdate {
110 // Step 1. Let input be the string being parsed, after conversion to Unicode,
111 // and with the following transformations applied:
112 // > Replace all U+0000 NULL characters by U+FFFD REPLACEMENT CHARACTERs.
113 // > Replace each U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair
114 // > by a single U+000A LINE FEED (LF) character.
115 // > Replace all remaining U+000D CARRIAGE RETURN characters by U+000A LINE FEED (LF) characters.
116 let input = input
117 .replace("\u{0000}", "\u{FFFD}")
118 .replace("\u{000D}\u{000A}", "\u{000A}")
119 .replace("\u{000D}", "\u{000A}");
120 // Step 2. Let position be a pointer into input, initially pointing at the start of the string.
121 // In an incremental WebVTT parser, when this algorithm (or further algorithms that it uses)
122 // moves the position pointer, the user agent must wait until appropriate further characters
123 // from the byte stream have been added to input before moving the pointer,
124 // so that the algorithm never reads past the end of the input string.
125 // Once the byte stream has ended, and all characters have been added to input,
126 // then the position pointer may, when so instructed by the algorithms,
127 // be moved past the end of input.
128 self.buffer.push_back(StrTendril::from(input));
129 self.step(cx)
130 }
131
132 fn step(&mut self, cx: &mut Context) -> ParserUpdate {
133 loop {
134 let current_state = self.state;
135 match current_state {
136 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
137 ParserState::FileTag => {
138 // https://w3c.github.io/webvtt/#webvtt-file-body
139 // > An optional U+FEFF BYTE ORDER MARK (BOM) character.
140 if self.buffer.peek().is_some_and(|c| c == '\u{FEFF}') {
141 let _ = self.buffer.next();
142 }
143 let Some(input) = self.buffer.eat("WEBVTT", u8::eq) else {
144 // Step 4. If input is less than six characters long, then abort these steps.
145 // The file does not start with the correct WebVTT file signature
146 // and was therefore not successfully processed.
147 if self.seen_eof {
148 return Err(WebVttParserError::InvalidHeader);
149 }
150 return Ok(());
151 };
152 // Step 5. If input is exactly six characters long but does not exactly equal "WEBVTT",
153 // then abort these steps. The file does not start with the correct WebVTT
154 // file signature and was therefore not successfully processed.
155 // Step 6. If input is more than six characters long but the first six characters
156 // do not exactly equal "WEBVTT", or the seventh character is not a U+0020 SPACE character,
157 // a U+0009 CHARACTER TABULATION (tab) character, or a U+000A LINE FEED (LF) character,
158 // then abort these steps. The file does not start with the correct WebVTT file signature
159 // and was therefore not successfully processed.
160 //
161 // We check the first part of this step here
162 if !input {
163 return Err(WebVttParserError::InvalidHeader);
164 }
165 self.state = ParserState::WhitespaceAfterFileTag;
166 continue;
167 },
168 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
169 ParserState::WhitespaceAfterFileTag => {
170 let Some(seventh) = self.buffer.peek() else {
171 // Input is exactly six characters and is a valid header
172 if self.seen_eof {
173 self.state = ParserState::Finished;
174 continue;
175 }
176 return Ok(());
177 };
178 // Step 6. If input is more than six characters long but the first six characters
179 // do not exactly equal "WEBVTT", or the seventh character is not a U+0020 SPACE character,
180 // a U+0009 CHARACTER TABULATION (tab) character, or a U+000A LINE FEED (LF) character,
181 // then abort these steps. The file does not start with the correct WebVTT file signature
182 // and was therefore not successfully processed.
183 //
184 // We check the second part of this step here
185 if !matches!(seventh, '\u{0020}' | '\u{0009}' | '\u{000A}') {
186 return Err(WebVttParserError::InvalidHeader);
187 }
188 self.state = ParserState::BeforeNewlineAfterFileTag;
189 continue;
190 },
191 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
192 ParserState::BeforeNewlineAfterFileTag => {
193 // Step 7. collect a sequence of code points that are not U+000A LINE FEED (LF) characters.
194 let Some(current_char) = self.buffer.next() else {
195 // Step 8. If position is past the end of input, then abort these steps.
196 // The file was successfully processed, but it contains no useful data and so
197 // no WebVTT cues were added to output.
198 if self.seen_eof {
199 self.state = ParserState::Finished;
200 continue;
201 }
202 return Ok(());
203 };
204 // Step 9. The character indicated by position is a U+000A LINE FEED (LF) character.
205 // Advance position to the next character in input.
206 if current_char == '\u{000A}' {
207 self.state = ParserState::BeforeHeader;
208 }
209 },
210 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
211 ParserState::BeforeHeader => {
212 let Some(current_char) = self.buffer.peek() else {
213 // Step 10. If position is past the end of input, then abort these steps.
214 // The file was successfully processed, but it contains no useful data and
215 // so no WebVTT cues were added to output.
216 if self.seen_eof {
217 self.state = ParserState::Finished;
218 continue;
219 }
220 return Ok(());
221 };
222 // Step 11. Header: If the character indicated by position is not
223 // a U+000A LINE FEED (LF) character,
224 // then collect a WebVTT block with the in header flag set.
225 // Otherwise, advance position to the next character in input.
226 if current_char != '\u{000A}' {
227 self.in_header = true;
228 self.start_collecting_webvtt_block();
229 } else {
230 self.buffer.next();
231 self.state = ParserState::Region;
232 }
233 },
234 // https://w3c.github.io/webvtt/#collect-a-webvtt-block
235 ParserState::InBlockLoop => {
236 let Some(current_char) =
237 self.buffer.pop_except_from(small_char_set!('\u{000A}'))
238 else {
239 // Step 11.3. If position is past the end of input, let seen EOF be true.
240 // Otherwise, the character indicated by position is a U+000A LINE FEED (LF) character;
241 // advance position to the next character in input.
242 //
243 // We check the first part of this step here
244 // Step 11.7. If seen EOF is true, break out of loop.
245 if self.seen_eof {
246 // It depends when we see the EOF whether there is still content in the buffer or not.
247 // In the case that the EOF is at the end of a line (e.g. no `\n` in between), we
248 // should copy the current line to the buffer. The buffer is then populated with the
249 // line as usual, so that the last line of a file can still be the cue text.
250 if !self.current_line_in_block.is_empty() {
251 if !self.current_buffer_in_block.is_empty() {
252 self.current_buffer_in_block.push('\n');
253 }
254 self.current_buffer_in_block
255 .push_str(&self.current_line_in_block);
256 }
257 self.state = ParserState::AfterBlockLoop;
258 continue;
259 }
260 return Ok(());
261 };
262 match current_char {
263 // Step 11.3. If position is past the end of input, let seen EOF be true.
264 // Otherwise, the character indicated by position is a U+000A LINE FEED (LF) character;
265 // advance position to the next character in input.
266 //
267 // We check the second part of this step here
268 SetResult::FromSet('\u{000A}') => {
269 self.lines_from_previous_position.push_char('\u{000A}');
270 // Step 11.2. Increment line count by 1.
271 self.line_count += 1;
272 // Step 11.4. If line contains the three-character substring "-->"
273 // (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN),
274 // then run these substeps:
275 if self.current_line_in_block.contains("-->") {
276 // Step 11.4.1. If in header is not set and at least
277 // one of the following conditions are true:
278 if !self.in_header &&
279 (
280 // line count is 1
281 self.line_count == 1
282 // line count is 2 and seen arrow is false
283 || (self.line_count == 2 && !self.seen_arrow)
284 )
285 {
286 // Step 11.4.1.1. Let seen arrow be true.
287 self.seen_arrow = true;
288 // Step 11.4.1.2. Let previous position be position.
289 self.lines_from_previous_position.clear();
290 // Step 11.4.1.3. Cue creation: Let cue be a new WebVTT cue and initialize it as follows:
291 // Step 11.4.1.3.1. Let cue’s text track cue identifier be buffer.
292 let identifier = self.current_buffer_in_block.clone();
293 // Step 11.4.1.4. Collect WebVTT cue timings and settings from line using regions for cue.
294 // If that fails, let cue be null.
295 // Otherwise, let buffer be the empty string and let seen cue be true.
296 let cue = collect_webvtt_cue_timings_and_settings(
297 identifier,
298 &self.current_line_in_block,
299 );
300 let has_cue = cue.is_some();
301 self.current_cue_in_block = cue;
302 if has_cue {
303 self.current_buffer_in_block.clear();
304 self.current_line_in_block.clear();
305 self.seen_cue = true;
306 }
307 } else {
308 // Otherwise, let position be previous position and break out of loop.
309 self.state = ParserState::AfterBlockLoop;
310 self.buffer.push_front(std::mem::take(
311 &mut self.lines_from_previous_position,
312 ));
313 }
314 continue;
315 } else if self.current_line_in_block.is_empty() {
316 // Step 11.5. Otherwise, if line is the empty string, break out of loop.
317 self.state = ParserState::AfterBlockLoop;
318 } else {
319 // Step 11.6. Otherwise, run these substeps:
320 // Step 11.6.1. If in header is not set and line count is 2, run these substeps:
321 // TODO
322 // Step 11.6.2. If buffer is not the empty string,
323 // append a U+000A LINE FEED (LF) character to buffer.
324 if !self.current_buffer_in_block.is_empty() {
325 self.current_buffer_in_block.push('\u{000A}');
326 }
327 // Step 11.6.3. Append line to buffer.
328 self.current_buffer_in_block
329 .push_str(&self.current_line_in_block);
330 // Step 11.6.4. Let previous position be position.
331 self.current_line_in_block.clear();
332 self.lines_from_previous_position.clear();
333 }
334 continue;
335 },
336 // Step 11.1. collect a sequence of code points that are not U+000A LINE FEED (LF) characters.
337 // Let line be those characters, if any.
338 SetResult::NotFromSet(current_tendril) => {
339 self.lines_from_previous_position
340 .push_tendril(¤t_tendril);
341 self.current_line_in_block.push_tendril(¤t_tendril);
342 },
343 _ => {
344 unreachable!();
345 },
346 }
347 },
348 ParserState::AfterBlockLoop => {
349 // https://w3c.github.io/webvtt/#collect-a-webvtt-block
350 // Step 12. If cue is not null, let the cue text of cue be buffer, and return cue.
351 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
352 // Step 14.2. If block is a WebVTT cue, add block to the text track list of cues output.
353 if let Some(mut cue) = self.current_cue_in_block.take() {
354 cue.text = self.current_buffer_in_block.clone();
355 self.sink.consume_cue(cx, cue);
356 }
357 // Step 14.3. Otherwise, if block is a CSS style sheet, add block to stylesheets.
358 // TODO
359 // Step 14.4. Otherwise, if block is a WebVTT region object, add block to regions.
360 // TODO
361 // Step 14.5. collect a sequence of code points that are U+000A LINE FEED (LF) characters.
362 let Some(current_char) = self.buffer.peek() else {
363 if self.seen_eof {
364 self.state = ParserState::Finished;
365 continue;
366 }
367 return Ok(());
368 };
369 if current_char == '\u{000A}' {
370 // Since we don't change the state here, it means that if the next character is
371 // also a newline, we re-enter this block and consume it again. Therefore, we
372 // only consume one-by-one.
373 let _ = self.buffer.next();
374 } else {
375 // If we were in the header block, then we should proceed with the next step
376 // which is collecting a region in step 12. Otherwise, we are in the general loop of
377 // step 14.
378
379 if mem::take(&mut self.in_header) {
380 self.state = ParserState::Region;
381 } else {
382 self.start_collecting_webvtt_block();
383 }
384 }
385 },
386 // https://w3c.github.io/webvtt/#webvtt-parser-algorithm
387 ParserState::Region => {
388 // Step 12. collect a sequence of code points that are U+000A LINE FEED (LF) characters.
389 // TODO
390 self.start_collecting_webvtt_block();
391 },
392 ParserState::Finished => {
393 // Step 15. End: The file has ended. Abort these steps. The WebVTT parser has finished.
394 // The file was successfully processed.
395 return Ok(());
396 },
397 }
398 }
399 }
400
401 /// <https://w3c.github.io/webvtt/#collect-a-webvtt-block>
402 fn start_collecting_webvtt_block(&mut self) {
403 // Step 2. Let line count be zero.
404 self.line_count = 0;
405 // Step 3. Let previous position be position.
406 self.lines_from_previous_position.clear();
407 // Step 4. Let line be the empty string.
408 self.current_line_in_block.clear();
409 // Step 5. Let buffer be the empty string.
410 self.current_buffer_in_block.clear();
411 // Step 7. Let seen arrow be false.
412 self.seen_arrow = false;
413 // Step 8. Let cue be null.
414 self.current_cue_in_block = None;
415 self.state = ParserState::InBlockLoop;
416 }
417}
418
419#[cfg(any(test, feature = "test-util"))]
420pub mod shared_test_setup;
421
422#[cfg(test)]
423mod tests {
424 use crate::WebVttParserError;
425 use crate::shared_test_setup::{compute_result_in_seconds, parser_with_dummy_sink};
426
427 #[test]
428 fn test_header_in_two_chunks() {
429 let mut parser = parser_with_dummy_sink();
430 assert_eq!(parser.parse(&mut (), "WEB"), Ok(()));
431 assert_eq!(parser.parse(&mut (), "VTT"), Ok(()));
432 assert_eq!(parser.end(&mut ()), Ok(()));
433 }
434
435 #[test]
436 fn test_invalid_header_in_two_chunks() {
437 let mut parser = parser_with_dummy_sink();
438 assert_eq!(parser.parse(&mut (), "WEB"), Ok(()));
439 assert_eq!(
440 parser.parse(&mut (), "NOT"),
441 Err(WebVttParserError::InvalidHeader)
442 );
443 }
444
445 #[test]
446 fn test_valid_space_character_after_header() {
447 let mut parser = parser_with_dummy_sink();
448 assert_eq!(parser.parse_sync(&mut (), "WEBVTT "), Ok(()));
449 }
450
451 #[test]
452 fn test_no_space_character_after_header_multiple_chunks() {
453 let mut parser = parser_with_dummy_sink();
454 assert_eq!(parser.parse(&mut (), "WEB"), Ok(()));
455 assert_eq!(parser.parse(&mut (), "VTT"), Ok(()));
456 assert_eq!(
457 parser.parse(&mut (), "2"),
458 Err(WebVttParserError::InvalidHeader)
459 );
460 }
461
462 mod cue_settings {
463 use crate::tests::compute_result_in_seconds;
464 use crate::{WebVttCue, collect_webvtt_cue_timings_and_settings};
465
466 #[test]
467 fn test_parses_cue_correctly() {
468 assert_eq!(
469 collect_webvtt_cue_timings_and_settings(
470 Default::default(),
471 "01:10:03.000 --> 02:20:23.000"
472 ),
473 Some(WebVttCue {
474 start_time: compute_result_in_seconds(1., 10., 3., 0.),
475 end_time: compute_result_in_seconds(2., 20., 23., 0.),
476 ..Default::default()
477 })
478 );
479 }
480
481 #[test]
482 fn test_does_not_require_whitespace_around_arrow() {
483 assert_eq!(
484 collect_webvtt_cue_timings_and_settings(
485 Default::default(),
486 "01:10:03.000-->02:20:23.000"
487 ),
488 Some(WebVttCue {
489 start_time: compute_result_in_seconds(1., 10., 3., 0.),
490 end_time: compute_result_in_seconds(2., 20., 23., 0.),
491 ..Default::default()
492 })
493 );
494 }
495
496 #[test]
497 fn test_can_handle_tabs_around_arrow() {
498 assert_eq!(
499 collect_webvtt_cue_timings_and_settings(
500 Default::default(),
501 "01:10:03.000\t-->\t02:20:23.000"
502 ),
503 Some(WebVttCue {
504 start_time: compute_result_in_seconds(1., 10., 3., 0.),
505 end_time: compute_result_in_seconds(2., 20., 23., 0.),
506 ..Default::default()
507 })
508 );
509 }
510
511 #[test]
512 fn test_arrow_too_short_is_invalid() {
513 assert_eq!(
514 collect_webvtt_cue_timings_and_settings(
515 Default::default(),
516 "01:10:03.000 -> t02:20:23.000"
517 ),
518 None
519 );
520 }
521
522 #[test]
523 fn test_arrow_too_long_is_invalid() {
524 assert_eq!(
525 collect_webvtt_cue_timings_and_settings(
526 Default::default(),
527 "01:10:03.000 ---> t02:20:23.000"
528 ),
529 None
530 );
531 }
532
533 #[test]
534 fn test_skips_whitespace_at_start() {
535 assert_eq!(
536 collect_webvtt_cue_timings_and_settings(
537 Default::default(),
538 " 01:10:03.000 --> 02:20:23.000"
539 ),
540 Some(WebVttCue {
541 start_time: compute_result_in_seconds(1., 10., 3., 0.),
542 end_time: compute_result_in_seconds(2., 20., 23., 0.),
543 ..Default::default()
544 })
545 );
546 }
547 }
548}