forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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