Skip to main content

servo_webvtt/cue/
text.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::cell::{Ref, RefCell};
6use std::fmt;
7use std::iter::Peekable;
8use std::rc::{Rc, Weak};
9use std::str::Chars;
10
11use html5ever::data::{C1_REPLACEMENTS, NAMED_ENTITIES};
12
13use crate::collectors::collect_webvtt_timestamp;
14
15/// <https://w3c.github.io/webvtt/#webvtt-internal-node-object>
16#[derive(Debug, Default, PartialEq)]
17pub enum WebVTTNodeObjectKind {
18    /// <https://w3c.github.io/webvtt/#list-of-webvtt-node-objects>
19    #[default]
20    List,
21    /// <https://w3c.github.io/webvtt/#webvtt-class-object>
22    Class,
23    /// <https://w3c.github.io/webvtt/#webvtt-italic-object>
24    Italic,
25    /// <https://w3c.github.io/webvtt/#webvtt-bold-object>
26    Bold,
27    /// <https://w3c.github.io/webvtt/#webvtt-underline-object>
28    Underline,
29    /// <https://w3c.github.io/webvtt/#webvtt-ruby-object>
30    Ruby,
31    /// <https://w3c.github.io/webvtt/#webvtt-ruby-text-object>
32    RubyText,
33    /// <https://w3c.github.io/webvtt/#webvtt-voice-object>
34    /// The string is the name of the voice
35    Voice(String),
36    /// <https://w3c.github.io/webvtt/#webvtt-language-object>
37    Language,
38    /// <https://w3c.github.io/webvtt/#webvtt-text-object>
39    Text(String),
40    /// <https://w3c.github.io/webvtt/#webvtt-timestamp-object>
41    /// The float is the timestamp value
42    Timestamp(WebVTTTimestamp),
43}
44
45/// <https://w3c.github.io/webvtt/#webvtt-timestamp>
46#[derive(Debug, Default, PartialEq)]
47pub struct WebVTTTimestamp(f64);
48
49impl fmt::Display for WebVTTTimestamp {
50    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51        // Step 1. Optionally (required if hours is non-zero):
52        let time = if self.0 >= 60. * 60. {
53            let hours = self.0.div_euclid(60. * 60.);
54            // Step 1.1. Two or more ASCII digits,
55            // representing the hours as a base ten integer.
56            if hours < 10. {
57                write!(f, "0")?;
58            }
59            // Step 1.2. A U+003A COLON character (:)
60            write!(f, "{hours}:")?;
61            self.0.rem_euclid(60. * 60.)
62        } else {
63            // In https://w3c.github.io/webvtt/#dom-construction-rules it
64            // states that it should also include all optional parts. Currently
65            // this is the only place where we serialize a timestamp, hence
66            // for now we always write the hours
67            write!(f, "00:")?;
68            self.0
69        };
70        // Step 2. Two ASCII digits, representing the minutes as
71        // a base ten integer in the range 0 ≤ minutes ≤ 59.
72        let minutes = time.div_euclid(60.);
73        debug_assert!(minutes < 60., "{minutes} minutes is 60 or more");
74        if minutes < 10. {
75            write!(f, "0")?;
76        }
77        // Step 3. A U+003A COLON character (:)
78        write!(f, "{minutes}:")?;
79        // Step 4. Two ASCII digits, representing the seconds as
80        // a base ten integer in the range 0 ≤ seconds ≤ 59.
81        // Step 5. A U+002E FULL STOP character (.).
82        // Step 6. Three ASCII digits, representing the thousandths
83        // of a second seconds-frac as a base ten integer.
84        let seconds = time.rem_euclid(60.);
85        debug_assert!(seconds < 60., "{seconds} seconds is 60 or more");
86        if seconds < 10. {
87            write!(f, "0")?;
88        }
89        write!(f, "{seconds:.3}")?;
90        Ok(())
91    }
92}
93
94/// <https://w3c.github.io/webvtt/#webvtt-node-object>
95#[derive(Debug, Default)]
96pub struct WebVTTNodeObject {
97    /// <https://w3c.github.io/webvtt/#webvtt-node-objects-applicable-classes>
98    pub applicable_classes: Vec<String>,
99    /// <https://w3c.github.io/webvtt/#webvtt-node-objects-applicable-language>
100    pub applicable_language: String,
101    /// <https://w3c.github.io/webvtt/#webvtt-internal-node-object>
102    pub kind: WebVTTNodeObjectKind,
103    children: RefCell<Vec<Rc<WebVTTNodeObject>>>,
104    parent: Weak<WebVTTNodeObject>,
105    index: usize,
106}
107
108impl WebVTTNodeObject {
109    pub fn children(&self) -> Ref<'_, Vec<Rc<WebVTTNodeObject>>> {
110        self.children.borrow()
111    }
112}
113
114impl PartialEq for WebVTTNodeObject {
115    fn eq(&self, other: &Self) -> bool {
116        // We compare all fields except parent
117        self.children.eq(&other.children) &&
118            self.applicable_classes.eq(&other.applicable_classes) &&
119            self.applicable_language.eq(&other.applicable_language) &&
120            self.kind.eq(&other.kind)
121    }
122}
123
124pub trait WebVTTNodeObjectIterable {
125    fn into_iter(self) -> WebVTTNodeObjectIterator;
126}
127
128impl WebVTTNodeObjectIterable for Rc<WebVTTNodeObject> {
129    fn into_iter(self) -> WebVTTNodeObjectIterator {
130        WebVTTNodeObjectIterator {
131            root: self.clone(),
132            current: Some(self),
133            current_child: 0,
134        }
135    }
136}
137
138#[derive(Debug, PartialEq)]
139pub enum WebVTTNodeObjectIteratorDirection {
140    NewChild(Rc<WebVTTNodeObject>),
141    BackToParent,
142}
143
144pub struct WebVTTNodeObjectIterator {
145    // To make sure that the weak pointers are kept alive
146    // while iterating through all objects
147    root: Rc<WebVTTNodeObject>,
148    current: Option<Rc<WebVTTNodeObject>>,
149    current_child: usize,
150}
151
152impl Iterator for WebVTTNodeObjectIterator {
153    type Item = WebVTTNodeObjectIteratorDirection;
154
155    fn next(&mut self) -> Option<WebVTTNodeObjectIteratorDirection> {
156        let current = self.current.clone()?;
157        if let Some(current_child) = current.children.borrow().get(self.current_child) {
158            if matches!(current_child.kind, WebVTTNodeObjectKind::Text(_)) {
159                self.current_child += 1;
160            } else {
161                self.current_child = 0;
162                self.current = Some(current_child.clone());
163            }
164            return Some(WebVTTNodeObjectIteratorDirection::NewChild(
165                current_child.clone(),
166            ));
167        }
168        self.current_child = current.index + 1;
169        self.current = current.parent.upgrade();
170        if self.current.as_ref().is_some_and(|current| {
171            current != &self.root || current.children.borrow().len() > self.current_child
172        }) {
173            return Some(WebVTTNodeObjectIteratorDirection::BackToParent);
174        }
175        None
176    }
177}
178
179/// <https://w3c.github.io/webvtt/#webvtt-cue-text-parsing-rules>
180pub fn webvtt_cue_text_parsing_rules(
181    input: &str,
182    language: Option<String>,
183) -> Rc<WebVTTNodeObject> {
184    // Step 1. Let input be the string being parsed.
185    // Step 2. Let position be a pointer into input,
186    // initially pointing at the start of the string.
187    let mut chars = input.chars().peekable();
188    // Step 3. Let result be a list of WebVTT Node Objects, initially empty.
189    let mut result = WebVTTNodeObject::default();
190    // Step 5. Let language stack be a stack of language tags, initially empty.
191    let mut language_stack = vec![];
192    // Step 6. If language is set, set result’s applicable language to language,
193    // and push language onto the language stack.
194    if let Some(language) = language {
195        result.applicable_language = language.clone();
196        language_stack.push(language);
197    }
198    // Step 4. Let current be the WebVTT Internal Node Object result.
199    let result = Rc::new(result);
200    let mut current = result.clone();
201    // Step 7. Loop: If position is past the end of input, return result and abort these steps.
202    // Step 10. Jump to the step labeled loop.
203    while chars.peek().is_some() {
204        // Step 8. Let token be the result of invoking the WebVTT cue text tokenizer.
205        let token = webvtt_cue_text_tokenizer(&mut chars);
206        // Step 9. Run the appropriate steps given the type of token:
207        match token {
208            // > If token is a string
209            CueTokenizerResult::String(str_) => {
210                // Step 1. Create a WebVTT Text Object whose value is the value of the string token token.
211                // Step 2. Append the newly created WebVTT Text Object to current.
212                let mut children = current.children.borrow_mut();
213
214                let text = Rc::new(WebVTTNodeObject {
215                    kind: WebVTTNodeObjectKind::Text(str_),
216                    index: children.len(),
217                    parent: Rc::downgrade(&current),
218                    ..Default::default()
219                });
220                children.push(text);
221            },
222            // > If token is a start tag
223            CueTokenizerResult::StartTag(tag_name, applicable_classes, annotation) => {
224                // > How the start tag token token is processed depends on its tag name, as follows:
225                let kind = match tag_name.as_ref() {
226                    // > If the tag name is "c"
227                    "c" => {
228                        // > Attach a WebVTT Class Object.
229                        WebVTTNodeObjectKind::Class
230                    },
231                    // > If the tag name is "i"
232                    "i" => {
233                        // > Attach a WebVTT Italic Object.
234                        WebVTTNodeObjectKind::Italic
235                    },
236                    // > If the tag name is "b"
237                    "b" => {
238                        // > Attach a WebVTT Bold Object.
239                        WebVTTNodeObjectKind::Bold
240                    },
241                    // > If the tag name is "u"
242                    "u" => {
243                        // > Attach a WebVTT Underline Object.
244                        WebVTTNodeObjectKind::Underline
245                    },
246                    // > If the tag name is "ruby"
247                    "ruby" => {
248                        // > Attach a WebVTT Ruby Object.
249                        WebVTTNodeObjectKind::Ruby
250                    },
251                    // > If the tag name is "rt"
252                    "rt" => {
253                        // > If current is a WebVTT Ruby Object,
254                        // > then attach a WebVTT Ruby Text Object.
255                        if current.kind != WebVTTNodeObjectKind::Ruby {
256                            continue;
257                        }
258                        WebVTTNodeObjectKind::RubyText
259                    },
260                    // > If the tag name is "v"
261                    "v" => {
262                        // > Attach a WebVTT Voice Object,
263                        // > and set its value to the token’s annotation string,
264                        // > or the empty string if there is no annotation string.
265                        WebVTTNodeObjectKind::Voice(annotation)
266                    },
267                    // > If the tag name is "lang"
268                    "lang" => {
269                        // > Push the value of the token’s annotation string,
270                        // > or the empty string if there is no annotation string,
271                        // > onto the language stack; then attach a WebVTT Language Object.
272                        language_stack.push(annotation);
273                        WebVTTNodeObjectKind::Language
274                    },
275                    // > Otherwise
276                    _ => {
277                        // > Ignore the token.
278                        continue;
279                    },
280                };
281                // https://w3c.github.io/webvtt/#attach-a-webvtt-internal-node-object
282                // Step 1. Create a new WebVTT Internal Node Object of the specified concrete class.
283                current = {
284                    let mut children = current.children.borrow_mut();
285                    let new = WebVTTNodeObject {
286                        kind,
287                        // Step 2. Set the new object’s list of applicable classes
288                        // to the list of classes in the token,
289                        // excluding any classes that are the empty string.
290                        applicable_classes: applicable_classes
291                            .into_iter()
292                            .filter(|class| !class.is_empty())
293                            .collect(),
294                        // Step 3. Set the new object’s applicable language to the top entry on the language stack,
295                        // if the stack is not empty.
296                        applicable_language: language_stack
297                            .last()
298                            .map(|str_| str_.to_string())
299                            .unwrap_or_default(),
300                        index: children.len(),
301                        parent: Rc::downgrade(&current),
302                        ..Default::default()
303                    };
304                    // Step 4. Append the newly created node object to current.
305                    let new = Rc::new(new);
306                    children.push(new.clone());
307                    // Step 5. Let current be the newly created node object.
308                    new
309                };
310            },
311            // > If token is an end tag
312            CueTokenizerResult::EndTag(tag_name) => {
313                // > If any of the following conditions is true,
314                // > then let current be the parent node of current.
315                let matches = match tag_name.as_ref() {
316                    // > The tag name of the end tag token token is "c" and current is a WebVTT Class Object.
317                    "c" => current.kind == WebVTTNodeObjectKind::Class,
318                    // > The tag name of the end tag token token is "i" and current is a WebVTT Italic Object.
319                    "i" => current.kind == WebVTTNodeObjectKind::Italic,
320                    // > The tag name of the end tag token token is "b" and current is a WebVTT Bold Object.
321                    "b" => current.kind == WebVTTNodeObjectKind::Bold,
322                    // > The tag name of the end tag token token is "u" and current is a WebVTT Underline Object.
323                    "u" => current.kind == WebVTTNodeObjectKind::Underline,
324                    // > The tag name of the end tag token token is "ruby" and current is a WebVTT Ruby Object.
325                    "ruby" => {
326                        // > Otherwise, if the tag name of the end tag token token is "ruby"
327                        // > and current is a WebVTT Ruby Text Object,
328                        // > then let current be the parent node of the parent node of current.
329                        if current.kind == WebVTTNodeObjectKind::RubyText {
330                            current = current.parent.upgrade().expect("Must always have a parent");
331                            true
332                        } else {
333                            current.kind == WebVTTNodeObjectKind::Ruby
334                        }
335                    },
336                    // > The tag name of the end tag token token is "rt" and current is a WebVTT Ruby Text Object.
337                    "rt" => current.kind == WebVTTNodeObjectKind::RubyText,
338                    // > The tag name of the end tag token token is "v" and current is a WebVTT Voice Object.
339                    "v" => matches!(current.kind, WebVTTNodeObjectKind::Voice(_)),
340                    // > Otherwise, if the tag name of the end tag token token is "lang"
341                    // > and current is a WebVTT Language Object,
342                    // > then let current be the parent node of current,
343                    // > and pop the top value from the language stack.
344                    "lang" => {
345                        let matches = current.kind == WebVTTNodeObjectKind::Language;
346                        if matches {
347                            language_stack.pop();
348                        }
349                        matches
350                    },
351                    // > Otherwise, ignore the token.
352                    _ => false,
353                };
354                if matches && let Some(parent) = current.parent.upgrade() {
355                    current = parent;
356                }
357            },
358            // > If token is a timestamp tag
359            CueTokenizerResult::TimestampTag(input) => {
360                // Step 1. Let input be the tag value.
361                //
362                // That's part of the match
363
364                // Step 2. Let position be a pointer into input, initially pointing at the start of the string.
365                let mut position = input.chars().peekable();
366                // Step 3. Collect a WebVTT timestamp.
367                // Step 4. If that algorithm does not fail, and if position now points at the end of input
368                // (i.e. there are no trailing characters after the timestamp),
369                // then create a WebVTT Timestamp Object whose value is the collected time,
370                // then append it to current.
371                // Otherwise, ignore the token.
372                if let Some(timestamp) = collect_webvtt_timestamp(position.by_ref()) &&
373                    position.peek().is_none()
374                {
375                    let mut children = current.children.borrow_mut();
376                    let new = WebVTTNodeObject {
377                        kind: WebVTTNodeObjectKind::Timestamp(WebVTTTimestamp(timestamp)),
378                        parent: Rc::downgrade(&current),
379                        index: children.len(),
380                        ..Default::default()
381                    };
382                    children.push(Rc::new(new));
383                }
384            },
385        }
386    }
387    result
388}
389
390/// <https://w3c.github.io/webvtt/#webvtt-cue-text-tokenizer>
391#[derive(PartialEq)]
392enum TokenizerState {
393    WebVTTData,
394    HTMLCharacterReferenceInData,
395    WebVTTTag,
396    WebVTTStartTag,
397    WebVTTStartTagClass,
398    WebVTTStartTagAnnotation,
399    HTMLCharacterReferenceInAnnotation,
400    WebVTTEndTag,
401    WebVTTTimestampTag,
402}
403
404/// <https://w3c.github.io/webvtt/#webvtt-cue-text-tokenizer>
405enum CueTokenizerResult {
406    String(String),
407    StartTag(String, Vec<String>, String),
408    EndTag(String),
409    TimestampTag(String),
410}
411
412/// <https://w3c.github.io/webvtt/#webvtt-cue-text-tokenizer>
413fn webvtt_cue_text_tokenizer(position: &mut Peekable<Chars<'_>>) -> CueTokenizerResult {
414    // Step 1. Let input and position be the same variables as
415    // those of the same name in the algorithm that invoked these steps.
416    //
417    // Passed in as arguments
418
419    // Step 2. Let tokenizer state be WebVTT data state.
420    let mut tokenizer_state = TokenizerState::WebVTTData;
421    // Step 3. Let result be the empty string.
422    let mut result = String::new();
423    let mut buffer = String::new();
424    // Step 4. Let classes be an empty list.
425    let mut classes = vec![];
426    loop {
427        // Step 5. Loop: If position is past the end of input,
428        // let c be an end-of-file marker. Otherwise, let c be the character in input pointed to by position.
429        //
430        // We codify the end-of-file marker as `None`
431        let c = position.peek().copied();
432        // Step 6. Jump to the state given by tokenizer state:
433        match tokenizer_state {
434            // https://w3c.github.io/webvtt/#webvtt-data-state
435            TokenizerState::WebVTTData => {
436                // > Jump to the entry that matches the value of c:
437                match c {
438                    // > U+0026 AMPERSAND (&)
439                    Some('\u{0026}') => {
440                        // > Set tokenizer state to the HTML character reference in data state,
441                        // > and jump to the step labeled next.
442                        tokenizer_state = TokenizerState::HTMLCharacterReferenceInData;
443                    },
444                    // > U+003C LESS-THAN SIGN (<)
445                    Some('\u{003C}') => {
446                        // > If result is the empty string, then set tokenizer state
447                        // > to the WebVTT tag state and jump to the step labeled next.
448                        if result.is_empty() {
449                            tokenizer_state = TokenizerState::WebVTTTag;
450                        } else {
451                            // > Otherwise, return a string token whose value is result and abort these steps.
452                            return CueTokenizerResult::String(result);
453                        }
454                    },
455                    // > End-of-file marker
456                    None => {
457                        // > Return a string token whose value is result and abort these steps.
458                        return CueTokenizerResult::String(result);
459                    },
460                    // > Anything else
461                    Some(c) => {
462                        // > Append c to result and jump to the step labeled next.
463                        result.push(c);
464                    },
465                }
466            },
467            // https://w3c.github.io/webvtt/#html-character-reference-in-data-state
468            TokenizerState::HTMLCharacterReferenceInData => {
469                // > Attempt to consume an HTML character reference, with no additional allowed character.
470                // > If nothing is returned, append a U+0026 AMPERSAND character (&) to result.
471                // > Otherwise, append the data of the character tokens that were returned to result.
472                if let Some([first, second]) = consume_html_char_ref(position) {
473                    result.push(first);
474                    if second != '\0' {
475                        result.push(second)
476                    }
477                } else {
478                    result.push('&');
479                }
480                // > Then, in any case, set tokenizer state to the WebVTT data state,
481                // > and jump to the step labeled next.
482                tokenizer_state = TokenizerState::WebVTTData;
483                // consume_html_char_ref has already managed position, so skip to next loop
484                continue;
485            },
486            // https://w3c.github.io/webvtt/#webvtt-tag-state
487            TokenizerState::WebVTTTag => {
488                // > Jump to the entry that matches the value of c:
489                match c {
490                    // > U+0009 CHARACTER TABULATION (tab) character
491                    // > U+000A LINE FEED (LF) character
492                    // > U+000C FORM FEED (FF) character
493                    // > U+0020 SPACE character
494                    Some('\u{0009}' | '\u{000A}' | '\u{000C}' | '\u{0020}') => {
495                        // > Set tokenizer state to the WebVTT start tag annotation state,
496                        // > and jump to the step labeled next.
497                        tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
498                    },
499                    // > U+002E FULL STOP character (.)
500                    Some('\u{002E}') => {
501                        // > Set tokenizer state to the WebVTT start tag class state,
502                        // > and jump to the step labeled next.
503                        tokenizer_state = TokenizerState::WebVTTStartTagClass;
504                    },
505                    // > U+002F SOLIDUS character (/)
506                    Some('\u{002F}') => {
507                        // > Set tokenizer state to the WebVTT end tag state,
508                        // > and jump to the step labeled next.
509                        tokenizer_state = TokenizerState::WebVTTEndTag;
510                    },
511                    // > ASCII digits
512                    Some(c) if c.is_ascii_digit() => {
513                        // > Set result to c, set tokenizer state to the WebVTT timestamp tag state,
514                        // > and jump to the step labeled next.
515                        result = String::new();
516                        result.push(c);
517                        tokenizer_state = TokenizerState::WebVTTTimestampTag;
518                    },
519                    // > U+003E GREATER-THAN SIGN character (>)
520                    Some('\u{003E}') => {
521                        // > Advance position to the next character in input,
522                        // > then jump to the next "end-of-file marker" entry below.
523                        position.next();
524                        return CueTokenizerResult::StartTag(
525                            Default::default(),
526                            Default::default(),
527                            Default::default(),
528                        );
529                    },
530                    // > End-of-file marker
531                    None => {
532                        // > Return a start tag whose tag name is the empty string,
533                        // > with no classes and no annotation, and abort these steps.
534                        return CueTokenizerResult::StartTag(
535                            Default::default(),
536                            Default::default(),
537                            Default::default(),
538                        );
539                    },
540                    // > Anything else
541                    Some(c) => {
542                        // > Set result to c, set tokenizer state to the WebVTT start tag state,
543                        // > and jump to the step labeled next.
544                        result = c.into();
545                        tokenizer_state = TokenizerState::WebVTTStartTag;
546                    },
547                }
548            },
549            // https://w3c.github.io/webvtt/#webvtt-start-tag-state
550            TokenizerState::WebVTTStartTag => {
551                // > Jump to the entry that matches the value of c:
552                match c {
553                    // > U+0009 CHARACTER TABULATION (tab) character
554                    // > U+000C FORM FEED (FF) character
555                    // > U+0020 SPACE character
556                    Some('\u{0009}' | '\u{000C}' | '\u{0020}') => {
557                        // > Set tokenizer state to the WebVTT start tag annotation state,
558                        // > and jump to the step labeled next.
559                        tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
560                    },
561                    // > U+000A LINE FEED (LF) character
562                    Some('\u{000A}') => {
563                        // > Set buffer to c, set tokenizer state to the WebVTT start tag annotation state,
564                        // > and jump to the step labeled next.
565                        buffer = '\u{000A}'.into();
566                        tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
567                    },
568                    // > U+002E FULL STOP character (.)
569                    Some('\u{002E}') => {
570                        // > Set tokenizer state to the WebVTT start tag class state,
571                        // > and jump to the step labeled next.
572                        tokenizer_state = TokenizerState::WebVTTStartTagClass;
573                    },
574                    // > U+003E GREATER-THAN SIGN character (>)
575                    Some('\u{003E}') => {
576                        // > Advance position to the next character in input,
577                        // > then jump to the next "end-of-file marker" entry below.
578                        position.next();
579                        return CueTokenizerResult::StartTag(
580                            result,
581                            Default::default(),
582                            Default::default(),
583                        );
584                    },
585                    // > End-of-file marker
586                    None => {
587                        // > Return a start tag whose tag name is result,
588                        // > with no classes and no annotation, and abort these steps.
589                        return CueTokenizerResult::StartTag(
590                            result,
591                            Default::default(),
592                            Default::default(),
593                        );
594                    },
595                    // > Anything else
596                    Some(c) => {
597                        // > Append c to result and jump to the step labeled next.
598                        result.push(c);
599                    },
600                }
601            },
602            // https://w3c.github.io/webvtt/#webvtt-start-tag-class-state
603            TokenizerState::WebVTTStartTagClass => {
604                // > Jump to the entry that matches the value of c:
605                match c {
606                    // > U+0009 CHARACTER TABULATION (tab) character
607                    // > U+000C FORM FEED (FF) character
608                    // > U+0020 SPACE character
609                    Some('\u{0009}' | '\u{000C}' | '\u{0020}') => {
610                        // > Append to classes an entry whose value is buffer,
611                        classes.push(buffer);
612                        // > set buffer to the empty string,
613                        buffer = String::new();
614                        // > set tokenizer state to the WebVTT start tag annotation state,
615                        // > and jump to the step labeled next.
616                        tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
617                    },
618                    // > U+000A LINE FEED (LF) character
619                    Some('\u{000A}') => {
620                        // > Append to classes an entry whose value is buffer,
621                        classes.push(buffer);
622                        // > set buffer to c,
623                        buffer = '\u{000A}'.into();
624                        // > set tokenizer state to the WebVTT start tag annotation state,
625                        // > and jump to the step labeled next.
626                        tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
627                    },
628                    // > U+002E FULL STOP character (.)
629                    Some('\u{002E}') => {
630                        // > Append to classes an entry whose value is buffer,
631                        classes.push(buffer);
632                        // > set buffer to the empty string,
633                        buffer = String::new();
634                        // > and jump to the step labeled next.
635                    },
636                    // > U+003E GREATER-THAN SIGN character (>)
637                    Some('\u{003E}') => {
638                        // > Advance position to the next character in input,
639                        // > then jump to the next "end-of-file marker" entry below.
640                        position.next();
641                        classes.push(buffer);
642                        return CueTokenizerResult::StartTag(result, classes, String::new());
643                    },
644                    // > End-of-file marker
645                    None => {
646                        // > Append to classes an entry whose value is buffer,
647                        classes.push(buffer);
648                        // > then return a start tag whose tag name is result,
649                        // > with the classes given in classes but no annotation,
650                        // > and abort these steps.
651                        return CueTokenizerResult::StartTag(result, classes, String::new());
652                    },
653                    // > Anything else
654                    Some(c) => {
655                        // > Append c to buffer and jump to the step labeled next.
656                        buffer.push(c);
657                    },
658                }
659            },
660            // https://w3c.github.io/webvtt/#webvtt-start-tag-annotation-state
661            TokenizerState::WebVTTStartTagAnnotation => {
662                // > Jump to the entry that matches the value of c:
663                match c {
664                    // > U+0026 AMPERSAND (&)
665                    Some('\u{0026}') => {
666                        // > Set tokenizer state to the HTML character reference in annotation state,
667                        // > and jump to the step labeled next.
668                        tokenizer_state = TokenizerState::HTMLCharacterReferenceInAnnotation;
669                    },
670                    // > U+003E GREATER-THAN SIGN character (>)
671                    Some('\u{003E}') => {
672                        // > Advance position to the next character in input,
673                        // > then jump to the next "end-of-file marker" entry below.
674                        position.next();
675                        return CueTokenizerResult::StartTag(
676                            result,
677                            classes,
678                            buffer.trim().to_owned(),
679                        );
680                    },
681                    // > End-of-file marker
682                    None => {
683                        // > Remove any leading or trailing ASCII whitespace characters from buffer,
684                        // > and replace any sequence of one or more consecutive ASCII whitespace characters
685                        // > in buffer with a single U+0020 SPACE character;
686                        // > then, return a start tag whose tag name is result,
687                        // > with the classes given in classes, and with buffer as the annotation,
688                        // > and abort these steps.
689                        // TODO: consecutive whitespace replacing
690                        return CueTokenizerResult::StartTag(
691                            result,
692                            classes,
693                            buffer.trim().to_owned(),
694                        );
695                    },
696                    // > Anything else
697                    Some(c) => {
698                        // > Append c to buffer and jump to the step labeled next.
699                        buffer.push(c);
700                    },
701                }
702            },
703            TokenizerState::HTMLCharacterReferenceInAnnotation => {
704                // > Attempt to consume an HTML character reference,
705                // > with the additional allowed character being U+003E GREATER-THAN SIGN (>).
706                // > If nothing is returned, append a U+0026 AMPERSAND character (&) to buffer.
707                // > Otherwise, append the data of the character tokens that were returned to buffer.
708                if let Some([first, second]) = consume_html_char_ref(position) {
709                    buffer.push(first);
710                    if second != '\0' {
711                        buffer.push(second)
712                    }
713                } else {
714                    buffer.push('&');
715                }
716                // > Then, in any case, set tokenizer state to the WebVTT start tag annotation state,
717                // > and jump to the step labeled next.
718                tokenizer_state = TokenizerState::WebVTTStartTagAnnotation;
719                // consume_html_char_ref has already managed position, so skip to next loop
720                continue;
721            },
722            // https://w3c.github.io/webvtt/#webvtt-end-tag-state
723            TokenizerState::WebVTTEndTag => {
724                // > Jump to the entry that matches the value of c:
725                match c {
726                    // > U+003E GREATER-THAN SIGN character (>)
727                    Some('\u{003E}') => {
728                        // > Advance position to the next character in input,
729                        // > then jump to the next "end-of-file marker" entry below.
730                        position.next();
731                        return CueTokenizerResult::EndTag(result);
732                    },
733                    // > End-of-file marker
734                    None => {
735                        // > Return an end tag whose tag name is result and abort these steps.
736                        return CueTokenizerResult::EndTag(result);
737                    },
738                    // > Anything else
739                    Some(c) => {
740                        // > Append c to result and jump to the step labeled next.
741                        result.push(c);
742                    },
743                }
744            },
745            // https://w3c.github.io/webvtt/#webvtt-timestamp-tag-state
746            TokenizerState::WebVTTTimestampTag => {
747                // > Jump to the entry that matches the value of c:
748                match c {
749                    // > U+003E GREATER-THAN SIGN character (>)
750                    Some('\u{003E}') => {
751                        // > Advance position to the next character in input,
752                        // > then jump to the next "end-of-file marker" entry below.
753                        position.next();
754                        return CueTokenizerResult::TimestampTag(result);
755                    },
756                    // > End-of-file marker
757                    None => {
758                        // > Return a timestamp tag whose tag name is result and abort these steps.
759                        return CueTokenizerResult::TimestampTag(result);
760                    },
761                    // > Anything else
762                    Some(c) => {
763                        // > Append c to result and jump to the step labeled next.
764                        result.push(c);
765                    },
766                }
767            },
768        }
769        // Step 7. Next: Advance position to the next character in input.
770        position.next();
771        // Step 8. Jump to the step labeled loop.
772    }
773}
774
775/// <https://html.spec.whatwg.org/multipage/#character-references>
776fn consume_html_char_ref(position: &mut Peekable<Chars<'_>>) -> Option<[char; 2]> {
777    if position.peek() == Some(&'#') {
778        consume_numeric_char_ref(position)
779    } else {
780        consume_named_char_ref(position)
781    }
782}
783
784/// <https://html.spec.whatwg.org/multipage/#numeric-character-reference-state>
785fn consume_numeric_char_ref(position: &mut Peekable<Chars<'_>>) -> Option<[char; 2]> {
786    let mut lookahead = position.clone();
787
788    // We've already confirmed that the next char is '#',
789    // so start counting at 1.
790    let mut consumed = 1;
791    lookahead.next();
792
793    let base = match lookahead.peek() {
794        // > U+0078 LATIN SMALL LETTER X
795        // > U+0058 LATIN CAPITAL LETTER X
796        // > Switch to the hexadecimal character reference start state.
797        Some(&'x') | Some(&'X') => {
798            lookahead.next();
799            consumed += 1;
800            16
801        },
802        // > ASCII digit
803        // > Reconsume in the decimal character reference state.
804        Some(c) if c.is_ascii_digit() => 10,
805        // > This is an absence-of-digits-in-numeric-character-reference parse error.
806        // > Flush code points consumed as a character reference.
807        _ => return None,
808    };
809
810    let mut digits = String::new();
811    while let Some(&c) = lookahead.peek() {
812        if !c.is_digit(base) {
813            break;
814        }
815
816        digits.push(c);
817        lookahead.next();
818        consumed += 1;
819    }
820
821    // > This is an absence-of-digits-in-numeric-character-reference parse error.
822    // > Flush code points consumed as a character reference.
823    if digits.is_empty() {
824        return None;
825    }
826
827    if lookahead.peek() == Some(&';') {
828        consumed += 1;
829    }
830
831    let value = u32::from_str_radix(&digits, base).unwrap_or(u32::MAX);
832    // <https://html.spec.whatwg.org/multipage/#numeric-character-reference-end-state>
833    let char = match value {
834        // > If the number is 0x00, then this is a null-character-reference parse error.
835        // > Set the character reference code to 0xFFFD.
836        // > If the number is greater than 0x10FFFF, then this is a
837        // > character-reference-outside-unicode-range parse error.
838        // > Set the character reference code to 0xFFFD.
839        // > If the number is a surrogate, then this is a
840        // > surrogate-character-reference parse error.
841        // > Set the character reference code to 0xFFFD.
842        0 | 0xD800..=0xDFFF | 0x110000.. => '\u{FFFD}',
843        0x80..=0x9F => C1_REPLACEMENTS[(value - 0x80) as usize]?,
844        value => char::from_u32(value)?,
845    };
846
847    for _ in 0..consumed {
848        position.next();
849    }
850
851    Some([char, '\0'])
852}
853
854/// <https://html.spec.whatwg.org/multipage/#named-character-reference-state>
855fn consume_named_char_ref(position: &mut Peekable<Chars<'_>>) -> Option<[char; 2]> {
856    let lookahead = position.clone();
857    let mut named_char_buffer = String::new();
858    let mut matched: Option<(usize, u32, u32)> = None;
859
860    // > Consume the maximum number of characters possible,
861    // > where the consumed characters are one of the identifiers
862    // > in the first column of the named character references table.
863    // > Append each character to the temporary buffer when it's consumed.
864    for c in lookahead {
865        if !(c.is_ascii_alphanumeric() || c == ';') {
866            break;
867        }
868        named_char_buffer.push(c);
869
870        // <https://html.spec.whatwg.org/multipage/#named-character-references>
871        match NAMED_ENTITIES.get(&named_char_buffer) {
872            Some(&(first, second)) if first != 0 => {
873                // It's possible the char ref could be valid without the ';',
874                // as with &amp, so we store the first match we find
875                // but keep checking until we hit a delimiter
876                matched = Some((named_char_buffer.len(), first, second));
877                if c == ';' {
878                    break;
879                }
880            },
881            // If the first value in the tuple is 0,
882            // we have not matched against a full name yet
883            Some(_) => {
884                if c == ';' {
885                    break;
886                }
887            },
888            None => break,
889        }
890    }
891
892    let (len, first, second) = matched?;
893
894    for _ in 0..len {
895        position.next();
896    }
897
898    // > Flush code points consumed as a character reference.
899    let first_char = char::from_u32(first)?;
900    let second_char = if second == 0 {
901        '\0'
902    } else {
903        char::from_u32(second)?
904    };
905
906    Some([first_char, second_char])
907}
908
909#[cfg(any(test, feature = "test-util"))]
910impl WebVTTNodeObjectIterator {
911    pub fn assert_and_return_next_child(&mut self) -> Rc<WebVTTNodeObject> {
912        let Some(iterator_direction) = self.next() else {
913            unreachable!("Must have a new item");
914        };
915        let WebVTTNodeObjectIteratorDirection::NewChild(node) = iterator_direction else {
916            unreachable!("Must be a new child");
917        };
918        node
919    }
920
921    pub fn next_is_parent(&mut self) -> bool {
922        let Some(iterator_direction) = self.next() else {
923            unreachable!("Must have a new item");
924        };
925        iterator_direction == WebVTTNodeObjectIteratorDirection::BackToParent
926    }
927}
928
929#[cfg(test)]
930mod tests {
931    use crate::cue::text::WebVTTTimestamp;
932    use crate::shared_test_setup::compute_result_in_seconds;
933
934    #[test]
935    fn test_formats_timestamp_exact_hour_correctly() {
936        let timestamp = WebVTTTimestamp(compute_result_in_seconds(1., 0., 0., 0.));
937
938        assert_eq!(format!("{timestamp}"), "01:00:00.000");
939    }
940
941    #[test]
942    fn test_formats_timestamp_hour_plus_one_minute_correctly() {
943        let timestamp = WebVTTTimestamp(compute_result_in_seconds(1., 1., 0., 0.));
944
945        assert_eq!(format!("{timestamp}"), "01:01:00.000");
946    }
947}