vello_encoding/image_delta.rs
1// Copyright 2026 the Tilo Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Images that are another image changed in a few rects (Tilo patch).
5//!
6//! A web page's frame is a new image every time the page paints, though a
7//! blinking caret changes a few hundred of its millions of pixels. Whoever
8//! makes such a frame says which image it follows and where it differs
9//! ([`register_image_delta`]); an image cache that holds the earlier image
10//! hands its atlas slot to the new one and uploads only those rects. A cache
11//! that does not hold it (another renderer, an evicted slot) uploads the new
12//! image whole, as without a delta.
13
14use std::collections::VecDeque;
15use std::sync::{Arc, Mutex};
16
17/// Deltas kept, newest last: a few frames each of several pages.
18const KEPT: usize = 64;
19
20/// A rect of an image, in its pixels: x, y, width, height.
21pub type ImageRect = [u32; 4];
22
23struct Delta {
24 to: u64,
25 from: u64,
26 rects: Arc<[ImageRect]>,
27}
28
29static DELTAS: Mutex<VecDeque<Delta>> = Mutex::new(VecDeque::new());
30
31/// Say that the image whose blob id is `to` has the same size and format as
32/// the one whose blob id is `from` and the same pixels outside `rects`.
33pub fn register_image_delta(from: u64, to: u64, rects: &[ImageRect]) {
34 let mut deltas = DELTAS
35 .lock()
36 .unwrap_or_else(std::sync::PoisonError::into_inner);
37 deltas.retain(|delta| delta.to != to);
38 if deltas.len() >= KEPT {
39 deltas.pop_front();
40 }
41 deltas.push_back(Delta {
42 to,
43 from,
44 rects: rects.into(),
45 });
46}
47
48/// The image `to` follows and the rects where they differ, if known.
49pub fn image_delta(to: u64) -> Option<(u64, Arc<[ImageRect]>)> {
50 let deltas = DELTAS
51 .lock()
52 .unwrap_or_else(std::sync::PoisonError::into_inner);
53 deltas
54 .iter()
55 .rev()
56 .find(|delta| delta.to == to)
57 .map(|delta| (delta.from, delta.rects.clone()))
58}