Skip to main content

docling_core/
vtt.rs

1//! WebVTT export (#614) — a port of docling-core's `WebVTTDocSerializer`
2//! (`transforms/serializer/webvtt.py`, docling-core 2.101) and the
3//! `WebVTTFile` / `WebVTTCueBlock` formatting it hands its cues to, which is
4//! what docling's `--to vtt` writes.
5//!
6//! The walk is upstream's: the body-layer items in document order (picture
7//! children skipped, captions kept), where only a text item whose `source`
8//! is a track makes a cue — a WebVTT input's cues and an ASR segment
9//! ([`Node::Track`](crate::Node::Track)) — and a title item names the file
10//! (`WEBVTT <title>`). Everything else (tables, pictures, lists, untimed
11//! text) is not represented, so a document without timed text is the bare
12//! `WEBVTT` header, as upstream writes it. The items are read from the
13//! document's JSON export, so this sees exactly the labels, groups,
14//! formatting and tracks the JSON carries.
15//!
16//! Per item, its text gets the cue spans of its formatting — `<b>`, then
17//! `<i>`, then `<u>` around that (upstream's `post_process` order) — and a
18//! `<v voice>` span outermost. An inline group joins its items' texts.
19//! Consecutive items of one cue (same identifier and timings — a voice span
20//! broken over lines in the source) join with a line feed. Redundant tag
21//! pairs (`</i><i>`, `</v>\n<v A>`) are merged by the ports of upstream's two
22//! regular expressions below. Text is escaped as `WebVTTCueTextSpan` writes it
23//! (`&amp;`, `&lt;`); upstream re-parses the cue text instead, and fails on a
24//! raw `&` or `<`.
25
26use serde_json::Value;
27
28use crate::DoclingDocument;
29
30/// Options of the WebVTT export — docling-core's `WebVTTParams`.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct VttExportOptions {
33    /// Write `MM:SS.mmm` when a cue's hour is 0 (`omit_hours_if_zero`).
34    pub omit_hours_if_zero: bool,
35    /// Drop the `</v>` of a cue whose payload is one voice span
36    /// (`omit_voice_end`).
37    pub omit_voice_end: bool,
38}
39
40impl Default for VttExportOptions {
41    /// What docling's `--to vtt` writes (`DoclingDocument.save_as_vtt`): hours
42    /// always, voice end tags omitted.
43    fn default() -> Self {
44        Self {
45            omit_hours_if_zero: false,
46            omit_voice_end: true,
47        }
48    }
49}
50
51pub(crate) fn to_vtt(doc: &DoclingDocument, options: &VttExportOptions) -> String {
52    // Tables stay typed (#875): cues never come from them.
53    let (json, _tables) = crate::json::to_json_typed_tables(doc, false);
54    let mut parts = Vec::new();
55    let mut inline_done = std::collections::HashSet::new();
56    walk(&json, &json["body"], &mut parts, &mut inline_done);
57    serialize_doc(&parts, options)
58}
59
60/// One serialized top-level part: its text and the item that times it.
61struct Part<'a> {
62    text: String,
63    title: bool,
64    track: Option<&'a Value>,
65}
66
67fn resolve<'a>(json: &'a Value, r: &str) -> Option<&'a Value> {
68    let path = r.strip_prefix("#/")?;
69    if path == "body" {
70        return Some(&json["body"]);
71    }
72    let (bucket, idx) = path.split_once('/')?;
73    json.get(bucket)?.get(idx.parse::<usize>().ok()?)
74}
75
76fn children<'a>(json: &'a Value, item: &'a Value) -> Vec<&'a Value> {
77    item["children"]
78        .as_array()
79        .into_iter()
80        .flatten()
81        .filter_map(|c| c["$ref"].as_str().and_then(|r| resolve(json, r)))
82        .collect()
83}
84
85fn is_text(item: &Value) -> bool {
86    item["self_ref"]
87        .as_str()
88        .is_some_and(|r| r.starts_with("#/texts/"))
89}
90
91/// docling-core's `_iterate_items_with_stack` with `with_groups`: every
92/// body-layer node in pre-order, a picture's children skipped bar its
93/// captions; an inline group serializes its items itself (they are then
94/// `visited`).
95fn walk<'a>(
96    json: &'a Value,
97    item: &'a Value,
98    parts: &mut Vec<Part<'a>>,
99    done: &mut std::collections::HashSet<&'a str>,
100) {
101    let self_ref = item["self_ref"].as_str().unwrap_or("");
102    let body_layer = item["content_layer"].as_str().is_none_or(|l| l == "body");
103    if body_layer && !done.contains(self_ref) {
104        if is_text(item) {
105            if let Some(part) = text_part(item, false) {
106                parts.push(part);
107            }
108        } else if item["label"] == "inline" && self_ref.starts_with("#/groups/") {
109            let kids = children(json, item);
110            let mut text = String::new();
111            for kid in &kids {
112                if let Some(r) = kid["self_ref"].as_str() {
113                    done.insert(r);
114                }
115                if is_text(kid) && kid["content_layer"].as_str().is_none_or(|l| l == "body") {
116                    if let Some(part) = text_part(kid, true) {
117                        text.push_str(&part.text);
118                    }
119                }
120            }
121            let text = remove_pairs_until_stable(text);
122            if !text.is_empty() {
123                // The group's first child times it.
124                let first = kids.first().copied();
125                parts.push(Part {
126                    text,
127                    title: false,
128                    track: first.and_then(track_of),
129                });
130            }
131        }
132    }
133    let picture = self_ref.starts_with("#/pictures/");
134    let captions: Vec<&str> = item["captions"]
135        .as_array()
136        .into_iter()
137        .flatten()
138        .filter_map(|c| c["$ref"].as_str())
139        .collect();
140    for (child_ref, child) in item["children"]
141        .as_array()
142        .into_iter()
143        .flatten()
144        .filter_map(|c| c["$ref"].as_str())
145        .filter_map(|r| Some((r, resolve(json, r)?)))
146    {
147        if picture && !captions.contains(&child_ref) {
148            continue;
149        }
150        walk(json, child, parts, done);
151    }
152}
153
154fn track_of(item: &Value) -> Option<&Value> {
155    let source = item["source"].as_array()?.first()?;
156    (source["kind"] == "track").then_some(source)
157}
158
159/// `WebVTTTextSerializer.serialize`: a title's text as is, a timed item's
160/// text with its formatting and voice spans, nothing for the rest.
161fn text_part(item: &Value, inline: bool) -> Option<Part<'_>> {
162    let text = item["text"].as_str().unwrap_or("");
163    if item["label"] == "title" {
164        return Some(Part {
165            text: text.to_string(),
166            title: true,
167            track: None,
168        });
169    }
170    let track = track_of(item)?;
171    if text.is_empty() {
172        return None;
173    }
174    let mut out = escape(text);
175    let f = &item["formatting"];
176    for (flag, tag) in [("bold", "b"), ("italic", "i"), ("underline", "u")] {
177        if f[flag].as_bool() == Some(true) {
178            out = format!("<{tag}>{out}</{tag}>");
179        }
180    }
181    if let Some(voice) = track["voice"].as_str().filter(|v| !v.is_empty()) {
182        out = format!(
183            "<v {}>{out}</v>",
184            voice.replace('&', "&amp;").replace('>', "&gt;")
185        );
186    }
187    if inline {
188        out = remove_pairs_until_stable(out);
189    }
190    Some(Part {
191        text: out,
192        title: false,
193        track: Some(track),
194    })
195}
196
197/// `WebVTTCueTextSpan.__str__`: `&` and the cue-text terminator `<` escaped.
198fn escape(text: &str) -> String {
199    text.replace('&', "&amp;").replace('<', "&lt;")
200}
201
202/// `WebVTTTimestamp.from_seconds(s)`: whole milliseconds, rounded half to
203/// even like Python's `round`.
204fn millis(seconds: f64) -> u64 {
205    (seconds * 1000.0).round_ties_even().max(0.0) as u64
206}
207
208/// `WebVTTTimestamp.seconds` of [`millis`]: what upstream compares a later
209/// item's start/end against when it merges items into one cue.
210fn timestamp_seconds(ms: u64) -> f64 {
211    let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
212    let (m, rest) = (rest / 60_000, rest % 60_000);
213    let (s, milli) = (rest / 1000, rest % 1000);
214    (h * 3600 + m * 60 + s) as f64 + milli as f64 / 1000.0
215}
216
217fn format_timestamp(ms: u64, omit_hours_if_zero: bool) -> String {
218    let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
219    let (m, rest) = (rest / 60_000, rest % 60_000);
220    let (s, milli) = (rest / 1000, rest % 1000);
221    if omit_hours_if_zero && h == 0 {
222        format!("{m:02}:{s:02}.{milli:03}")
223    } else {
224        format!("{h:02}:{m:02}:{s:02}.{milli:03}")
225    }
226}
227
228struct Cue {
229    identifier: Option<String>,
230    start: u64,
231    end: u64,
232    text: String,
233}
234
235/// docling-core's `_cue_timings` (docling-core#1014): both ends in
236/// milliseconds; a segment that rounds onto a zero-length range — a track
237/// source accepts any end after its start, a WebVTT timestamp carries
238/// milliseconds only — is stretched by the smallest step, 1 ms, and the
239/// loss of precision reported, instead of writing `11.000 --> 11.000`
240/// (upstream used to raise for the whole document).
241fn cue_timings(start_s: f64, end_s: f64) -> (u64, u64) {
242    let (start, end) = (millis(start_s), millis(end_s));
243    if end > start {
244        return (start, end);
245    }
246    crate::debug_log!(
247        "vtt: track segment {start_s}..{end_s} collapses onto {} at WebVTT millisecond \
248         precision, extending the cue end to {}",
249        format_timestamp(start, false),
250        format_timestamp(start + 1, false)
251    );
252    (start, start + 1)
253}
254
255/// `WebVTTDocSerializer.serialize_doc` with `WebVTTFile.format`.
256fn serialize_doc(parts: &[Part], options: &VttExportOptions) -> String {
257    let mut title: Option<&str> = None;
258    let mut cues: Vec<Cue> = Vec::new();
259    for part in parts {
260        if part.text.is_empty() {
261            continue;
262        }
263        if part.title {
264            title = Some(&part.text);
265            continue;
266        }
267        let Some(track) = part.track else {
268            continue;
269        };
270        let start_s = track["start_time"].as_f64().unwrap_or(0.0);
271        let end_s = track["end_time"].as_f64().unwrap_or(0.0);
272        let identifier = track["identifier"].as_str().map(str::to_string);
273        if let Some(cue) = cues.last_mut().filter(|c| {
274            c.identifier == identifier
275                && timestamp_seconds(c.start) == start_s
276                && timestamp_seconds(c.end) == end_s
277        }) {
278            let joined = format!("{}\n{}", cue.text.trim_end(), part.text);
279            cue.text = remove_pairs_until_stable(joined);
280        } else {
281            let (start, end) = cue_timings(start_s, end_s);
282            cues.push(Cue {
283                identifier,
284                start,
285                end,
286                text: part.text.clone(),
287            });
288        }
289    }
290    let mut out = match title {
291        Some(t) => format!("WEBVTT {t}\n"),
292        None => "WEBVTT\n".to_string(),
293    };
294    for cue in &cues {
295        out.push('\n');
296        if let Some(id) = &cue.identifier {
297            out.push_str(id);
298            out.push('\n');
299        }
300        out.push_str(&format_timestamp(cue.start, options.omit_hours_if_zero));
301        out.push_str(" --> ");
302        out.push_str(&format_timestamp(cue.end, options.omit_hours_if_zero));
303        out.push('\n');
304        let payload = cue.text.trim_end_matches('\n');
305        if options.omit_voice_end && is_single_voice_span(payload) {
306            out.push_str(payload.strip_suffix("</v>").unwrap_or(payload));
307        } else {
308            out.push_str(payload);
309        }
310        out.push('\n');
311    }
312    out.trim_end_matches('\n').to_string()
313}
314
315/// Whether the payload is one `<v …>…</v>` span — `WebVTTCueBlock.format`'s
316/// condition for `omit_voice_end` (a single component of kind `v`).
317fn is_single_voice_span(payload: &str) -> bool {
318    if !payload.starts_with("<v") || !payload.ends_with("</v>") {
319        return false;
320    }
321    // The opening `<v …>` must be closed by the final `</v>` and nothing else
322    // at depth 0.
323    let mut depth = 0i32;
324    let mut i = 0;
325    let b = payload.as_bytes();
326    while i < b.len() {
327        if b[i] == b'<' {
328            let close = payload[i..].find('>').map(|j| i + j);
329            let Some(end) = close else { return false };
330            let tag = &payload[i + 1..end];
331            if tag.starts_with('/') {
332                depth -= 1;
333                if depth == 0 && end + 1 != b.len() {
334                    return false;
335                }
336            } else if !tag.chars().next().is_some_and(|c| c.is_ascii_digit()) {
337                // `<00:00:01.000>` timestamps are not spans.
338                depth += 1;
339            }
340            i = end + 1;
341        } else {
342            if depth == 0 {
343                return false;
344            }
345            i += 1;
346        }
347    }
348    depth == 0
349}
350
351/// The span names upstream's merge patterns match (`[bciuv]|lang`).
352fn span_name(s: &str) -> Option<&str> {
353    if s.starts_with("lang") {
354        Some("lang")
355    } else {
356        s.chars()
357            .next()
358            .filter(|c| "bciuv".contains(*c))
359            .map(|_| &s[..1])
360    }
361}
362
363/// A start tag `<name(.class)*( annotation)?>` at the start of `s` with the
364/// given name (any name when `None`): (name, classes, annotation, length).
365fn start_tag<'a>(s: &'a str, want: Option<&str>) -> Option<(&'a str, &'a str, &'a str, usize)> {
366    let rest = s.strip_prefix('<')?;
367    let name = match want {
368        Some(w) => rest.starts_with(w).then_some(&rest[..w.len()])?,
369        None => span_name(rest)?,
370    };
371    let mut pos = 1 + name.len();
372    // (?:\.\w+)*
373    let classes_start = pos;
374    loop {
375        let tail = &s[pos..];
376        let Some(after_dot) = tail.strip_prefix('.') else {
377            break;
378        };
379        let word = after_dot
380            .char_indices()
381            .find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
382            .map_or(after_dot.len(), |(i, _)| i);
383        if word == 0 {
384            break;
385        }
386        pos += 1 + word;
387    }
388    let classes = &s[classes_start..pos];
389    // (?:\s+([^>]+))? then `>`
390    let tail = &s[pos..];
391    if let Some(stripped) = tail.strip_prefix('>') {
392        let _ = stripped;
393        return Some((name, classes, "", pos + 1));
394    }
395    let ws = tail
396        .char_indices()
397        .find(|(_, c)| !c.is_whitespace())
398        .map_or(tail.len(), |(i, _)| i);
399    if ws == 0 {
400        return None;
401    }
402    let anno_start = pos + ws;
403    let close = s[anno_start..].find('>')?;
404    if close == 0 {
405        return None;
406    }
407    Some((
408        name,
409        classes,
410        &s[anno_start..anno_start + close],
411        anno_start + close + 1,
412    ))
413}
414
415/// Upstream's first pattern, `re.sub` left to right: `<tag…>content</tag>
416/// ws <tag…>` with matching classes and annotation becomes `<tag…>content
417/// ws` — the second start tag and the first end tag dropped. `content` is the
418/// text up to the first `</tag>` and may not hold a line break (`.` stops at
419/// one); a non-matching pair is consumed unchanged.
420fn merge_adjacent(text: &str) -> String {
421    let mut out = String::with_capacity(text.len());
422    let mut i = 0;
423    while i < text.len() {
424        if let Some(m) = match_adjacent(&text[i..]) {
425            out.push_str(&m.0);
426            i += m.1;
427        } else {
428            let c = text[i..].chars().next().expect("in bounds");
429            out.push(c);
430            i += c.len_utf8();
431        }
432    }
433    out
434}
435
436fn match_adjacent(s: &str) -> Option<(String, usize)> {
437    let (name, classes1, anno1, open_len) = start_tag(s, None)?;
438    let end_tag = format!("</{name}>");
439    let close = s[open_len..].find(&end_tag)?;
440    let content = &s[open_len..open_len + close];
441    if content.contains('\n') {
442        return None;
443    }
444    let after_close = open_len + close + end_tag.len();
445    let tail = &s[after_close..];
446    let ws_len = tail
447        .char_indices()
448        .find(|(_, c)| !c.is_whitespace())
449        .map_or(tail.len(), |(i, _)| i);
450    let ws = &tail[..ws_len];
451    let (_, classes2, anno2, open2_len) = start_tag(&tail[ws_len..], Some(name))?;
452    let total = after_close + ws_len + open2_len;
453    if classes1 == classes2 && anno1 == anno2 {
454        let anno = if anno1.is_empty() {
455            String::new()
456        } else {
457            format!(" {anno1}")
458        };
459        Some((format!("<{name}{classes1}{anno}>{content}{ws}"), total))
460    } else {
461        Some((s[..total].to_string(), total))
462    }
463}
464
465/// Upstream's second pattern: `</tag><other…><tag…>` becomes `<other…>`.
466fn merge_around(text: &str) -> String {
467    let mut out = String::with_capacity(text.len());
468    let mut i = 0;
469    while i < text.len() {
470        if let Some((keep, len)) = match_around(&text[i..]) {
471            out.push_str(keep);
472            i += len;
473        } else {
474            let c = text[i..].chars().next().expect("in bounds");
475            out.push(c);
476            i += c.len_utf8();
477        }
478    }
479    out
480}
481
482fn match_around(s: &str) -> Option<(&str, usize)> {
483    let rest = s.strip_prefix("</")?;
484    let name = span_name(rest)?;
485    let after_name = 2 + name.len();
486    if !s[after_name..].starts_with('>') {
487        return None;
488    }
489    let mid_start = after_name + 1;
490    let tail = &s[mid_start..];
491    if !tail.starts_with('<') {
492        return None;
493    }
494    let mid_close = tail[1..].find('>')? + 1;
495    if mid_close < 2 {
496        return None;
497    }
498    let mid = &tail[..mid_close + 1];
499    let (_, _, _, open_len) = start_tag(&tail[mid.len()..], Some(name))?;
500    Some((mid, mid_start + mid.len() + open_len))
501}
502
503/// `_remove_consecutive_pairs` until nothing changes.
504fn remove_pairs_until_stable(mut text: String) -> String {
505    loop {
506        let next = merge_around(&merge_adjacent(&text));
507        if next == text {
508            return text;
509        }
510        text = next;
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    #[test]
519    fn merges_like_upstreams_patterns() {
520        // Each expected value is docling-core 2.101's `_remove_consecutive_pairs`
521        // run to a fixed point on the same input.
522        let cases = [
523            ("<i>a</i> <i>b</i>", "<i>a b</i>"),
524            (
525                "<v Speaker A>OK,</v>\n<v Speaker A>I think</v>",
526                "<v Speaker A>OK,\nI think</v>",
527            ),
528            ("<v A>x</v> <v B>y</v>", "<v A>x</v> <v B>y</v>"),
529            (
530                "<i><b>unexpected</b></i><i> </i><u><i>arcobaleno</i></u><i> of flavors</i>",
531                "<i><b>unexpected</b> <u>arcobaleno</u> of flavors</i>",
532            ),
533            ("<b.loud>a</b><b.loud>b</b>", "<b.loud>ab</b>"),
534            ("<b.loud>a</b><b>b</b>", "<b.loud>a</b><b>b</b>"),
535            // `.` stops at a line break: no merge across one inside a span.
536            ("<i>a\nb</i><i>c</i>", "<i>a\nb</i><i>c</i>"),
537            ("<lang en>x</lang><lang en>y</lang>", "<lang en>xy</lang>"),
538            // Two tags in between: neither pattern applies.
539            ("<u>a</u><i></i><u>b</u>", "<u>a</u><i></i><u>b</u>"),
540            ("<b>a</b>  \n <b>c</b>", "<b>a  \n c</b>"),
541        ];
542        for (input, want) in cases {
543            assert_eq!(
544                remove_pairs_until_stable(input.to_string()),
545                want,
546                "{input}"
547            );
548        }
549    }
550
551    /// An ASR segment as `docling-asr` builds it: the `[time: …]`
552    /// paragraph wrapped in its track.
553    fn segment(start: f64, end: f64, words: &str) -> crate::Node {
554        crate::Node::Track {
555            track: crate::tree::TreeTrack {
556                start_time: start,
557                end_time: end,
558                identifier: None,
559                voice: None,
560            },
561            cue: words.into(),
562            inner: Box::new(crate::Node::Paragraph {
563                text: format!("[time: {start}-{end}] {words}"),
564            }),
565        }
566    }
567
568    /// docling-core#1014
569    /// (`test_webvtt_cue_shorter_than_a_millisecond_stays_serializable`): a
570    /// sub-millisecond segment keeps a 1 ms cue; the next cue is unchanged.
571    #[test]
572    fn sub_millisecond_cue_stays_serializable() {
573        let mut doc = DoclingDocument::new("sub-millisecond-cue");
574        doc.push(segment(11.00001, 11.00002, "short cue"));
575        doc.push(segment(12.0, 13.5, "normal cue"));
576        assert_eq!(
577            doc.export_to_vtt(),
578            "WEBVTT\n\n00:00:11.000 --> 00:00:11.001\nshort cue\n\n\
579             00:00:12.000 --> 00:00:13.500\nnormal cue"
580        );
581    }
582
583    /// The flat (ASR) path against docling-core 2.101: the same segments as
584    /// `add_text(..., source=TrackSource(...))` items give exactly these
585    /// files — cues of the words alone, identical timings merged into one
586    /// cue, the zero-duration bump visible, hours written.
587    #[test]
588    fn asr_segments_become_cues_like_upstream() {
589        let mut doc = DoclingDocument::new("talk");
590        for (s, e, t) in [
591            (0.0, 2.345678, "And so my fellow Americans"),
592            (2.5, 2.501, "ask not"),
593            (3.0, 4.25, "what your country"),
594            (3.0, 4.25, "can do for you"),
595            (3661.2, 3662.0, "late remark"),
596        ] {
597            doc.push(segment(s, e, t));
598        }
599        assert_eq!(
600            doc.export_to_vtt(),
601            "WEBVTT\n\n00:00:00.000 --> 00:00:02.346\nAnd so my fellow Americans\n\n\
602             00:00:02.500 --> 00:00:02.501\nask not\n\n00:00:03.000 --> 00:00:04.250\n\
603             what your country\ncan do for you\n\n01:01:01.200 --> 01:01:02.000\nlate remark"
604        );
605        // The JSON item is docling 2.135's ASR item: the words as text, the
606        // timing as its track source.
607        let json = doc.export_to_json_value();
608        assert_eq!(json["texts"][0]["text"], "And so my fellow Americans");
609        assert_eq!(json["texts"][0]["orig"], "And so my fellow Americans");
610        assert_eq!(
611            json["texts"][0]["source"],
612            serde_json::json!([{"kind": "track", "start_time": 0.0, "end_time": 2.345678}])
613        );
614        // Markdown is untouched by the wrapper.
615        assert!(doc
616            .export_to_markdown()
617            .starts_with("[time: 0-2.345678] And so"));
618    }
619
620    /// Without timed text the file is the header — with the title, if any
621    /// (docling-core writes `WEBVTT My Title` / `WEBVTT`).
622    #[test]
623    fn untimed_documents_are_the_bare_header() {
624        let mut doc = DoclingDocument::new("x");
625        doc.push(crate::Node::Heading {
626            level: 1,
627            text: "My Title".into(),
628        });
629        doc.push(crate::Node::Paragraph {
630            text: "no timing".into(),
631        });
632        assert_eq!(doc.export_to_vtt(), "WEBVTT My Title");
633        let mut doc = DoclingDocument::new("y");
634        doc.push(crate::Node::Paragraph {
635            text: "no timing".into(),
636        });
637        assert_eq!(doc.export_to_vtt(), "WEBVTT");
638    }
639
640    /// Cue text is escaped as `WebVTTCueTextSpan` writes it (upstream fails
641    /// on a raw `&` or `<` instead).
642    #[test]
643    fn cue_text_is_escaped() {
644        let mut doc = DoclingDocument::new("e");
645        doc.push(segment(1.0, 2.0, "Q&A: a < b > c"));
646        assert_eq!(
647            doc.export_to_vtt(),
648            "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nQ&amp;A: a &lt; b > c"
649        );
650    }
651
652    #[test]
653    fn timestamps_round_half_even_and_format() {
654        assert_eq!(format_timestamp(millis(4.963), false), "00:00:04.963");
655        assert_eq!(format_timestamp(millis(14_586.5), false), "04:03:06.500");
656        assert_eq!(format_timestamp(millis(62.0), true), "01:02.000");
657        assert_eq!(millis(0.0005), 0); // 0.5 ms → even
658        assert_eq!(millis(0.0015), 2);
659        assert_eq!(timestamp_seconds(millis(4.963)), 4.963);
660    }
661
662    #[test]
663    fn voice_end_is_omitted_only_for_a_lone_voice_span() {
664        assert!(is_single_voice_span("<v A>OK,\nI think</v>"));
665        assert!(is_single_voice_span("<v A><i>x</i> y</v>"));
666        assert!(!is_single_voice_span("<v Esme>Hee!</v> <i>laughter</i>"));
667        assert!(!is_single_voice_span("<v A>x</v><v B>y</v>"));
668        assert!(!is_single_voice_span("plain"));
669    }
670}