Skip to main content

ultrafast_render/
review.rs

1//! `ultrafast review`: an automatic second pair of eyes for agents. Renders the
2//! film and reports what a viewer would trip over: text that never becomes
3//! readable, is on screen too briefly to read, runs off the frame or into
4//! the platform UI, collides with other text, or is too small; and flashing
5//! that risks photosensitive viewers.
6//!
7//! Every check is measured on the rendered frames (not guessed from
8//! params): a text's contrast is the final image under its glyphs against
9//! the final image around them, so masks, crops, fades and layers on top
10//! all count.
11
12use crate::{Placed, RenderError, Renderer, local_time};
13use serde::Serialize;
14use ultrafast_gpu::{PixelFormat, TextureDesc};
15use ultrafast_graph::Document;
16
17/// What one text looked like in one rendered frame.
18#[derive(Debug, Clone)]
19pub struct TextProbe {
20    pub node: String,
21    pub text: String,
22    /// Glyph bounds in frame px (may extend past the frame).
23    pub bounds: [f32; 4],
24    /// Sampled glyph pixels, and how many of them fall outside the frame.
25    pub ink: usize,
26    pub clipped: usize,
27    /// WCAG contrast ratio of the final frame under the glyphs against
28    /// around them: 1 = invisible, 3 = readable large text, 21 = max.
29    pub contrast: f32,
30    /// Type size in frame px (size param times absorbed scale).
31    pub size_px: f32,
32    /// Frame indices of sampled glyph pixels, sorted (overlap tests).
33    pub pixels: Vec<u32>,
34    /// Glanced at rather than read (`skim` on the text: code, data
35    /// labels): no reading-time check.
36    pub skim: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub enum SafeArea {
41    /// Keep text this fraction of the short side away from the edges.
42    Margin(f32),
43    /// Vertical social video: clear of the caption and button overlays
44    /// (bottom 20 %, right 12 %, top 8 %).
45    Social,
46}
47
48impl SafeArea {
49    /// The rectangle text should stay inside, `[x0, y0, x1, y1]` in frame
50    /// px. Captions keep to the same one by default (see `captions`).
51    pub fn rect(self, fw: f64, fh: f64) -> [f64; 4] {
52        let short = fw.min(fh);
53        match self {
54            SafeArea::Margin(m) => {
55                let m = m as f64 * short;
56                [m, m, fw - m, fh - m]
57            }
58            SafeArea::Social => [0.04 * short, 0.08 * fh, fw - 0.12 * fw, fh - 0.2 * fh],
59        }
60    }
61}
62
63#[derive(Debug, Clone)]
64pub struct ReviewOptions {
65    /// Seconds between text probes (flashes are checked every frame).
66    pub step: f64,
67    pub safe: SafeArea,
68}
69
70impl Default for ReviewOptions {
71    fn default() -> Self {
72        Self {
73            step: 0.1,
74            safe: SafeArea::Margin(0.04),
75        }
76    }
77}
78
79#[derive(Debug, Clone, Serialize)]
80pub struct Issue {
81    pub severity: &'static str,
82    pub kind: &'static str,
83    pub node: String,
84    pub from: f64,
85    pub to: f64,
86    pub message: String,
87}
88
89#[derive(Debug, Clone, Serialize)]
90pub struct Review {
91    pub issues: Vec<Issue>,
92    pub frames: u64,
93    pub texts: usize,
94    pub seconds: f64,
95}
96
97/// Relative luminance of an sRGB8 pixel.
98fn luminance(p: &[u8]) -> f32 {
99    let lin = |c: u8| {
100        let c = c as f32 / 255.0;
101        if c <= 0.04045 {
102            c / 12.92
103        } else {
104            ((c + 0.055) / 1.055).powf(2.4)
105        }
106    };
107    0.2126 * lin(p[0]) + 0.7152 * lin(p[1]) + 0.0722 * lin(p[2])
108}
109
110fn median(v: &mut [f32]) -> Option<f32> {
111    if v.is_empty() {
112        return None;
113    }
114    let m = v.len() / 2;
115    v.select_nth_unstable_by(m, |a, b| a.total_cmp(b));
116    Some(v[m])
117}
118
119/// Sampling stride over glyph texels.
120const STRIDE: usize = 2;
121
122impl Renderer {
123    /// Renders frame `t` and measures every visible text in it. Returns the
124    /// frame (sRGB RGBA8, opaque) and the probes.
125    pub fn probe_texts(&mut self, doc: &Document, t: f64) -> Result<(Vec<u8>, Vec<TextProbe>), RenderError> {
126        // Text rasters drawn whole, not stopped at the frame: what runs off
127        // it is what the probe measures.
128        let framed = std::mem::replace(&mut self.no_framed, true);
129        let rendered = self.render_rgba8(doc, t);
130        self.no_framed = framed;
131        let (frame, _) = rendered?;
132        let flat = if crate::needs_flat(doc) {
133            Some(self.flattened(doc)?)
134        } else {
135            None
136        };
137        let doc: &Document = flat.as_ref().map(|f| &f.doc).unwrap_or(doc);
138        let (fw, fh) = (doc.format.width as i64, doc.format.height as i64);
139        let active = self.active.take().expect("plan");
140        let live = crate::live_groups(&active.plan, t);
141        let mut found: Vec<(String, Placed, f32, Option<Hom>)> = Vec::new();
142        let plan = &active.plan;
143        let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); plan.nodes.len()];
144        for (i, n) in plan.nodes.iter().enumerate() {
145            for &s in &n.inputs {
146                consumers[s].push(i);
147            }
148        }
149        for (gi, g) in active.plan.groups.iter().enumerate() {
150            let Some(rc) = &g.raster else { continue };
151            let pn = &active.plan.nodes[rc.node];
152            if pn.def.name != "text" || !live[gi] || !local_time(pn, t).1 {
153                continue;
154            }
155            // Skip type hidden on its way to the output (cropped away,
156            // faded out): it is not on screen, whatever its raster holds.
157            if let Some(b) = self.bounds.get(&pn.id) {
158                let rect = [b[0] as f64, b[1] as f64, b[2] as f64, b[3] as f64];
159                if !reaches_screen(plan, doc, &consumers, g.root, rect, 1.0, t) {
160                    continue;
161                }
162            }
163            let Some(placed) = active.raster[gi].clone() else {
164                continue;
165            };
166            // Pins and transforms after the raster move its type on screen:
167            // it is measured where they put it.
168            let map = to_screen(plan, doc, &consumers, g.root, &rc.transforms, t);
169            let node = &doc.nodes[&pn.id];
170            let (lt, _) = local_time(pn, t);
171            let outer = crate::absorbed(&active.plan, doc, &rc.transforms, t);
172            let m = outer.mul(crate::geom::placement_affine(node, lt)).0;
173            let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt();
174            let size = node
175                .params
176                .get("size")
177                .and_then(|p| p.eval(lt))
178                .and_then(|v| v.first().copied())
179                .unwrap_or(64.0);
180            found.push((pn.id.clone(), placed, (size * scale) as f32, map));
181        }
182        self.active = Some(active);
183
184        // Luminance of the whole frame, once.
185        let lut: Vec<f32> = (0..256u32)
186            .map(|c| {
187                let c = c as f32 / 255.0;
188                if c <= 0.04045 {
189                    c / 12.92
190                } else {
191                    ((c + 0.055) / 1.055).powf(2.4)
192                }
193            })
194            .collect();
195        let lum: Vec<f32> = frame
196            .chunks_exact(4)
197            .map(|p| 0.2126 * lut[p[0] as usize] + 0.7152 * lut[p[1] as usize] + 0.0722 * lut[p[2] as usize])
198            .collect();
199        let at = |x: i64, y: i64| -> Option<f32> {
200            (x >= 0 && y >= 0 && x < fw && y < fh).then(|| lum[(y * fw + x) as usize])
201        };
202        let mut probes = Vec::new();
203        for (id, placed, raster_px, map) in found {
204            let d = placed.tex.desc();
205            let rgba = self.device.create_texture(TextureDesc {
206                width: d.width,
207                height: d.height,
208                format: PixelFormat::Rgba8Unorm,
209                cpu_readable: true,
210            });
211            let mut list = self.device.begin();
212            list.dispatch(
213                &self.kernels.utility("k_encode_srgb8"),
214                &rgba,
215                &[&placed.tex],
216                &[0.0, 1.0, d.width as f32, d.height as f32, 0.0, 0.0, 0.0],
217            );
218            list.submit().wait()?;
219            let px = self.device.readback(&rgba);
220            let (ox, oy) = (placed.origin[0] as i64, placed.origin[1] as i64);
221            let (tw, th) = (d.width as usize, d.height as usize);
222            // Frame px of the raster to screen px, and how much it scales the
223            // type there (the pin's local scale at the raster's middle).
224            let to = |x: i64, y: i64| -> Option<(i64, i64)> {
225                match &map {
226                    None => Some((x, y)),
227                    Some(m) => hom_apply(m, x as f64, y as f64).map(|(x, y)| (x.round() as i64, y.round() as i64)),
228                }
229            };
230            let zoom = map
231                .as_ref()
232                .and_then(|m| {
233                    let (cx, cy) = (ox as f64 + tw as f64 / 2.0, oy as f64 + th as f64 / 2.0);
234                    let (a, b, c) = (
235                        hom_apply(m, cx, cy)?,
236                        hom_apply(m, cx + 1.0, cy)?,
237                        hom_apply(m, cx, cy + 1.0)?,
238                    );
239                    let det = (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0);
240                    Some(det.abs().sqrt())
241                })
242                .unwrap_or(1.0) as f32;
243            let size_px = raster_px * zoom;
244            // Glyph texels (solid ones: edges mix with the ground) and the
245            // ground between and around them, in screen px.
246            let mut solid = Vec::new();
247            let mut edge = Vec::new();
248            let mut ground = Vec::new();
249            let mut edge_ground = Vec::new();
250            let near_r = ((raster_px * 0.05).round() as i64).clamp(2, 8);
251            // The ink's bounds in the raster's frame px.
252            let mut rb = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];
253            let mut pixels = Vec::new();
254            let (mut ink, mut clipped) = (0usize, 0usize);
255            let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
256            let inside = |x: i64, y: i64| x >= 0 && y >= 0 && x < fw && y < fh;
257            // Coverage relative to the text's own opacity (translucent type
258            // is still type).
259            let peak = px.chunks_exact(4).map(|p| p[3]).max().unwrap_or(0).max(1) as u32;
260            let cov = |a: u8| (a as u32 * 255 / peak).min(255) as u8;
261            for y in (0..th).step_by(STRIDE) {
262                for x in (0..tw).step_by(STRIDE) {
263                    let a = cov(px[(y * tw + x) * 4 + 3]);
264                    let (rx, ry) = (ox + x as i64, oy + y as i64);
265                    let Some((fx, fy)) = to(rx, ry) else {
266                        if a > 128 {
267                            ink += 1;
268                            clipped += 1;
269                        }
270                        continue;
271                    };
272                    if a > 128 {
273                        ink += 1;
274                        rb = [rb[0].min(rx), rb[1].min(ry), rb[2].max(rx), rb[3].max(ry)];
275                        b = [
276                            b[0].min(fx as f32),
277                            b[1].min(fy as f32),
278                            b[2].max(fx as f32),
279                            b[3].max(fy as f32),
280                        ];
281                        if inside(fx, fy) {
282                            pixels.push((fy * fw + fx) as u32);
283                            if a > 220 {
284                                solid.push((fx, fy))
285                            } else {
286                                edge.push((fx, fy))
287                            }
288                        } else {
289                            clipped += 1;
290                        }
291                    } else if a < 5 && inside(fx, fy) {
292                        // The ground right at the letters' edges is what
293                        // they are read against (an outline or a shadow
294                        // there counts); farther ground only if none.
295                        let alpha = |x: i64, y: i64| {
296                            if x < 0 || y < 0 || x >= tw as i64 || y >= th as i64 {
297                                0
298                            } else {
299                                cov(px[(y as usize * tw + x as usize) * 4 + 3])
300                            }
301                        };
302                        let r = near_r;
303                        let (xi, yi) = (x as i64, y as i64);
304                        let near = [(r, 0), (-r, 0), (0, r), (0, -r), (r, r), (-r, -r), (r, -r), (-r, r)]
305                            .iter()
306                            .any(|&(dx, dy)| alpha(xi + dx, yi + dy) > 128);
307                        if near {
308                            edge_ground.push((fx, fy));
309                        } else {
310                            ground.push((fx, fy));
311                        }
312                    }
313                }
314            }
315            if ink == 0 {
316                continue;
317            }
318            let pad = (size_px * 0.15).clamp(4.0, 40.0) as i64;
319            let (x0, y0) = (b[0] as i64 - pad, b[1] as i64 - pad);
320            // The ground past the raster's edges, out to `pad` screen px
321            // around the ink: walked in the raster's frame px, then put on
322            // screen.
323            let rpad = (pad as f32 / zoom.max(1e-3)).ceil() as i64;
324            for y in (rb[1] - rpad..=rb[3] + rpad).step_by(STRIDE) {
325                for x in (rb[0] - rpad..=rb[2] + rpad).step_by(STRIDE) {
326                    let within = x >= ox && y >= oy && x < ox + tw as i64 && y < oy + th as i64;
327                    if within {
328                        continue;
329                    }
330                    if let Some((sx, sy)) = to(x, y).filter(|&(x, y)| inside(x, y)) {
331                        ground.push((sx, sy));
332                    }
333                }
334            }
335            if solid.len() < 30 {
336                solid.extend(edge);
337            }
338            // Effects downstream (lens warps, refraction, glitches) move the
339            // glyphs a little, by different amounts along a line: each tile
340            // of the text is measured at the offset where it lines up best.
341            let reach = (size_px * 0.3).clamp(3.0, 28.0) as i64;
342            let stride = (reach / 5).max(1);
343            let tile = (size_px * 1.5).max(48.0) as i64;
344            let key = |(x, y): (i64, i64)| ((x - x0).div_euclid(tile), (y - y0).div_euclid(tile));
345            let contrast_against = |ground: &[(i64, i64)]| -> f32 {
346                let mut tiles: std::collections::HashMap<(i64, i64), (Vec<(i64, i64)>, Vec<(i64, i64)>)> =
347                    Default::default();
348                for &p in &solid {
349                    tiles.entry(key(p)).or_default().0.push(p);
350                }
351                for &p in ground {
352                    if let Some(t) = tiles.get_mut(&key(p)) {
353                        t.1.push(p);
354                    }
355                }
356                let mut ink_l = Vec::new();
357                let mut ground_l = Vec::new();
358                for (ink_px, ground_px) in tiles.values() {
359                    if ground_px.is_empty() {
360                        continue;
361                    }
362                    let sample = |dx: i64, dy: i64, every: usize| -> (Vec<f32>, Vec<f32>) {
363                        (
364                            ink_px
365                                .iter()
366                                .step_by(every)
367                                .filter_map(|&(x, y)| at(x + dx, y + dy))
368                                .collect(),
369                            ground_px
370                                .iter()
371                                .step_by(every)
372                                .filter_map(|&(x, y)| at(x + dx, y + dy))
373                                .collect(),
374                        )
375                    };
376                    let score = |(a, mut g): (Vec<f32>, Vec<f32>)| -> f32 {
377                        let m = if a.is_empty() {
378                            return 1.0;
379                        } else {
380                            a.iter().sum::<f32>() / a.len() as f32
381                        };
382                        match median(&mut g) {
383                            Some(g) => (m.max(g) + 0.05) / (m.min(g) + 0.05),
384                            None => 1.0,
385                        }
386                    };
387                    let every = ((ink_px.len() + ground_px.len()) / 400).max(1);
388                    let mut best = (0, 0, score(sample(0, 0, every)));
389                    let mut dy = -reach;
390                    while dy <= reach {
391                        let mut dx = -reach;
392                        while dx <= reach {
393                            let c = score(sample(dx, dy, every));
394                            if c > best.2 + 1e-4 {
395                                best = (dx, dy, c);
396                            }
397                            dx += stride;
398                        }
399                        dy += stride;
400                    }
401                    let (a, g) = sample(best.0, best.1, 1);
402                    ink_l.extend(a);
403                    ground_l.extend(g);
404                }
405                // Ink at its typical level (mean: the eye integrates scanlines
406                // and halftones), ground at its median (stray highlights around
407                // the type do not count).
408                if ink_l.is_empty() {
409                    1.0
410                } else {
411                    let m = ink_l.iter().sum::<f32>() / ink_l.len() as f32;
412                    match median(&mut ground_l) {
413                        Some(g) => (m.max(g) + 0.05) / (m.min(g) + 0.05),
414                        None => 1.0,
415                    }
416                }
417            };
418            // Read against the ground right at the letters' edges (an outline
419            // or shadow there counts) or the ground beyond (a glow around
420            // them does not hide them): whichever reads better.
421            let far: Vec<(i64, i64)> = ground.clone();
422            let contrast = if edge_ground.len() >= 30 {
423                contrast_against(&edge_ground).max(contrast_against(&far))
424            } else {
425                let mut all = far;
426                all.extend(edge_ground);
427                contrast_against(&all)
428            };
429            pixels.sort_unstable();
430            let text = crate::geom::display_text(&doc.nodes[&id], t);
431            let skim = matches!(
432                doc.nodes[&id].params.get("skim"),
433                Some(ultrafast_graph::Param::Bool(true))
434            );
435            probes.push(TextProbe {
436                node: id,
437                text,
438                bounds: b,
439                ink,
440                clipped,
441                contrast,
442                size_px,
443                pixels,
444                skim,
445            });
446        }
447        Ok((frame, probes))
448    }
449}
450
451/// A 3x3 projective map of frame px, row-major (`x' = (m0 x + m1 y + m2) /
452/// (m6 x + m7 y + m8)`).
453type Hom = [f64; 9];
454
455fn hom_mul(a: &Hom, b: &Hom) -> Hom {
456    let mut m = [0.0; 9];
457    for r in 0..3 {
458        for c in 0..3 {
459            m[r * 3 + c] = (0..3).map(|k| a[r * 3 + k] * b[k * 3 + c]).sum();
460        }
461    }
462    m
463}
464
465fn hom_apply(m: &Hom, x: f64, y: f64) -> Option<(f64, f64)> {
466    let w = m[6] * x + m[7] * y + m[8];
467    // Behind the pin's horizon: nowhere on screen.
468    (w > 1e-9).then(|| ((m[0] * x + m[1] * y + m[2]) / w, (m[3] * x + m[4] * y + m[5]) / w))
469}
470
471/// Where a geometric op moves frame px, active at `t`: a `transform` (an
472/// affine) or a `corner_pin` (its source rect onto its corners). None for
473/// everything else.
474fn op_map(pn: &crate::plan::PlanNode, doc: &Document, t: f64) -> Option<Hom> {
475    let node = &doc.nodes[&pn.id];
476    let (lt, on) = local_time(pn, t);
477    if !on {
478        return None;
479    }
480    match pn.def.name {
481        "transform" => {
482            let m = crate::ops::transform_affine(node, &doc.format, lt).0;
483            Some([m[0], m[2], m[4], m[1], m[3], m[5], 0.0, 0.0, 1.0])
484        }
485        "corner_pin" => {
486            let (w, h) = (doc.format.width as f64, doc.format.height as f64);
487            let vec = |k: &str, d: [f64; 8]| -> Vec<f64> {
488                node.params
489                    .get(k)
490                    .and_then(|p| p.eval(lt))
491                    .filter(|v| v.len() >= d.len().min(4))
492                    .unwrap_or_else(|| d.to_vec())
493            };
494            let c = vec("corners", [0.0, 0.0, w, 0.0, w, h, 0.0, h]);
495            let s = vec("source_rect", [0.0, 0.0, w, h, 0.0, 0.0, 0.0, 0.0]);
496            if c.len() < 8 || s.len() < 4 {
497                return None;
498            }
499            let from = [
500                [s[0], s[1]],
501                [s[0] + s[2], s[1]],
502                [s[0] + s[2], s[1] + s[3]],
503                [s[0], s[1] + s[3]],
504            ];
505            let to = [[c[0], c[1]], [c[2], c[3]], [c[4], c[5]], [c[6], c[7]]];
506            crate::ops::homography(&from, &to)
507        }
508        _ => None,
509    }
510}
511
512/// The bounding rect of `rect` mapped by `m` (None if part of it falls
513/// behind a pin's horizon).
514fn map_rect(m: &Hom, r: [f64; 4]) -> Option<[f64; 4]> {
515    let pts: Vec<(f64, f64)> = [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])]
516        .iter()
517        .map(|&(x, y)| hom_apply(m, x, y))
518        .collect::<Option<_>>()?;
519    Some([
520        pts.iter().map(|p| p.0).fold(f64::MAX, f64::min),
521        pts.iter().map(|p| p.1).fold(f64::MAX, f64::min),
522        pts.iter().map(|p| p.0).fold(f64::MIN, f64::max),
523        pts.iter().map(|p| p.1).fold(f64::MIN, f64::max),
524    ])
525}
526
527/// Work enough for any real document's walk to its output; past it a
528/// text is taken to be on screen.
529const WALK_STEPS: usize = 200_000;
530
531/// Whether node `i`'s content, covering `rect` (frame px) at opacity
532/// `alpha`, survives the crops, fades and windows between it and the
533/// output, on some path to it: the rect moves with the transforms and
534/// corner pins on the way. However deep the stack (the walk once gave up
535/// after 48 levels and took the rest for visible).
536fn reaches_screen(
537    plan: &crate::plan::Plan,
538    doc: &Document,
539    consumers: &[Vec<usize>],
540    i: usize,
541    rect: [f64; 4],
542    alpha: f64,
543    t: f64,
544) -> bool {
545    let out = plan.nodes.len() - 1;
546    // What reached each node already: a later arrival no more opaque and
547    // no larger is not walked again.
548    let mut seen: Vec<Vec<(f64, [f64; 4])>> = vec![Vec::new(); plan.nodes.len()];
549    let mut stack = vec![(i, rect, alpha)];
550    let mut steps = 0;
551    while let Some((i, r, a)) = stack.pop() {
552        if a < 0.05 || r[0] >= r[2] || r[1] >= r[3] {
553            continue;
554        }
555        if i == out {
556            return true;
557        }
558        steps += 1;
559        if steps > WALK_STEPS {
560            return true;
561        }
562        let inside = |o: &[f64; 4]| r[0] >= o[0] && r[1] >= o[1] && r[2] <= o[2] && r[3] <= o[3];
563        if seen[i].iter().any(|(sa, sr)| a <= *sa && inside(sr)) {
564            continue;
565        }
566        seen[i].push((a, r));
567        for &c in &consumers[i] {
568            let pn = &plan.nodes[c];
569            let node = &doc.nodes[&pn.id];
570            let (lt, on) = local_time(pn, t);
571            let port = pn.inputs.iter().position(|&x| x == i).unwrap_or(0);
572            if !on {
573                // An inactive node passes one input through, or nothing.
574                if crate::ops::passthrough(pn.def, pn.inputs.len()) == Some(port) {
575                    stack.push((c, r, a));
576                }
577                continue;
578            }
579            let num = |k: &str, d: f64| {
580                node.params
581                    .get(k)
582                    .and_then(|p| p.eval(lt))
583                    .and_then(|v| v.first().copied())
584                    .unwrap_or(d)
585            };
586            let (mut r, mut a) = (r, a);
587            match pn.def.name {
588                "crop" => {
589                    let cr = node.params.get("rect").and_then(|p| p.eval(lt)).unwrap_or_default();
590                    if cr.len() >= 4 {
591                        r = [
592                            r[0].max(cr[0]),
593                            r[1].max(cr[1]),
594                            r[2].min(cr[0] + cr[2]),
595                            r[3].min(cr[1] + cr[3]),
596                        ];
597                    }
598                }
599                "opacity" => a *= num("opacity", 1.0),
600                "over" | "blend" if port == 0 => a *= num("opacity", 1.0),
601                "transform" | "corner_pin" => {
602                    if let Some(m) = op_map(pn, doc, t) {
603                        match map_rect(&m, r) {
604                            Some(m) => r = m,
605                            None => continue,
606                        }
607                    }
608                }
609                _ => {}
610            }
611            stack.push((c, r, a));
612        }
613    }
614    false
615}
616
617/// Where node `i`'s frame px land on screen: the transforms and corner pins
618/// between it and the output (but those in `absorbed`, already drawn into
619/// its raster), composed along its first path to the output. None when
620/// nothing on the way moves it.
621fn to_screen(
622    plan: &crate::plan::Plan,
623    doc: &Document,
624    consumers: &[Vec<usize>],
625    i: usize,
626    absorbed: &[usize],
627    t: f64,
628) -> Option<Hom> {
629    let out = plan.nodes.len() - 1;
630    let identity: Hom = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
631    let mut seen = vec![false; plan.nodes.len()];
632    let mut stack = vec![(i, identity, false)];
633    let mut steps = 0;
634    while let Some((i, m, moved)) = stack.pop() {
635        if i == out {
636            return moved.then_some(m);
637        }
638        steps += 1;
639        if seen[i] || steps > WALK_STEPS {
640            continue;
641        }
642        seen[i] = true;
643        // Pushed in reverse, so the first consumer is walked first.
644        for &c in consumers[i].iter().rev() {
645            let step = (!absorbed.contains(&c))
646                .then(|| op_map(&plan.nodes[c], doc, t))
647                .flatten();
648            match step {
649                Some(s) => stack.push((c, hom_mul(&s, &m), true)),
650                None => stack.push((c, m, moved)),
651            }
652        }
653    }
654    None
655}
656
657/// Visible: distinguishable from what is around it. Readable: WCAG AA for
658/// large text.
659const VISIBLE: f32 = 1.5;
660const READABLE: f32 = 3.0;
661
662fn mean_luminance(frame: &[u8]) -> f32 {
663    let n = frame.len() / 4;
664    let step = (n / 20000).max(1);
665    let mut s = 0.0;
666    let mut k = 0;
667    for i in (0..n).step_by(step) {
668        s += luminance(&frame[i * 4..i * 4 + 4]);
669        k += 1;
670    }
671    s / k.max(1) as f32
672}
673
674fn words(text: &str) -> usize {
675    text.split_whitespace().count().max(1)
676}
677
678/// Seconds a viewer needs to read `text`: about 270 words a minute plus a
679/// moment to find it (a single bold word reads in about half a second).
680fn reading_time(text: &str) -> f64 {
681    0.25 + 0.22 * words(text) as f64
682}
683
684/// Longest run of consecutive samples satisfying `ok`, as (from, to).
685fn longest_run(samples: &[(f64, bool)], step: f64) -> Option<(f64, f64)> {
686    let mut best: Option<(f64, f64)> = None;
687    let mut start: Option<f64> = None;
688    let mut last = 0.0;
689    for &(t, ok) in samples {
690        if ok {
691            if start.is_none() {
692                start = Some(t);
693            }
694            last = t;
695        } else if let Some(s) = start.take()
696            && best.is_none_or(|(a, b)| last - s > b - a)
697        {
698            best = Some((s, last));
699        }
700    }
701    if let Some(s) = start
702        && best.is_none_or(|(a, b)| last - s > b - a)
703    {
704        best = Some((s, last));
705    }
706    best.map(|(a, b)| (a, b + step))
707}
708
709/// Spans (at least `min` long) where `bad` holds, as (from, to).
710fn spans(samples: &[(f64, bool)], step: f64, min: f64) -> Vec<(f64, f64)> {
711    let mut out = Vec::new();
712    let mut start: Option<f64> = None;
713    let mut last = 0.0;
714    for &(t, bad) in samples.iter().chain(std::iter::once(&(f64::MAX, false))) {
715        if bad {
716            start.get_or_insert(t);
717            last = t;
718        } else if let Some(s) = start.take()
719            && last + step - s >= min - 1e-9
720        {
721            out.push((s, last + step));
722        }
723    }
724    out
725}
726
727fn iou(a: [f32; 4], b: [f32; 4]) -> f32 {
728    let w = (a[2].min(b[2]) - a[0].max(b[0])).max(0.0);
729    let h = (a[3].min(b[3]) - a[1].max(b[1])).max(0.0);
730    let i = w * h;
731    let area = |r: [f32; 4]| (r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0);
732    i / (area(a) + area(b) - i).max(1e-6)
733}
734
735fn r2(v: f64) -> f64 {
736    (v * 100.0).round() / 100.0
737}
738
739/// Renders the whole film and reports problems.
740pub fn review(r: &mut Renderer, doc: &Document, opts: &ReviewOptions) -> Result<Review, RenderError> {
741    let start = std::time::Instant::now();
742    let fmt = doc.format;
743    let total = (fmt.duration * fmt.fps).round() as u64;
744    let every = ((opts.step * fmt.fps).round() as u64).max(1);
745    let step = every as f64 / fmt.fps;
746    let (fw, fh) = (fmt.width as f32, fmt.height as f32);
747    let mut lumas = Vec::with_capacity(total as usize);
748    // Per text node: (t, probe) samples.
749    let mut per: std::collections::BTreeMap<String, Vec<(f64, TextProbe)>> = Default::default();
750    let mut overlaps: std::collections::BTreeMap<(String, String), Vec<f64>> = Default::default();
751    for f in 0..total {
752        let t = fmt.time_of(f);
753        if f % every == 0 {
754            let (frame, probes) = r.probe_texts(doc, t)?;
755            lumas.push(mean_luminance(&frame));
756            for i in 0..probes.len() {
757                for j in i + 1..probes.len() {
758                    let (a, b) = (&probes[i], &probes[j]);
759                    // Text crossing in a transition (fading, half there)
760                    // is not a collision: only both fully legible is.
761                    if a.contrast < READABLE || b.contrast < READABLE {
762                        continue;
763                    }
764                    // Stacked copies of one text overlap by design.
765                    if a.text == b.text && iou(a.bounds, b.bounds) > 0.6 {
766                        continue;
767                    }
768                    let (small, big) = if a.pixels.len() < b.pixels.len() {
769                        (a, b)
770                    } else {
771                        (b, a)
772                    };
773                    let shared = small
774                        .pixels
775                        .iter()
776                        .filter(|p| big.pixels.binary_search(p).is_ok())
777                        .count();
778                    if shared as f32 > 0.03 * small.pixels.len() as f32 {
779                        let key = if a.node < b.node {
780                            (a.node.clone(), b.node.clone())
781                        } else {
782                            (b.node.clone(), a.node.clone())
783                        };
784                        overlaps.entry(key).or_default().push(t);
785                    }
786                }
787            }
788            for p in probes {
789                per.entry(p.node.clone()).or_default().push((t, p));
790            }
791        } else {
792            let (frame, _) = r.render_rgba8(doc, t)?;
793            lumas.push(mean_luminance(&frame));
794        }
795    }
796
797    let mut issues = Vec::new();
798    let mut push = |severity, kind, node: &str, from: f64, to: f64, message: String| {
799        issues.push(Issue {
800            severity,
801            kind,
802            node: node.to_string(),
803            from: r2(from),
804            to: r2(to),
805            message,
806        })
807    };
808    let short = fw.min(fh);
809    // Stacked copies (a shadow, an outline, a glow made from the same text)
810    // are judged together: a copy is fine wherever a more legible copy of
811    // the same text sits on it.
812    let mut at_time: std::collections::HashMap<u64, Vec<&TextProbe>> = Default::default();
813    for samples in per.values() {
814        for (t, p) in samples {
815            at_time.entry(t.to_bits()).or_default().push(p);
816        }
817    }
818    let backed = |t: f64, p: &TextProbe| {
819        at_time.get(&t.to_bits()).is_some_and(|ps| {
820            ps.iter().any(|q| {
821                q.node != p.node && q.text == p.text && q.contrast > p.contrast && iou(q.bounds, p.bounds) > 0.6
822            })
823        })
824    };
825    let per: std::collections::BTreeMap<String, Vec<(f64, TextProbe)>> = per
826        .iter()
827        .map(|(n, samples)| {
828            let own: Vec<(f64, TextProbe)> = samples.iter().filter(|(t, p)| !backed(*t, p)).cloned().collect();
829            (n.clone(), own)
830        })
831        .filter(|(_, v)| !v.is_empty())
832        .collect();
833    for (node, samples) in &per {
834        let text = samples[0].1.text.clone();
835        let label = if text.chars().count() > 40 {
836            format!("\"{}…\"", text.chars().take(40).collect::<String>())
837        } else {
838            format!("\"{text}\"")
839        };
840        // Type set wider than the frame on both sides is texture (marquees,
841        // patterns), not copy to be read.
842        if samples
843            .iter()
844            .any(|(_, p)| (p.bounds[0] < 0.0 && p.bounds[2] >= fw) || (p.bounds[1] < 0.0 && p.bounds[3] >= fh))
845        {
846            continue;
847        }
848        let best = samples.iter().map(|(_, p)| p.contrast).fold(1.0f32, f32::max);
849        if std::env::var("ULTRAFAST_DEBUG_REVIEW").is_ok() {
850            let sz = samples.iter().map(|(_, p)| p.size_px).fold(f32::MAX, f32::min);
851            eprintln!(
852                "{node}: {} samples, best contrast {best:.2}, size {sz:.1}",
853                samples.len()
854            );
855        }
856        let first = samples[0].0;
857        let last = samples.last().unwrap().0 + step;
858        if best < VISIBLE {
859            push(
860                "info",
861                "never_visible",
862                node,
863                first,
864                last,
865                format!("{label} never shows in the final image (fine if it is only a matte or source)"),
866            );
867            continue;
868        }
869        if best < READABLE {
870            push(
871                "warning",
872                "low_contrast",
873                node,
874                first,
875                last,
876                format!(
877                    "{label} never reaches readable contrast (best {best:.1}:1, want 3:1 or more): darken/lighten it, add a shadow or a backing panel"
878                ),
879            );
880        } else {
881            let readable: Vec<(f64, bool)> = samples.iter().map(|(t, p)| (*t, p.contrast >= READABLE)).collect();
882            if let Some((a, b)) = longest_run(&readable, step) {
883                let need = reading_time(&text);
884                if b - a < need - 1e-9 && !samples[0].1.skim {
885                    push(
886                        if words(&text) <= 2 { "info" } else { "warning" },
887                        "too_brief",
888                        node,
889                        a,
890                        b,
891                        format!(
892                            "{label} is readable for {:.1} s; {} word(s) need about {:.1} s",
893                            b - a,
894                            words(&text),
895                            need
896                        ),
897                    );
898                }
899            }
900            // Dim stretches while it is otherwise readable.
901            let dim: Vec<(f64, bool)> = samples
902                .iter()
903                .map(|(t, p)| (*t, p.contrast >= VISIBLE && p.contrast < READABLE))
904                .collect();
905            for (a, b) in spans(&dim, step, 0.6) {
906                // A fade in or out (dim next to invisible) is a transition,
907                // not a problem, unless it drags on.
908                let before = samples
909                    .iter()
910                    .rev()
911                    .find(|(t, _)| *t < a - 1e-9)
912                    .map(|(_, p)| p.contrast);
913                let after = samples.iter().find(|(t, _)| *t >= b - 1e-9).map(|(_, p)| p.contrast);
914                let fading = before.is_none_or(|c| c < VISIBLE) || after.is_none_or(|c| c < VISIBLE);
915                if fading && b - a < 1.2 {
916                    continue;
917                }
918                let worst = samples
919                    .iter()
920                    .filter(|(t, _)| *t >= a && *t < b)
921                    .map(|(_, p)| p.contrast)
922                    .fold(f32::MAX, f32::min);
923                push(
924                    "warning",
925                    "low_contrast",
926                    node,
927                    a,
928                    b,
929                    format!("{label} is hard to read here (down to {worst:.1}:1)"),
930                );
931            }
932        }
933        // Off the frame while visible.
934        let off: Vec<(f64, bool)> = samples
935            .iter()
936            .map(|(t, p)| (*t, p.contrast >= VISIBLE && p.clipped as f32 > 0.02 * p.ink as f32))
937            .collect();
938        for (a, b) in spans(&off, step, 0.5) {
939            let p = &samples.iter().find(|(t, _)| *t >= a).unwrap().1;
940            let mut edges = Vec::new();
941            if p.bounds[0] < 0.0 {
942                edges.push(format!("left by {:.0} px", -p.bounds[0]));
943            }
944            if p.bounds[2] >= fw {
945                edges.push(format!("right by {:.0} px", p.bounds[2] - fw + 1.0));
946            }
947            if p.bounds[1] < 0.0 {
948                edges.push(format!("top by {:.0} px", -p.bounds[1]));
949            }
950            if p.bounds[3] >= fh {
951                edges.push(format!("bottom by {:.0} px", p.bounds[3] - fh + 1.0));
952            }
953            push(
954                "warning",
955                "clipped",
956                node,
957                a,
958                b,
959                format!(
960                    "{label} runs off the frame ({}; {:.0}% of the glyphs): make it smaller or move it in",
961                    edges.join(", "),
962                    100.0 * p.clipped as f32 / p.ink as f32
963                ),
964            );
965        }
966        // Safe area.
967        let [l, t, rr, bb] = opts.safe.rect(fw as f64, fh as f64).map(|v| v as f32);
968        let why = match opts.safe {
969            SafeArea::Margin(_) => "the safe margin",
970            SafeArea::Social => "the social UI area (captions and buttons cover it)",
971        };
972        let unsafe_: Vec<(f64, bool)> = samples
973            .iter()
974            .map(|(tt, p)| {
975                let b = p.bounds;
976                (
977                    *tt,
978                    p.contrast >= READABLE && p.clipped == 0 && (b[0] < l || b[1] < t || b[2] > rr || b[3] > bb),
979                )
980            })
981            .collect();
982        for (a, b) in spans(&unsafe_, step, 0.5) {
983            let p = &samples.iter().find(|(tt, _)| *tt >= a).unwrap().1;
984            push(
985                if opts.safe == SafeArea::Social {
986                    "warning"
987                } else {
988                    "info"
989                },
990                "unsafe_area",
991                node,
992                a,
993                b,
994                format!(
995                    "{label} sits in {why} (bounds {:.0},{:.0} to {:.0},{:.0})",
996                    p.bounds[0], p.bounds[1], p.bounds[2], p.bounds[3]
997                ),
998            );
999        }
1000        // Size.
1001        let small = samples
1002            .iter()
1003            .filter(|(_, p)| p.contrast >= READABLE)
1004            .map(|(_, p)| p.size_px)
1005            .fold(f32::MAX, f32::min);
1006        if small < 0.022 * short && small > 0.0 {
1007            push(
1008                "info",
1009                "small_text",
1010                node,
1011                first,
1012                last,
1013                format!(
1014                    "{label} is set at {small:.0} px; below about {:.0} px it is hard to read on a phone",
1015                    0.022 * short
1016                ),
1017            );
1018        }
1019    }
1020    for ((a, b), times) in &overlaps {
1021        let samples: Vec<(f64, bool)> = times.iter().map(|t| (*t, true)).collect();
1022        // Consecutive probe times form spans.
1023        // Collisions last; text crossing in a transition (a second or so) does not.
1024        for (from, to) in spans(&samples, step, 1.5) {
1025            push(
1026                "warning",
1027                "overlap",
1028                a,
1029                from,
1030                to,
1031                format!("text `{a}` and `{b}` overlap on screen"),
1032            );
1033        }
1034    }
1035    // Flashes (WCAG 2.3.1): more than three pairs of opposing changes in
1036    // mean luminance of 10% or more (the darker state below 0.8) within any
1037    // second.
1038    let mut transitions = Vec::new();
1039    let (mut lo, mut hi, mut dir) = (lumas[0], lumas[0], 0i32);
1040    for (i, &l) in lumas.iter().enumerate().skip(1) {
1041        match dir {
1042            1 if l > hi => hi = l,
1043            -1 if l < lo => lo = l,
1044            1 if hi - l >= 0.1 && l < 0.8 => {
1045                dir = -1;
1046                lo = l;
1047                transitions.push(i);
1048            }
1049            -1 if l - lo >= 0.1 && lo < 0.8 => {
1050                dir = 1;
1051                hi = l;
1052                transitions.push(i);
1053            }
1054            0 => {
1055                if l - lo >= 0.1 && lo < 0.8 {
1056                    dir = 1;
1057                    hi = l;
1058                    transitions.push(i);
1059                } else if hi - l >= 0.1 && l < 0.8 {
1060                    dir = -1;
1061                    lo = l;
1062                    transitions.push(i);
1063                } else {
1064                    lo = lo.min(l);
1065                    hi = hi.max(l);
1066                }
1067            }
1068            _ => {}
1069        }
1070    }
1071    let win = fmt.fps.round() as usize;
1072    let mut flashes = Vec::new();
1073    let mut j = 0;
1074    for i in 0..transitions.len() {
1075        while transitions[i] - transitions[j] >= win {
1076            j += 1;
1077        }
1078        if (i - j).div_ceil(2) > 3 {
1079            flashes.push(transitions[i]);
1080        }
1081    }
1082    if let (Some(&a), Some(&b)) = (flashes.first(), flashes.last()) {
1083        push(
1084            "error",
1085            "flashing",
1086            "",
1087            fmt.time_of(a as u64) - 1.0,
1088            fmt.time_of(b as u64),
1089            "more than 3 flashes per second: a photosensitive seizure risk (WCAG 2.3.1); slow or soften them".into(),
1090        );
1091    }
1092    issues.sort_by(|a, b| a.from.total_cmp(&b.from));
1093    // Many labels at one small size are one finding.
1094    let mut merged: Vec<Issue> = Vec::new();
1095    for i in issues {
1096        if let Some(last) = merged.last_mut() {
1097            let size = |m: &str| m.split(" set at ").nth(1).map(|s| s.to_string());
1098            if i.kind == "small_text"
1099                && last.kind == "small_text"
1100                && last.from == i.from
1101                && last.to == i.to
1102                && size(&last.message) == size(&i.message)
1103            {
1104                last.node = format!("{}, {}", last.node, i.node);
1105                let n = last.node.split(", ").count();
1106                last.message = format!("{n} texts are set at {}", size(&i.message).unwrap_or_default());
1107                continue;
1108            }
1109        }
1110        merged.push(i);
1111    }
1112    let issues = merged;
1113    Ok(Review {
1114        issues,
1115        frames: total,
1116        texts: per.len(),
1117        seconds: start.elapsed().as_secs_f64(),
1118    })
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124
1125    #[test]
1126    fn runs_and_spans() {
1127        let s = [(0.0, false), (0.1, true), (0.2, true), (0.3, false), (0.4, true)];
1128        assert_eq!(longest_run(&s, 0.1), Some((0.1, 0.30000000000000004)));
1129        assert_eq!(spans(&s, 0.1, 0.15).len(), 1);
1130        assert!((reading_time("one two three") - 0.91).abs() < 1e-9);
1131    }
1132}