forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6a8d990Tahinli16 days ago1049 commits

assrender.rs1077 lines, 34.6 KiBHistoryRawDownload
1//! Advanced SubStation Alpha drawn as libass draws it: each event in its style's
2//! face, scaled from `PlayRes` to the frame, with its outline, shadow, blur and
3//! fade, composed onto the picture. An event's coverage is rasterised once and
4//! kept while the frame size holds, so a fade is a blend, not a rasterisation.
5
6use std::collections::HashMap;
7use std::path::Path;
8
9use ab_glyph::{Font, FontRef, GlyphId, OutlineCurve, point};
10use ab_glyph_rasterizer::Rasterizer;
11use ec_subs::{Segment, SubtitleStyle};
12
13use crate::colorspace::is_sd;
14use crate::text::{self, mix, yuv};
15
16const ITALIC_SHEAR: f32 = 0.2;
17const DEFAULT_EVENT_FORMAT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text";
18
19/// One event on screen: its index in the script and its span on the timeline, in microseconds.
20#[derive(Clone, Copy, Debug)]
21pub struct Shown {
22 /// The event's index in the script, in file order.
23 pub event: usize,
24 /// When the event starts on the timeline.
25 pub start_us: i64,
26 /// When the event ends on the timeline.
27 pub end_us: i64,
28}
29
30/// An ASS script ready to draw: its PlayRes, styles and events, and the coverage of the events drawn.
31pub struct Captions {
32 play: (f32, f32),
33 scaled: bool,
34 storage_h: f32,
35 wrap: u8,
36 styles: Vec<Style>,
37 events: Vec<Event>,
38 cache: HashMap<usize, Drawn>,
39}
40
41impl Captions {
42 /// The script a `.ass` or `.ssa` file holds, or `None` for another file or one that is not a script.
43 pub fn from_file(path: &Path) -> Option<Captions> {
44 let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
45 if !matches!(ext.as_str(), "ass" | "ssa") {
46 return None;
47 }
48 Captions::parse(&std::fs::read(path).ok()?)
49 }
50
51 /// The script in `bytes`, or `None` when it has no events section.
52 pub fn parse(bytes: &[u8]) -> Option<Captions> {
53 let track = ec_ass::parse(bytes).ok()?;
54 let (nums, rows) = scan(&ec_subs::decode(bytes));
55 let meta = |key: &str| track.metadata.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
56 let res = |key: &str, default: f32| {
57 meta(key).and_then(|v| v.parse::<f32>().ok()).filter(|v| *v > 0.0).unwrap_or(default)
58 };
59 let mut styles: Vec<Style> = track
60 .styles
61 .iter()
62 .map(|s| Style::of(s, nums.get(&s.name).copied()))
63 .collect();
64 if styles.is_empty() {
65 styles.push(Style::default());
66 }
67 let events = track
68 .cues
69 .iter()
70 .enumerate()
71 .map(|(i, cue)| {
72 let row = rows.get(i).cloned().unwrap_or_default();
73 Event {
74 layer: row.layer,
75 style: cue.style_ref.clone(),
76 margins: row.margins,
77 an: row.an,
78 pos: cue.positioning.and_then(|p| p.x.zip(p.y)),
79 segments: cue.segments.clone(),
80 }
81 })
82 .collect();
83 Some(Captions {
84 play: (res("play_res_x", 384.0), res("play_res_y", 288.0)),
85 scaled: meta("scaled_border_and_shadow").is_some_and(|v| v.eq_ignore_ascii_case("yes")),
86 storage_h: 0.0,
87 wrap: meta("wrap_style").and_then(|v| v.parse().ok()).unwrap_or(0),
88 styles,
89 events,
90 cache: HashMap::new(),
91 })
92 }
93
94 /// Blur is sized in pixels of a `height`-row video, as libass sizes it against its storage size.
95 pub fn for_video_height(mut self, height: u32) -> Captions {
96 self.storage_h = height as f32;
97 self
98 }
99
100 /// Draws the events `shown` lists at `t_us` onto a BGRA canvas of `size` pixels.
101 pub fn draw_bgra(&mut self, canvas: &mut [u8], size: (u32, u32), shown: &[Shown], t_us: i64) {
102 let (w, h) = (size.0 as usize, size.1 as usize);
103 if canvas.len() < w * h * 4 {
104 return;
105 }
106 for (event, fade) in self.prepare(size, shown, t_us) {
107 if let Some(d) = self.cache.get(&event) {
108 paint_bgra(d, canvas, (w, h), fade);
109 }
110 }
111 }
112
113 /// Draws the events `shown` lists at `t_us` into I420 planes of `size` pixels.
114 pub fn draw_i420(
115 &mut self,
116 planes: (&mut [u8], &mut [u8], &mut [u8]),
117 size: (u32, u32),
118 full_range: bool,
119 shown: &[Shown],
120 t_us: i64,
121 ) {
122 let (w, h) = (size.0 as usize, size.1 as usize);
123 let cw = w.div_ceil(2);
124 if planes.0.len() < w * h || planes.1.len() < cw * h.div_ceil(2) || planes.2.len() != planes.1.len() {
125 return;
126 }
127 for (event, fade) in self.prepare(size, shown, t_us) {
128 if let Some(d) = self.cache.get(&event) {
129 paint_i420(d, (&mut *planes.0, &mut *planes.1, &mut *planes.2), (w, h), full_range, fade);
130 }
131 }
132 }
133
134 fn prepare(&mut self, size: (u32, u32), shown: &[Shown], t_us: i64) -> Vec<(usize, u8)> {
135 let mut order: Vec<&Shown> = shown.iter().collect();
136 order.sort_by_key(|s| (self.events.get(s.event).map_or(0, |e| e.layer), s.event));
137 self.cache.retain(|k, d| d.size == size && shown.iter().any(|s| s.event == *k));
138 let mut out = Vec::new();
139 for s in order {
140 if !self.cache.contains_key(&s.event) {
141 let drawn = self.render(s.event, size).map(|d| (s.event, d));
142 self.cache.extend(drawn);
143 }
144 if let Some(d) = self.cache.get(&s.event) {
145 out.push((s.event, fade_at(d.fade, t_us - s.start_us, s.end_us - s.start_us)));
146 }
147 }
148 out
149 }
150
151 fn render(&self, event: usize, (width, height): (u32, u32)) -> Option<Drawn> {
152 let ev = self.events.get(event)?;
153 let style_i = ev
154 .style
155 .as_deref()
156 .and_then(|n| self.styles.iter().position(|s| s.name == n))
157 .unwrap_or(0);
158 let style = &self.styles[style_i];
159 let mut walk = Walk {
160 styles: &self.styles,
161 style: style_i,
162 ir: Ir::default(),
163 sticky: Sticky::default(),
164 fade: None,
165 runs: Vec::new(),
166 items: Vec::new(),
167 };
168 walk.segments(&ev.segments);
169 let faces = walk
170 .runs
171 .iter()
172 .map(|r| Face::of(r.family.as_deref(), r.bold))
173 .collect::<Option<Vec<Face>>>()?;
174 let style_face = Face::of(style.family.as_deref(), style.bold)?;
175 let (sx, sy) = (width as f32 / self.play.0, height as f32 / self.play.1);
176 let (wf, hf) = (width as f32, height as f32);
177 let margin = |k: usize| (if ev.margins[k] != 0 { ev.margins[k] } else { style.margins[k] }) as f32;
178 let (ml, mr, mv) = (margin(0) * sx, margin(1) * sx, margin(2) * sy);
179 let cells: Vec<Option<Cell>> = walk
180 .items
181 .iter()
182 .map(|item| match *item {
183 Item::Break => None,
184 Item::Char(c, r) => Some(Cell::new(c, r, &walk.runs[r], faces[r], (sx, sy))),
185 })
186 .collect();
187 let lines = wrap_lines(cells, (self.wrap != 2).then_some(wf - ml - mr));
188 let an = ev.an.unwrap_or(style.an);
189 let (col, row) = (usize::from((an - 1) % 3), usize::from((an - 1) / 3));
190 let lh = style.size * sy;
191 let split = |size: f32, f: &Face| {
192 let h = size * sy;
193 let a = h * f.asc / (f.asc + f.desc).max(1.0);
194 (a, h - a)
195 };
196 let metrics: Vec<(f32, f32)> = lines
197 .iter()
198 .map(|line| {
199 line.iter()
200 .map(|c| split(walk.runs[c.run].size * walk.runs[c.run].scale_y, &faces[c.run]))
201 .reduce(|p, q| (p.0.max(q.0), p.1.max(q.1)))
202 .unwrap_or_else(|| split(style.size * style.scale_y, &style_face))
203 })
204 .collect();
205 let block: f32 = metrics.iter().map(|(a, d)| a + d).sum();
206 let anchor_x = match ev.pos {
207 Some((px, _)) => px * sx,
208 None => match col {
209 0 => ml,
210 2 => wf - mr,
211 _ => (ml + wf - mr) / 2.0,
212 },
213 };
214 let top = match (row, ev.pos.map(|(_, py)| py * sy)) {
215 (0, None) => hf - mv - block,
216 (0, Some(y)) => y - block,
217 (1, None) => (hf - block) / 2.0,
218 (1, Some(y)) => y - block / 2.0,
219 (_, None) => mv,
220 (_, Some(y)) => y,
221 };
222 let mut placed = Vec::new();
223 let mut x_range = (f32::INFINITY, f32::NEG_INFINITY);
224 let mut line_top = top;
225 for (line, &(asc, desc)) in lines.iter().zip(&metrics) {
226 let line_w: f32 = line.iter().map(|c| c.adv).sum();
227 let left = match col {
228 0 => anchor_x,
229 1 => anchor_x - line_w / 2.0,
230 _ => anchor_x - line_w,
231 };
232 x_range = (x_range.0.min(left), x_range.1.max(left + line_w));
233 let baseline = line_top + asc;
234 line_top += asc + desc;
235 let mut pen = left;
236 for c in line {
237 if c.c != ' ' {
238 placed.push(Placed {
239 run: c.run,
240 font: c.font,
241 id: c.id,
242 x: pen,
243 y: baseline,
244 kx: c.kx,
245 ky: c.ky,
246 shear: c.shear,
247 });
248 }
249 pen += c.adv;
250 }
251 }
252 if placed.is_empty() {
253 return None;
254 }
255 let (x0, x1) = x_range;
256 let y0 = top;
257 let y1 = top + block;
258 let bsc = if self.scaled { sy } else { 1.0 };
259 let blur_px = if self.storage_h > 0.0 { hf / self.storage_h } else { 1.0 };
260 let sigma_of = |r: &Run| ((0.849 * r.blur).powi(2) + 0.5 * r.edge_blur).sqrt() * blur_px;
261 let reach = walk
262 .runs
263 .iter()
264 .map(|r| {
265 let sigma = sigma_of(r);
266 r.border.abs() * bsc + r.shadow.abs() * bsc + 3.0 * sigma
267 })
268 .fold(0.0, f32::max);
269 let pad = (reach + lh * 0.25).ceil() as i32 + 2;
270 let (ox, oy) = (x0.floor() as i32 - pad, y0.floor() as i32 - pad);
271 let mw = (x1.ceil() as i32 + pad - ox).max(1) as usize;
272 let mh = (y1.ceil() as i32 + pad - oy).max(1) as usize;
273 if mw.saturating_mul(mh) > 1 << 26 {
274 return None;
275 }
276 let mut shadows = Vec::new();
277 let mut outlines = Vec::new();
278 let mut fills = Vec::new();
279 for (r, run) in walk.runs.iter().enumerate() {
280 let glyphs: Vec<&Placed> = placed.iter().filter(|p| p.run == r).collect();
281 if glyphs.is_empty() {
282 continue;
283 }
284 let mut fill = coverage(&glyphs, (mw, mh), (ox as f32, oy as f32));
285 let border = run.border * bsc;
286 let shadow = (run.shadow * bsc).round() as i32;
287 let sigma = sigma_of(run);
288 let mut edge = Vec::new();
289 if border > 0.0 {
290 edge = dilate(&fill, mw, mh, border);
291 if sigma > 0.0 {
292 edge = gauss(&edge, mw, mh, sigma);
293 }
294 } else if sigma > 0.0 {
295 fill = gauss(&fill, mw, mh, sigma);
296 }
297 if shadow != 0 && run.back[3] > 0 {
298 let base = if border > 0.0 { &edge } else { &fill };
299 shadows.push(Layer { rgba: run.back, cov: shift(base, mw, mh, shadow, shadow) });
300 }
301 if border > 0.0 && run.outline[3] > 0 {
302 outlines.push(Layer { rgba: run.outline, cov: edge });
303 }
304 if run.fill[3] > 0 {
305 fills.push(Layer { rgba: run.fill, cov: fill });
306 }
307 }
308 Some(Drawn {
309 size: (width, height),
310 x0: ox,
311 y0: oy,
312 w: mw,
313 h: mh,
314 layers: shadows.into_iter().chain(outlines).chain(fills).collect(),
315 fade: walk.fade,
316 })
317 }
318}
319
320#[derive(Clone, Debug)]
321struct Drawn {
322 size: (u32, u32),
323 x0: i32,
324 y0: i32,
325 w: usize,
326 h: usize,
327 layers: Vec<Layer>,
328 fade: Option<(i64, i64)>,
329}
330
331#[derive(Clone, Debug)]
332struct Layer {
333 rgba: [u8; 4],
334 cov: Vec<u8>,
335}
336
337#[derive(Clone, Debug)]
338struct Event {
339 layer: i32,
340 style: Option<String>,
341 margins: [i32; 3],
342 an: Option<u8>,
343 pos: Option<(f32, f32)>,
344 segments: Vec<Segment>,
345}
346
347#[derive(Clone, Debug)]
348struct Style {
349 name: String,
350 family: Option<String>,
351 size: f32,
352 primary: [u8; 4],
353 outline: [u8; 4],
354 back: [u8; 4],
355 bold: bool,
356 italic: bool,
357 scale_x: f32,
358 scale_y: f32,
359 spacing: f32,
360 border: f32,
361 shadow: f32,
362 an: u8,
363 margins: [i32; 3],
364}
365
366impl Default for Style {
367 fn default() -> Self {
368 Style {
369 name: String::new(),
370 family: None,
371 size: 20.0,
372 primary: [255; 4],
373 outline: [0, 0, 0, 255],
374 back: [0, 0, 0, 128],
375 bold: false,
376 italic: false,
377 scale_x: 1.0,
378 scale_y: 1.0,
379 spacing: 0.0,
380 border: 2.0,
381 shadow: 2.0,
382 an: 2,
383 margins: [10; 3],
384 }
385 }
386}
387
388impl Style {
389 fn of(s: &SubtitleStyle, n: Option<Nums>) -> Style {
390 let n = n.unwrap_or_default();
391 let rgba = |c: Option<(u8, u8, u8, u8)>, default: [u8; 4]| c.map_or(default, |(r, g, b, a)| [r, g, b, a]);
392 let d = Style::default();
393 Style {
394 name: s.name.clone(),
395 family: s.font_family.clone(),
396 size: s.font_size.unwrap_or(d.size),
397 primary: rgba(s.primary_color, d.primary),
398 outline: rgba(s.outline_color, d.outline),
399 back: rgba(s.back_color, d.back),
400 bold: s.bold,
401 italic: s.italic,
402 scale_x: n.scale_x,
403 scale_y: n.scale_y,
404 spacing: n.spacing,
405 border: s.outline.unwrap_or(0.0),
406 shadow: s.shadow.unwrap_or(0.0),
407 an: n.an,
408 margins: [s.margin_l.unwrap_or(0), s.margin_r.unwrap_or(0), s.margin_v.unwrap_or(0)],
409 }
410 }
411}
412
413#[derive(Clone, Copy)]
414struct Nums {
415 scale_x: f32,
416 scale_y: f32,
417 spacing: f32,
418 an: u8,
419}
420
421impl Default for Nums {
422 fn default() -> Self {
423 Nums { scale_x: 1.0, scale_y: 1.0, spacing: 0.0, an: 2 }
424 }
425}
426
427#[derive(Clone, Default)]
428struct Row {
429 layer: i32,
430 margins: [i32; 3],
431 an: Option<u8>,
432}
433
434fn scan(text: &str) -> (HashMap<String, Nums>, Vec<Row>) {
435 let mut nums = HashMap::new();
436 let mut rows = Vec::new();
437 let mut section = String::new();
438 let mut style_format: Vec<String> = Vec::new();
439 let mut event_format: Vec<String> = Vec::new();
440 for line in text.lines() {
441 let t = line.trim();
442 if let Some(name) = t.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
443 section = name.trim().to_ascii_lowercase();
444 continue;
445 }
446 let Some((key, value)) = t.split_once(':') else {
447 continue;
448 };
449 let (key, value) = (key.trim(), value.trim());
450 let styles = section.ends_with("styles");
451 if styles && key == "Format" {
452 style_format = fields(value);
453 } else if styles && key == "Style" {
454 let values: Vec<&str> = value.split(',').collect();
455 if let Some(name) = column(&style_format, &values, "Name") {
456 nums.insert(name.to_owned(), Nums::of(&style_format, &values, section == "v4 styles"));
457 }
458 } else if section == "events" && key == "Format" {
459 event_format = fields(value);
460 } else if section == "events" && key == "Dialogue" {
461 rows.extend(dialogue_row(&event_format, value));
462 }
463 }
464 (nums, rows)
465}
466
467fn fields(value: &str) -> Vec<String> {
468 value.split(',').map(|f| f.trim().to_owned()).collect()
469}
470
471fn column<'a>(format: &[String], values: &[&'a str], name: &str) -> Option<&'a str> {
472 let at = format.iter().position(|f| f.eq_ignore_ascii_case(name))?;
473 values.get(at).copied().map(str::trim)
474}
475
476impl Nums {
477 fn of(format: &[String], values: &[&str], v4: bool) -> Nums {
478 let num = |key: &str| column(format, values, key).and_then(|v| v.parse::<f32>().ok());
479 let code = column(format, values, "Alignment").and_then(|v| v.parse::<i32>().ok()).unwrap_or(2);
480 let an = if v4 {
481 ssa_numpad(code)
482 } else if (1..=9).contains(&code) {
483 code as u8
484 } else {
485 2
486 };
487 Nums {
488 scale_x: num("ScaleX").unwrap_or(100.0) / 100.0,
489 scale_y: num("ScaleY").unwrap_or(100.0) / 100.0,
490 spacing: num("Spacing").unwrap_or(0.0),
491 an,
492 }
493 }
494}
495
496fn ssa_numpad(code: i32) -> u8 {
497 let col = match code & 3 {
498 1 => 0,
499 3 => 2,
500 _ => 1,
501 };
502 let row = if code & 4 != 0 {
503 2
504 } else if code & 8 != 0 {
505 1
506 } else {
507 0
508 };
509 (row * 3 + col + 1) as u8
510}
511
512fn dialogue_row(format: &[String], value: &str) -> Option<Row> {
513 let format = if format.is_empty() { fields(DEFAULT_EVENT_FORMAT) } else { format.to_vec() };
514 let values: Vec<&str> = value.splitn(format.len(), ',').collect();
515 column(&format, &values, "Start").and_then(ec_subs::parse_clock)?;
516 column(&format, &values, "End").and_then(ec_subs::parse_clock)?;
517 let int = |key: &str| column(&format, &values, key).and_then(|v| v.parse::<i32>().ok()).unwrap_or(0);
518 Some(Row {
519 layer: int("Layer"),
520 margins: [int("MarginL"), int("MarginR"), int("MarginV")],
521 an: column(&format, &values, "Text").and_then(an_tag),
522 })
523}
524
525fn an_tag(text: &str) -> Option<u8> {
526 let at = text.find("\\an")?;
527 text[at + 3..]
528 .chars()
529 .next()?
530 .to_digit(10)
531 .filter(|d| (1..=9).contains(d))
532 .map(|d| d as u8)
533}
534
535fn hex(arg: &str) -> Option<u32> {
536 let digits = arg.trim().trim_matches('&').trim_start_matches(['H', 'h']);
537 u32::from_str_radix(digits, 16).ok()
538}
539
540fn colour(arg: &str) -> Option<[u8; 4]> {
541 let v = hex(arg)?;
542 Some([(v & 0xFF) as u8, ((v >> 8) & 0xFF) as u8, ((v >> 16) & 0xFF) as u8, 255 - ((v >> 24) & 0xFF) as u8])
543}
544
545fn alpha(arg: &str) -> Option<u8> {
546 hex(arg).map(|v| 255 - (v & 0xFF) as u8)
547}
548
549#[derive(Clone, Default)]
550struct Ir {
551 bold: bool,
552 italic: bool,
553 colour: Option<[u8; 3]>,
554 family: Option<String>,
555 size: Option<f32>,
556}
557
558#[derive(Clone, Default)]
559struct Sticky {
560 fill_a: Option<u8>,
561 outline_a: Option<u8>,
562 back_a: Option<u8>,
563 outline: Option<[u8; 3]>,
564 back: Option<[u8; 3]>,
565 border: Option<f32>,
566 shadow: Option<f32>,
567 blur: Option<f32>,
568 edge_blur: Option<u32>,
569}
570
571#[derive(Clone)]
572struct Run {
573 family: Option<String>,
574 size: f32,
575 bold: bool,
576 italic: bool,
577 fill: [u8; 4],
578 outline: [u8; 4],
579 back: [u8; 4],
580 border: f32,
581 shadow: f32,
582 blur: f32,
583 edge_blur: f32,
584 scale_x: f32,
585 scale_y: f32,
586 spacing: f32,
587}
588
589enum Item {
590 Char(char, usize),
591 Break,
592}
593
594struct Walk<'a> {
595 styles: &'a [Style],
596 style: usize,
597 ir: Ir,
598 sticky: Sticky,
599 fade: Option<(i64, i64)>,
600 runs: Vec<Run>,
601 items: Vec<Item>,
602}
603
604impl Walk<'_> {
605 fn segments(&mut self, segments: &[Segment]) {
606 for segment in segments {
607 self.segment(segment);
608 }
609 }
610
611 fn segment(&mut self, segment: &Segment) {
612 match segment {
613 Segment::Text(text) => {
614 let run = self.run();
615 self.items.extend(text.chars().map(|c| Item::Char(c, run)));
616 }
617 Segment::LineBreak => self.items.push(Item::Break),
618 Segment::Bold(children) => self.nested(children, |ir| ir.bold = true),
619 Segment::Italic(children) => self.nested(children, |ir| ir.italic = true),
620 Segment::Underline(children) | Segment::Strike(children) => self.segments(children),
621 Segment::Voice { children, .. } | Segment::Class { children, .. } => self.segments(children),
622 Segment::Karaoke { children, .. } => self.segments(children),
623 Segment::Color { rgb, children } => {
624 let rgb = *rgb;
625 self.nested(children, move |ir| ir.colour = Some([rgb.0, rgb.1, rgb.2]));
626 }
627 Segment::Font { family, size, children } => {
628 let (family, size) = (family.clone(), *size);
629 self.nested(children, move |ir| {
630 if family.is_some() {
631 ir.family = family;
632 }
633 if size.is_some() {
634 ir.size = size;
635 }
636 });
637 }
638 Segment::Raw(text) => {
639 if let Some(block) = text.strip_prefix('{') {
640 self.block(block.trim_end_matches('}'));
641 }
642 }
643 Segment::Timestamp { .. } => {}
644 }
645 }
646
647 fn nested(&mut self, children: &[Segment], set: impl FnOnce(&mut Ir)) {
648 let saved = self.ir.clone();
649 set(&mut self.ir);
650 self.segments(children);
651 self.ir = saved;
652 }
653
654 fn block(&mut self, body: &str) {
655 for tag in body.split('\\').map(str::trim).filter(|t| !t.is_empty()) {
656 self.tag(tag);
657 }
658 }
659
660 fn tag(&mut self, tag: &str) {
661 if let Some(name) = tag.strip_prefix('r') {
662 self.style = self
663 .styles
664 .iter()
665 .position(|s| s.name == name.trim())
666 .unwrap_or(self.style);
667 self.ir = Ir::default();
668 self.sticky = Sticky::default();
669 return;
670 }
671 let k = &mut self.sticky;
672 if let Some(arg) = tag.strip_prefix("alpha") {
673 if let Some(a) = alpha(arg) {
674 k.fill_a = Some(a);
675 k.outline_a = Some(a);
676 k.back_a = Some(a);
677 }
678 } else if let Some(arg) = tag.strip_prefix("1a") {
679 k.fill_a = alpha(arg).or(k.fill_a);
680 } else if let Some(arg) = tag.strip_prefix("3a") {
681 k.outline_a = alpha(arg).or(k.outline_a);
682 } else if let Some(arg) = tag.strip_prefix("4a") {
683 k.back_a = alpha(arg).or(k.back_a);
684 } else if let Some(arg) = tag.strip_prefix("3c") {
685 k.outline = colour(arg).map(|c| [c[0], c[1], c[2]]).or(k.outline);
686 } else if let Some(arg) = tag.strip_prefix("4c") {
687 k.back = colour(arg).map(|c| [c[0], c[1], c[2]]).or(k.back);
688 } else if let Some(arg) = tag.strip_prefix("bord") {
689 k.border = arg.trim().parse().ok().or(k.border);
690 } else if let Some(arg) = tag.strip_prefix("shad") {
691 k.shadow = arg.trim().parse().ok().or(k.shadow);
692 } else if let Some(arg) = tag.strip_prefix("blur") {
693 k.blur = arg.trim().parse().ok().or(k.blur);
694 } else if let Some(arg) = tag.strip_prefix("be") {
695 k.edge_blur = arg.trim().parse().ok().or(k.edge_blur);
696 } else if let Some(arg) = tag.strip_prefix("fad") {
697 let times: Vec<i64> = arg
698 .trim_matches(['(', ')'])
699 .split(',')
700 .filter_map(|n| n.trim().parse().ok())
701 .collect();
702 if let [fin, fout] = times[..] {
703 self.fade = Some((fin, fout));
704 }
705 }
706 }
707
708 fn run(&mut self) -> usize {
709 let s = &self.styles[self.style];
710 let (ir, k) = (&self.ir, &self.sticky);
711 let rgb = |c: Option<[u8; 3]>, base: [u8; 4]| c.unwrap_or([base[0], base[1], base[2]]);
712 let run = Run {
713 family: ir.family.clone().or_else(|| s.family.clone()),
714 size: ir.size.unwrap_or(s.size),
715 bold: ir.bold || s.bold,
716 italic: ir.italic || s.italic,
717 fill: with_alpha(rgb(ir.colour, s.primary), k.fill_a.unwrap_or(s.primary[3])),
718 outline: with_alpha(rgb(k.outline, s.outline), k.outline_a.unwrap_or(s.outline[3])),
719 back: with_alpha(rgb(k.back, s.back), k.back_a.unwrap_or(s.back[3])),
720 border: k.border.unwrap_or(s.border),
721 shadow: k.shadow.unwrap_or(s.shadow),
722 blur: k.blur.unwrap_or(0.0),
723 edge_blur: k.edge_blur.unwrap_or(0) as f32,
724 scale_x: s.scale_x,
725 scale_y: s.scale_y,
726 spacing: s.spacing,
727 };
728 self.runs.push(run);
729 self.runs.len() - 1
730 }
731}
732
733fn with_alpha(rgb: [u8; 3], a: u8) -> [u8; 4] {
734 [rgb[0], rgb[1], rgb[2], a]
735}
736
737#[derive(Clone, Copy)]
738struct Face {
739 font: &'static FontRef<'static>,
740 asc: f32,
741 desc: f32,
742}
743
744impl Face {
745 fn of(name: Option<&str>, bold: bool) -> Option<Face> {
746 let family = name.and_then(text::family_face).or_else(|| text::bundled_family(bold))?;
747 let (font, data, index) = family.parts();
748 let (asc, desc) = vertical(data, index);
749 Some(Face { font, asc, desc })
750 }
751}
752
753fn vertical(data: &[u8], index: u32) -> (f32, f32) {
754 let Ok(face) = ttf_parser::Face::parse(data, index) else {
755 return (0.8, 0.2);
756 };
757 if let Some(os2) = face.tables().os2.as_ref() {
758 let (asc, desc) = (f32::from(os2.windows_ascender()), -f32::from(os2.windows_descender()));
759 if asc + desc > 0.0 {
760 return (asc, desc);
761 }
762 }
763 (f32::from(face.ascender()), -f32::from(face.descender()))
764}
765
766fn glyph(font: &'static FontRef<'static>, c: char) -> (&'static FontRef<'static>, GlyphId) {
767 let id = font.glyph_id(c);
768 if id.0 != 0 {
769 return (font, id);
770 }
771 let fallback = text::bundled_family(false).map_or(font, |f| f.parts().0);
772 (fallback, fallback.glyph_id(c))
773}
774
775struct Cell {
776 c: char,
777 run: usize,
778 font: &'static FontRef<'static>,
779 id: GlyphId,
780 adv: f32,
781 kx: f32,
782 ky: f32,
783 shear: f32,
784}
785
786impl Cell {
787 fn new(c: char, run: usize, r: &Run, face: Face, (sx, sy): (f32, f32)) -> Cell {
788 let (font, id) = glyph(face.font, c);
789 let scale = r.size / (face.asc + face.desc).max(1.0);
790 let kx = sx * r.scale_x * scale;
791 let ky = sy * r.scale_y * scale;
792 Cell {
793 c,
794 run,
795 font,
796 id,
797 adv: font.h_advance_unscaled(id) * kx + r.spacing * sx,
798 kx,
799 ky,
800 shear: if r.italic { ITALIC_SHEAR } else { 0.0 },
801 }
802 }
803}
804
805struct Placed {
806 run: usize,
807 font: &'static FontRef<'static>,
808 id: GlyphId,
809 x: f32,
810 y: f32,
811 kx: f32,
812 ky: f32,
813 shear: f32,
814}
815
816fn wrap_lines(cells: Vec<Option<Cell>>, max: Option<f32>) -> Vec<Vec<Cell>> {
817 let mut lines = Lines { max, done: Vec::new(), line: Vec::new(), width: 0.0 };
818 let mut word = Vec::new();
819 for cell in cells {
820 match cell {
821 None => {
822 lines.word(&mut word);
823 lines.end();
824 }
825 Some(c) if c.c == ' ' => {
826 lines.word(&mut word);
827 lines.width += c.adv;
828 lines.line.push(c);
829 }
830 Some(c) => word.push(c),
831 }
832 }
833 lines.word(&mut word);
834 lines.end();
835 lines.done
836}
837
838struct Lines {
839 max: Option<f32>,
840 done: Vec<Vec<Cell>>,
841 line: Vec<Cell>,
842 width: f32,
843}
844
845impl Lines {
846 fn word(&mut self, word: &mut Vec<Cell>) {
847 if word.is_empty() {
848 return;
849 }
850 let w: f32 = word.iter().map(|c| c.adv).sum();
851 if self.max.is_some_and(|m| self.width + w > m) && self.line.iter().any(|c| c.c != ' ') {
852 self.end();
853 }
854 self.width += w;
855 self.line.append(word);
856 }
857
858 fn end(&mut self) {
859 while let Some(c) = self.line.last().filter(|c| c.c == ' ') {
860 self.width -= c.adv;
861 self.line.pop();
862 }
863 self.done.push(std::mem::take(&mut self.line));
864 self.width = 0.0;
865 }
866}
867
868fn draw_glyph(ras: &mut Rasterizer, p: &Placed, (ox, oy): (f32, f32)) {
869 let Some(outline) = p.font.outline(p.id) else {
870 return;
871 };
872 let map = |q: ab_glyph::Point| point(p.x - ox + p.kx * (q.x + p.shear * q.y), p.y - oy - p.ky * q.y);
873 for curve in outline.curves {
874 match curve {
875 OutlineCurve::Line(a, b) => ras.draw_line(map(a), map(b)),
876 OutlineCurve::Quad(a, b, c) => ras.draw_quad(map(a), map(b), map(c)),
877 OutlineCurve::Cubic(a, b, c, d) => ras.draw_cubic(map(a), map(b), map(c), map(d)),
878 }
879 }
880}
881
882fn coverage(glyphs: &[&Placed], (w, h): (usize, usize), origin: (f32, f32)) -> Vec<u8> {
883 let mut ras = Rasterizer::new(w, h);
884 for p in glyphs {
885 draw_glyph(&mut ras, p, origin);
886 }
887 let mut out = vec![0u8; w * h];
888 ras.for_each_pixel_2d(|x, y, c| {
889 out[y as usize * w + x as usize] = (c.clamp(0.0, 1.0) * 255.0).round() as u8;
890 });
891 out
892}
893
894fn dilate(src: &[u8], w: usize, h: usize, r: f32) -> Vec<u8> {
895 let n = r.ceil() as i32;
896 let mut taps = Vec::new();
897 for dy in -n..=n {
898 for dx in -n..=n {
899 let d = ((dx * dx + dy * dy) as f32).sqrt();
900 let weight = (r + 0.5 - d).clamp(0.0, 1.0);
901 if weight > 0.0 {
902 taps.push((dx, dy, weight));
903 }
904 }
905 }
906 let mut out = vec![0u8; w * h];
907 for y in 0..h {
908 for x in 0..w {
909 let mut best = 0f32;
910 for &(dx, dy, weight) in &taps {
911 let (sx, sy) = (x as i32 + dx, y as i32 + dy);
912 if sx < 0 || sy < 0 || sx >= w as i32 || sy >= h as i32 {
913 continue;
914 }
915 best = best.max(f32::from(src[sy as usize * w + sx as usize]) * weight);
916 }
917 out[y * w + x] = best.round() as u8;
918 }
919 }
920 out
921}
922
923fn gauss(src: &[u8], w: usize, h: usize, sigma: f32) -> Vec<u8> {
924 let n = (3.0 * sigma).ceil() as isize;
925 let k: Vec<f32> = (-n..=n)
926 .map(|i| (-((i * i) as f32) / (2.0 * sigma * sigma)).exp())
927 .collect();
928 let total: f32 = k.iter().sum();
929 let mut tmp = vec![0f32; w * h];
930 for y in 0..h {
931 for x in 0..w {
932 let mut acc = 0f32;
933 for (j, kv) in k.iter().enumerate() {
934 let sx = x as isize + j as isize - n;
935 if (0..w as isize).contains(&sx) {
936 acc += kv * f32::from(src[y * w + sx as usize]);
937 }
938 }
939 tmp[y * w + x] = acc / total;
940 }
941 }
942 let mut out = vec![0u8; w * h];
943 for y in 0..h {
944 for x in 0..w {
945 let mut acc = 0f32;
946 for (j, kv) in k.iter().enumerate() {
947 let sy = y as isize + j as isize - n;
948 if (0..h as isize).contains(&sy) {
949 acc += kv * tmp[sy as usize * w + x];
950 }
951 }
952 out[y * w + x] = (acc / total).round().clamp(0.0, 255.0) as u8;
953 }
954 }
955 out
956}
957
958fn shift(src: &[u8], w: usize, h: usize, dx: i32, dy: i32) -> Vec<u8> {
959 let mut out = vec![0u8; w * h];
960 for y in 0..h {
961 let sy = y as i32 - dy;
962 if sy < 0 || sy >= h as i32 {
963 continue;
964 }
965 for x in 0..w {
966 let sx = x as i32 - dx;
967 if sx >= 0 && sx < w as i32 {
968 out[y * w + x] = src[sy as usize * w + sx as usize];
969 }
970 }
971 }
972 out
973}
974
975fn fade_at(fade: Option<(i64, i64)>, t: i64, dur: i64) -> u8 {
976 let Some((fin, fout)) = fade.map(|(i, o)| (i * 1000, o * 1000)) else {
977 return 255;
978 };
979 let mut k = 1.0f32;
980 if fin > 0 && t < fin {
981 k = k.min(t as f32 / fin as f32);
982 }
983 if fout > 0 && dur - t < fout {
984 k = k.min((dur - t) as f32 / fout as f32);
985 }
986 (k.clamp(0.0, 1.0) * 255.0).round() as u8
987}
988
989fn mul(a: u8, b: u8) -> u8 {
990 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
991}
992
993fn clip(d: &Drawn, (w, h): (usize, usize)) -> (usize, usize, usize, usize) {
994 let x0 = d.x0.clamp(0, w as i32) as usize;
995 let x1 = (d.x0 + d.w as i32).clamp(0, w as i32) as usize;
996 let y0 = d.y0.clamp(0, h as i32) as usize;
997 let y1 = (d.y0 + d.h as i32).clamp(0, h as i32) as usize;
998 (x0, y0, x1, y1)
999}
1000
1001fn paint_bgra(d: &Drawn, canvas: &mut [u8], (w, h): (usize, usize), fade: u8) {
1002 let (x0, y0, x1, y1) = clip(d, (w, h));
1003 for layer in &d.layers {
1004 let [r, g, b, a] = layer.rgba;
1005 let k = mul(a, fade);
1006 for py in y0..y1 {
1007 for px in x0..x1 {
1008 let c = layer.cov[(py as i32 - d.y0) as usize * d.w + (px as i32 - d.x0) as usize];
1009 if c == 0 {
1010 continue;
1011 }
1012 let alpha = mul(c, k);
1013 let i = (py * w + px) * 4;
1014 canvas[i] = mix(canvas[i], b, alpha);
1015 canvas[i + 1] = mix(canvas[i + 1], g, alpha);
1016 canvas[i + 2] = mix(canvas[i + 2], r, alpha);
1017 }
1018 }
1019 }
1020}
1021
1022fn paint_i420(d: &Drawn, planes: (&mut [u8], &mut [u8], &mut [u8]), (w, h): (usize, usize), full_range: bool, fade: u8) {
1023 let (yp, up, vp) = planes;
1024 let cw = w.div_ceil(2);
1025 let bt709 = !is_sd(w as u32, h as u32);
1026 let (x0, y0, x1, y1) = clip(d, (w, h));
1027 if x0 >= x1 || y0 >= y1 {
1028 return;
1029 }
1030 for layer in &d.layers {
1031 let k = mul(layer.rgba[3], fade);
1032 let (yy, uu, vv) = yuv(layer.rgba, bt709, full_range);
1033 let alpha = |px: usize, py: usize| -> u32 {
1034 let c = layer.cov[(py as i32 - d.y0) as usize * d.w + (px as i32 - d.x0) as usize];
1035 u32::from(mul(c, k))
1036 };
1037 for py in y0..y1 {
1038 for px in x0..x1 {
1039 let a = alpha(px, py) as u8;
1040 if a > 0 {
1041 let i = py * w + px;
1042 yp[i] = mix(yp[i], yy, a);
1043 }
1044 }
1045 }
1046 for cy in y0 / 2..=(y1 - 1) / 2 {
1047 for cx in x0 / 2..=(x1 - 1) / 2 {
1048 let (mut sa, mut su, mut sv) = (0u32, 0u32, 0u32);
1049 for dy in 0..2 {
1050 for dx in 0..2 {
1051 let (px, py) = (cx * 2 + dx, cy * 2 + dy);
1052 if (x0..x1).contains(&px) && (y0..y1).contains(&py) {
1053 let a = alpha(px, py);
1054 sa += a;
1055 su += a * u32::from(uu);
1056 sv += a * u32::from(vv);
1057 }
1058 }
1059 }
1060 if sa > 0 {
1061 let i = cy * cw + cx;
1062 let cover = (sa / 4) as u8;
1063 up[i] = mix(up[i], (su / sa) as u8, cover);
1064 vp[i] = mix(vp[i], (sv / sa) as u8, cover);
1065 }
1066 }
1067 }
1068 }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073 #[test]
1074 fn colour_is_bgr_with_a_transparency_byte() {
1075 assert_eq!(super::colour("&H64100908"), Some([8, 9, 16, 155]));
1076 }
1077}