forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

text.rs2602 lines, 102.0 KiBHistoryRawDownload
1//! Text in the picture: a pure-Rust glyph rasteriser for burned-in captions
2//! and title cards. Front-end free like the rest of the engine, so the export,
3//! [`crate::export::compose_at_with`] and the playback path all draw one look.
4//!
5//! The look is the subtitle plate the preview already draws, cut down to what
6//! a picture can carry: white Archivo text, optionally outlined in black
7//! ([`Outline`]), optionally on a translucent black box, centred on the frame
8//! and placed at the bottom, the top or the middle ([`Place`]). Sizes are a
9//! share of the *frame height* ([`TextStyle::size`]), so a caption reads the
10//! same on a 640x360 proxy and a 4K master.
11//!
12//! A character Archivo has no glyph for is looked up in order: the bundled Noto
13//! Sans (Latin, Greek, Cyrillic and more), then the bundled Arabic, Hebrew,
14//! Devanagari and Thai faces, then the system colour emoji font (painted in
15//! colour), then the bundled monochrome Noto Emoji, then the system Noto Sans CJK
16//! (read only when a character needs it). Only a character none of them has is
17//! drawn as the empty box ([`missing_glyphs`] names them). Runs of a non-Latin
18//! face are shaped with `rustybuzz`, and right-to-left runs are reordered by the
19//! bidi algorithm; Archivo's runs keep the plain advance-and-kern path, so Latin
20//! text draws exactly as it always did.
21//!
22//! Several cues on screen at once are laid out together by [`overlay_stack`],
23//! stacked so none covers another.
24//!
25//! The coverage is computed once per text ([`Overlay`]) and composed per frame.
26//! [`Overlay::blend_bgra`] composes over a BGRA canvas; [`Overlay::blend_i420`]
27//! composes over the planes an encoder reads, which is what the export uses so
28//! a burned-in frame never leaves the planar format it was encoded from.
29
30use std::collections::BTreeMap;
31use std::sync::{Mutex, OnceLock};
32
33use ab_glyph::{Font, FontRef, GlyphId, PxScale, ScaleFont, point};
34use unicode_bidi::BidiInfo;
35
36use crate::colorspace::is_sd;
37
38/// The text face this crate draws Latin with, bundled so no system font is ever
39/// read. The path is relative to this file: `src/` up three to the repository root.
40const ARCHIVO: usize = 0;
41/// Noto Sans: Latin, Greek and Cyrillic, plus the symbols Archivo lacks.
42const NOTO_SANS: usize = 1;
43/// The monochrome emoji face, the last outline face before the system fonts.
44const MONO_EMOJI: usize = 6;
45/// Archivo Bold, drawn in place of [`ARCHIVO`] when a style asks for [`Weight::Bold`].
46const ARCHIVO_BOLD: usize = 7;
47/// How many bundled outline faces there are.
48const OUTLINE_FACES: usize = 8;
49
50/// The bundled outline faces, in lookup order (see the module docs). All are
51/// SIL Open Font License fonts under `assets/fonts`, the variable ones at their
52/// default instance. The path is relative to this file.
53static OUTLINE_BYTES: [&[u8]; OUTLINE_FACES] = [
54 include_bytes!("../../../assets/fonts/Archivo-Medium.ttf"),
55 include_bytes!("../../../assets/fonts/NotoSans[wght].ttf"),
56 include_bytes!("../../../assets/fonts/NotoSansArabic[wght].ttf"),
57 include_bytes!("../../../assets/fonts/NotoSansHebrew[wght].ttf"),
58 include_bytes!("../../../assets/fonts/NotoSansDevanagari[wght].ttf"),
59 include_bytes!("../../../assets/fonts/NotoSansThai[wght].ttf"),
60 // Noto Emoji, monochrome outlines (`assets/fonts/OFL-notoemoji.txt`).
61 include_bytes!("../../../assets/fonts/NotoEmoji-Regular.ttf"),
62 include_bytes!("../../../assets/fonts/Archivo-Bold.ttf"),
63];
64
65/// Each bundled face, parsed the first time a character reaches it.
66static PARSED: [OnceLock<Option<FontRef<'static>>>; OUTLINE_FACES] = [const { OnceLock::new() }; OUTLINE_FACES];
67
68/// The outline face at index `i` of [`OUTLINE_BYTES`], parsed once.
69fn outline_face(i: usize) -> Option<&'static FontRef<'static>> {
70 PARSED[i]
71 .get_or_init(|| FontRef::try_from_slice(OUTLINE_BYTES[i]).ok())
72 .as_ref()
73}
74
75static SHAPERS: [OnceLock<Option<rustybuzz::Face<'static>>>; OUTLINE_FACES] = [const { OnceLock::new() }; OUTLINE_FACES];
76
77/// The shaping face of outline face `i`, parsed once: `rustybuzz` reads the same
78/// bytes ab_glyph draws from, so the glyph ids it returns are the ones drawn.
79fn shaper(i: usize) -> Option<&'static rustybuzz::Face<'static>> {
80 SHAPERS[i]
81 .get_or_init(|| rustybuzz::Face::from_slice(OUTLINE_BYTES[i], 0))
82 .as_ref()
83}
84
85/// The system colour emoji font, read from the first of these that exists.
86const COLOUR_PATHS: [&str; 2] = [
87 "/usr/share/fonts/google-noto-color-emoji-fonts/Noto-COLRv1.ttf",
88 "/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf",
89];
90
91/// The system Noto Sans CJK collection, the first path that exists. Index 0 of
92/// the collection is read: the Japanese faces, whose ideographs are the common
93/// forms. Read only when a character needs it.
94const CJK_PATHS: [&str; 4] = [
95 "/usr/share/fonts/google-noto-sans-cjk-vf-fonts/NotoSansCJK-VF.ttc",
96 "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
97 "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
98 "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
99];
100
101/// The bytes of the first readable path in `paths`, read once.
102fn system_bytes(cell: &'static OnceLock<Option<Vec<u8>>>, paths: &[&str]) -> Option<&'static [u8]> {
103 cell.get_or_init(|| paths.iter().find_map(|p| std::fs::read(p).ok()))
104 .as_deref()
105}
106
107/// The system colour emoji face, parsed once. None when the system has no such font.
108fn colour_face() -> Option<&'static ttf_parser::Face<'static>> {
109 static BYTES: OnceLock<Option<Vec<u8>>> = OnceLock::new();
110 static FACE: OnceLock<Option<ttf_parser::Face<'static>>> = OnceLock::new();
111 FACE.get_or_init(|| {
112 let bytes = system_bytes(&BYTES, &COLOUR_PATHS)?;
113 ttf_parser::Face::parse(bytes, 0).ok()
114 })
115 .as_ref()
116}
117
118/// The system CJK face, parsed once and only on first use. It is a variable font
119/// whose default weight is Thin (wght 100), which reads grey beside the title's
120/// Medium, so it is set to Medium (wght 500). ab_glyph cannot set an axis, so
121/// this face is read through ttf-parser and drawn by [`draw_outline`].
122fn cjk_face() -> Option<&'static ttf_parser::Face<'static>> {
123 static BYTES: OnceLock<Option<Vec<u8>>> = OnceLock::new();
124 static FACE: OnceLock<Option<ttf_parser::Face<'static>>> = OnceLock::new();
125 FACE.get_or_init(|| {
126 let bytes = system_bytes(&BYTES, &CJK_PATHS)?;
127 let mut face = ttf_parser::Face::parse(bytes, 0).ok()?;
128 face.set_variation(ttf_parser::Tag::from_bytes(b"wght"), 500.0);
129 Some(face)
130 })
131 .as_ref()
132}
133
134/// The size each outline face is set at, as a multiple of the em. Archivo is 1, so
135/// Latin is unchanged. Every other face's x-height (the OS/2 `sxHeight`) is set to
136/// Archivo's, so a Cyrillic, Arabic or Thai letter is as tall as a Latin one
137/// beside it. The mono emoji face is left at 1. Its ab_glyph scale is per face
138/// height, so the factor is the ratio of heights times the ratio of x-heights.
139fn face_k() -> &'static [f32; OUTLINE_FACES] {
140 static K: OnceLock<[f32; OUTLINE_FACES]> = OnceLock::new();
141 K.get_or_init(|| {
142 let mut k = [1.0; OUTLINE_FACES];
143 let Some(text) = ttf_parser::Face::parse(OUTLINE_BYTES[ARCHIVO], 0)
144 .ok()
145 .and_then(|f| f.x_height())
146 else {
147 return k;
148 };
149 let text_h = outline_face(ARCHIVO).map_or(1.0, |f| f.height_unscaled());
150 for (i, slot) in k.iter_mut().enumerate().take(MONO_EMOJI).skip(ARCHIVO + 1) {
151 let (Some(font), Ok(face)) = (
152 outline_face(i),
153 ttf_parser::Face::parse(OUTLINE_BYTES[i], 0),
154 ) else {
155 continue;
156 };
157 if let Some(x) = face.x_height().filter(|&x| x > 0) {
158 *slot = (font.height_unscaled() / text_h) * (f32::from(text) / f32::from(x));
159 }
160 }
161 k
162 })
163}
164
165/// A system family a style names: its face, and the scale that sets its height and x-height to
166/// Archivo's, as [`face_k`] does for the bundled faces.
167#[derive(Clone, Copy)]
168pub(crate) struct Family {
169 font: &'static FontRef<'static>,
170 k: f32,
171}
172
173/// The scale that sets a system face's height and x-height to Archivo's.
174fn family_k(font: &FontRef<'_>, data: &[u8], index: u32) -> f32 {
175 let text_h = outline_face(ARCHIVO).map_or(1.0, |f| f.height_unscaled());
176 let text_x = ttf_parser::Face::parse(OUTLINE_BYTES[ARCHIVO], 0).ok().and_then(|f| f.x_height());
177 let own_x = ttf_parser::Face::parse(data, index).ok().and_then(|f| f.x_height()).filter(|&x| x > 0);
178 match (text_x, own_x) {
179 (Some(t), Some(x)) => (font.height_unscaled() / text_h) * (f32::from(t) / f32::from(x)),
180 _ => font.height_unscaled() / text_h,
181 }
182}
183
184/// The system face `name` names, or None when the system has no such family or its face does not
185/// parse. Each name is looked up once; the database is read on first use. A face's bytes live for
186/// the rest of the process, as the bundled faces do.
187pub(crate) fn family_face(name: &str) -> Option<Family> {
188 static DB: OnceLock<fontdb::Database> = OnceLock::new();
189 static FOUND: Mutex<BTreeMap<String, Option<Family>>> = Mutex::new(BTreeMap::new());
190 let mut found = FOUND.lock().ok()?;
191 if let Some(known) = found.get(name) {
192 return *known;
193 }
194 let db = DB.get_or_init(|| {
195 let mut db = fontdb::Database::new();
196 db.load_system_fonts();
197 db
198 });
199 let query = fontdb::Query { families: &[fontdb::Family::Name(name)], ..fontdb::Query::default() };
200 let family = db.query(&query).and_then(|id| {
201 db.with_face_data(id, |data, index| {
202 let data: &'static [u8] = Box::leak(data.to_vec().into_boxed_slice());
203 let font = FontRef::try_from_slice_and_index(data, index).ok()?;
204 let k = family_k(&font, data, index);
205 Some(Family { font: Box::leak(Box::new(font)), k })
206 })
207 .flatten()
208 });
209 found.insert(name.to_string(), family);
210 family
211}
212
213/// Where a character's glyph comes from, in lookup order.
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215enum Src {
216 /// One of the bundled outline faces, by its index in [`OUTLINE_BYTES`].
217 Outline(usize),
218 /// The system colour emoji face, painted in its colours.
219 Colour,
220 /// The system CJK face.
221 Cjk,
222 /// The family a style names, when the system has it (see [`Faces::family`]).
223 Family,
224}
225
226/// The first source with a glyph for `c` and that glyph's id there, or None when
227/// no face has one (the character is drawn as the empty box).
228fn lookup(c: char) -> Option<(Src, u16)> {
229 let outline = |i: usize| {
230 let g = outline_face(i)?.glyph_id(c).0;
231 (g != 0).then_some((Src::Outline(i), g))
232 };
233 let colour = || {
234 let face = colour_face()?;
235 let g = face.glyph_index(c)?;
236 face.is_color_glyph(g).then_some((Src::Colour, g.0))
237 };
238 let cjk = || {
239 let g = cjk_face()?.glyph_index(c)?.0;
240 (g != 0).then_some((Src::Cjk, g))
241 };
242 (0..MONO_EMOJI)
243 .find_map(outline)
244 .or_else(colour)
245 .or_else(|| outline(MONO_EMOJI))
246 .or_else(cjk)
247}
248
249/// The source and glyph a character is drawn with: Archivo's empty glyph (the
250/// box) when no source has one.
251fn pick(c: char) -> (Src, u16) {
252 lookup(c).unwrap_or((Src::Outline(ARCHIVO), 0))
253}
254
255/// [`pick`] for the faces a block is set in: the named family first, when it has the character.
256fn pick_in(faces: &Faces, c: char) -> (Src, u16) {
257 if let Some(family) = faces.family {
258 let g = family.font.glyph_id(c).0;
259 if g != 0 {
260 return (Src::Family, g);
261 }
262 }
263 pick(c)
264}
265
266/// Em size range in permille of the frame height: 1% (a sliver) to 20%.
267pub const SIZE_RANGE: (u32, u32) = (10, 200);
268
269/// The em size a style gets when nothing says otherwise: 5% of the frame
270/// height, the size a 1080p caption reads at.
271pub const DEFAULT_SIZE: u32 = 50;
272
273/// How far the text sits from the frame's edges, in fractions of the height:
274/// the title-safe margin, the same on all four sides.
275const MARGIN: f32 = 0.05;
276
277/// The gap between two stacked blocks, in ems: enough that their boxes do not touch.
278const STACK_GAP: f32 = 0.4;
279
280/// The default box's opacity, 0 to 255: dark enough to read white text over a
281/// bright picture, light enough that the picture still shows through.
282const BOX_ALPHA: u8 = 153;
283
284/// How the glyphs are edged. Thin and thick are a stroke of a fixed share of
285/// the em, so the outline grows with the text rather than staying a hairline.
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
287pub enum Outline {
288 #[default]
289 None,
290 Thin,
291 Thick,
292}
293
294/// Where the block of text sits on the frame, vertically. Across the frame it
295/// sits where [`HPlace`] says.
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
297pub enum Place {
298 #[default]
299 Bottom,
300 Top,
301 Centre,
302}
303
304/// Where the block of text sits across the frame: centred, or against the left
305/// or right title-safe margin.
306#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
307pub enum HPlace {
308 #[default]
309 Centre,
310 Left,
311 Right,
312}
313
314/// How heavy the Latin letters are drawn: Archivo Medium, or Archivo Bold. Other
315/// scripts are set in their one bundled weight either way.
316#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
317pub enum Weight {
318 #[default]
319 Regular,
320 Bold,
321}
322
323/// How the lines of one block line up against each other.
324#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
325pub enum Align {
326 #[default]
327 Centre,
328 Left,
329 Right,
330}
331
332/// Everything the rasteriser needs to draw a block of text. `Eq` on purpose:
333/// a style is part of a project's saved state and of an export's settings, and
334/// both compare by value.
335#[derive(Clone, Debug, PartialEq, Eq)]
336pub struct TextStyle {
337 /// Em size as permille of the frame height, clamped to [`SIZE_RANGE`].
338 pub size: u32,
339 pub outline: Outline,
340 /// The translucent black box behind the whole block.
341 pub boxed: bool,
342 pub place: Place,
343 /// Where the block sits across the frame.
344 pub hplace: HPlace,
345 /// The colour of the letters, `[r, g, b]`.
346 pub ink: [u8; 3],
347 pub weight: Weight,
348 /// How the lines of a block line up inside it.
349 pub align: Align,
350 /// The box's colour and opacity, `[r, g, b, a]`; read only when `boxed`.
351 pub box_color: [u8; 4],
352 /// The system family the text is set in, by its name. `None`, or a name the system does not
353 /// have, draws with the bundled faces; a character the family lacks falls back to them.
354 pub family: Option<String>,
355 /// How a burned caption is animated against its word times. Only the
356 /// caption path ([`crate::captionanim::plan`]) reads it; a title ignores it.
357 pub caption: crate::captionanim::CaptionStyle,
358}
359
360impl Default for TextStyle {
361 fn default() -> Self {
362 Self {
363 size: DEFAULT_SIZE,
364 outline: Outline::None,
365 boxed: true,
366 place: Place::Bottom,
367 hplace: HPlace::Centre,
368 ink: [255, 255, 255],
369 weight: Weight::Regular,
370 align: Align::Centre,
371 box_color: [0, 0, 0, BOX_ALPHA],
372 family: None,
373 caption: crate::captionanim::CaptionStyle::default(),
374 }
375 }
376}
377
378impl TextStyle {
379 /// The same style with its size inside [`SIZE_RANGE`]. Every entry point
380 /// goes through it, so a hand-built or loaded style cannot draw nothing
381 /// or a whole frame.
382 pub fn clamped(&self) -> Self {
383 Self {
384 size: self.size.clamp(SIZE_RANGE.0, SIZE_RANGE.1),
385 caption: self.caption.clamped(),
386 ..self.clone()
387 }
388 }
389}
390
391/// The coverage of one block of text on one frame size, in three planes the
392/// same size as the frame (one byte each, 255 is full), composed bottom to top:
393/// the box, the outline, then the white glyphs; a colour glyph is composed last,
394/// over those, from the `colour` plane. Only `bounds` can be non-zero.
395#[derive(Clone, Debug, PartialEq, Eq)]
396pub struct Overlay {
397 width: u32,
398 height: u32,
399 /// `[x0, y0, x1, y1)`, the rectangle every plane is confined to.
400 bounds: (u32, u32, u32, u32),
401 plate: Vec<u8>,
402 stroke: Vec<u8>,
403 fill: Vec<u8>,
404 /// Colour glyphs, straight (not premultiplied) RGBA per pixel. Empty unless a
405 /// colour glyph was drawn, so text without one carries no fourth plane.
406 colour: Vec<[u8; 4]>,
407 /// The colour the fill plane mixes toward (white unless the style says so).
408 ink: [u8; 3],
409 /// The colour the plate plane mixes toward (black unless the style says so).
410 plate_rgb: [u8; 3],
411}
412
413impl Overlay {
414 fn empty(width: u32, height: u32) -> Self {
415 let n = width as usize * height as usize;
416 Self {
417 width,
418 height,
419 bounds: (0, 0, 0, 0),
420 plate: vec![0; n],
421 stroke: vec![0; n],
422 fill: vec![0; n],
423 colour: Vec::new(),
424 ink: [255; 3],
425 plate_rgb: [0; 3],
426 }
427 }
428
429 /// The colour glyph at pixel `i`, when it covers the pixel at all.
430 fn colour_at(&self, i: usize) -> Option<[u8; 4]> {
431 self.colour.get(i).copied().filter(|c| c[3] > 0)
432 }
433
434 /// Whether any pixel is covered at all: a blank string or a size-less
435 /// frame composes to nothing.
436 pub fn is_blank(&self) -> bool {
437 self.bounds.0 >= self.bounds.2 || self.bounds.1 >= self.bounds.3
438 }
439
440 /// The glyph coverage, one byte a pixel. Exposed for tests and for a
441 /// caller that wants the shape without a canvas.
442 pub fn fill(&self) -> &[u8] {
443 &self.fill
444 }
445
446 /// The outline coverage: the stroke around the glyphs, where it is drawn
447 /// under the white fill.
448 pub fn stroke(&self) -> &[u8] {
449 &self.stroke
450 }
451
452 /// Composes the text over a tightly packed BGRA canvas of this overlay's
453 /// size. The canvas's own alpha byte is left as it was.
454 pub fn blend_bgra(&self, canvas: &mut [u8]) {
455 let (x0, y0, x1, y1) = self.bounds;
456 let w = self.width as usize;
457 if canvas.len() < w * self.height as usize * 4 {
458 return;
459 }
460 for y in y0 as usize..y1 as usize {
461 for x in x0 as usize..x1 as usize {
462 let i = y * w + x;
463 let (p, s, f) = (self.plate[i], self.stroke[i], self.fill[i]);
464 let colour = self.colour_at(i);
465 if p == 0 && s == 0 && f == 0 && colour.is_none() {
466 continue;
467 }
468 let px = &mut canvas[i * 4..i * 4 + 4];
469 // The canvas is blue, green, red; `ink` and `plate_rgb` are red, green, blue.
470 for (k, c) in px[..3].iter_mut().enumerate() {
471 let v = mix(*c, self.plate_rgb[2 - k], p);
472 let v = mix(v, 0, s);
473 *c = mix(v, self.ink[2 - k], f);
474 }
475 // The colour is BGRA-ordered on the canvas: blue, green, red.
476 if let Some([r, g, b, a]) = colour {
477 px[0] = mix(px[0], b, a);
478 px[1] = mix(px[1], g, a);
479 px[2] = mix(px[2], r, a);
480 }
481 }
482 }
483 }
484
485 /// Composes the text over planar I420 samples of this overlay's size, the
486 /// planes an encoder reads. Luma is pulled to the black or white of the
487 /// frame's own range (`full_range` as [`crate::colorspace::ColorDescription`]
488 /// says it). Every colour here is grey, so chroma only moves toward 128,
489 /// and a chroma sample is covered by the mean of its 2x2 luma pixels.
490 pub fn blend_i420(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], full_range: bool) {
491 let (w, h) = (self.width as usize, self.height as usize);
492 if y.len() < w * h || u.len() < w.div_ceil(2) * h.div_ceil(2) || v.len() != u.len() {
493 return;
494 }
495 let black = if full_range { 0 } else { 16 };
496 // The matrix the frame is coded in, the one `colorspace` gives its size.
497 let bt709 = !is_sd(self.width, self.height);
498 let (ink_y, ink_cb, ink_cr) = yuv([self.ink[0], self.ink[1], self.ink[2], 255], bt709, full_range);
499 let (plate_y, plate_cb, plate_cr) =
500 yuv([self.plate_rgb[0], self.plate_rgb[1], self.plate_rgb[2], 255], bt709, full_range);
501 let grey = self.ink[0] == self.ink[1]
502 && self.ink[1] == self.ink[2]
503 && self.plate_rgb[0] == self.plate_rgb[1]
504 && self.plate_rgb[1] == self.plate_rgb[2];
505 let (x0, y0, x1, y1) = self.bounds;
506 let cw = w.div_ceil(2);
507 // The total coverage of each luma pixel, the chroma's to average.
508 let cover = |i: usize| -> u8 {
509 let (p, s, f) = (
510 self.plate[i] as u64,
511 self.stroke[i] as u64,
512 self.fill[i] as u64,
513 );
514 let k = self.colour_at(i).map_or(0, |c| c[3]) as u64;
515 // Four factors over 255^3 is the three-factor cover over 255^2, exactly.
516 let kept = (255 - p) * (255 - s) * (255 - f) * (255 - k);
517 (255 - kept / (255 * 255 * 255)) as u8
518 };
519 for py in y0 as usize..y1 as usize {
520 for px in x0 as usize..x1 as usize {
521 let i = py * w + px;
522 let (p, s, f) = (self.plate[i], self.stroke[i], self.fill[i]);
523 let colour = self.colour_at(i);
524 if p == 0 && s == 0 && f == 0 && colour.is_none() {
525 continue;
526 }
527 let mut luma = y[i];
528 luma = mix(luma, plate_y, p);
529 luma = mix(luma, black, s);
530 luma = mix(luma, ink_y, f);
531 if let Some(c) = colour {
532 let (yc, _, _) = yuv(c, bt709, full_range);
533 luma = mix(luma, yc, c[3]);
534 }
535 y[i] = luma;
536 }
537 }
538 for cy in (y0 as usize / 2)..(y1 as usize).div_ceil(2) {
539 for cx in (x0 as usize / 2)..(x1 as usize).div_ceil(2) {
540 let mut sum = 0u32;
541 let mut n = 0u32;
542 // With a colour glyph in the block, each pixel pulls the chroma
543 // toward its own colour's (weighted by its coverage) and a grey
544 // pixel toward 128: `tu` and `tv` are those weighted targets.
545 let mut coloured = false;
546 let (mut tu, mut tv) = (0f32, 0f32);
547 for dy in 0..2 {
548 for dx in 0..2 {
549 let (px, py) = (cx * 2 + dx, cy * 2 + dy);
550 if px < w && py < h {
551 let i = py * w + px;
552 let c = cover(i) as u32;
553 sum += c;
554 n += 1;
555 let (cb, cr) = match self.colour_at(i) {
556 Some(k) => {
557 coloured = true;
558 let (_, cb, cr) = yuv(k, bt709, full_range);
559 (f32::from(cb), f32::from(cr))
560 }
561 None => (128.0, 128.0),
562 };
563 tu += c as f32 * cb;
564 tv += c as f32 * cr;
565 }
566 }
567 }
568 if n == 0 {
569 continue;
570 }
571 let ci = cy * cw + cx;
572 if ci < u.len() {
573 if !grey {
574 // Coloured ink or box: each layer pulls the chroma toward its own, by its mean coverage.
575 let (mut p, mut s, mut f, mut ka) = (0u32, 0u32, 0u32, 0u32);
576 let (mut kcb, mut kcr) = (0f32, 0f32);
577 for dy in 0..2 {
578 for dx in 0..2 {
579 let (px, py) = (cx * 2 + dx, cy * 2 + dy);
580 if px < w && py < h {
581 let i = py * w + px;
582 p += u32::from(self.plate[i]);
583 s += u32::from(self.stroke[i]);
584 f += u32::from(self.fill[i]);
585 if let Some(k) = self.colour_at(i) {
586 let (_, cb, cr) = yuv(k, bt709, full_range);
587 ka += u32::from(k[3]);
588 kcb += f32::from(k[3]) * f32::from(cb);
589 kcr += f32::from(k[3]) * f32::from(cr);
590 }
591 }
592 }
593 }
594 let mean = |t: u32| (t / n) as u8;
595 for (c, plate, ink) in [(&mut u[ci], plate_cb, ink_cb), (&mut v[ci], plate_cr, ink_cr)] {
596 *c = mix(*c, plate, mean(p));
597 *c = mix(*c, 128, mean(s));
598 *c = mix(*c, ink, mean(f));
599 }
600 if ka > 0 {
601 let a = mean(ka);
602 u[ci] = mix(u[ci], (kcb / ka as f32).round() as u8, a);
603 v[ci] = mix(v[ci], (kcr / ka as f32).round() as u8, a);
604 }
605 } else if coloured {
606 let keep = 1.0 - sum as f32 / (255.0 * n as f32);
607 let target = 1.0 / (255.0 * n as f32);
608 u[ci] = (f32::from(u[ci]) * keep + tu * target)
609 .round()
610 .clamp(0.0, 255.0) as u8;
611 v[ci] = (f32::from(v[ci]) * keep + tv * target)
612 .round()
613 .clamp(0.0, 255.0) as u8;
614 } else {
615 let a = (sum / n) as u8;
616 u[ci] = mix(u[ci], 128, a);
617 v[ci] = mix(v[ci], 128, a);
618 }
619 }
620 }
621 }
622 }
623}
624
625impl Overlay {
626 /// The same coverage with every plane scaled by `alpha` (255 leaves it
627 /// as it is, 0 draws nothing): what a title's fade is. Each plane is a
628 /// mix toward its colour, so scaling the coverage scales the mix.
629 pub fn faded(&self, alpha: u8) -> Self {
630 let scale = |p: &[u8]| -> Vec<u8> {
631 p.iter()
632 .map(|&c| ((u32::from(c) * u32::from(alpha) + 127) / 255) as u8)
633 .collect()
634 };
635 Self {
636 width: self.width,
637 height: self.height,
638 bounds: self.bounds,
639 ink: self.ink,
640 plate_rgb: self.plate_rgb,
641 plate: scale(&self.plate),
642 stroke: scale(&self.stroke),
643 fill: scale(&self.fill),
644 colour: self
645 .colour
646 .iter()
647 .map(|c| {
648 let a = (u32::from(c[3]) * u32::from(alpha) + 127) / 255;
649 [c[0], c[1], c[2], a as u8]
650 })
651 .collect(),
652 }
653 }
654}
655
656impl Overlay {
657 /// The same coverage moved `dx` pixels right and `dy` down, what a title's slide is. The part
658 /// that moves off the frame is cut, as the frame cuts any picture.
659 pub fn moved(&self, dx: i32, dy: i32) -> Self {
660 let (w, h) = (self.width as i64, self.height as i64);
661 let shift = |p: &[u8]| -> Vec<u8> {
662 let mut out = vec![0u8; p.len()];
663 let (x0, y0, x1, y1) = self.bounds;
664 for y in y0 as i64..y1 as i64 {
665 for x in x0 as i64..x1 as i64 {
666 let (nx, ny) = (x + i64::from(dx), y + i64::from(dy));
667 if (0..w).contains(&nx) && (0..h).contains(&ny) {
668 out[(ny * w + nx) as usize] = p[(y * w + x) as usize];
669 }
670 }
671 }
672 out
673 };
674 let (x0, y0, x1, y1) = self.bounds;
675 let bounds = (
676 (i64::from(x0) + i64::from(dx)).clamp(0, w) as u32,
677 (i64::from(y0) + i64::from(dy)).clamp(0, h) as u32,
678 (i64::from(x1) + i64::from(dx)).clamp(0, w) as u32,
679 (i64::from(y1) + i64::from(dy)).clamp(0, h) as u32,
680 );
681 let mut colour = vec![[0u8; 4]; self.colour.len()];
682 if !self.colour.is_empty() {
683 for y in y0 as i64..y1 as i64 {
684 for x in x0 as i64..x1 as i64 {
685 let (nx, ny) = (x + i64::from(dx), y + i64::from(dy));
686 if (0..w).contains(&nx) && (0..h).contains(&ny) {
687 colour[(ny * w + nx) as usize] = self.colour[(y * w + x) as usize];
688 }
689 }
690 }
691 }
692 Self {
693 width: self.width,
694 height: self.height,
695 bounds,
696 plate: shift(&self.plate),
697 stroke: shift(&self.stroke),
698 fill: shift(&self.fill),
699 colour,
700 ink: self.ink,
701 plate_rgb: self.plate_rgb,
702 }
703 }
704}
705
706/// `dst` pulled toward `src` by `a / 255`.
707fn mix(dst: u8, src: u8, a: u8) -> u8 {
708 let a = u32::from(a);
709 ((u32::from(dst) * (255 - a) + u32::from(src) * a + 127) / 255) as u8
710}
711
712/// The Y, Cb and Cr of a colour in the matrix (BT.709 or BT.601) and range a frame
713/// is coded in: full range spans 0 to 255, limited range 16 to 235 and 16 to 240.
714fn yuv(c: [u8; 4], bt709: bool, full_range: bool) -> (u8, u8, u8) {
715 let (kr, kb) = if bt709 {
716 (0.2126, 0.0722)
717 } else {
718 (0.299, 0.114)
719 };
720 let kg = 1.0 - kr - kb;
721 let (r, g, b) = (f32::from(c[0]), f32::from(c[1]), f32::from(c[2]));
722 let luma = (kr * r + kg * g + kb * b) / 255.0;
723 let cb = (b / 255.0 - luma) / (2.0 * (1.0 - kb));
724 let cr = (r / 255.0 - luma) / (2.0 * (1.0 - kr));
725 let (ys, cs, yo) = if full_range {
726 (255.0, 255.0, 0.0)
727 } else {
728 (219.0, 224.0, 16.0)
729 };
730 let to_u8 = |v: f32| v.round().clamp(0.0, 255.0) as u8;
731 (
732 to_u8(yo + ys * luma),
733 to_u8(128.0 + cs * cb),
734 to_u8(128.0 + cs * cr),
735 )
736}
737
738/// A rectangle `(x0, y0, x1, y1)` in pixels, the edges as floats.
739type Rect = (f32, f32, f32, f32);
740
741/// The smallest rectangle holding both `acc` and `r`.
742fn grow(acc: Option<Rect>, r: Rect) -> Option<Rect> {
743 Some(match acc {
744 None => r,
745 Some(b) => (b.0.min(r.0), b.1.min(r.1), b.2.max(r.2), b.3.max(r.3)),
746 })
747}
748
749/// Lays `lines` out in `style` on a `width` x `height` frame and returns the
750/// coverage. Each entry of `lines` is a paragraph: they are wrapped to the
751/// frame's width, never joined. A blank list or a zero-sized frame is an
752/// overlay that [`Overlay::is_blank`].
753pub fn overlay(style: &TextStyle, width: u32, height: u32, lines: &[String]) -> Overlay {
754 overlay_stack(style, width, height, &[lines.to_vec()])
755}
756
757/// Lays several blocks of text out together and returns their coverage: each
758/// block is one cue's lines, wrapped as [`overlay`] wraps them. The blocks
759/// stack from the edge the style places them at, the first block nearest that
760/// edge (for [`Place::Bottom`] the first sits lowest, and each later one sits
761/// above it; [`Place::Top`] stacks downward; [`Place::Centre`] centres the
762/// stack and puts the first lowest). Boxes are per block and never touch. A
763/// block with no words takes no room.
764pub fn overlay_stack(
765 style: &TextStyle,
766 width: u32,
767 height: u32,
768 blocks: &[Vec<String>],
769) -> Overlay {
770 let plain: Vec<Block> = blocks
771 .iter()
772 .map(|b| Block { lines: b.clone(), fx: Vec::new(), kara: Vec::new() })
773 .collect();
774 overlay_blocks(style, width, height, &plain)
775}
776
777/// What one word of an animated block is drawn with.
778#[derive(Clone, Copy, Debug, PartialEq)]
779pub struct WordFx {
780 /// Not drawn at all, but its room in the line is kept, so the words around it do not move.
781 pub hidden: bool,
782 /// The size of the word against its line, about its own centre.
783 pub scale: f32,
784 /// How far the word is lifted off the baseline, in ems.
785 pub lift: f32,
786 /// The highlight: its colour, and whether it is a rounded box behind white text
787 /// rather than coloured text.
788 pub highlight: Option<([u8; 3], bool)>,
789}
790
791impl Default for WordFx {
792 fn default() -> Self {
793 Self { hidden: false, scale: 1.0, lift: 0.0, highlight: None }
794 }
795}
796
797/// One cue's text for [`overlay_blocks`]: its lines, and optionally one [`WordFx`] per
798/// whitespace-separated word of them, in reading order. An `fx` of another length (or none)
799/// draws the lines plainly, as [`overlay_stack`] does.
800#[derive(Clone, Debug, PartialEq)]
801pub struct Block {
802 pub lines: Vec<String>,
803 pub fx: Vec<WordFx>,
804 /// The karaoke syllables of an ASS cue, drawn when `fx` is empty.
805 pub kara: Vec<Syl>,
806}
807
808/// One karaoke syllable of a [`Block`] as it looks now: which letters, and what colours.
809#[derive(Clone, Copy, Debug, PartialEq)]
810pub struct Syl {
811 /// The first of its characters, counting the block's non-whitespace characters from 0.
812 pub from: usize,
813 /// How many characters it covers.
814 pub len: usize,
815 /// The colour of the part of the syllable left of the split, and of the part right of it;
816 /// `None` is the style's own ink.
817 pub left: Option<[u8; 3]>,
818 pub right: Option<[u8; 3]>,
819 /// Where the split falls across the syllable's width, 0 to 1.
820 pub split: f32,
821 /// Drawn without the outline (an outline karaoke syllable that has not begun).
822 pub bare: bool,
823}
824
825/// [`overlay_stack`] over blocks whose words may carry an effect.
826pub fn overlay_blocks(style: &TextStyle, width: u32, height: u32, blocks: &[Block]) -> Overlay {
827 overlay_blocks_shown(style, width, height, blocks, None)
828}
829
830/// The text laid out whole, with only its first `ink` letters (non-whitespace characters) drawn:
831/// the rest keep their room, so a title that types on does not move. `ink` at or past the text's
832/// letters draws all of it.
833pub fn overlay_revealed(style: &TextStyle, width: u32, height: u32, lines: &[String], ink: usize) -> Overlay {
834 overlay_blocks_shown(style, width, height, &[Block { lines: lines.to_vec(), fx: Vec::new(), kara: Vec::new() }], Some(ink))
835}
836
837/// [`overlay_blocks`] with an optional count of the letters drawn (see [`overlay_revealed`]).
838fn overlay_blocks_shown(style: &TextStyle, width: u32, height: u32, blocks: &[Block], shown: Option<usize>) -> Overlay {
839 let mut out = Overlay::empty(width, height);
840 let blank = |b: &Block| b.lines.iter().all(|l| l.trim().is_empty());
841 if width == 0 || height == 0 || blocks.iter().all(blank) {
842 return out;
843 }
844 let style = style.clamped();
845 let em = (style.size as f32 / 1000.0 * height as f32).max(6.0);
846 let Some(faces) = Faces::with_style(em, &style) else {
847 return out;
848 };
849 out.ink = style.ink;
850 out.plate_rgb = [style.box_color[0], style.box_color[1], style.box_color[2]];
851 let margin = MARGIN * height as f32;
852 let max_w = (width as f32 - 2.0 * margin).max(em);
853 let laid: Vec<(Vec<String>, &[WordFx], &[Syl])> = blocks
854 .iter()
855 .filter(|b| !blank(b))
856 .map(|b| {
857 let lines = wrap(&faces, &b.lines, max_w);
858 // Wrapping that cut a word (one wider than the frame) loses the count: plain then.
859 let words = lines.iter().map(|l| l.split_whitespace().count()).sum::<usize>();
860 let fx: &[WordFx] = if b.fx.len() == words { &b.fx } else { &[] };
861 let kara: &[Syl] = if fx.is_empty() { &b.kara } else { &[] };
862 (lines, fx, kara)
863 })
864 .filter(|(w, _, _)| !w.is_empty())
865 .collect();
866 if laid.is_empty() {
867 return out;
868 }
869 let line_h = (faces.text.height() + faces.text.line_gap()) * 1.1;
870 let heights: Vec<f32> = laid.iter().map(|(w, _, _)| line_h * w.len() as f32).collect();
871 let gap = em * STACK_GAP;
872 let total = heights.iter().sum::<f32>() + gap * (laid.len() - 1) as f32;
873 // The top of each block, in the order the blocks were given.
874 let tops: Vec<f32> = match style.place {
875 Place::Top => {
876 let mut y = margin;
877 heights
878 .iter()
879 .map(|h| {
880 let t = y;
881 y += h + gap;
882 t
883 })
884 .collect()
885 }
886 Place::Bottom | Place::Centre => {
887 let mut y = match style.place {
888 Place::Centre => (height as f32 + total) / 2.0,
889 _ => height as f32 - margin,
890 };
891 heights
892 .iter()
893 .map(|h| {
894 y -= h;
895 let t = y;
896 y -= gap;
897 t
898 })
899 .collect()
900 }
901 };
902 // Each block's own rectangle, which its box and the bounds are cut from.
903 let mut rects: Vec<Rect> = Vec::with_capacity(laid.len());
904 // The cells colour glyphs were painted in, which can reach past their line.
905 let mut colour_cells: Option<Rect> = None;
906 let mut scratch: Vec<u8> = Vec::new();
907 // The letters of the lines already laid, against `shown`.
908 let mut seen = 0usize;
909 // Syllables with no outline, drawn once the outline is: `(text, x, baseline)`.
910 let mut bare: Vec<(String, f32, f32)> = Vec::new();
911 for ((lines, fx, kara), top) in laid.iter().zip(&tops) {
912 let mut rect: Option<Rect> = None;
913 let mut next_word = 0;
914 let mut kara_seen = 0;
915 let block_w = lines.iter().map(|l| string_width(&faces, l)).fold(0.0f32, f32::max);
916 // The block's left edge: against a margin, or centred.
917 let block_x = match style.hplace {
918 HPlace::Left => margin,
919 HPlace::Right => width as f32 - margin - block_w,
920 HPlace::Centre => (width as f32 - block_w) / 2.0,
921 };
922 for (n, line) in lines.iter().enumerate() {
923 let line_w = string_width(&faces, line);
924 let x0 = match (style.hplace, style.align) {
925 // Centred in a centred block is centred on the frame, as it always was.
926 (HPlace::Centre, Align::Centre) => (width as f32 - line_w) / 2.0,
927 (_, Align::Centre) => block_x + (block_w - line_w) / 2.0,
928 (_, Align::Left) => block_x,
929 (_, Align::Right) => block_x + block_w - line_w,
930 };
931 let baseline = top + n as f32 * line_h + faces.text.ascent();
932 let r = (
933 x0,
934 top + n as f32 * line_h,
935 x0 + line_w,
936 top + (n as f32 + 1.0) * line_h,
937 );
938 rect = grow(rect, r);
939 let cell = if !kara.is_empty() {
940 let at = Pen { x0, baseline, top: top + n as f32 * line_h, line_h };
941 draw_line_kara(&mut out, &faces, line, at, kara, &mut kara_seen, &mut scratch, &mut bare)
942 } else if fx.is_empty() {
943 let clip = reveal_clip(&faces, line, x0, shown, &mut seen);
944 draw_line(&mut out, &faces, line, x0, baseline, clip)
945 } else {
946 let count = line.split_whitespace().count();
947 let at = Pen { x0, baseline, top: top + n as f32 * line_h, line_h };
948 let cell = draw_line_fx(&mut out, &faces, line, at, &fx[next_word..next_word + count], &mut scratch);
949 next_word += count;
950 cell
951 };
952 if let Some(cell) = cell {
953 colour_cells = grow(colour_cells, cell);
954 }
955 }
956 rects.extend(rect);
957 }
958 let stroke_r = match style.outline {
959 Outline::None => 0,
960 Outline::Thin => (em / 24.0).round().max(1.0) as u32,
961 Outline::Thick => (em / 12.0).round().max(2.0) as u32,
962 };
963 // The bounds: every block, padded by the box and the stroke, inside the frame.
964 let pad = em * 0.3 + stroke_r as f32;
965 let mut bounds: Option<Rect> = colour_cells;
966 for &(bx0, by0, bx1, by1) in &rects {
967 bounds = grow(bounds, (bx0 - pad, by0 - pad, bx1 + pad, by1 + pad));
968 }
969 if let Some((x0, y0, x1, y1)) = bounds {
970 out.bounds = (
971 x0.floor().max(0.0) as u32,
972 y0.floor().max(0.0) as u32,
973 x1.ceil().min(width as f32) as u32,
974 y1.ceil().min(height as f32) as u32,
975 );
976 }
977 if stroke_r > 0 {
978 // The outline goes round the white glyphs and the colour ones alike.
979 let mut shape = out.fill.clone();
980 for (s, c) in shape.iter_mut().zip(&out.colour) {
981 *s = (*s).max(c[3]);
982 }
983 out.stroke = dilate(&shape, width, height, stroke_r);
984 }
985 for (text, x, baseline) in &bare {
986 let ink = Some(out.ink);
987 let reach = (*x, 0.0, x + string_width(&faces, text), height as f32);
988 draw_split(&mut out, &faces, text, (*x, *baseline), reach, (f32::INFINITY, ink, ink), &mut scratch);
989 }
990 if style.boxed {
991 for &(bx0, by0, bx1, by1) in &rects {
992 let (px0, py0) = (
993 (bx0 - em * 0.3).floor().max(0.0) as u32,
994 (by0 - em * 0.15).floor().max(0.0) as u32,
995 );
996 let (px1, py1) = (
997 (bx1 + em * 0.3).ceil().min(width as f32) as u32,
998 (by1 + em * 0.15).ceil().min(height as f32) as u32,
999 );
1000 for y in py0..py1 {
1001 let row = y as usize * width as usize;
1002 for x in px0..px1 {
1003 out.plate[row + x as usize] = style.box_color[3];
1004 }
1005 }
1006 }
1007 }
1008 out
1009}
1010
1011/// How much of the frame the text takes, for a warning about a title that fills it: the wrapped
1012/// line count and the share of the frame height its line boxes cover (0 to 1). `lines` are
1013/// paragraphs, as [`overlay`] takes them. A blank block or a zero-sized frame is `(0, 0.0)`.
1014/// Only the line boxes count, not the box or the stroke around them.
1015pub fn layout_share(style: &TextStyle, width: u32, height: u32, lines: &[String]) -> (usize, f32) {
1016 if width == 0 || height == 0 || lines.iter().all(|l| l.trim().is_empty()) {
1017 return (0, 0.0);
1018 }
1019 let style = style.clamped();
1020 let em = (style.size as f32 / 1000.0 * height as f32).max(6.0);
1021 let Some(faces) = Faces::with_style(em, &style) else {
1022 return (0, 0.0);
1023 };
1024 let margin = MARGIN * height as f32;
1025 let max_w = (width as f32 - 2.0 * margin).max(em);
1026 let count = wrap(&faces, lines, max_w).len();
1027 let line_h = (faces.text.height() + faces.text.line_gap()) * 1.1;
1028 (count, line_h * count as f32 / height as f32)
1029}
1030
1031/// Lays `lines` out and composes them over a BGRA canvas: [`overlay`] followed
1032/// by [`Overlay::blend_bgra`]. Blank text leaves the canvas as it was.
1033pub fn draw_text(canvas: &mut [u8], width: u32, height: u32, style: &TextStyle, lines: &[String]) {
1034 overlay(style, width, height, lines).blend_bgra(canvas);
1035}
1036
1037/// The characters in `lines` that neither bundled face has a glyph for, each
1038/// once and in the order they first appear: what a caption shows as an empty
1039/// box. Whitespace and the invisible joiners of an emoji sequence are not
1040/// missing. Empty when the faces are unavailable.
1041pub fn missing_glyphs(lines: &[String]) -> Vec<char> {
1042 let mut out: Vec<char> = Vec::new();
1043 for c in lines.iter().flat_map(|l| l.chars()) {
1044 if c.is_whitespace() || is_invisible(c) || out.contains(&c) {
1045 continue;
1046 }
1047 if lookup(c).is_none() {
1048 out.push(c);
1049 }
1050 }
1051 out
1052}
1053
1054/// Characters that take no room and draw nothing of their own: the zero-width
1055/// joiner that stitches an emoji sequence, and the variation selectors that
1056/// pick its presentation. They are skipped, never drawn as an empty box.
1057fn is_invisible(c: char) -> bool {
1058 matches!(c, '\u{200D}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')
1059}
1060
1061/// The faces one block is set in at one em size. The glyphs come from [`lookup`]
1062/// and the outline faces are parsed once for the whole process; this only holds
1063/// the em and Archivo's metrics, which a line is laid out on.
1064struct Faces {
1065 em: f32,
1066 /// Latin is set in Archivo Bold rather than Medium.
1067 bold: bool,
1068 text: Scaled<'static>,
1069 /// The system family the style names, drawn before the bundled faces when it has a glyph.
1070 family: Option<Family>,
1071}
1072
1073impl Faces {
1074 #[cfg(test)]
1075 fn new(em: f32) -> Option<Self> {
1076 Self::with_weight(em, Weight::Regular)
1077 }
1078
1079 fn with_weight(em: f32, weight: Weight) -> Option<Self> {
1080 let bold = weight == Weight::Bold;
1081 let text = outline_face(if bold { ARCHIVO_BOLD } else { ARCHIVO })?.as_scaled(PxScale::from(em));
1082 Some(Self { em, bold, text, family: None })
1083 }
1084
1085 /// The faces a style is set in at `em`: its weight, and its family when the system has it.
1086 fn with_style(em: f32, style: &TextStyle) -> Option<Self> {
1087 let mut faces = Self::with_weight(em, style.weight)?;
1088 faces.family = style.family.as_deref().and_then(family_face);
1089 Some(faces)
1090 }
1091
1092 /// The same faces at another em (a word that scales in an animation).
1093 fn rescaled(&self, em: f32) -> Option<Self> {
1094 let mut faces = Self::with_weight(em, if self.bold { Weight::Bold } else { Weight::Regular })?;
1095 faces.family = self.family;
1096 Some(faces)
1097 }
1098
1099 /// The outline face `src` is drawn with at this em, or None for a colour
1100 /// glyph, which [`draw_colour`] paints instead.
1101 fn font(&self, src: Src) -> Option<Scaled<'static>> {
1102 match src {
1103 Src::Outline(i) => {
1104 let i = if self.bold && i == ARCHIVO { ARCHIVO_BOLD } else { i };
1105 let px = PxScale::from(self.em * face_k()[i]);
1106 Some(outline_face(i)?.as_scaled(px))
1107 }
1108 Src::Family => {
1109 let family = self.family?;
1110 Some(family.font.as_scaled(PxScale::from(self.em * family.k)))
1111 }
1112 Src::Cjk | Src::Colour => None,
1113 }
1114 }
1115}
1116
1117/// One glyph of a laid-out line, in the order it is drawn. The pen moves by
1118/// `kern` before the glyph and by `advance` after it. The glyph itself is drawn
1119/// `shift` to the right of the pen and `lift` above the baseline, which moves
1120/// nothing (a mark sits on its base that way).
1121#[derive(Clone, Copy, Debug, PartialEq)]
1122struct Placed {
1123 src: Src,
1124 id: u16,
1125 kern: f32,
1126 shift: f32,
1127 lift: f32,
1128 advance: f32,
1129}
1130
1131/// The runs of `s` in visual order, left to right across the line, each with
1132/// whether it is right-to-left. A line with no right-to-left text is one run.
1133fn visual_parts(s: &str) -> Vec<(bool, &str)> {
1134 // ASCII has no right-to-left character, and most captions are ASCII: skip the analysis.
1135 if s.is_ascii() {
1136 return vec![(false, s)];
1137 }
1138 let info = BidiInfo::new(s, None);
1139 if !info.has_rtl() {
1140 return vec![(false, s)];
1141 }
1142 info.paragraphs
1143 .iter()
1144 .flat_map(|para| {
1145 let (levels, runs) = info.visual_runs(para, para.range.clone());
1146 runs.into_iter()
1147 .map(|r| (levels[r.start].is_rtl(), &s[r]))
1148 .collect::<Vec<_>>()
1149 })
1150 .collect()
1151}
1152
1153/// The characters of `part` split into runs of one source, in logical order.
1154/// Invisible characters are dropped.
1155fn segments(faces: &Faces, part: &str) -> Vec<(Src, String)> {
1156 let mut out: Vec<(Src, String)> = Vec::new();
1157 for ch in part.chars() {
1158 if is_invisible(ch) {
1159 continue;
1160 }
1161 let (src, _) = pick_in(faces, ch);
1162 match out.last_mut() {
1163 Some((s, text)) if *s == src => text.push(ch),
1164 _ => out.push((src, ch.to_string())),
1165 }
1166 }
1167 out
1168}
1169
1170/// The glyphs of `s` in the order they are drawn, left to right across the line.
1171/// A right-to-left run is reversed into visual order and shaped right-to-left.
1172/// Invisible characters are dropped.
1173fn run(faces: &Faces, s: &str) -> Vec<Placed> {
1174 let mut out = Vec::new();
1175 for (rtl, part) in visual_parts(s) {
1176 let mut segs = segments(faces, part);
1177 if rtl {
1178 segs.reverse();
1179 }
1180 for (src, text) in segs {
1181 out.extend(place(faces, src, &text, rtl));
1182 }
1183 }
1184 out
1185}
1186
1187/// The glyphs of one run of one source: shaped for the scripts that need it,
1188/// plain for Archivo and the emoji and CJK faces, painted from the colour font
1189/// for a colour glyph.
1190fn place(faces: &Faces, src: Src, text: &str, rtl: bool) -> Vec<Placed> {
1191 match src {
1192 Src::Outline(i) if (NOTO_SANS..MONO_EMOJI).contains(&i) => {
1193 shape(faces, i, text, rtl).unwrap_or_else(|| plain(faces, src, text))
1194 }
1195 Src::Colour => colour_glyphs(faces, text),
1196 Src::Cjk => cjk_glyphs(faces, text),
1197 _ => plain(faces, src, text),
1198 }
1199}
1200
1201/// Advance-and-kern placement, the path Archivo has always been set with: each
1202/// glyph's advance and the pair kern before it, read from the face.
1203fn plain(faces: &Faces, src: Src, text: &str) -> Vec<Placed> {
1204 let Some(font) = faces.font(src) else {
1205 return Vec::new();
1206 };
1207 let mut out = Vec::new();
1208 let mut prev: Option<GlyphId> = None;
1209 for c in text.chars() {
1210 let id = font.glyph_id(c);
1211 let kern = prev.map_or(0.0, |p| font.kern(p, id));
1212 out.push(Placed {
1213 src,
1214 id: id.0,
1215 kern,
1216 shift: 0.0,
1217 lift: 0.0,
1218 advance: font.h_advance(id),
1219 });
1220 prev = Some(id);
1221 }
1222 out
1223}
1224
1225/// Shapes one run with `rustybuzz`: joining forms, reordering and conjuncts come
1226/// from the face's own GSUB and GPOS. None when the face does not parse.
1227fn shape(faces: &Faces, i: usize, text: &str, rtl: bool) -> Option<Vec<Placed>> {
1228 let face = shaper(i)?;
1229 let mut buf = rustybuzz::UnicodeBuffer::new();
1230 buf.push_str(text);
1231 buf.set_direction(if rtl {
1232 rustybuzz::Direction::RightToLeft
1233 } else {
1234 rustybuzz::Direction::LeftToRight
1235 });
1236 let glyphs = rustybuzz::shape(face, &[], buf);
1237 // The same scale ab_glyph draws the outlines at: the em over the face's height.
1238 let scale = faces.em / outline_face(i)?.height_unscaled();
1239 Some(
1240 glyphs
1241 .glyph_infos()
1242 .iter()
1243 .zip(glyphs.glyph_positions())
1244 .map(|(info, pos)| Placed {
1245 src: Src::Outline(i),
1246 id: info.glyph_id as u16,
1247 kern: 0.0,
1248 shift: pos.x_offset as f32 * scale,
1249 lift: pos.y_offset as f32 * scale,
1250 advance: pos.x_advance as f32 * scale,
1251 })
1252 .collect(),
1253 )
1254}
1255
1256/// The CJK glyphs of `text`: no shaping, each advancing by its own advance in the
1257/// variable face at Medium. One em is one unit of the face's own em.
1258fn cjk_glyphs(faces: &Faces, text: &str) -> Vec<Placed> {
1259 let Some(face) = cjk_face() else {
1260 return Vec::new();
1261 };
1262 let scale = faces.em / f32::from(face.units_per_em());
1263 text.chars()
1264 .filter_map(|c| face.glyph_index(c))
1265 .map(|g| Placed {
1266 src: Src::Cjk,
1267 id: g.0,
1268 kern: 0.0,
1269 shift: 0.0,
1270 lift: 0.0,
1271 advance: f32::from(face.glyph_hor_advance(g).unwrap_or(0)) * scale,
1272 })
1273 .collect()
1274}
1275
1276/// The colour glyphs of `text`, each advancing by its own advance in the colour
1277/// font. Empty when the system has no colour font.
1278fn colour_glyphs(faces: &Faces, text: &str) -> Vec<Placed> {
1279 let Some(face) = colour_face() else {
1280 return Vec::new();
1281 };
1282 let scale = em_scale(faces.em, face);
1283 text.chars()
1284 .filter_map(|c| face.glyph_index(c))
1285 .map(|g| Placed {
1286 src: Src::Colour,
1287 id: g.0,
1288 kern: 0.0,
1289 shift: 0.0,
1290 lift: 0.0,
1291 advance: f32::from(face.glyph_hor_advance(g).unwrap_or(0)) * scale,
1292 })
1293 .collect()
1294}
1295
1296/// Where a line sits: its pen start and baseline, and the box of the line.
1297struct Pen {
1298 x0: f32,
1299 baseline: f32,
1300 top: f32,
1301 line_h: f32,
1302}
1303
1304/// [`draw_line`] a word at a time, each with its [`WordFx`]: a hidden word keeps its room and
1305/// draws nothing, a scaled or lifted one is drawn about its own place, and a highlighted one goes
1306/// to the colour plane (over a rounded box of the colour, when that is asked). `fx` has one entry
1307/// per word of `line`. Returns the cell the effects reached past the line's own.
1308fn draw_line_fx(
1309 out: &mut Overlay,
1310 faces: &Faces,
1311 line: &str,
1312 at: Pen,
1313 fx: &[WordFx],
1314 scratch: &mut Vec<u8>,
1315) -> Option<Rect> {
1316 let words: Vec<&str> = line.split_whitespace().collect();
1317 let em = faces.em;
1318 let mut cells: Option<Rect> = None;
1319 for (i, (word, f)) in words.iter().zip(fx).enumerate() {
1320 if f.hidden {
1321 continue;
1322 }
1323 let before = if i == 0 { 0.0 } else { string_width(faces, &format!("{} ", words[..i].join(" "))) };
1324 let natural = string_width(faces, word);
1325 let scaled = faces.rescaled(em * f.scale.max(0.1));
1326 let face = scaled.as_ref().unwrap_or(faces);
1327 let width = string_width(face, word);
1328 let x = at.x0 + before + (natural - width) / 2.0;
1329 let baseline = at.baseline - f.lift * em;
1330 let reach = (x - 0.25 * em, baseline - 1.3 * face.em, x + width + 0.25 * em, baseline + 0.5 * face.em);
1331 match f.highlight {
1332 None => {
1333 if let Some(c) = draw_line(out, face, word, x, baseline, f32::INFINITY) {
1334 cells = grow(cells, c);
1335 }
1336 if f.scale != 1.0 || f.lift != 0.0 {
1337 cells = grow(cells, reach);
1338 }
1339 }
1340 Some((rgb, boxed)) => {
1341 let colour = if boxed {
1342 let (px, py) = (0.2 * em, at.line_h * 0.04);
1343 let r = (at.x0 + before - px, at.top + py, at.x0 + before + natural + px, at.top + at.line_h - py);
1344 rounded_box(out, r, rgb);
1345 cells = grow(cells, r);
1346 [255, 255, 255]
1347 } else {
1348 rgb
1349 };
1350 // The word is drawn into a clean fill plane, then moved to the colour plane.
1351 let n = out.fill.len();
1352 scratch.clear();
1353 scratch.resize(n, 0);
1354 std::mem::swap(&mut out.fill, scratch);
1355 let c = draw_line(out, face, word, x, baseline, f32::INFINITY);
1356 std::mem::swap(&mut out.fill, scratch);
1357 let (w, h) = (out.width as usize, out.height as usize);
1358 let (x0, x1) = (reach.0.max(0.0) as usize, (reach.2.ceil().max(0.0) as usize).min(w));
1359 let (y0, y1) = (reach.1.max(0.0) as usize, (reach.3.ceil().max(0.0) as usize).min(h));
1360 for py in y0..y1 {
1361 for px in x0..x1 {
1362 let a = scratch[py * w + px];
1363 if a > 0 {
1364 put_colour(out, py * w + px, colour, a);
1365 }
1366 }
1367 }
1368 cells = grow(cells, reach);
1369 if let Some(c) = c {
1370 cells = grow(cells, c);
1371 }
1372 }
1373 }
1374 }
1375 cells
1376}
1377
1378/// [`draw_line`] a line whose letters belong to karaoke syllables ([`Syl`]), a syllable at a time:
1379/// each at the place the line's own layout gives it, split in two colours where it is half sung.
1380/// `seen` counts the block's non-whitespace characters across its lines. A syllable without an
1381/// outline is not drawn but put in `bare`, for after the outline. Returns the cell the colours
1382/// reached.
1383#[allow(clippy::too_many_arguments)]
1384fn draw_line_kara(
1385 out: &mut Overlay,
1386 faces: &Faces,
1387 line: &str,
1388 at: Pen,
1389 kara: &[Syl],
1390 seen: &mut usize,
1391 scratch: &mut Vec<u8>,
1392 bare: &mut Vec<(String, f32, f32)>,
1393) -> Option<Rect> {
1394 // The syllable of each non-whitespace character (`None` for one no syllable covers).
1395 let letters: Vec<(usize, char)> = line.char_indices().filter(|(_, c)| !c.is_whitespace()).collect();
1396 let owner: Vec<Option<usize>> = letters
1397 .iter()
1398 .map(|_| {
1399 *seen += 1;
1400 kara.iter().position(|k| (k.from..k.from + k.len).contains(&(*seen - 1)))
1401 })
1402 .collect();
1403 let mut cells: Option<Rect> = None;
1404 let mut i = 0;
1405 while i < letters.len() {
1406 // The run of one syllable (the spaces inside it stay), or of unlit text.
1407 let mut j = i + 1;
1408 while j < letters.len() && owner[j] == owner[i] {
1409 j += 1;
1410 }
1411 let (start, (last, c)) = (letters[i].0, letters[j - 1]);
1412 let text = &line[start..last + c.len_utf8()];
1413 let x = at.x0 + string_width(faces, &line[..start]);
1414 match owner[i].map(|k| kara[k]) {
1415 None => {
1416 if let Some(c) = draw_line(out, faces, text, x, at.baseline, f32::INFINITY) {
1417 cells = grow(cells, c);
1418 }
1419 }
1420 Some(k) if k.bare => bare.push((text.to_string(), x, at.baseline)),
1421 Some(k) => {
1422 let em = faces.em;
1423 let w = string_width(faces, text);
1424 let reach = (x - 0.25 * em, at.baseline - 1.3 * em, x + w + 0.25 * em, at.baseline + 0.5 * em);
1425 draw_split(out, faces, text, (x, at.baseline), reach, (x + w * k.split, k.left, k.right), scratch);
1426 cells = grow(cells, reach);
1427 }
1428 }
1429 i = j;
1430 }
1431 cells
1432}
1433
1434/// The x past which `line` draws nothing under a reveal of `shown` letters: `seen` counts the
1435/// letters of the lines before it and is advanced past this one. Without a reveal, `INFINITY`.
1436fn reveal_clip(faces: &Faces, line: &str, x0: f32, shown: Option<usize>, seen: &mut usize) -> f32 {
1437 let Some(shown) = shown else { return f32::INFINITY };
1438 let ink = line.chars().filter(|c| !c.is_whitespace()).count();
1439 let here = shown.saturating_sub(*seen).min(ink);
1440 *seen += ink;
1441 if here == ink {
1442 return f32::INFINITY;
1443 }
1444 if here == 0 {
1445 return f32::NEG_INFINITY;
1446 }
1447 // Cut where the first letter not yet drawn begins.
1448 let cut = line.char_indices().filter(|(_, c)| !c.is_whitespace()).nth(here).map_or(line.len(), |(i, _)| i);
1449 x0 + string_width(faces, &line[..cut])
1450}
1451
1452/// `text` drawn at `(x, baseline)` in two colours: the part left of column `split.0` in `split.1`,
1453/// the rest in `split.2` (`None` is the ink, in the fill plane; a colour goes to the colour plane).
1454/// Only the pixels inside `reach` are looked at.
1455fn draw_split(
1456 out: &mut Overlay,
1457 faces: &Faces,
1458 text: &str,
1459 (x, baseline): (f32, f32),
1460 reach: Rect,
1461 (split, left, right): (f32, Option<[u8; 3]>, Option<[u8; 3]>),
1462 scratch: &mut Vec<u8>,
1463) {
1464 // The glyphs go into a clean fill plane, then each pixel to the plane of its side.
1465 let n = out.fill.len();
1466 scratch.clear();
1467 scratch.resize(n, 0);
1468 std::mem::swap(&mut out.fill, scratch);
1469 draw_line(out, faces, text, x, baseline, f32::INFINITY);
1470 std::mem::swap(&mut out.fill, scratch);
1471 let (w, h) = (out.width as usize, out.height as usize);
1472 let (x0, x1) = (reach.0.max(0.0) as usize, (reach.2.ceil().max(0.0) as usize).min(w));
1473 let (y0, y1) = (reach.1.max(0.0) as usize, (reach.3.ceil().max(0.0) as usize).min(h));
1474 for py in y0..y1 {
1475 for px in x0..x1 {
1476 let a = scratch[py * w + px];
1477 if a == 0 {
1478 continue;
1479 }
1480 match if (px as f32 + 0.5) < split { left } else { right } {
1481 None => out.fill[py * w + px] = out.fill[py * w + px].max(a),
1482 Some(rgb) => put_colour(out, py * w + px, rgb, a),
1483 }
1484 }
1485 }
1486}
1487
1488/// `rgb` laid over the colour plane's pixel `i` with coverage `a`: the straight-alpha "over".
1489fn put_colour(out: &mut Overlay, i: usize, rgb: [u8; 3], a: u8) {
1490 if out.colour.is_empty() {
1491 out.colour = vec![[0; 4]; out.width as usize * out.height as usize];
1492 }
1493 let d = out.colour[i];
1494 let (sa, da) = (f32::from(a) / 255.0, f32::from(d[3]) / 255.0);
1495 let oa = sa + da * (1.0 - sa);
1496 if oa <= 0.0 {
1497 return;
1498 }
1499 let mut v = [0u8; 4];
1500 for k in 0..3 {
1501 let c = (f32::from(rgb[k]) * sa + f32::from(d[k]) * da * (1.0 - sa)) / oa;
1502 v[k] = c.round().clamp(0.0, 255.0) as u8;
1503 }
1504 v[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8;
1505 out.colour[i] = v;
1506}
1507
1508/// A rounded rectangle of `rgb` in the colour plane, its corners a quarter of its height round.
1509fn rounded_box(out: &mut Overlay, r: Rect, rgb: [u8; 3]) {
1510 let (w, h) = (out.width as usize, out.height as usize);
1511 let rad = (r.3 - r.1) * 0.28;
1512 let (cx, cy) = ((r.0 + r.2) / 2.0, (r.1 + r.3) / 2.0);
1513 let (hx, hy) = ((r.2 - r.0) / 2.0 - rad, (r.3 - r.1) / 2.0 - rad);
1514 let (x0, x1) = (r.0.floor().max(0.0) as usize, (r.2.ceil().max(0.0) as usize).min(w));
1515 let (y0, y1) = (r.1.floor().max(0.0) as usize, (r.3.ceil().max(0.0) as usize).min(h));
1516 for py in y0..y1 {
1517 for px in x0..x1 {
1518 let (dx, dy) = ((px as f32 + 0.5 - cx).abs() - hx, (py as f32 + 0.5 - cy).abs() - hy);
1519 let d = dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0) - rad;
1520 let a = (0.5 - d).clamp(0.0, 1.0);
1521 if a > 0.0 {
1522 put_colour(out, py * w + px, rgb, (a * 255.0).round() as u8);
1523 }
1524 }
1525 }
1526}
1527
1528/// Draws one line's glyphs into `out`, the pen starting at `x0` on `baseline`.
1529/// Returns the cell a colour glyph was painted in, when the line has one.
1530/// `clip` is the x past which nothing of the line is drawn (`f32::INFINITY` for all of it): a
1531/// title that is still typing on draws the letters before its cut and keeps the rest's room.
1532fn draw_line(out: &mut Overlay, faces: &Faces, line: &str, x0: f32, baseline: f32, clip: f32) -> Option<Rect> {
1533 let (width, height) = (out.width, out.height);
1534 let (w, h) = (width as i32, height as i32);
1535 let mut caret = x0;
1536 let mut cells: Option<Rect> = None;
1537 for p in run(faces, line) {
1538 caret += p.kern;
1539 match p.src {
1540 Src::Colour if caret >= clip => {}
1541 Src::Colour => {
1542 if let Some(cell) = draw_colour(out, faces.em, p.id, caret, baseline) {
1543 cells = grow(cells, cell);
1544 }
1545 }
1546 Src::Cjk if caret >= clip => {}
1547 Src::Cjk => {
1548 if let Some(face) = cjk_face() {
1549 let scale = faces.em / f32::from(face.units_per_em());
1550 let cell = draw_outline(out, face, p.id, scale, caret, baseline);
1551 if let Some(cell) = cell {
1552 cells = grow(cells, cell);
1553 }
1554 }
1555 }
1556 src => {
1557 if let Some(font) = faces.font(src) {
1558 let at = point(caret + p.shift, baseline - p.lift);
1559 let glyph = GlyphId(p.id).with_scale_and_position(font.scale(), at);
1560 if let Some(og) = font.outline_glyph(glyph) {
1561 let b = og.px_bounds();
1562 // A face other than Archivo can reach past its line: its ink joins the bounds.
1563 if src != Src::Outline(ARCHIVO) {
1564 let ink = (b.min.x, b.min.y, b.max.x, b.max.y);
1565 cells = grow(cells, ink);
1566 }
1567 let fill = &mut out.fill;
1568 og.draw(|gx, gy, c| {
1569 let x = b.min.x as i32 + gx as i32;
1570 let y = b.min.y as i32 + gy as i32;
1571 if x >= 0 && y >= 0 && x < w && y < h && (x as f32) < clip {
1572 let i = y as usize * width as usize + x as usize;
1573 fill[i] = fill[i].max((c * 255.0).round() as u8);
1574 }
1575 });
1576 }
1577 }
1578 }
1579 }
1580 caret += p.advance;
1581 }
1582 cells
1583}
1584
1585/// Rasterises glyph `id` of `face` at `scale` pixels a unit, its origin at `(x, baseline)`,
1586/// into `out`'s fill (the larger coverage wins). Returns the cell it covers. This is
1587/// the path for a face ab_glyph cannot set an axis of, so it reads the outline itself.
1588fn draw_outline(
1589 out: &mut Overlay,
1590 face: &ttf_parser::Face<'_>,
1591 id: u16,
1592 scale: f32,
1593 x: f32,
1594 baseline: f32,
1595) -> Option<Rect> {
1596 let bb = face.glyph_bounding_box(ttf_parser::GlyphId(id))?;
1597 let (ex0, ey0) = (
1598 x + f32::from(bb.x_min) * scale,
1599 baseline - f32::from(bb.y_max) * scale,
1600 );
1601 let (ex1, ey1) = (
1602 x + f32::from(bb.x_max) * scale,
1603 baseline - f32::from(bb.y_min) * scale,
1604 );
1605 // The cell, one pixel wider than the glyph and clipped to the frame.
1606 let (cx0, cy0) = ((ex0.floor() - 1.0).max(0.0), (ey0.floor() - 1.0).max(0.0));
1607 let (cx1, cy1) = (
1608 (ex1.ceil() + 1.0).min(out.width as f32),
1609 (ey1.ceil() + 1.0).min(out.height as f32),
1610 );
1611 if cx1 <= cx0 || cy1 <= cy0 {
1612 return None;
1613 }
1614 let (w, h) = ((cx1 - cx0) as usize, (cy1 - cy0) as usize);
1615 let mut ras = ab_glyph_rasterizer::Rasterizer::new(w, h);
1616 let mut path = CellPath {
1617 ras: &mut ras,
1618 t: IDENTITY,
1619 scale,
1620 origin: (x - cx0, baseline - cy0),
1621 last: ab_glyph_rasterizer::point(0.0, 0.0),
1622 start: ab_glyph_rasterizer::point(0.0, 0.0),
1623 };
1624 face.outline_glyph(ttf_parser::GlyphId(id), &mut path);
1625 // A CFF glyph may end on an implicitly closed contour: close it here, as ab_glyph does.
1626 ttf_parser::OutlineBuilder::close(&mut path);
1627 let stride = out.width as usize;
1628 let (ox, oy) = (cx0 as usize, cy0 as usize);
1629 let fill = &mut out.fill;
1630 ras.for_each_pixel_2d(|px, py, cov| {
1631 let i = (oy + py as usize) * stride + ox + px as usize;
1632 fill[i] = fill[i].max((cov.clamp(0.0, 1.0) * 255.0).round() as u8);
1633 });
1634 Some((cx0, cy0, cx1, cy1))
1635}
1636
1637/// The font at one size, as [`FontRef::as_scaled`] hands it out.
1638type Scaled<'a> = ab_glyph::PxScaleFont<&'a FontRef<'static>>;
1639
1640/// The width of `s` in pixels as the faces set it, kerning included.
1641fn string_width(faces: &Faces, s: &str) -> f32 {
1642 run(faces, s).iter().map(|p| p.kern + p.advance).sum()
1643}
1644
1645/// The matrix of a rotation-free affine map `[a, b, c, d, e, f]`: `x' = a*x + c*y + e`,
1646/// `y' = b*x + d*y + f`. `outer` applied after `inner`.
1647fn compose(outer: [f32; 6], inner: [f32; 6]) -> [f32; 6] {
1648 let [a1, b1, c1, d1, e1, f1] = outer;
1649 let [a2, b2, c2, d2, e2, f2] = inner;
1650 [
1651 a1 * a2 + c1 * b2,
1652 b1 * a2 + d1 * b2,
1653 a1 * c2 + c1 * d2,
1654 b1 * c2 + d1 * d2,
1655 a1 * e2 + c1 * f2 + e1,
1656 b1 * e2 + d1 * f2 + f1,
1657 ]
1658}
1659
1660const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
1661
1662/// Paints one colour glyph of the system colour font: each layer's outline is
1663/// rasterised in its paint and composited over the layers below. Clip paths and
1664/// blend modes are not applied, and a gradient is painted as the mean of its
1665/// stops, so each layer is one flat colour.
1666struct ColourPainter<'a> {
1667 face: &'a ttf_parser::Face<'a>,
1668 /// Font units to cell pixels.
1669 scale: f32,
1670 /// The glyph origin in cell pixels.
1671 origin: (f32, f32),
1672 width: usize,
1673 height: usize,
1674 /// The transform stack, the top one applied to every outline.
1675 transforms: Vec<[f32; 6]>,
1676 /// The outline the next paint fills.
1677 glyph: Option<ttf_parser::GlyphId>,
1678 /// Premultiplied RGBA per cell pixel.
1679 canvas: Vec<[f32; 4]>,
1680}
1681
1682impl ColourPainter<'_> {
1683 fn top(&self) -> [f32; 6] {
1684 self.transforms.last().copied().unwrap_or(IDENTITY)
1685 }
1686}
1687
1688/// Feeds an outline to the rasteriser in cell pixels, through a transform.
1689struct CellPath<'r> {
1690 ras: &'r mut ab_glyph_rasterizer::Rasterizer,
1691 t: [f32; 6],
1692 scale: f32,
1693 origin: (f32, f32),
1694 last: ab_glyph_rasterizer::Point,
1695 start: ab_glyph_rasterizer::Point,
1696}
1697
1698impl CellPath<'_> {
1699 fn map(&self, x: f32, y: f32) -> ab_glyph_rasterizer::Point {
1700 let [a, b, c, d, e, f] = self.t;
1701 let (tx, ty) = (a * x + c * y + e, b * x + d * y + f);
1702 ab_glyph_rasterizer::point(
1703 self.origin.0 + tx * self.scale,
1704 self.origin.1 - ty * self.scale,
1705 )
1706 }
1707}
1708
1709impl ttf_parser::OutlineBuilder for CellPath<'_> {
1710 fn move_to(&mut self, x: f32, y: f32) {
1711 let p = self.map(x, y);
1712 self.start = p;
1713 self.last = p;
1714 }
1715
1716 fn line_to(&mut self, x: f32, y: f32) {
1717 let p = self.map(x, y);
1718 self.ras.draw_line(self.last, p);
1719 self.last = p;
1720 }
1721
1722 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1723 let (c, p) = (self.map(x1, y1), self.map(x, y));
1724 self.ras.draw_quad(self.last, c, p);
1725 self.last = p;
1726 }
1727
1728 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1729 let (c1, c2, p) = (self.map(x1, y1), self.map(x2, y2), self.map(x, y));
1730 self.ras.draw_cubic(self.last, c1, c2, p);
1731 self.last = p;
1732 }
1733
1734 fn close(&mut self) {
1735 self.ras.draw_line(self.last, self.start);
1736 self.last = self.start;
1737 }
1738}
1739
1740impl<'a> ttf_parser::colr::Painter<'a> for ColourPainter<'a> {
1741 fn outline_glyph(&mut self, glyph_id: ttf_parser::GlyphId) {
1742 self.glyph = Some(glyph_id);
1743 }
1744
1745 fn paint(&mut self, paint: ttf_parser::colr::Paint<'a>) {
1746 use ttf_parser::colr::Paint;
1747 let Some(glyph) = self.glyph else {
1748 return;
1749 };
1750 let colour = match paint {
1751 Paint::Solid(c) => c,
1752 Paint::LinearGradient(g) => mean_stop(g.stops(0, &[])),
1753 Paint::RadialGradient(g) => mean_stop(g.stops(0, &[])),
1754 Paint::SweepGradient(g) => mean_stop(g.stops(0, &[])),
1755 };
1756 let (w, h) = (self.width, self.height);
1757 let mut ras = ab_glyph_rasterizer::Rasterizer::new(w, h);
1758 let mut path = CellPath {
1759 ras: &mut ras,
1760 t: self.top(),
1761 scale: self.scale,
1762 origin: self.origin,
1763 last: ab_glyph_rasterizer::point(0.0, 0.0),
1764 start: ab_glyph_rasterizer::point(0.0, 0.0),
1765 };
1766 self.face.outline_glyph(glyph, &mut path);
1767 ttf_parser::OutlineBuilder::close(&mut path);
1768 let alpha = f32::from(colour.alpha) / 255.0;
1769 let rgb = [
1770 f32::from(colour.red) / 255.0,
1771 f32::from(colour.green) / 255.0,
1772 f32::from(colour.blue) / 255.0,
1773 ];
1774 let canvas = &mut self.canvas;
1775 ras.for_each_pixel_2d(|x, y, cover| {
1776 let sa = cover.clamp(0.0, 1.0) * alpha;
1777 if sa <= 0.0 || x as usize >= w || y as usize >= h {
1778 return;
1779 }
1780 let d = &mut canvas[y as usize * w + x as usize];
1781 let keep = 1.0 - sa;
1782 *d = [
1783 rgb[0] * sa + d[0] * keep,
1784 rgb[1] * sa + d[1] * keep,
1785 rgb[2] * sa + d[2] * keep,
1786 sa + d[3] * keep,
1787 ];
1788 });
1789 }
1790
1791 fn push_clip(&mut self) {}
1792
1793 fn push_clip_box(&mut self, _clipbox: ttf_parser::colr::ClipBox) {}
1794
1795 fn pop_clip(&mut self) {}
1796
1797 fn push_layer(&mut self, _mode: ttf_parser::colr::CompositeMode) {}
1798
1799 fn pop_layer(&mut self) {}
1800
1801 fn push_transform(&mut self, t: ttf_parser::Transform) {
1802 let inner = [t.a, t.b, t.c, t.d, t.e, t.f];
1803 self.transforms.push(compose(self.top(), inner));
1804 }
1805
1806 fn pop_transform(&mut self) {
1807 self.transforms.pop();
1808 }
1809}
1810
1811/// The mean of a gradient's colour stops: the one flat colour a gradient is painted in.
1812fn mean_stop(stops: impl Iterator<Item = ttf_parser::colr::ColorStop>) -> ttf_parser::RgbaColor {
1813 let (mut n, mut r, mut g, mut b, mut a) = (0u32, 0u32, 0u32, 0u32, 0u32);
1814 for s in stops {
1815 n += 1;
1816 r += u32::from(s.color.red);
1817 g += u32::from(s.color.green);
1818 b += u32::from(s.color.blue);
1819 a += u32::from(s.color.alpha);
1820 }
1821 let mean = |v: u32| (v / n.max(1)) as u8;
1822 ttf_parser::RgbaColor {
1823 red: mean(r),
1824 green: mean(g),
1825 blue: mean(b),
1826 alpha: mean(a),
1827 }
1828}
1829
1830/// The scale that sets a face's units at `em`, the way ab_glyph sets its outlines:
1831/// the em over the face's height (ascender less descender), not its units per em.
1832fn em_scale(em: f32, face: &ttf_parser::Face<'_>) -> f32 {
1833 em / (f32::from(face.ascender()) - f32::from(face.descender()))
1834}
1835
1836/// Paints the system colour glyph `id` with its origin at `pen_x` on `baseline`
1837/// into `out`'s colour plane. Returns the cell painted, or None when there is no
1838/// colour font, the glyph has no colour layers, or nothing landed on the frame.
1839fn draw_colour(out: &mut Overlay, em: f32, id: u16, pen_x: f32, baseline: f32) -> Option<Rect> {
1840 let face = colour_face()?;
1841 let scale = em_scale(em, face);
1842 // The cell: the em, with room for the overhang an emoji draws past it.
1843 let (x0, y0) = ((pen_x - 0.25 * em).floor(), (baseline - 1.5 * em).floor());
1844 let (x1, y1) = ((pen_x + 1.75 * em).ceil(), (baseline + 0.5 * em).ceil());
1845 let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
1846 let mut painter = ColourPainter {
1847 face,
1848 scale,
1849 origin: (pen_x - x0, baseline - y0),
1850 width: w,
1851 height: h,
1852 transforms: Vec::new(),
1853 glyph: None,
1854 canvas: vec![[0.0; 4]; w * h],
1855 };
1856 let black = ttf_parser::RgbaColor {
1857 red: 0,
1858 green: 0,
1859 blue: 0,
1860 alpha: 255,
1861 };
1862 face.paint_color_glyph(ttf_parser::GlyphId(id), 0, black, &mut painter)?;
1863 let (ow, oh) = (out.width as i64, out.height as i64);
1864 let mut hit = false;
1865 for cy in 0..h {
1866 for cx in 0..w {
1867 let [r, g, b, a] = painter.canvas[cy * w + cx];
1868 let (x, y) = (x0 as i64 + cx as i64, y0 as i64 + cy as i64);
1869 if a <= 0.0 || x < 0 || y < 0 || x >= ow || y >= oh {
1870 continue;
1871 }
1872 if out.colour.is_empty() {
1873 out.colour = vec![[0; 4]; out.width as usize * out.height as usize];
1874 }
1875 let to_u8 = |v: f32| (v * 255.0).round().clamp(0.0, 255.0) as u8;
1876 let straight = [r / a, g / a, b / a].map(|v| to_u8(v.min(1.0)));
1877 let alpha = to_u8(a);
1878 if alpha == 0 {
1879 continue;
1880 }
1881 out.colour[y as usize * out.width as usize + x as usize] =
1882 [straight[0], straight[1], straight[2], alpha];
1883 hit = true;
1884 }
1885 }
1886 hit.then_some((x0, y0, x1, y1))
1887}
1888
1889/// Word wrap. A paragraph that fits the frame stays one line, so a cue's own
1890/// line breaks are kept. A paragraph that does not fit breaks into the fewest
1891/// lines it can, balanced by [`balanced`], so no line is left an orphan word.
1892/// A blank paragraph is an empty line, which keeps a deliberate gap in a title
1893/// card.
1894fn wrap(faces: &Faces, lines: &[String], max_w: f32) -> Vec<String> {
1895 let mut out = Vec::new();
1896 for para in lines {
1897 let words: Vec<&str> = para.split_whitespace().collect();
1898 if words.is_empty() {
1899 out.push(String::new());
1900 continue;
1901 }
1902 let whole = words.join(" ");
1903 if string_width(faces, &whole) <= max_w {
1904 out.push(whole);
1905 } else if words.iter().any(|w| string_width(faces, w) > max_w) {
1906 // A word wider than the frame has no balanced break: cut it greedily.
1907 out.extend(greedy(faces, &words, max_w));
1908 } else {
1909 let n = greedy(faces, &words, max_w).len();
1910 out.extend(balanced(faces, &words, n, max_w));
1911 }
1912 }
1913 out
1914}
1915
1916/// Greedy word wrap: breaks at the spaces where a line would overflow `max_w`,
1917/// and a single word wider than the frame breaks by character.
1918fn greedy(faces: &Faces, words: &[&str], max_w: f32) -> Vec<String> {
1919 let mut out = Vec::new();
1920 let mut line = String::new();
1921 for word in words {
1922 let candidate = match line.is_empty() {
1923 true => word.to_string(),
1924 false => format!("{line} {word}"),
1925 };
1926 if string_width(faces, &candidate) <= max_w {
1927 line = candidate;
1928 continue;
1929 }
1930 if !line.is_empty() {
1931 out.push(std::mem::take(&mut line));
1932 }
1933 // The word alone may still be wider than the frame: cut it.
1934 let mut piece = String::new();
1935 for ch in word.chars() {
1936 piece.push(ch);
1937 if string_width(faces, &piece) > max_w && piece.chars().count() > 1 {
1938 piece.pop();
1939 out.push(std::mem::take(&mut piece));
1940 piece.push(ch);
1941 }
1942 }
1943 line = piece;
1944 }
1945 if !line.is_empty() {
1946 out.push(line);
1947 }
1948 out
1949}
1950
1951/// Breaks `words` into exactly `n` lines that each fit `max_w`, choosing the
1952/// split that minimises the sum of squared line widths, so the lines come out
1953/// even. `n` must be the fewest lines that fit (what [`greedy`] returns); no
1954/// word may be wider than `max_w`. Falls back to [`greedy`] if no split fits.
1955fn balanced(faces: &Faces, words: &[&str], n: usize, max_w: f32) -> Vec<String> {
1956 let m = words.len();
1957 let width = |i: usize, j: usize| string_width(faces, &words[i..j].join(" "));
1958 // best[k][j]: least cost of covering the first `j` words with `k` lines.
1959 let mut best = vec![vec![f32::INFINITY; m + 1]; n + 1];
1960 let mut from = vec![vec![0usize; m + 1]; n + 1];
1961 best[0][0] = 0.0;
1962 for k in 1..=n {
1963 for j in 1..=m {
1964 for i in 0..j {
1965 if !best[k - 1][i].is_finite() {
1966 continue;
1967 }
1968 let w = width(i, j);
1969 if w > max_w {
1970 continue;
1971 }
1972 let cost = best[k - 1][i] + w * w;
1973 if cost < best[k][j] {
1974 best[k][j] = cost;
1975 from[k][j] = i;
1976 }
1977 }
1978 }
1979 }
1980 if !best[n][m].is_finite() {
1981 return greedy(faces, words, max_w);
1982 }
1983 let mut out = Vec::with_capacity(n);
1984 let (mut j, mut k) = (m, n);
1985 while k > 0 {
1986 let i = from[k][j];
1987 out.push(words[i..j].join(" "));
1988 j = i;
1989 k -= 1;
1990 }
1991 out.reverse();
1992 out
1993}
1994
1995/// The coverage grown by `r` pixels in every direction: a square max filter,
1996/// separable, so two passes of a 1-D window. Clamped at the frame's edges.
1997fn dilate(src: &[u8], w: u32, h: u32, r: u32) -> Vec<u8> {
1998 let (w, h, r) = (w as usize, h as usize, r as usize);
1999 let mut tmp = vec![0u8; w * h];
2000 for y in 0..h {
2001 let row = &src[y * w..(y + 1) * w];
2002 for x in 0..w {
2003 let lo = x.saturating_sub(r);
2004 let hi = (x + r).min(w - 1);
2005 tmp[y * w + x] = row[lo..=hi].iter().copied().max().unwrap_or(0);
2006 }
2007 }
2008 let mut out = vec![0u8; w * h];
2009 for y in 0..h {
2010 let lo = y.saturating_sub(r);
2011 let hi = (y + r).min(h - 1);
2012 for x in 0..w {
2013 out[y * w + x] = (lo..=hi).map(|yy| tmp[yy * w + x]).max().unwrap_or(0);
2014 }
2015 }
2016 out
2017}
2018
2019#[cfg(test)]
2020mod tests {
2021 use super::*;
2022
2023 const W: u32 = 640;
2024 const H: u32 = 360;
2025
2026 fn lines(s: &str) -> Vec<String> {
2027 vec![s.to_string()]
2028 }
2029
2030 /// The faces at the size a 1080p frame's caption is set at.
2031 fn caption_faces() -> Faces {
2032 Faces::new(60.0 / 1000.0 * 1920.0).unwrap()
2033 }
2034
2035 /// The rows of `o`'s glyph coverage that hold any ink, top to bottom.
2036 fn ink_rows(o: &Overlay) -> Vec<u32> {
2037 let w = o.width as usize;
2038 (0..o.height as usize)
2039 .filter(|&y| o.fill[y * w..(y + 1) * w].iter().any(|&c| c > 0))
2040 .map(|y| y as u32)
2041 .collect()
2042 }
2043
2044 #[test]
2045 fn draws_non_zero_pixels_over_a_black_canvas() {
2046 let mut canvas = vec![0u8; (W * H * 4) as usize];
2047 let style = TextStyle {
2048 boxed: false,
2049 ..TextStyle::default()
2050 };
2051 draw_text(&mut canvas, W, H, &style, &lines("Hello"));
2052 assert!(canvas.iter().any(|&b| b != 0), "no text was drawn");
2053 // Every lit pixel is white or a blend toward it: the colour channels
2054 // move together over black, so B, G and R agree.
2055 let lit = canvas
2056 .as_chunks::<4>()
2057 .0
2058 .iter()
2059 .filter(|p| p[0] > 0)
2060 .count();
2061 assert!(lit > 100, "only {lit} lit pixels for five letters");
2062 }
2063
2064 /// The x range `[min, max]` of `o`'s glyph coverage.
2065 fn ink_cols(o: &Overlay) -> (usize, usize) {
2066 let w = o.width as usize;
2067 let cols: Vec<usize> = (0..w)
2068 .filter(|&x| (0..o.height as usize).any(|y| o.fill[y * w + x] > 0))
2069 .collect();
2070 (cols[0], *cols.last().unwrap())
2071 }
2072
2073 #[test]
2074 fn a_title_colour_tints_the_glyphs_in_bgra_and_in_chroma() {
2075 let style = TextStyle { ink: [255, 0, 0], boxed: false, ..TextStyle::default() };
2076 let o = overlay(&style, W, H, &lines("MMMM"));
2077 let mut canvas = vec![0u8; (W * H * 4) as usize];
2078 o.blend_bgra(&mut canvas);
2079 let i = o.fill.iter().position(|&c| c == 255).expect("a solid glyph pixel");
2080 assert_eq!(&canvas[i * 4..i * 4 + 3], &[0, 0, 255], "blue, green, red");
2081 // Planar: red pulls Cr far above 128 and Cb below it.
2082 let (mut y, mut u, mut v) = (vec![16u8; (W * H) as usize], vec![128u8; (W * H / 4) as usize], vec![128u8; (W * H / 4) as usize]);
2083 o.blend_i420(&mut y, &mut u, &mut v, false);
2084 assert!(v.iter().any(|&c| c > 200), "red text raises Cr");
2085 assert!(u.iter().all(|&c| c <= 128), "red text lowers Cb");
2086 // The default is white: chroma stays grey.
2087 let white = overlay(&TextStyle { boxed: false, ..TextStyle::default() }, W, H, &lines("MMMM"));
2088 let (mut y, mut u, mut v) = (vec![16u8; (W * H) as usize], vec![128u8; (W * H / 4) as usize], vec![128u8; (W * H / 4) as usize]);
2089 white.blend_i420(&mut y, &mut u, &mut v, false);
2090 assert!(u.iter().chain(&v).all(|&c| c == 128));
2091 }
2092
2093 #[test]
2094 fn a_box_colour_and_opacity_paint_the_plate() {
2095 let style = TextStyle { box_color: [0, 0, 255, 255], ..TextStyle::default() };
2096 let o = overlay(&style, W, H, &lines("Hi"));
2097 let mut canvas = vec![0u8; (W * H * 4) as usize];
2098 o.blend_bgra(&mut canvas);
2099 let i = o.plate.iter().position(|&a| a == 255).expect("an opaque plate pixel");
2100 assert!(o.fill[i] == 0, "a plate pixel clear of ink");
2101 assert_eq!(&canvas[i * 4..i * 4 + 3], &[255, 0, 0], "a blue box is blue in BGRA");
2102 let faint = overlay(&TextStyle { box_color: [0, 0, 0, 40], ..TextStyle::default() }, W, H, &lines("Hi"));
2103 assert_eq!(faint.plate.iter().copied().max(), Some(40));
2104 }
2105
2106 #[test]
2107 fn bold_is_wider_and_the_block_goes_to_the_side_asked() {
2108 let regular = overlay(&TextStyle { boxed: false, ..TextStyle::default() }, W, H, &lines("Heading"));
2109 let bold = overlay(&TextStyle { boxed: false, weight: Weight::Bold, ..TextStyle::default() }, W, H, &lines("Heading"));
2110 let sum = |o: &Overlay| o.fill.iter().map(|&c| u64::from(c)).sum::<u64>();
2111 assert!(sum(&bold) > sum(&regular), "bold has more ink");
2112 let at = |hplace| ink_cols(&overlay(&TextStyle { hplace, boxed: false, ..TextStyle::default() }, W, H, &lines("Heading")));
2113 let (l, c, r) = (at(HPlace::Left), at(HPlace::Centre), at(HPlace::Right));
2114 assert!(l.0 < c.0 && c.0 < r.0, "{l:?} {c:?} {r:?}");
2115 assert!(l.0 as f32 <= MARGIN * H as f32 + 8.0, "left sits on the margin");
2116 assert!((W as f32 - r.1 as f32) <= MARGIN * H as f32 + 8.0, "right sits on the margin");
2117 }
2118
2119 #[test]
2120 fn lines_align_inside_the_block() {
2121 let two = vec!["a much longer line".to_string(), "short".to_string()];
2122 let short_left = |align| {
2123 let o = overlay(&TextStyle { align, hplace: HPlace::Left, boxed: false, ..TextStyle::default() }, W, H, &two[1..]);
2124 ink_cols(&o).0
2125 };
2126 // `short` alone is its own block, so alignment cannot move it; with the long line it can.
2127 assert_eq!(short_left(Align::Left), short_left(Align::Right));
2128 let both = |align| {
2129 // The bottom line of the two-line block is the second one (stack bottom-up is per block, lines go down).
2130 let o = overlay(&TextStyle { align, hplace: HPlace::Left, boxed: false, ..TextStyle::default() }, W, H, &two);
2131 let rows = ink_rows(&o);
2132 let bottom = *rows.last().unwrap() as usize;
2133 let w = W as usize;
2134 (0..w).find(|&x| o.fill[(bottom - 3) * w + x] > 0 || o.fill[(bottom - 6) * w + x] > 0).unwrap()
2135 };
2136 assert!(both(Align::Left) < both(Align::Centre) && both(Align::Centre) < both(Align::Right));
2137 }
2138
2139 #[test]
2140 fn a_default_look_blends_as_it_always_did() {
2141 // White, regular, centred, on the 60% black box: the exact planes of the old rasteriser.
2142 let o = overlay(&TextStyle::default(), W, H, &lines("Hello"));
2143 assert_eq!(o.ink, [255; 3]);
2144 assert_eq!(o.plate_rgb, [0; 3]);
2145 assert_eq!(o.plate.iter().copied().max(), Some(BOX_ALPHA));
2146 }
2147
2148 #[test]
2149 fn a_blank_string_or_an_empty_frame_draws_nothing() {
2150 let mut canvas = vec![7u8; (W * H * 4) as usize];
2151 draw_text(&mut canvas, W, H, &TextStyle::default(), &lines(" "));
2152 assert!(canvas.iter().all(|&b| b == 7));
2153 assert!(overlay(&TextStyle::default(), 0, 0, &lines("x")).is_blank());
2154 }
2155
2156 #[test]
2157 fn a_long_line_wraps_into_at_least_two_lines() {
2158 // The em of a 640x360 frame at the default size, against a 320px width.
2159 let faces = Faces::new(DEFAULT_SIZE as f32 / 1000.0 * 360.0).unwrap();
2160 let long =
2161 "a considerably longer caption that cannot possibly fit on one line of a small frame";
2162 let wrapped = wrap(&faces, &[long.to_string()], 320.0);
2163 assert!(wrapped.len() >= 2, "wrapped to {wrapped:?}");
2164 assert!(
2165 wrapped
2166 .iter()
2167 .all(|l| string_width(&faces, l) <= 320.0 + 0.5)
2168 );
2169 // And the words survive the break, in order.
2170 assert_eq!(wrapped.join(" "), long);
2171 }
2172
2173 /// The caption layout the burn uses: a 1080x1920 frame at size 60, where
2174 /// the text width is the frame less its margins.
2175 fn caption_wrap(lines: &[&str]) -> Vec<String> {
2176 let faces = caption_faces();
2177 let max_w = 1080.0 - 2.0 * MARGIN * 1920.0;
2178 let owned: Vec<String> = lines.iter().map(|s| s.to_string()).collect();
2179 wrap(&faces, &owned, max_w)
2180 }
2181
2182 #[test]
2183 fn a_cue_line_that_fits_keeps_its_own_break() {
2184 assert_eq!(
2185 caption_wrap(&["Forty years ago", "this coast"]),
2186 ["Forty years ago", "this coast"]
2187 );
2188 }
2189
2190 #[test]
2191 fn a_cue_line_too_wide_breaks_balanced_with_no_orphan_word() {
2192 let out = caption_wrap(&["Forty years ago, this", "coast was empty sand"]);
2193 // Both cue lines are too wide, so each splits in two, evenly, and no
2194 // line is left holding a single word.
2195 assert_eq!(
2196 out,
2197 ["Forty years", "ago, this", "coast was", "empty sand"],
2198 "wrapped to {out:?}"
2199 );
2200 }
2201
2202 #[test]
2203 fn balanced_splits_evenly_and_never_past_the_width() {
2204 let faces = caption_faces();
2205 let words = ["aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff"];
2206 let max_w = string_width(&faces, "aaaa bbbb cccc dddd") + 1.0;
2207 let out = balanced(&faces, &words, 2, max_w);
2208 assert_eq!(out, ["aaaa bbbb cccc", "dddd eeee ffff"]);
2209 assert!(out.iter().all(|l| string_width(&faces, l) <= max_w));
2210 }
2211
2212 #[test]
2213 fn an_outline_puts_dark_pixels_around_white_glyphs() {
2214 // A mid-grey canvas, so the outline has something to darken and the
2215 // fill something to brighten.
2216 let style = TextStyle {
2217 outline: Outline::Thick,
2218 boxed: false,
2219 ..TextStyle::default()
2220 };
2221 let o = overlay(&style, W, H, &lines("Ill"));
2222 let fill = o.fill();
2223 let stroke = o.stroke();
2224 let ring = fill
2225 .iter()
2226 .zip(stroke)
2227 .filter(|(f, s)| **f == 0 && **s > 0)
2228 .count();
2229 assert!(ring > 50, "only {ring} outline pixels around the glyphs");
2230 let mut canvas = vec![128u8; (W * H * 4) as usize];
2231 o.blend_bgra(&mut canvas);
2232 let dark = fill
2233 .iter()
2234 .zip(stroke)
2235 .enumerate()
2236 .filter(|(_, (f, s))| **f == 0 && **s > 0)
2237 .filter(|(i, _)| canvas[i * 4] < 128)
2238 .count();
2239 assert_eq!(dark, ring, "every outline pixel must darken the grey");
2240 }
2241
2242 #[test]
2243 fn the_i420_overlay_moves_luma_to_white_and_chroma_to_grey() {
2244 let style = TextStyle {
2245 boxed: false,
2246 ..TextStyle::default()
2247 };
2248 let o = overlay(&style, W, H, &lines("Hi"));
2249 let (cw, ch) = ((W / 2) as usize, (H / 2) as usize);
2250 let mut y = vec![40u8; (W * H) as usize];
2251 let mut u = vec![200u8; cw * ch];
2252 let mut v = vec![60u8; cw * ch];
2253 o.blend_i420(&mut y, &mut u, &mut v, false);
2254 let whitest = y.iter().copied().max().unwrap();
2255 assert_eq!(whitest, 235, "limited-range white is 235");
2256 assert!(
2257 u.iter().any(|&s| s != 200),
2258 "chroma under text must move to 128"
2259 );
2260 assert!(y.contains(&40), "pixels off the text must be untouched");
2261 }
2262
2263 #[test]
2264 fn an_emoji_is_drawn_from_a_face_not_as_a_box() {
2265 // Archivo has no pictograph, so each of these goes to another source.
2266 for emoji in ["\u{1F3AC}", "\u{1F30D}", "\u{1F1F9}", "\u{1F1F7}"] {
2267 let (src, id) = pick(emoji.chars().next().unwrap());
2268 assert_ne!(src, Src::Outline(ARCHIVO), "{emoji} came from Archivo");
2269 assert_ne!(id, 0, "{emoji} has no glyph");
2270 }
2271 // A letter stays on Archivo.
2272 assert_eq!(pick('a').0, Src::Outline(ARCHIVO));
2273 // The emoji leaves ink on the frame, where a box would too: the test
2274 // is that it is not the empty glyph, so compare against a rare codepoint
2275 // that no face has. Ink is any pixel the canvas took.
2276 let ink = |s: &str| {
2277 let o = overlay(
2278 &TextStyle {
2279 boxed: false,
2280 ..TextStyle::default()
2281 },
2282 W,
2283 H,
2284 &lines(s),
2285 );
2286 let mut canvas = vec![0u8; (W * H * 4) as usize];
2287 o.blend_bgra(&mut canvas);
2288 canvas
2289 .as_chunks::<4>()
2290 .0
2291 .iter()
2292 .filter(|p| p[0] | p[1] | p[2] > 0)
2293 .count()
2294 };
2295 let emoji_ink = ink("\u{1F3AC}");
2296 assert!(
2297 emoji_ink > 30,
2298 "only {emoji_ink} ink pixels for the clapper"
2299 );
2300 assert_ne!(emoji_ink, ink("\u{10FFFD}"), "emoji drew the empty box");
2301 }
2302
2303 #[test]
2304 fn a_zero_width_joiner_or_selector_draws_nothing_and_is_not_missing() {
2305 // The woman-astronaut sequence and a heart with its selector: each
2306 // character is a glyph or invisible, and only the glyphs count.
2307 assert!(missing_glyphs(&lines("\u{1F469}\u{200D}\u{1F680}")).is_empty());
2308 assert!(missing_glyphs(&lines("\u{2764}\u{FE0F}")).is_empty());
2309 assert_eq!(string_width(&caption_faces(), "\u{FE0F}"), 0.0);
2310 }
2311
2312 #[test]
2313 fn a_long_title_reports_its_wrapped_lines_and_its_share_of_the_frame() {
2314 let style = TextStyle::default();
2315 let (n, share) = layout_share(&style, 1280, 720, &lines("Hello"));
2316 assert_eq!(n, 1);
2317 assert!(share < 0.1, "{share}");
2318 assert_eq!(layout_share(&style, 1280, 720, &lines(" ")), (0, 0.0));
2319 let (n, share) = layout_share(&style, 1280, 720, &lines(&"word ".repeat(100)));
2320 assert!(n > 6 && share > 0.4, "{n} lines, share {share}");
2321 }
2322
2323 #[test]
2324 fn cyrillic_arabic_and_the_other_scripts_have_faces_and_name_no_missing_glyphs() {
2325 assert!(missing_glyphs(&lines("Привет мир · مرحبا · שלום · नमस्ते · สวัสดี")).is_empty());
2326 assert_eq!(
2327 pick('П'),
2328 (
2329 Src::Outline(NOTO_SANS),
2330 outline_face(NOTO_SANS).unwrap().glyph_id('П').0
2331 )
2332 );
2333 assert_eq!(pick('م').0, Src::Outline(2), "Arabic is on its own face");
2334 assert_eq!(pick('ש').0, Src::Outline(3), "Hebrew is on its own face");
2335 assert_eq!(
2336 pick('न').0,
2337 Src::Outline(4),
2338 "Devanagari is on its own face"
2339 );
2340 assert_eq!(pick('ส').0, Src::Outline(5), "Thai is on its own face");
2341 assert!(missing_glyphs(&lines("Plain Latin, 1080p! 50%")).is_empty());
2342 }
2343
2344 #[test]
2345 fn every_script_face_has_archivos_x_height_and_archivo_is_unscaled() {
2346 // Archivo is the reference: its factor is exactly 1, so Latin is untouched.
2347 let k = face_k();
2348 assert_eq!(k[ARCHIVO], 1.0);
2349 let x_px = |i: usize| {
2350 let face = ttf_parser::Face::parse(OUTLINE_BYTES[i], 0).unwrap();
2351 let x = f32::from(face.x_height().unwrap());
2352 x * k[i] / outline_face(i).unwrap().height_unscaled()
2353 };
2354 let text = x_px(ARCHIVO);
2355 for i in [NOTO_SANS, 2, 3, 4, 5] {
2356 assert!(
2357 (x_px(i) - text).abs() < 1e-4,
2358 "face {i}: {} vs {text}",
2359 x_px(i)
2360 );
2361 }
2362 }
2363
2364 #[test]
2365 fn cyrillic_text_is_drawn_in_ink_not_boxes() {
2366 let style = TextStyle {
2367 boxed: false,
2368 ..TextStyle::default()
2369 };
2370 let ink = |s: &str| {
2371 let o = overlay(&style, W, H, &lines(s));
2372 o.fill().iter().filter(|&&c| c > 0).count()
2373 };
2374 // The empty box is the only thing a missing glyph would draw: a Cyrillic
2375 // letter draws ink of its own, not that box.
2376 let box_ink = ink("\u{10FFFD}");
2377 let letter = ink("\u{41F}");
2378 assert!(
2379 letter > 30,
2380 "only {letter} ink pixels for a Cyrillic capital"
2381 );
2382 assert_ne!(letter, box_ink, "the Cyrillic letter drew the empty box");
2383 }
2384
2385 #[test]
2386 fn arabic_letters_join_so_a_medial_letter_is_not_its_isolated_form() {
2387 // The base letter of each word is the glyph with an advance; the dot marks
2388 // beside it have none. Alone the letter takes its isolated form, but set
2389 // twice in a row the first takes the joining form and the last the final.
2390 let faces = caption_faces();
2391 let bases = |s: &str| -> Vec<u16> {
2392 run(&faces, s)
2393 .iter()
2394 .filter(|p| p.advance > 0.0)
2395 .map(|p| p.id)
2396 .collect()
2397 };
2398 let alone = bases("\u{628}");
2399 let joined = bases("\u{628}\u{628}");
2400 assert_eq!(alone.len(), 1);
2401 assert_eq!(joined.len(), 2, "joined letters stay two letters");
2402 assert_ne!(
2403 joined[0], alone[0],
2404 "joining did not change the first letter"
2405 );
2406 assert_ne!(
2407 joined[1], alone[0],
2408 "the final letter is not in its isolated form"
2409 );
2410 }
2411
2412 #[test]
2413 fn hebrew_is_drawn_right_to_left() {
2414 let faces = caption_faces();
2415 // "alef bet": in logical order alef comes first, so on the page bet is left.
2416 assert_eq!(
2417 visual_parts("\u{5D0}\u{5D1}"),
2418 vec![(true, "\u{5D0}\u{5D1}")]
2419 );
2420 let placed = run(&faces, "\u{5D0}\u{5D1}");
2421 let bet = outline_face(3).unwrap().glyph_id('\u{5D1}').0;
2422 let alef = outline_face(3).unwrap().glyph_id('\u{5D0}').0;
2423 assert_eq!(placed.len(), 2);
2424 assert_eq!(placed[0].id, bet, "bet should be drawn first, on the left");
2425 assert_eq!(
2426 placed[1].id, alef,
2427 "alef should follow, to the right of bet"
2428 );
2429 }
2430
2431 #[test]
2432 fn devanagari_matra_is_reordered_before_its_consonant() {
2433 let faces = caption_faces();
2434 // KA with the vowel sign I: the sign is shaped into its pre-base form and
2435 // written before KA, so the first glyph on the page is not KA.
2436 let placed = run(&faces, "\u{915}\u{93F}");
2437 let ka = outline_face(4).unwrap().glyph_id('\u{915}').0;
2438 assert_eq!(placed.len(), 2, "{placed:?}");
2439 assert_eq!(placed[1].id, ka, "KA should come second on the page");
2440 assert_ne!(
2441 placed[0].id, ka,
2442 "the vowel sign is not reordered before KA"
2443 );
2444 }
2445
2446 #[test]
2447 fn a_cjk_character_is_drawn_from_the_system_font_when_there_is_one() {
2448 let Some(_) = cjk_face() else {
2449 return; // no system CJK font here: the box is the right answer
2450 };
2451 assert_eq!(pick('你').0, Src::Cjk);
2452 let style = TextStyle {
2453 boxed: false,
2454 ..TextStyle::default()
2455 };
2456 let o = overlay(&style, W, H, &lines("你好"));
2457 assert!(
2458 o.fill().iter().filter(|&&c| c > 0).count() > 100,
2459 "CJK drew nothing"
2460 );
2461 }
2462
2463 #[test]
2464 fn a_colour_emoji_paints_colour_pixels_when_there_is_a_system_colour_font() {
2465 let Some(_) = colour_face() else {
2466 return; // no colour font here: the monochrome outline is the answer
2467 };
2468 assert_eq!(pick('\u{1F389}').0, Src::Colour);
2469 let style = TextStyle {
2470 boxed: false,
2471 ..TextStyle::default()
2472 };
2473 let o = overlay(&style, W, H, &lines("\u{1F389}"));
2474 let mut canvas = vec![0u8; (W * H * 4) as usize];
2475 o.blend_bgra(&mut canvas);
2476 let coloured = canvas
2477 .as_chunks::<4>()
2478 .0
2479 .iter()
2480 .filter(|p| p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2]) > 40)
2481 .count();
2482 assert!(
2483 coloured > 30,
2484 "only {coloured} coloured pixels for the party popper"
2485 );
2486 }
2487
2488 #[test]
2489 fn a_mixed_script_title_draws_and_keeps_its_glyphs() {
2490 let style = TextStyle {
2491 outline: Outline::Thin,
2492 ..TextStyle::default()
2493 };
2494 // The bundled faces cover every script but CJK, and the colour emoji
2495 // falls back to the bundled monochrome one, so only the CJK part needs
2496 // a system face; without it the CJK characters are the missing glyphs.
2497 let bundled = lines("Привет мир · مرحبا · \u{1F389}");
2498 assert!(missing_glyphs(&bundled).is_empty());
2499 let text = lines("Привет мир · مرحبا · 你好 · \u{1F389}");
2500 if cjk_face().is_some() {
2501 assert!(missing_glyphs(&text).is_empty());
2502 } else {
2503 assert_eq!(missing_glyphs(&text), vec!['你', '好']);
2504 }
2505 let (n, share) = layout_share(&style, W, H, &text);
2506 assert_eq!(n, 1, "the title should fit one line");
2507 assert!(share > 0.0);
2508 let o = overlay(&style, W, H, &text);
2509 assert!(o.fill().iter().any(|&c| c > 0));
2510 }
2511
2512 #[test]
2513 fn missing_glyphs_names_only_what_no_face_draws_once_in_order() {
2514 let text = vec![
2515 "Emoji test \u{1F3AC} ok".to_string(),
2516 "\u{10FFFD} and \u{10FFFD} again \u{10FFFC}".to_string(),
2517 ];
2518 assert_eq!(missing_glyphs(&text), vec!['\u{10FFFD}', '\u{10FFFC}']);
2519 assert!(missing_glyphs(&lines("plain ascii, 1080p")).is_empty());
2520 }
2521
2522 #[test]
2523 fn overlapping_cues_stack_upward_from_the_bottom_without_covering_each_other() {
2524 let style = TextStyle {
2525 boxed: false,
2526 ..TextStyle::default()
2527 };
2528 let first = overlay(&style, W, H, &lines("First cue"));
2529 let second = overlay(&style, W, H, &lines("Second cue"));
2530 let both = overlay_stack(&style, W, H, &[lines("First cue"), lines("Second cue")]);
2531 // The first cue keeps its place on the bottom edge, exactly as alone.
2532 let first_rows = ink_rows(&first);
2533 let both_rows = ink_rows(&both);
2534 assert_eq!(first_rows.last(), both_rows.last(), "first cue moved");
2535 // The second cue sits wholly above the first: the stack reaches higher
2536 // than the first cue alone by at least its own line height.
2537 let (top_alone, top_both) = (first_rows[0], both_rows[0]);
2538 assert!(
2539 top_both + 20 < top_alone,
2540 "second cue not stacked above: {top_both} vs {top_alone}"
2541 );
2542 // Each cue's ink is the same as when drawn alone (the same glyphs), so
2543 // the stack adds the two ink counts without any pixel shared.
2544 let ink = |o: &Overlay| o.fill().iter().filter(|&&c| c > 0).count();
2545 let (a, b, s) = (ink(&first), ink(&second), ink(&both));
2546 assert!(
2547 (s as i64 - (a + b) as i64).abs() <= ((a + b) / 50) as i64,
2548 "stack ink {s} is not the sum of its cues {a} + {b}"
2549 );
2550 // The gap between the two cues keeps their boxes apart too.
2551 let gap_rows = both_rows.windows(2).filter(|w| w[1] - w[0] > 1).count();
2552 assert!(gap_rows >= 1, "the two cues run into one another");
2553 }
2554
2555 #[test]
2556 fn a_stacked_cue_with_no_words_takes_no_room() {
2557 let style = TextStyle::default();
2558 let alone = overlay(&style, W, H, &lines("Hello"));
2559 let with_blank = overlay_stack(&style, W, H, &[lines(" "), lines("Hello")]);
2560 assert_eq!(alone.fill(), with_blank.fill());
2561 }
2562
2563 const LATIN_BGRA_HASH: u64 = 17148267790522720847;
2564 const LATIN_I420_HASHES: [u64; 3] = [
2565 3766897427118592358,
2566 14679306852776097573,
2567 14679306852776097573,
2568 ];
2569
2570 /// FNV-1a, 64 bits: a hash that does not change with the Rust release.
2571 fn fnv1a(bytes: &[u8]) -> u64 {
2572 bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
2573 (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
2574 })
2575 }
2576
2577 #[test]
2578 fn latin_text_renders_exactly_as_the_archivo_only_rasteriser_did() {
2579 // Pinned before the script faces, the shaper and the colour glyphs came in:
2580 // a Latin title must not move a pixel. The text is set in the default
2581 // size with outline, box and a second line of punctuation.
2582 let style = TextStyle {
2583 outline: Outline::Thick,
2584 boxed: true,
2585 ..TextStyle::default()
2586 };
2587 let text = lines("Hello, world! 1080p 50% “quotes” — dashes…\nSecond line: fi ffl AV");
2588 let o = overlay(&style, W, H, &text);
2589 let mut canvas = vec![90u8; (W * H * 4) as usize];
2590 o.blend_bgra(&mut canvas);
2591 assert_eq!(fnv1a(&canvas), LATIN_BGRA_HASH, "bgra hash moved");
2592 let (cw, ch) = ((W / 2) as usize, (H / 2) as usize);
2593 let (mut y, mut u, mut v) = (
2594 vec![60u8; (W * H) as usize],
2595 vec![128u8; cw * ch],
2596 vec![128u8; cw * ch],
2597 );
2598 o.blend_i420(&mut y, &mut u, &mut v, false);
2599 let planes = [fnv1a(&y), fnv1a(&u), fnv1a(&v)];
2600 assert_eq!(planes, LATIN_I420_HASHES, "i420 hashes moved");
2601 }
2602}