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