1use crate::{Placed, RenderError, Renderer, local_time};
13use serde::Serialize;
14use ultrafast_gpu::{PixelFormat, TextureDesc};
15use ultrafast_graph::Document;
16
17#[derive(Debug, Clone)]
19pub struct TextProbe {
20 pub node: String,
21 pub text: String,
22 pub bounds: [f32; 4],
24 pub ink: usize,
26 pub clipped: usize,
27 pub contrast: f32,
30 pub size_px: f32,
32 pub pixels: Vec<u32>,
34 pub skim: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub enum SafeArea {
41 Margin(f32),
43 Social,
46}
47
48impl SafeArea {
49 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 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
97fn 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
119const STRIDE: usize = 2;
121
122impl Renderer {
123 pub fn probe_texts(&mut self, doc: &Document, t: f64) -> Result<(Vec<u8>, Vec<TextProbe>), RenderError> {
126 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 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 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 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 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 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 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 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 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 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 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 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 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
451type 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 (w > 1e-9).then(|| ((m[0] * x + m[1] * y + m[2]) / w, (m[3] * x + m[4] * y + m[5]) / w))
469}
470
471fn 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
512fn 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
527const WALK_STEPS: usize = 200_000;
530
531fn 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 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 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
617fn 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 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
657const 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
678fn reading_time(text: &str) -> f64 {
681 0.25 + 0.22 * words(text) as f64
682}
683
684fn 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
709fn 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
739pub 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 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 if a.contrast < READABLE || b.contrast < READABLE {
762 continue;
763 }
764 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 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 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 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 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 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 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 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 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 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 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}