perf(fonts,render): bound FontDb outline caches and prune/LRU media and color-glyph caches (#7900) (#7910)

This commit is contained in:
Lucas Batista Vargas
2026-12-03 01:20:17 +00:00
committed by GitHub
parent 9dad9fca5f
commit d885a9d997
8 changed files with 191 additions and 59 deletions
+44 -6
View File
@@ -42,14 +42,52 @@ pub(crate) use names::{last_resort_face, legacy_family};
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
/// Fixed-capacity FIFO cache shared by outline and hinting tables so old zoom/script entries evict
/// incrementally instead of wiping the whole table at once.
pub(super) struct BoundedCache<K, V> {
map: HashMap<K, V>,
order: std::collections::VecDeque<K>,
cap: usize,
}
impl<K: Eq + std::hash::Hash + Clone, V> BoundedCache<K, V> {
pub(super) fn new(cap: usize) -> Self {
Self { map: HashMap::new(), order: std::collections::VecDeque::new(), cap: cap.max(1) }
}
pub(super) fn get(&self, key: &K) -> Option<&V> {
self.map.get(key)
}
pub(super) fn insert(&mut self, key: K, val: V) {
if let Some(existing) = self.map.get_mut(&key) {
*existing = val;
return;
}
while self.map.len() >= self.cap {
let Some(oldest) = self.order.pop_front() else {
break;
};
self.map.remove(&oldest);
}
self.order.push_back(key.clone());
self.map.insert(key, val);
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.map.len()
}
}
/// Process-wide font database.
pub struct FontDb {
faces: RwLock<Vec<Arc<FontFace>>>,
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
outlines: Mutex<BoundedCache<(u32, u32), Arc<BezPath>>>,
/// Screen-hinted outlines per (face, glyph, ppem bits); `None` where the face can't be hinted.
hinted: Mutex<HashMap<(u32, u32, u32), Option<Arc<BezPath>>>>,
hinted: Mutex<BoundedCache<(u32, u32, u32), Option<Arc<BezPath>>>>,
/// Light hinting instances per (face, ppem bits); `None` where the face can't be hinted.
hinters: Mutex<HashMap<(u32, u32), Option<Arc<HintingInstance>>>>,
hinters: Mutex<BoundedCache<(u32, u32), Option<Arc<HintingInstance>>>>,
/// Fallback faces found per (character, excluded face), valid while the face count is the
/// one stored (faces are only ever added). Layout asks once per uncovered character, and the
/// search sorts every loaded face, so without this text in a script the requested font lacks
@@ -123,9 +161,9 @@ impl FontDb {
}
Self {
faces: RwLock::new(faces),
outlines: Mutex::new(HashMap::new()),
hinted: Mutex::new(HashMap::new()),
hinters: Mutex::new(HashMap::new()),
outlines: Mutex::new(BoundedCache::new(face::OUTLINE_CACHE_MAX)),
hinted: Mutex::new(BoundedCache::new(face::HINTED_CACHE_MAX)),
hinters: Mutex::new(BoundedCache::new(face::HINTER_CACHE_MAX)),
fallbacks: RwLock::new(FallbackCache::default()),
run_fallbacks: RwLock::new(RunFallbackCache::default()),
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
+6 -2
View File
@@ -541,9 +541,13 @@ fn is_explicit_serif(name: &str) -> bool {
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
pub(super) const OUTLINE_CACHE_MAX: usize = 50_000;
/// Unhinted glyph outlines kept per (face, glyph).
pub(super) const OUTLINE_CACHE_MAX: usize = 16_384;
/// Screen-hinted outlines kept per (face, glyph, ppem bits); narrower than [`OUTLINE_CACHE_MAX`]
/// because zoom changes create entries per size.
pub(super) const HINTED_CACHE_MAX: usize = 8_192;
/// Hinting instances kept (one per face and text size on screen).
pub(super) const HINTER_CACHE_MAX: usize = 256;
pub(super) const HINTER_CACHE_MAX: usize = 128;
/// Sizes hinted, in device pixels per em: below, text is too small to read anyway; above, the
/// half-pixel hinting moves is invisible (and each size would cost a cache entry).
pub(super) const HINT_PPEM: std::ops::RangeInclusive<f32> = 4.0..=96.0;
+4 -16
View File
@@ -1,4 +1,4 @@
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM, HINTER_CACHE_MAX, OUTLINE_CACHE_MAX};
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::read_fallback_file;
#[cfg(not(target_arch = "wasm32"))]
@@ -220,11 +220,7 @@ impl FontDb {
return p.clone();
}
let p = Arc::new(face.glyph_outline(gid));
let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
p
}
@@ -247,21 +243,13 @@ impl FontDb {
None => {
// Built outside the lock: running a font's hinting programs takes a while.
let h = face.screen_hinter(ppem).map(Arc::new);
let mut cache = self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= HINTER_CACHE_MAX {
cache.clear();
}
cache.insert(hkey, h.clone());
self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(hkey, h.clone());
h
}
}
};
let p = hinter.and_then(|h| face.hinted_glyph_outline(gid, &h)).map(Arc::new);
let mut cache = self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
}
cache.insert(key, p.clone());
self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
p
}
}
+12
View File
@@ -154,6 +154,18 @@ fn screen_hinting_refuses_hostile_sizes() {
assert!(db.hinted_outline(&face, u32::MAX, 20.0).is_none_or(|o| o.elements().is_empty()));
}
#[test]
fn bounded_outline_cache_evicts_oldest_incrementally() {
let mut c = BoundedCache::new(2);
c.insert(1u32, "a");
c.insert(2u32, "b");
c.insert(3u32, "c");
assert_eq!(c.len(), 2);
assert!(c.get(&1).is_none(), "oldest entry evicted");
assert_eq!(c.get(&2), Some(&"b"), "newer entry retained");
assert_eq!(c.get(&3), Some(&"c"));
}
/// The issue's run (#1549): Thai letters and digits, Latin letters, digits and the baht sign.
const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู่ ๑๒๓๔๕๖๗๘๙๐ ฿1,250.50";
+26 -12
View File
@@ -1,6 +1,5 @@
//! Decoded-media cache: hits need the same allocation, and the byte budget bounds what is kept.
use std::collections::HashMap;
use std::sync::Arc;
use wordcraft_doc::Document;
@@ -11,7 +10,7 @@ use super::{CACHE_BYTES, MediaCache, RenderOptions, render_items, wave_path};
#[test]
fn media_cache_only_hits_the_same_allocation() {
let mut c: MediaCache<u32> = MediaCache { map: HashMap::new(), bytes: 0 };
let mut c: MediaCache<u32> = MediaCache::default();
let a = Arc::new(vec![1u8, 2, 3]);
let b = Arc::new(vec![1u8, 2, 3]);
c.insert("pic", &a, 7, 3);
@@ -22,22 +21,26 @@ fn media_cache_only_hits_the_same_allocation() {
}
#[test]
fn media_cache_is_bounded_by_bytes() {
let mut c: MediaCache<u32> = MediaCache { map: HashMap::new(), bytes: 0 };
fn media_cache_is_bounded_by_bytes_and_evicts_lru() {
let mut c: MediaCache<u32> = MediaCache::default();
let src = Arc::new(vec![0u8]);
let big = CACHE_BYTES / 2 + 1;
c.insert("a", &src, 1, big);
c.insert("b", &src, 2, big);
assert_eq!(c.get("a", &src), None, "the first entry is evicted to make room");
assert_eq!(c.get("b", &src), Some(2));
let third = CACHE_BYTES / 3;
c.insert("a", &src, 1, third);
c.insert("b", &src, 2, third);
// Touch "a" so "b" becomes the least recently used entry.
assert_eq!(c.get("a", &src), Some(1));
c.insert("c", &src, 3, CACHE_BYTES / 2);
assert_eq!(c.get("a", &src), Some(1), "recently used entry stays cached");
assert_eq!(c.get("b", &src), None, "least recently used entry is evicted to make room");
assert_eq!(c.get("c", &src), Some(3));
assert!(c.bytes <= CACHE_BYTES);
c.insert("huge", &src, 3, CACHE_BYTES + 1);
c.insert("huge", &src, 4, CACHE_BYTES + 1);
assert_eq!(c.get("huge", &src), None, "a value over the whole budget is not kept");
}
#[test]
fn media_cache_counts_what_it_keeps_and_lets_sources_go() {
let mut c: MediaCache<Option<u32>> = MediaCache { map: HashMap::new(), bytes: 0 };
fn media_cache_prunes_dropped_sources_and_lets_sources_go() {
let mut c: MediaCache<Option<u32>> = MediaCache::default();
let src = Arc::new(vec![0u8; 1000]);
c.insert("broken", &src, None, 0);
c.insert("pic", &src, Some(1), 24);
@@ -49,6 +52,17 @@ fn media_cache_counts_what_it_keeps_and_lets_sources_go() {
c.insert("huge", &huge, None, 0);
assert_eq!(c.get("huge", &huge), Some(None));
assert_eq!(CACHE_BYTES * 2, 256 * 1024 * 1024, "the image and vector caches share about 256 MB");
let live = Arc::new(vec![1u8]);
let dead = Arc::new(vec![2u8]);
let half = CACHE_BYTES / 2 + 1;
c.insert("live", &live, Some(2), half);
c.insert("dead", &dead, Some(3), half / 2);
drop(dead);
// Inserting another half-budget entry prunes the dropped source without evicting "live".
c.insert("live2", &live, Some(4), half / 2);
assert_eq!(c.get("live", &live), Some(Some(2)), "live entry kept when dropped source is reclaimed");
assert_eq!(c.get("live2", &live), Some(Some(4)));
}
/// A wave stroke starting around 1e20 never advanced (`x + step == x`), pushing curves until memory ran out.
+41 -11
View File
@@ -4,7 +4,7 @@
//! and turns it into vello fills. The colours come from the font: a dark page doesn't invert them,
//! the same as pictures. Only the font's "text colour" entries follow the run's colour.
use std::collections::HashMap;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use vello_cpu::kurbo::{self, Affine, Point, Rect, Shape};
@@ -29,15 +29,17 @@ impl Drawable {
}
}
/// Upper bounds on the colour-glyph cache: entries and approximate bytes. Past either it starts over.
/// Upper bounds on the colour-glyph cache: entries and approximate bytes. Evicts oldest entries
/// incrementally past either cap.
const CACHE_ENTRIES: usize = 4096;
const CACHE_BYTES: usize = 64 * 1024 * 1024;
const CACHE_BYTES: usize = 32 * 1024 * 1024;
type Key = (u32, u32, u32);
#[derive(Default)]
struct Cache {
map: HashMap<Key, Option<Arc<Drawable>>>,
map: HashMap<Key, (Option<Arc<Drawable>>, usize)>,
order: VecDeque<Key>,
bytes: usize,
}
@@ -62,23 +64,40 @@ pub(crate) fn drawable(face: &FontFace, gid: u32, ppem: f64, cached: bool) -> Op
return build(face, gid, bucket).map(Arc::new);
}
let key = (face.id(), gid, bucket);
if let Some(v) = crate::lock(cache()).map.get(&key) {
if let Some((v, _)) = crate::lock(cache()).map.get(&key) {
return v.clone();
}
let d = build(face, gid, bucket).map(Arc::new);
let size = d.as_ref().map_or(0, |d| d.bytes()).saturating_add(64);
let mut c = crate::lock(cache());
if c.map.len() >= CACHE_ENTRIES || c.bytes.saturating_add(size) > CACHE_BYTES {
c.map.clear();
c.bytes = 0;
}
if size <= CACHE_BYTES {
c.map.insert(key, d.clone());
c.bytes = c.bytes.saturating_add(size);
c.insert(key, d.clone(), size);
}
d
}
impl Cache {
fn insert(&mut self, key: Key, val: Option<Arc<Drawable>>, size: usize) {
if let Some((_, old_size)) = self.map.remove(&key) {
self.bytes = self.bytes.saturating_sub(old_size);
}
while self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
let Some(oldest) = self.order.pop_front() else {
break;
};
if let Some((_, old_size)) = self.map.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(old_size);
}
}
if self.map.capacity() > self.map.len().saturating_mul(4).max(64) {
self.map.shrink_to(self.map.len().saturating_mul(2).max(32));
}
self.order.push_back(key);
self.map.insert(key, (val, size));
self.bytes = self.bytes.saturating_add(size);
}
}
fn build(face: &FontFace, gid: u32, ppem: u32) -> Option<Drawable> {
match face.color_glyph(gid, ppem as f32)? {
ColorGlyph::Layers(ops) => Some(Drawable::Layers(ops)),
@@ -438,4 +457,15 @@ mod tests {
assert_eq!((p.width, p.height), (4, 4), "a plain glyph reads");
assert_eq!(decode_png(&png(1, 1), 1, 1).map(|p| (p.width(), p.height())), Some((1, 1)));
}
#[test]
fn color_glyph_cache_evicts_oldest_within_byte_budget() {
let mut c = Cache::default();
let entry = CACHE_BYTES / 2 + 1;
c.insert((1, 1, 16), None, entry);
c.insert((1, 2, 16), None, entry);
assert!(!c.map.contains_key(&(1, 1, 16)), "oldest entry evicted to stay under budget");
assert!(c.map.contains_key(&(1, 2, 16)), "newest entry retained");
assert!(c.bytes <= CACHE_BYTES);
}
}
+56 -10
View File
@@ -17,22 +17,56 @@ const CACHE_ENTRIES: usize = 256;
pub(crate) struct MediaCache<T> {
pub(crate) map: HashMap<String, Entry<T>>,
pub(crate) bytes: usize,
clock: u64,
}
impl<T> Default for MediaCache<T> {
fn default() -> Self {
Self { map: HashMap::new(), bytes: 0, clock: 0 }
}
}
pub(crate) struct Entry<T> {
src: Weak<Vec<u8>>,
val: T,
size: usize,
stamp: u64,
}
impl<T: Clone> MediaCache<T> {
pub(crate) fn get(&self, key: &str, src: &Arc<Vec<u8>>) -> Option<T> {
let e = self.map.get(key)?;
std::ptr::eq(e.src.as_ptr(), Arc::as_ptr(src)).then(|| e.val.clone())
pub(crate) fn get(&mut self, key: &str, src: &Arc<Vec<u8>>) -> Option<T> {
let hit = self.map.get(key).is_some_and(|e| std::ptr::eq(e.src.as_ptr(), Arc::as_ptr(src)));
if hit {
self.clock = self.clock.wrapping_add(1);
let stamp = self.clock;
if let Some(e) = self.map.get_mut(key) {
e.stamp = stamp;
return Some(e.val.clone());
}
}
// Reclaim dead entry immediately if its source document/allocation is gone.
if self.map.get(key).is_some_and(|e| e.src.strong_count() == 0)
&& let Some(dead) = self.map.remove(key)
{
self.bytes = self.bytes.saturating_sub(dead.size);
}
None
}
/// Stores `val` (about `size` bytes) for `src`. Clears the cache first when the budget or entry
/// cap is hit; an entry larger than the whole budget is not kept.
/// Reclaims decoded media whose source allocations have already been dropped.
fn prune_dead(&mut self) {
let bytes = &mut self.bytes;
self.map.retain(|_, e| {
let alive = e.src.strong_count() > 0;
if !alive {
*bytes = bytes.saturating_sub(e.size);
}
alive
});
}
/// Stores `val` (about `size` bytes) for `src`, reclaiming dropped sources and evicting
/// least-recently-used entries incrementally within the entry and byte caps.
pub(crate) fn insert(&mut self, key: &str, src: &Arc<Vec<u8>>, val: T, size: usize) {
if size > CACHE_BYTES {
return;
@@ -41,10 +75,22 @@ impl<T: Clone> MediaCache<T> {
self.bytes = self.bytes.saturating_sub(old.size);
}
if self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
self.map.clear();
self.bytes = 0;
self.prune_dead();
}
self.map.insert(key.to_string(), Entry { src: Arc::downgrade(src), val, size });
while self.map.len() >= CACHE_ENTRIES || self.bytes.saturating_add(size) > CACHE_BYTES {
let Some(oldest) = self.map.iter().min_by_key(|(_, e)| e.stamp).map(|(k, _)| k.clone()) else {
break;
};
if let Some(removed) = self.map.remove(&oldest) {
self.bytes = self.bytes.saturating_sub(removed.size);
}
}
if self.map.capacity() > self.map.len().saturating_mul(4).max(32) {
self.map.shrink_to(self.map.len().saturating_mul(2).max(16));
}
self.clock = self.clock.wrapping_add(1);
let stamp = self.clock;
self.map.insert(key.to_string(), Entry { src: Arc::downgrade(src), val, size, stamp });
self.bytes = self.bytes.saturating_add(size);
}
}
@@ -58,12 +104,12 @@ pub(crate) type Decoded = Result<Arc<Pixmap>, Refusal>;
fn images() -> &'static Mutex<MediaCache<Decoded>> {
static C: std::sync::OnceLock<Mutex<MediaCache<Decoded>>> = std::sync::OnceLock::new();
C.get_or_init(|| Mutex::new(MediaCache { map: HashMap::new(), bytes: 0 }))
C.get_or_init(|| Mutex::new(MediaCache::default()))
}
fn vectors() -> &'static Mutex<MediaCache<Option<Arc<Vector>>>> {
static C: std::sync::OnceLock<Mutex<MediaCache<Option<Arc<Vector>>>>> = std::sync::OnceLock::new();
C.get_or_init(|| Mutex::new(MediaCache { map: HashMap::new(), bytes: 0 }))
C.get_or_init(|| Mutex::new(MediaCache::default()))
}
/// Largest side (pixels) a document picture may decode to: what a `Pixmap` can hold (`u16`
+2 -2
View File
@@ -572,7 +572,7 @@ fn pictures_too_large_for_the_cache_are_kept_smaller() {
assert!(bytes <= CACHE_BYTES / 2, "{} x {}", small.width(), small.height());
assert!(small.width() >= 3000 && small.width() == small.height(), "aspect kept");
assert!(small.data().iter().all(|p| (p.r, p.g, p.b, p.a) == (40, 80, 120, 200)), "flat stays flat");
let mut cache = MediaCache { map: HashMap::new(), bytes: 0 };
let mut cache = MediaCache::default();
// A source file larger than the whole cache (an uncompressed BMP, say) doesn't count against it.
let src = Arc::new(vec![0u8; CACHE_BYTES + 1]);
cache.insert("big", &src, Some(Arc::new(small)), bytes);
@@ -1237,7 +1237,7 @@ fn heavy_geometry_still_leaves_the_bitmaps_a_cacheable_size() {
assert!(size + geometry <= CACHE_BYTES, "{size} bytes");
// The shrunk picture is accepted by the cache and hit again.
let src = Arc::new(vec![0u8; 1]);
let mut c: MediaCache<u8> = MediaCache { map: Default::default(), bytes: 0 };
let mut c: MediaCache<u8> = MediaCache::default();
c.insert("heavy", &src, 7, size + geometry);
assert_eq!(c.get("heavy", &src), Some(7));
// Just under and just over the eighth: both shrink the bitmap to a positive size, none to nothing.