Skip to main content

ultrafast_render/
captions.rs

1//! Animated captions from word timings: the karaoke, pop-on and reveal
2//! styles of social video, as ordinary text nodes.
3//!
4//! Words (from a transcript file or inline) are laid out into pages that
5//! fit `width` and `max_lines`, breaking at sentence ends and pauses. Every
6//! word is its own `text` node, colored, scaled and faded by keyframes at
7//! its own time, and every page is a layer with a visibility window, so a
8//! caption track costs only the page on screen, and any word can be
9//! edited afterwards (`ultrafast captions` writes the component).
10
11use crate::geom::{Fonts, measure};
12use std::collections::BTreeMap;
13use std::path::Path;
14use ultrafast_graph::{Component, Document, Format, Node, Param};
15
16#[derive(Debug, Clone, PartialEq)]
17pub struct Word {
18    pub text: String,
19    pub start: f64,
20    pub end: f64,
21}
22
23/// Parses word timings: JSON (a list of `{word|text, start, end}`, or
24/// `{words: [...]}`, or Whisper's `{segments: [{words: [...]}]}`), SRT /
25/// WebVTT (each cue's words spread over the cue by length), or plain
26/// lines of `start end word`.
27pub fn parse(src: &str) -> Result<Vec<Word>, String> {
28    let s = src.trim_start_matches('\u{feff}').trim();
29    let words = if s.starts_with('[') || s.starts_with('{') {
30        let v: serde_json::Value = serde_json::from_str(s).map_err(|e| format!("captions JSON: {e}"))?;
31        let mut list = Vec::new();
32        collect_json(&v, &mut list);
33        list
34    } else if s.contains("-->") {
35        parse_cues(s)?
36    } else {
37        let mut list = Vec::new();
38        for (i, line) in s.lines().enumerate() {
39            let line = line.trim();
40            if line.is_empty() {
41                continue;
42            }
43            let mut it = line.splitn(3, char::is_whitespace);
44            let (a, b, w) = (it.next(), it.next(), it.next());
45            match (a.and_then(|a| a.parse().ok()), b.and_then(|b| b.parse().ok()), w) {
46                (Some(start), Some(end), Some(w)) => list.push(Word {
47                    text: w.trim().to_string(),
48                    start,
49                    end,
50                }),
51                _ => return Err(format!("captions line {}: expected `start end word`", i + 1)),
52            }
53        }
54        list
55    };
56    let mut words: Vec<Word> = words.into_iter().filter(|w| !w.text.trim().is_empty()).collect();
57    for w in &mut words {
58        w.text = w.text.trim().to_string();
59        if w.end < w.start {
60            w.end = w.start;
61        }
62    }
63    words.sort_by(|a, b| a.start.total_cmp(&b.start));
64    if words.is_empty() {
65        return Err("captions: no words".into());
66    }
67    Ok(words)
68}
69
70fn collect_json(v: &serde_json::Value, out: &mut Vec<Word>) {
71    match v {
72        serde_json::Value::Array(a) => a.iter().for_each(|x| collect_json(x, out)),
73        serde_json::Value::Object(o) => {
74            if let Some(ws) = o.get("words").or_else(|| o.get("segments")) {
75                return collect_json(ws, out);
76            }
77            let text = o.get("word").or_else(|| o.get("text")).and_then(|x| x.as_str());
78            let num = |k: &str| o.get(k).and_then(|x| x.as_f64());
79            if let (Some(t), Some(s), Some(e)) = (text, num("start"), num("end")) {
80                out.push(Word {
81                    text: t.to_string(),
82                    start: s,
83                    end: e,
84                });
85            }
86        }
87        _ => {}
88    }
89}
90
91fn parse_time(t: &str) -> Option<f64> {
92    // hh:mm:ss,mmm | mm:ss.mmm | ss.mmm
93    let t = t.trim().replace(',', ".");
94    let parts: Vec<&str> = t.split(':').collect();
95    let mut secs = 0.0;
96    for p in &parts {
97        secs = secs * 60.0 + p.trim().parse::<f64>().ok()?;
98    }
99    Some(secs)
100}
101
102fn parse_cues(s: &str) -> Result<Vec<Word>, String> {
103    let mut out = Vec::new();
104    let lines: Vec<&str> = s.lines().collect();
105    let mut i = 0;
106    while i < lines.len() {
107        if let Some((a, b)) = lines[i].split_once("-->") {
108            let start = parse_time(a).ok_or_else(|| format!("captions: bad time `{a}`"))?;
109            // VTT cue settings follow the end time.
110            let end = parse_time(b.split_whitespace().next().unwrap_or(""))
111                .ok_or_else(|| format!("captions: bad time `{b}`"))?;
112            let mut text = String::new();
113            i += 1;
114            while i < lines.len() && !lines[i].trim().is_empty() {
115                text.push(' ');
116                text.push_str(lines[i].trim());
117                i += 1;
118            }
119            // Strip simple markup (<i>, {\an8}).
120            let mut clean = String::new();
121            let mut skip = None;
122            for c in text.chars() {
123                match (skip, c) {
124                    (None, '<') => skip = Some('>'),
125                    (None, '{') => skip = Some('}'),
126                    (Some(e), c) if c == e => skip = None,
127                    (Some(_), _) => {}
128                    (None, c) => clean.push(c),
129                }
130            }
131            let ws: Vec<&str> = clean.split_whitespace().collect();
132            let total: usize = ws.iter().map(|w| w.chars().count() + 1).sum();
133            let mut t = start;
134            for w in ws {
135                let d = (end - start) * (w.chars().count() + 1) as f64 / total.max(1) as f64;
136                out.push(Word {
137                    text: w.to_string(),
138                    start: t,
139                    end: t + d,
140                });
141                t += d;
142            }
143        } else {
144            i += 1;
145        }
146    }
147    Ok(out)
148}
149
150/// Caption style knobs, read from the node's params.
151struct Style {
152    font: Param,
153    size: f64,
154    weight: f64,
155    color: String,
156    highlight: String,
157    spoken: String,
158    pill: Option<String>,
159    /// A rounded box behind each page.
160    backing: Option<String>,
161    mode: String,
162    width: f64,
163    max_lines: usize,
164    line_height: f64,
165    position: [f64; 2],
166    align: String,
167    uppercase: bool,
168    tracking: f64,
169    linger: f64,
170    /// `[x0, y0, x1, y1]` every page stays inside (`None`: exactly at
171    /// `position`).
172    safe: Option<[f64; 4]>,
173}
174
175/// The area captions keep to, from the `safe` param: `auto` (the default)
176/// is clear of the social apps' buttons and captions on a vertical frame
177/// (the area `review --safe social` checks) and inside a 4% margin
178/// otherwise; `social` and `margin` choose one; `none` places pages exactly
179/// at `position`.
180fn safe_area(node: &Node, fmt: &Format) -> Option<[f64; 4]> {
181    use crate::review::SafeArea;
182    let (w, h) = (fmt.width as f64, fmt.height as f64);
183    let area = match text(node, "safe").as_deref() {
184        Some("none") => return None,
185        Some("social") => SafeArea::Social,
186        Some("margin") => SafeArea::Margin(0.04),
187        _ if h > w => SafeArea::Social,
188        _ => SafeArea::Margin(0.04),
189    };
190    // A little inside it: ink overshoots the font's ascent and descent, and
191    // the spoken word swells.
192    let inset = 0.012 * w.min(h);
193    let [x0, y0, x1, y1] = area.rect(w, h);
194    Some([x0 + inset, y0 + inset, x1 - inset, y1 - inset])
195}
196
197fn text(node: &Node, k: &str) -> Option<String> {
198    match node.params.get(k) {
199        Some(Param::Text(s)) => Some(s.clone()),
200        _ => None,
201    }
202}
203
204fn number(node: &Node, k: &str, d: f64) -> f64 {
205    node.params
206        .get(k)
207        .and_then(|p| p.eval(0.0))
208        .and_then(|v| v.first().copied())
209        .unwrap_or(d)
210}
211
212fn style(node: &Node, fmt: &Format) -> Style {
213    let (w, h) = (fmt.width as f64, fmt.height as f64);
214    let size = number(node, "size", (w.min(h) * 0.065).round());
215    let color = text(node, "color").unwrap_or_else(|| "#ffffff".into());
216    let pos = node
217        .params
218        .get("position")
219        .and_then(|p| p.eval(0.0))
220        .unwrap_or_default();
221    let safe = safe_area(node, fmt);
222    // A page's backing box reaches past its words.
223    let pad_x = if text(node, "background").is_some() {
224        size * 0.42
225    } else {
226        0.0
227    };
228    let mut width = number(node, "width", w * 0.82);
229    let mut position = [
230        pos.first().copied().unwrap_or(w / 2.0),
231        pos.get(1).copied().unwrap_or(h * 0.72),
232    ];
233    if let Some([x0, _, x1, _]) = safe {
234        // Lines no wider than the area, and the line box inside it (pages
235        // are kept inside vertically as they are laid out).
236        width = width.min(x1 - x0 - 2.0 * pad_x).max(size);
237        let (lo, hi) = (x0 + pad_x + width / 2.0, x1 - pad_x - width / 2.0);
238        position[0] = if lo <= hi {
239            position[0].clamp(lo, hi)
240        } else {
241            (x0 + x1) / 2.0
242        };
243    }
244    Style {
245        font: node
246            .params
247            .get("font")
248            .cloned()
249            .unwrap_or(Param::Text("Helvetica Neue".into())),
250        size,
251        weight: number(node, "weight", 800.0),
252        highlight: text(node, "highlight").unwrap_or_else(|| "#ffd23f".into()),
253        spoken: text(node, "spoken").unwrap_or_else(|| color.clone()),
254        color,
255        pill: text(node, "highlight_background"),
256        backing: text(node, "background"),
257        mode: text(node, "style").unwrap_or_else(|| "karaoke".into()),
258        width,
259        max_lines: number(node, "max_lines", 2.0).max(1.0) as usize,
260        line_height: number(node, "line_height", 1.18),
261        position,
262        align: text(node, "align").unwrap_or_else(|| "center".into()),
263        uppercase: matches!(node.params.get("uppercase"), Some(Param::Bool(true))),
264        tracking: number(node, "tracking", 0.0),
265        linger: number(node, "linger", 0.6),
266        safe,
267    }
268}
269
270/// Params every caption node exposes on its instance.
271pub const PARAMS: &[&str] = &["opacity"];
272
273/// Lays the words out into pages of text nodes.
274pub fn build(words: &[Word], node: &Node, fmt: &Format, fonts: &mut Fonts, base: &Path) -> Result<Component, String> {
275    let st = style(node, fmt);
276    let shown = |w: &Word| {
277        if st.uppercase {
278            w.text.to_uppercase()
279        } else {
280            w.text.clone()
281        }
282    };
283    let word_node = |s: &str| {
284        let mut p = BTreeMap::new();
285        p.insert("text".to_string(), Param::Text(s.to_string()));
286        p.insert("font".to_string(), st.font.clone());
287        p.insert("size".to_string(), Param::Number(st.size));
288        p.insert("weight".to_string(), Param::Number(st.weight));
289        p.insert("tracking".to_string(), Param::Number(st.tracking));
290        for k in ["style", "variations", "features"] {
291            if let Some(v) = node.params.get(k)
292                && (k != "style" || matches!(v, Param::Text(s) if s == "italic" || s == "normal"))
293            {
294                p.insert(k.to_string(), v.clone());
295            }
296        }
297        Node {
298            op: "text".into(),
299            params: p,
300            ..Default::default()
301        }
302    };
303    let advance = |fonts: &mut Fonts, s: &str| -> Result<(f64, f64, f64), String> {
304        let m = measure("captions", &word_node(s), 0.0, fonts, base).map_err(|e| e.to_string())?;
305        Ok((m.advance, m.ascent, m.descent))
306    };
307    let (space, ascent, descent) = advance(fonts, " ")?;
308    // Room for the highlight pill between words.
309    let space = if st.pill.is_some() {
310        space + st.size * 0.16
311    } else {
312        space
313    };
314    let all: String = words.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" ");
315    let line_px = st.size * st.line_height * fonts.script_leading(&all);
316    // A right-to-left line starts at the right, and "left" means its start.
317    let rtl = fonts.reads_rtl(&all);
318
319    // Pages of lines of (word index, advance).
320    let mut pages: Vec<Vec<Vec<(usize, f64)>>> = Vec::new();
321    let mut lines: Vec<Vec<(usize, f64)>> = vec![Vec::new()];
322    let mut line_w = 0.0;
323    for (i, w) in words.iter().enumerate() {
324        let (adv, _, _) = advance(fonts, &shown(w))?;
325        let prev = i.checked_sub(1).map(|p| &words[p]);
326        let pause = prev.is_some_and(|p| w.start - p.end > 0.8);
327        let sentence = prev.is_some_and(|p| p.text.ends_with(['.', '?', '!']))
328            && lines.iter().map(|l| l.len()).sum::<usize>() >= 3;
329        let fits = lines.last().unwrap().is_empty() || line_w + space + adv <= st.width;
330        if (pause || sentence) && !lines[0].is_empty() {
331            pages.push(std::mem::replace(&mut lines, vec![Vec::new()]));
332            line_w = 0.0;
333        } else if !fits {
334            if lines.len() >= st.max_lines {
335                pages.push(std::mem::replace(&mut lines, vec![Vec::new()]));
336            } else {
337                lines.push(Vec::new());
338            }
339            line_w = 0.0;
340        }
341        let l = lines.last_mut().unwrap();
342        if !l.is_empty() {
343            line_w += space;
344        }
345        line_w += adv;
346        l.push((i, adv));
347    }
348    if !lines[0].is_empty() {
349        pages.push(lines);
350    }
351
352    let mut nodes = BTreeMap::new();
353    let mut page_layers = Vec::new();
354    for (pi, page) in pages.iter().enumerate() {
355        let first = words[page[0][0].0].start;
356        let last = words[page.last().unwrap().last().unwrap().0].end;
357        let next = pages.get(pi + 1).map(|p| words[p[0][0].0].start);
358        let t_in = (first - 0.04).max(0.0);
359        let t_out = match next {
360            Some(n) => (last + st.linger).min(n - 0.04).max(last),
361            None => last + st.linger,
362        };
363        // Block centered on position: lines stacked, each aligned, and
364        // moved into the safe area if it would cross it.
365        let block_h = ascent + descent + line_px * (page.len() - 1) as f64;
366        let mut cy = st.position[1];
367        if let Some([_, y0, _, y1]) = st.safe {
368            let pad_y = if st.backing.is_some() { st.size * 0.7 } else { 0.0 };
369            let half = block_h / 2.0 + pad_y;
370            if y1 - y0 >= 2.0 * half {
371                cy = cy.clamp(y0 + half, y1 - half);
372            }
373        }
374        let top = cy - block_h / 2.0;
375        let mut acc: Option<String> = None;
376        if let Some(bg) = &st.backing {
377            let widest = page
378                .iter()
379                .map(|l| l.iter().map(|(_, a)| a).sum::<f64>() + space * (l.len() - 1) as f64)
380                .fold(0.0, f64::max);
381            let pad = st.size * 0.42;
382            let cx = match st.align.as_str() {
383                "left" => st.position[0] - st.width / 2.0 + widest / 2.0,
384                "right" => st.position[0] + st.width / 2.0 - widest / 2.0,
385                _ => st.position[0],
386            };
387            let id = format!("p{pi}_background");
388            let mut p = BTreeMap::new();
389            p.insert("kind".to_string(), Param::Text("rect".into()));
390            p.insert("center".to_string(), Param::Vector(vec![cx, cy]));
391            p.insert(
392                "size".to_string(),
393                Param::Vector(vec![widest + 2.0 * pad, block_h + 1.4 * pad]),
394            );
395            p.insert("radius".to_string(), Param::Number(st.size * 0.35));
396            p.insert("color".to_string(), Param::Text(bg.clone()));
397            nodes.insert(
398                id.clone(),
399                Node {
400                    op: "shape".into(),
401                    params: p,
402                    ..Default::default()
403                },
404            );
405            acc = Some(id);
406        }
407        for (li, line) in page.iter().enumerate() {
408            let lw: f64 = line.iter().map(|(_, a)| a).sum::<f64>() + space * (line.len() - 1) as f64;
409            let mut x = match st.align.as_str() {
410                "left" if rtl => st.position[0] + st.width / 2.0 - lw,
411                "left" => st.position[0] - st.width / 2.0,
412                "right" => st.position[0] + st.width / 2.0 - lw,
413                _ => st.position[0] - lw / 2.0,
414            };
415            let baseline = top + ascent + line_px * li as f64;
416            let in_place: Vec<(usize, f64)> = if rtl {
417                line.iter().rev().copied().collect()
418            } else {
419                line.clone()
420            };
421            for &(wi, adv) in &in_place {
422                let w = &words[wi];
423                let id = format!("p{pi}_w{wi}");
424                let mut n = word_node(&shown(w));
425                let cx = x + adv / 2.0;
426                let cy = baseline - st.size * 0.35;
427                n.params.insert("valign".into(), Param::Text("baseline".into()));
428                n.params.insert("position".into(), Param::Vector(vec![cx, cy]));
429                n.params
430                    .insert("anchor".into(), Param::Vector(vec![adv / 2.0, -st.size * 0.35]));
431                let key = |t: f64, v: &str| serde_json::json!({"t": t, "v": v, "ease": "hold"});
432                let color = match st.mode.as_str() {
433                    "karaoke" | "pop" => {
434                        serde_json::json!({"keys": [key(0.0, &st.color), key(w.start, &st.highlight), key(w.end.max(w.start + 0.08), &st.spoken)]})
435                    }
436                    _ => serde_json::json!(st.color),
437                };
438                n.params.insert(
439                    "color".into(),
440                    serde_json::from_value(color).map_err(|e| e.to_string())?,
441                );
442                let anim = |ks: serde_json::Value| -> Result<Param, String> {
443                    serde_json::from_value(serde_json::json!({ "keys": ks })).map_err(|e| e.to_string())
444                };
445                match st.mode.as_str() {
446                    "pop" => {
447                        n.params.insert(
448                            "scale".into(),
449                            anim(serde_json::json!([
450                                {"t": w.start, "v": [0.55, 0.55], "ease": {"bezier": [0.2, 1.6, 0.4, 1.0]}},
451                                {"t": w.start + 0.2, "v": [1.0, 1.0]}
452                            ]))?,
453                        );
454                    }
455                    "karaoke" => {
456                        // The spoken word swells by up to 8%, never past
457                        // 40% of a space on either side (long words would
458                        // run into their neighbours).
459                        let s = (1.0 + 0.8 * space / adv.max(1.0)).min(1.08);
460                        n.params.insert(
461                            "scale".into(),
462                            anim(serde_json::json!([
463                                {"t": w.start, "v": [1.0, 1.0], "ease": "out_cubic"},
464                                {"t": w.start + 0.08, "v": [s, s], "ease": "in_out_cubic"},
465                                {"t": w.end.max(w.start + 0.16), "v": [1.0, 1.0]}
466                            ]))?,
467                        );
468                    }
469                    _ => {}
470                }
471                let mut layer = id.clone();
472                nodes.insert(id.clone(), n);
473                // Words that are not there yet: pop and reveal bring them in
474                // at their time.
475                if matches!(st.mode.as_str(), "pop" | "reveal") {
476                    let o = format!("{id}_in");
477                    let mut p = BTreeMap::new();
478                    p.insert(
479                        "opacity".to_string(),
480                        anim(serde_json::json!([
481                            {"t": w.start, "v": [0.0], "ease": "out_cubic"},
482                            {"t": w.start + if st.mode == "pop" { 0.06 } else { 0.14 }, "v": [1.0]}
483                        ]))?,
484                    );
485                    nodes.insert(
486                        o.clone(),
487                        Node {
488                            op: "opacity".into(),
489                            params: p,
490                            inputs: [("source".to_string(), layer)].into(),
491                            ..Default::default()
492                        },
493                    );
494                    layer = o;
495                }
496                // A rounded highlight behind the word being spoken.
497                if let Some(pill) = &st.pill {
498                    let pid = format!("{id}_pill");
499                    let mut p = BTreeMap::new();
500                    p.insert("kind".to_string(), Param::Text("rect".into()));
501                    p.insert(
502                        "center".to_string(),
503                        Param::Vector(vec![cx, baseline - (ascent - descent) / 2.0 + descent * 0.1]),
504                    );
505                    p.insert(
506                        "size".to_string(),
507                        Param::Vector(vec![adv + st.size * 0.28, (ascent + descent) * 0.92]),
508                    );
509                    p.insert("radius".to_string(), Param::Number(st.size * 0.18));
510                    p.insert("color".to_string(), Param::Text(pill.clone()));
511                    nodes.insert(
512                        pid.clone(),
513                        Node {
514                            op: "shape".into(),
515                            params: p,
516                            ..Default::default()
517                        },
518                    );
519                    let ov = format!("{id}_on_pill");
520                    nodes.insert(
521                        ov.clone(),
522                        Node {
523                            op: "over".into(),
524                            inputs: [("fg".to_string(), layer.clone()), ("bg".to_string(), pid)].into(),
525                            ..Default::default()
526                        },
527                    );
528                    // The pill shows only while the word is spoken.
529                    let lit = format!("{id}_lit");
530                    nodes.insert(
531                        lit.clone(),
532                        Node {
533                            op: "over".into(),
534                            inputs: [("fg".to_string(), ov), ("bg".to_string(), layer.clone())].into(),
535                            timing: Some(
536                                serde_json::from_value(
537                                    serde_json::json!({"in": w.start, "out": w.end.max(w.start + 0.08)}),
538                                )
539                                .map_err(|e| e.to_string())?,
540                            ),
541                            ..Default::default()
542                        },
543                    );
544                    layer = lit;
545                }
546                acc = Some(match acc {
547                    None => layer,
548                    Some(prev) => {
549                        let o = format!("{id}_over");
550                        nodes.insert(
551                            o.clone(),
552                            Node {
553                                op: "over".into(),
554                                inputs: [("fg".to_string(), layer), ("bg".to_string(), prev)].into(),
555                                ..Default::default()
556                            },
557                        );
558                        o
559                    }
560                });
561                x += adv + space;
562            }
563        }
564        page_layers.push((acc.unwrap(), t_in, t_out));
565    }
566    // Pages, each visible in its window.
567    let mut nodes_out = nodes;
568    nodes_out.insert(
569        "empty".into(),
570        Node {
571            op: "solid".into(),
572            params: [("color".to_string(), Param::Text("#00000000".into()))].into(),
573            ..Default::default()
574        },
575    );
576    let mut acc = "empty".to_string();
577    for (pi, (layer, t_in, t_out)) in page_layers.into_iter().enumerate() {
578        let id = format!("page{pi}");
579        nodes_out.insert(
580            id.clone(),
581            Node {
582                op: "over".into(),
583                inputs: [("fg".to_string(), layer), ("bg".to_string(), acc)].into(),
584                timing: Some(
585                    serde_json::from_value(serde_json::json!({"in": t_in, "out": t_out})).map_err(|e| e.to_string())?,
586                ),
587                ..Default::default()
588            },
589        );
590        acc = id;
591    }
592    nodes_out.insert(
593        "captions_out".into(),
594        Node {
595            op: "opacity".into(),
596            params: [("opacity".to_string(), Param::Text("$opacity".into()))].into(),
597            inputs: [("source".to_string(), acc)].into(),
598            ..Default::default()
599        },
600    );
601    Ok(Component {
602        nodes: nodes_out,
603        output: "captions_out".into(),
604        params: [("opacity".to_string(), Param::Number(1.0))].into(),
605        inputs: Vec::new(),
606    })
607}
608
609/// Whether `doc` has `captions` nodes to expand.
610pub fn used_by(doc: &Document) -> bool {
611    doc.nodes.values().any(|n| n.op == "captions")
612}
613
614/// The words of a `captions` node: `src` file or inline `words`.
615pub fn words_of(node: &Node, base: &Path) -> Result<Vec<Word>, String> {
616    if let Some(src) = text(node, "src") {
617        let p = if Path::new(&src).is_absolute() {
618            Path::new(&src).to_path_buf()
619        } else {
620            base.join(&src)
621        };
622        let s = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
623        return parse(&s);
624    }
625    match text(node, "words") {
626        Some(w) => parse(&w),
627        None => Err("`captions` needs `src` (a transcript file) or `words`".into()),
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634
635    #[test]
636    fn parses_word_lists_srt_and_lines() {
637        let j = r#"{"segments":[{"words":[{"word":" Hello","start":0.0,"end":0.4},{"word":"world.","start":0.5,"end":0.9}]}]}"#;
638        let w = parse(j).unwrap();
639        assert_eq!(w.len(), 2);
640        assert_eq!(w[0].text, "Hello");
641        let srt = "1\n00:00:01,000 --> 00:00:02,000\nfast <i>type</i>\n\n2\n00:00:02,500 --> 00:00:03,000\nnow\n";
642        let w = parse(srt).unwrap();
643        assert_eq!(
644            w.iter().map(|w| w.text.as_str()).collect::<Vec<_>>(),
645            ["fast", "type", "now"]
646        );
647        assert!((w[0].start - 1.0).abs() < 1e-9 && (w[1].end - 2.0).abs() < 1e-9);
648        let w = parse("0 0.3 one\n0.3 0.7 two words").unwrap();
649        assert_eq!(w[1].text, "two words");
650    }
651
652    /// Every word's box, `[x0, y0, x1, y1]`, from the expanded component.
653    fn word_boxes(params: &str, fmt: &Format) -> Vec<[f64; 4]> {
654        let node: Node = serde_json::from_str(&format!(r#"{{"op":"captions","params":{params}}}"#)).unwrap();
655        let words = words_of(&node, Path::new(".")).unwrap();
656        let mut fonts = Fonts::new();
657        let c = build(&words, &node, fmt, &mut fonts, Path::new(".")).unwrap();
658        c.nodes
659            .values()
660            .filter(|n| n.op == "text")
661            .map(|n| {
662                let m = measure("w", n, 0.0, &mut fonts, Path::new(".")).unwrap();
663                let pos = n.params["position"].eval(0.0).unwrap();
664                let anchor = n.params["anchor"].eval(0.0).unwrap();
665                let x0 = pos[0] - anchor[0];
666                let base = pos[1] - anchor[1];
667                [x0, base - m.ascent, x0 + m.advance, base + m.descent]
668            })
669            .collect()
670    }
671
672    #[test]
673    fn captions_keep_clear_of_social_buttons_on_vertical_frames() {
674        let fmt = Format {
675            width: 1080,
676            height: 1920,
677            fps: 30.0,
678            duration: 8.0,
679            motion_blur: None,
680        };
681        let words: String =
682            "Captions that run the whole width of a vertical frame used to slide under the share buttons"
683                .split(' ')
684                .enumerate()
685                .map(|(i, w)| format!("{} {} {w}\\n", i as f64 * 0.3, i as f64 * 0.3 + 0.3))
686                .collect();
687        let [x0, y0, x1, y1] = crate::review::SafeArea::Social.rect(1080.0, 1920.0);
688        // By default, and when placed low: inside the area `review --safe
689        // social` checks.
690        for at in ["", r#","position":[540,1800]"#, r#","position":[900,1000]"#] {
691            let boxes = word_boxes(
692                &format!(r#"{{"words":"{words}","font":"ultrafast:sans","size":84{at}}}"#),
693                &fmt,
694            );
695            assert!(!boxes.is_empty());
696            for b in &boxes {
697                assert!(b[0] >= x0 && b[2] <= x1 && b[1] >= y0 && b[3] <= y1, "{at}: {b:?}");
698            }
699        }
700        // `safe: none` places it exactly where asked.
701        let boxes = word_boxes(
702            &format!(r#"{{"words":"{words}","font":"ultrafast:sans","size":84,"position":[540,1800],"safe":"none"}}"#),
703            &fmt,
704        );
705        assert!(boxes.iter().any(|b| b[3] > y1));
706    }
707}