Skip to main content

nsh_core/
image.rs

1//! Image bytes that are in memory rather than in a file or behind a URL: a
2//! `data:` URI's, decoded once, and the blob a `blob:` URL names
3//! (`URL.createObjectURL`), which the JS VM hands over natively.
4//!
5//! The core decodes a `data:` source when it is set
6//! ([`ImageSource::inline`](crate::ImageSource)) and names it by a short key
7//! (`data:<type>;nsh-key=<digest>`), so caches keyed by URI hash a few
8//! dozen bytes rather than the whole URI, and the shadow tree keeps the bytes
9//! once rather than their text too. The bytes travel with the source
10//! ([`ImageSource::data`](crate::ImageSource)) to the platforms, which decode
11//! them as they do a download's. The backends that cannot take the source
12//! itself (Android's Java loader, the browser's `<img>`) look the bytes up by
13//! URI in an [`InlineImages`].
14//!
15//! Downloaded images are kept on disk by a [`DiskCache`] (native backends:
16//! `cache.rs` has the policy and the format). The native backends load
17//! through one [`loader`] (reads, downloads, decodes, the encoded bytes in
18//! memory) and keep what they decode in [`Images`] at display size, in one
19//! [`budget`] per process with leases on what views show ([`MemoryCache`]):
20//! `docs/dev/images.md`.
21
22use std::{
23    fmt,
24    ops::Deref,
25    path::PathBuf,
26    sync::{Arc, Weak},
27};
28
29use rustc_hash::FxHashMap;
30
31#[cfg(not(target_arch = "wasm32"))]
32#[cfg(feature = "animation")]
33pub mod animation;
34#[cfg(not(target_arch = "wasm32"))]
35mod cache;
36#[cfg(not(target_arch = "wasm32"))]
37pub use cache::{CacheHeaders, DEFAULT_DISK_CACHE_SIZE, DiskCache, Fetched, Lookup, Validators};
38#[cfg(not(target_arch = "wasm32"))]
39mod decoded;
40#[cfg(not(target_arch = "wasm32"))]
41pub mod loader;
42mod memory;
43mod natural;
44#[cfg(not(target_arch = "wasm32"))]
45pub use decoded::{Decoded, Decoder, Done, Frames, Images, Key, Request, Target, Want};
46pub use memory::{Budget, Lease, MemoryCache, bucket, budget, default_budget, wanted};
47pub use natural::Natural;
48
49/// Where a surface's bundled (`asset:/…`) files are.
50///
51/// Of every target, apart from [`loader`], which the web leaves out: a
52/// [`System`](crate::element::System) names where they are anywhere, and
53/// the loader reads them where there are files.
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub enum AssetBase {
56    /// Served over HTTP (the dev server): `http://host:port/assets/`.
57    Http(String),
58    /// A directory on disk.
59    Directory(PathBuf),
60    /// Directories on disk, looked in in order: a file is the first
61    /// directory's that has it (the app's own files, then an embedding
62    /// app's, say).
63    Directories(Vec<PathBuf>),
64}
65
66type Bytes = dyn AsRef<[u8]> + Send + Sync;
67
68/// The bytes of an in-memory image, shared: cloning one copies no bytes.
69/// Two are equal when they share their bytes (no byte is compared).
70#[derive(Clone)]
71pub struct ImageData {
72    bytes: Arc<Bytes>,
73    /// Set when the image is a pixel buffer ([`Self::rgba`]): then
74    /// [`Self::bytes`] is its PNG, encoded on first use.
75    rgba: Option<Arc<Rgba>>,
76}
77
78impl ImageData {
79    /// Image bytes held in `bytes` (a `Vec<u8>`, an `Arc<[u8]>`, ...), not
80    /// copied.
81    pub fn new(bytes: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
82        Self {
83            bytes: Arc::new(bytes),
84            rgba: None,
85        }
86    }
87
88    /// An image of `width` × `height` pixels held in `pixels`, not copied:
89    /// straight (not premultiplied) 8-bit RGBA, rows top to bottom with no
90    /// padding. The backends that draw pixels take them as they are; the
91    /// others get them as a PNG ([`Self::bytes`]).
92    ///
93    /// # Panics
94    ///
95    /// When `pixels` is not `width * height * 4` bytes long, or a side is 0.
96    pub(crate) fn from_rgba(
97        width: u32,
98        height: u32,
99        pixels: impl AsRef<[u8]> + Send + Sync + 'static,
100    ) -> Self {
101        let len = pixels.as_ref().len();
102        assert!(
103            width > 0 && height > 0 && len as u64 == u64::from(width) * u64::from(height) * 4,
104            "an RGBA image of {width}x{height} pixels takes {} bytes, not {len}",
105            u64::from(width) * u64::from(height) * 4
106        );
107        let rgba = Arc::new(Rgba {
108            width,
109            height,
110            pixels: Box::new(pixels),
111            png: std::sync::OnceLock::new(),
112        });
113        Self {
114            bytes: rgba.clone(),
115            rgba: Some(rgba),
116        }
117    }
118
119    /// The bytes: a pixel buffer's ([`Self::rgba`]) encoded as a PNG the
120    /// first time they are asked for.
121    pub fn bytes(&self) -> &[u8] {
122        (*self.bytes).as_ref()
123    }
124
125    /// The width, height and straight RGBA pixels of a pixel buffer, which
126    /// a backend that draws pixels takes without decoding [`Self::bytes`].
127    pub fn rgba(&self) -> Option<(u32, u32, &[u8])> {
128        self.rgba
129            .as_deref()
130            .map(|r| (r.width, r.height, (*r.pixels).as_ref()))
131    }
132
133    fn downgrade(&self) -> Weak<Bytes> {
134        Arc::downgrade(&self.bytes)
135    }
136}
137
138/// A pixel buffer, and the PNG it is to the backends that load encoded
139/// images only (iOS, Android, the browser).
140struct Rgba {
141    width: u32,
142    height: u32,
143    pixels: Box<Bytes>,
144    png: std::sync::OnceLock<Vec<u8>>,
145}
146
147impl AsRef<[u8]> for Rgba {
148    fn as_ref(&self) -> &[u8] {
149        self.png
150            .get_or_init(|| stored_png(self.width, self.height, (*self.pixels).as_ref()))
151    }
152}
153
154/// `rgba` (straight, `width * height * 4` bytes) as an uncompressed PNG:
155/// no compression to wait for, a copy and two checksums.
156fn stored_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
157    fn crc32(parts: &[&[u8]]) -> u32 {
158        static TABLE: std::sync::LazyLock<[u32; 256]> = std::sync::LazyLock::new(|| {
159            std::array::from_fn(|n| {
160                (0..8).fold(n as u32, |c, _| {
161                    if c & 1 == 1 {
162                        0xedb8_8320 ^ (c >> 1)
163                    } else {
164                        c >> 1
165                    }
166                })
167            })
168        });
169        !parts.iter().flat_map(|p| p.iter()).fold(!0u32, |c, &b| {
170            TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8)
171        })
172    }
173    fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
174        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
175        out.extend_from_slice(kind);
176        out.extend_from_slice(data);
177        out.extend_from_slice(&crc32(&[kind, data]).to_be_bytes());
178    }
179    let row = width as usize * 4;
180    // Each row is a filter byte (0: none) and its pixels.
181    let raw_len = (row + 1) * height as usize;
182    let mut zlib = Vec::with_capacity(raw_len + raw_len / 0xffff * 5 + 16);
183    zlib.extend_from_slice(&[0x78, 0x01]);
184    let (mut a, mut b) = (1u32, 0u32);
185    let mut raw = rgba
186        .chunks_exact(row)
187        .flat_map(|r| std::iter::once(&0u8).chain(r.iter()));
188    let mut left = raw_len;
189    while left > 0 {
190        let n = left.min(0xffff);
191        left -= n;
192        zlib.push(u8::from(left == 0));
193        zlib.extend_from_slice(&(n as u16).to_le_bytes());
194        zlib.extend_from_slice(&(!(n as u16)).to_le_bytes());
195        for &byte in raw.by_ref().take(n) {
196            zlib.push(byte);
197            a = (a + u32::from(byte)) % 65521;
198            b = (b + a) % 65521;
199        }
200    }
201    zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
202    let mut out = Vec::with_capacity(zlib.len() + 64);
203    out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
204    let mut ihdr = [0u8; 13];
205    ihdr[..4].copy_from_slice(&width.to_be_bytes());
206    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
207    ihdr[8..].copy_from_slice(&[8, 6, 0, 0, 0]);
208    chunk(&mut out, b"IHDR", &ihdr);
209    chunk(&mut out, b"IDAT", &zlib);
210    chunk(&mut out, b"IEND", &[]);
211    out
212}
213
214/// The short URI a pixel buffer goes by: unique to it, and of the form of a
215/// decoded `data:` URI's key, which an app cannot write itself
216/// ([`crate::ImageSource::inline`]). Every buffer is a new image: the
217/// caches drop what no view shows any more, as they do any image's.
218pub(crate) fn rgba_key() -> String {
219    use std::{
220        fmt::Write,
221        hash::BuildHasher,
222        sync::atomic::{AtomicU64, Ordering},
223    };
224    static NEXT: AtomicU64 = AtomicU64::new(0);
225    static SEED: std::sync::LazyLock<std::hash::RandomState> =
226        std::sync::LazyLock::new(std::hash::RandomState::new);
227    let n = NEXT.fetch_add(1, Ordering::Relaxed);
228    let mut key = String::from("data:image/png;nsh-key=");
229    let _ = write!(key, "{:016x}{n:016x}", SEED.hash_one(n));
230    key
231}
232
233impl Default for ImageData {
234    /// No bytes.
235    fn default() -> Self {
236        Self::new(Vec::new())
237    }
238}
239
240impl Deref for ImageData {
241    type Target = [u8];
242
243    fn deref(&self) -> &[u8] {
244        self.bytes()
245    }
246}
247
248impl AsRef<[u8]> for ImageData {
249    fn as_ref(&self) -> &[u8] {
250        self.bytes()
251    }
252}
253
254impl From<Vec<u8>> for ImageData {
255    fn from(bytes: Vec<u8>) -> Self {
256        Self::new(bytes)
257    }
258}
259
260impl PartialEq for ImageData {
261    fn eq(&self, other: &Self) -> bool {
262        std::ptr::addr_eq(Arc::as_ptr(&self.bytes), Arc::as_ptr(&other.bytes))
263    }
264}
265
266impl fmt::Debug for ImageData {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        match self.rgba() {
269            Some((w, h, _)) => write!(f, "ImageData({w}x{h} RGBA)"),
270            None => write!(f, "ImageData({} bytes)", self.bytes().len()),
271        }
272    }
273}
274
275/// The media type and bytes of a `data:` URI: base64 (standard or URL-safe,
276/// whitespace and padding ignored) or percent-encoded (`%xx` escapes
277/// decoded, invalid ones kept as they are).
278pub fn decode_data_uri(uri: &str) -> Result<(&str, Vec<u8>), String> {
279    let rest = uri.strip_prefix("data:").ok_or("not a data: URI")?;
280    let (meta, data) = rest.split_once(',').ok_or("malformed data: URI")?;
281    match meta.strip_suffix(";base64") {
282        Some(mime) => Ok((mime, base64(data)?)),
283        None => Ok((meta, percent_decode(data))),
284    }
285}
286
287/// The short URI a decoded `data:` source goes by: its type and a digest of
288/// its bytes, so equal URIs share their cache entries and loads. The
289/// platforms' caches are shared by every surface of a process, so the key
290/// is collision resistant (SHA-256, 128 bits of it): one app cannot make
291/// another's image show its bytes. It is the same in every run.
292pub(crate) fn data_key(mime: &str, bytes: &[u8]) -> String {
293    use std::fmt::Write;
294
295    use sha2::Digest;
296    let digest = sha2::Sha256::digest(bytes);
297    let mime = mime.split(';').next().unwrap_or_default();
298    let mut key = format!("data:{mime};nsh-key=");
299    for b in &digest[..16] {
300        let _ = write!(key, "{b:02x}");
301    }
302    key
303}
304
305fn base64(s: &str) -> Result<Vec<u8>, String> {
306    let value = |c: u8| match c {
307        b'A'..=b'Z' => Some(c - b'A'),
308        b'a'..=b'z' => Some(c - b'a' + 26),
309        b'0'..=b'9' => Some(c - b'0' + 52),
310        b'+' | b'-' => Some(62),
311        b'/' | b'_' => Some(63),
312        _ => None,
313    };
314    let mut out = Vec::with_capacity(s.len() / 4 * 3 + 2);
315    let (mut acc, mut bits) = (0u32, 0);
316    for c in s.bytes() {
317        if c == b'=' || c.is_ascii_whitespace() {
318            continue;
319        }
320        let v = value(c).ok_or("invalid base64 in a data: URI")?;
321        acc = (acc << 6) | u32::from(v);
322        bits += 6;
323        if bits >= 8 {
324            bits -= 8;
325            out.push((acc >> bits) as u8);
326        }
327    }
328    Ok(out)
329}
330
331fn percent_decode(s: &str) -> Vec<u8> {
332    let bytes = s.as_bytes();
333    let hex = |b: u8| (b as char).to_digit(16);
334    let mut out = Vec::with_capacity(bytes.len());
335    let mut i = 0;
336    while i < bytes.len() {
337        match (
338            bytes[i],
339            bytes.get(i + 1).and_then(|&b| hex(b)),
340            bytes.get(i + 2).and_then(|&b| hex(b)),
341        ) {
342            (b'%', Some(h), Some(l)) => {
343                out.push((h * 16 + l) as u8);
344                i += 3;
345            }
346            (b, _, _) => {
347                out.push(b);
348                i += 1;
349            }
350        }
351    }
352    out
353}
354
355/// The in-memory images a backend shows, by URI, for loaders that get the
356/// URI only (Android's Java loader, the browser's `<img>`). It holds no
357/// bytes: an entry lives as long as the core keeps a source with those
358/// bytes, so a source the app replaced (or a revoked `blob:` URL's view
359/// that went away) frees them.
360#[derive(Default)]
361pub struct InlineImages {
362    /// Every source's copy of a URI's bytes (sources decoded apart hold
363    /// equal bytes apart): the URI stays reachable while one lives.
364    map: FxHashMap<Arc<str>, Vec<Weak<Bytes>>>,
365}
366
367impl InlineImages {
368    /// Makes the bytes of `source` (when it has some) reachable by its URI;
369    /// true when the URI was not reachable before.
370    pub fn register(&mut self, source: &crate::ImageSource) -> bool {
371        let Some(data) = &source.data else {
372            return false;
373        };
374        let held = self.map.entry(source.uri.clone()).or_default();
375        let new = !held.iter().any(|w| w.strong_count() > 0);
376        let ptr = Arc::as_ptr(&data.bytes);
377        if !held.iter().any(|w| std::ptr::addr_eq(w.as_ptr(), ptr)) {
378            held.push(data.downgrade());
379        }
380        new
381    }
382
383    /// The bytes of `uri`, while a source the core keeps holds them.
384    pub fn get(&self, uri: &str) -> Option<ImageData> {
385        self.map
386            .get(uri)?
387            .iter()
388            .find_map(Weak::upgrade)
389            .map(|bytes| ImageData { bytes, rgba: None })
390    }
391
392    /// Forgets the URIs whose bytes no source keeps any more, and returns
393    /// them.
394    pub fn prune(&mut self) -> Vec<Arc<str>> {
395        let mut gone = Vec::new();
396        self.map.retain(|uri, held| {
397            held.retain(|w| w.strong_count() > 0);
398            if held.is_empty() {
399                gone.push(uri.clone());
400            }
401            !held.is_empty()
402        });
403        gone
404    }
405}
406
407/// `logo@2x.png` -> 2: the pixel density a file name declares (1 without).
408pub fn density(uri: &str) -> f32 {
409    let name = uri.rsplit(['/', '\\']).next().unwrap_or(uri);
410    let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
411    stem.rsplit_once('@')
412        .and_then(|(_, s)| s.strip_suffix('x'))
413        .and_then(|n| n.parse::<f32>().ok())
414        .filter(|n| *n > 0.0)
415        .unwrap_or(1.0)
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::ImageSource;
422
423    #[test]
424    fn decodes_base64_and_percent_encoded_uris() {
425        assert_eq!(
426            decode_data_uri("data:image/png;base64,aGk=").unwrap(),
427            ("image/png", b"hi".to_vec())
428        );
429        // URL-safe, whitespace, no padding.
430        assert_eq!(
431            decode_data_uri("data:;base64,_-8 \n").unwrap().1,
432            vec![0xff, 0xef]
433        );
434        assert_eq!(
435            decode_data_uri("data:image/svg+xml,%3Csvg%3E%zz").unwrap(),
436            ("image/svg+xml", b"<svg>%zz".to_vec())
437        );
438        assert!(decode_data_uri("data:nocomma").is_err());
439        assert!(decode_data_uri("data:;base64,a*b").is_err());
440        assert!(decode_data_uri("https://example.com/a.png").is_err());
441    }
442
443    #[test]
444    fn data_sources_are_decoded_once_under_a_short_key() {
445        let uri = format!("data:image/png;charset=x;base64,{}", "QUJD".repeat(1000));
446        let source = ImageSource {
447            uri: uri.as_str().into(),
448            ..ImageSource::default()
449        }
450        .inline();
451        let data = source.data.clone().unwrap();
452        assert_eq!(data.len(), 3000);
453        assert!(source.uri.starts_with("data:image/png;nsh-key="));
454        assert_eq!(source.uri.len(), "data:image/png;nsh-key=".len() + 32);
455        // The same URI gets the same key; other bytes another.
456        let again = ImageSource {
457            uri: uri.as_str().into(),
458            ..ImageSource::default()
459        }
460        .inline();
461        assert_eq!(again.uri, source.uri);
462        let other = ImageSource {
463            uri: "data:image/png;base64,QUJE".into(),
464            ..ImageSource::default()
465        }
466        .inline();
467        assert_ne!(other.uri, source.uri);
468        // A key the app writes itself names nothing: no cache knows it.
469        let forged = ImageSource {
470            uri: source.uri.clone(),
471            ..ImageSource::default()
472        }
473        .inline();
474        assert_eq!(&*forged.uri, "data:,");
475        assert!(forged.data.is_none());
476        // Other URIs are left as they are; bad data: URIs show nothing.
477        let remote = ImageSource {
478            uri: "https://x.org/a.png".into(),
479            ..ImageSource::default()
480        }
481        .inline();
482        assert_eq!(&*remote.uri, "https://x.org/a.png");
483        assert!(remote.data.is_none());
484        let bad = ImageSource {
485            uri: "data:nocomma".into(),
486            ..ImageSource::default()
487        }
488        .inline();
489        assert_eq!(&*bad.uri, "data:,");
490        assert!(bad.data.is_none());
491    }
492
493    #[test]
494    fn rgba_sources_keep_their_pixels_under_a_unique_key() {
495        let pixels: Arc<[u8]> = (0..3 * 2 * 4).map(|i| i as u8).collect();
496        let src = crate::element::ImageSrc::rgba(3, 2, pixels.clone());
497        let again = crate::element::ImageSrc::rgba(3, 2, pixels.clone());
498        // Each buffer is an image of its own, under a key an app cannot
499        // write itself.
500        assert_ne!(src.uri, again.uri);
501        assert!(src.uri.starts_with("data:image/png;nsh-key="));
502        assert_eq!(src.size, Some((3.0, 2.0)));
503        let sized = src.clone().size(crate::geometry::size_pt(1.5, 1.0));
504        assert_eq!(sized.size, Some((1.5, 1.0)));
505        assert_eq!(sized.uri, src.uri);
506        assert_eq!(sized.data, src.data);
507        let data = sized.data.clone().unwrap();
508        let (w, h, rgba) = data.rgba().unwrap();
509        assert_eq!((w, h), (3, 2));
510        assert!(std::ptr::eq(rgba, &*pixels));
511        assert_eq!(format!("{data:?}"), "ImageData(3x2 RGBA)");
512        let forged = ImageSource {
513            uri: src.uri.to_arc(),
514            ..ImageSource::default()
515        }
516        .inline();
517        assert_eq!(&*forged.uri, "data:,");
518        // The backends that load encoded images get a PNG.
519        assert_eq!(&data.bytes()[..8], b"\x89PNG\r\n\x1a\n");
520        assert_eq!(
521            crate::image::Natural::of(data.bytes()),
522            Some(crate::image::Natural::Pixels(3, 2))
523        );
524    }
525
526    #[test]
527    #[should_panic(expected = "takes 24 bytes, not 23")]
528    fn rgba_sources_check_their_length() {
529        crate::element::ImageSrc::rgba(3, 2, vec![0u8; 23]);
530    }
531
532    #[cfg(feature = "svg")]
533    #[test]
534    fn rgba_sources_encode_to_a_png_that_decodes_to_them() {
535        // Over one stored deflate block (65535 bytes).
536        let (w, h) = (130u32, 140u32);
537        let pixels: Vec<u8> = (0..w * h)
538            .flat_map(|i| [(i % 251) as u8, (i % 13) as u8, (i / 256) as u8, 255])
539            .collect();
540        let data = crate::ImageData::from_rgba(w, h, pixels.clone());
541        let png = resvg::tiny_skia::Pixmap::decode_png(data.bytes()).unwrap();
542        assert_eq!((png.width(), png.height()), (w, h));
543        assert_eq!(png.data(), &pixels[..]);
544    }
545
546    #[test]
547    fn inline_images_live_as_long_as_their_sources() {
548        let mut images = InlineImages::default();
549        let source = ImageSource {
550            uri: "blob:nsh://app/1".into(),
551            data: Some(ImageData::new(vec![1u8, 2, 3])),
552            ..ImageSource::default()
553        };
554        assert!(images.register(&source));
555        assert!(!images.register(&source.clone()));
556        assert_eq!(images.get("blob:nsh://app/1").unwrap().bytes(), &[1, 2, 3]);
557        assert!(images.prune().is_empty());
558        drop(source);
559        assert!(images.get("blob:nsh://app/1").is_none());
560        assert_eq!(images.prune(), vec![Arc::<str>::from("blob:nsh://app/1")]);
561        assert!(!images.register(&ImageSource {
562            uri: "https://x.org/a.png".into(),
563            ..ImageSource::default()
564        }));
565        // Sources decoded apart hold equal bytes apart: the URI stays while
566        // either lives.
567        let a = ImageSource::default().with_bytes("image/png", vec![7u8].into());
568        let b = ImageSource::default().with_bytes("image/png", vec![7u8].into());
569        assert_eq!(a.uri, b.uri);
570        assert!(images.register(&a));
571        assert!(!images.register(&b));
572        drop(a);
573        assert!(images.prune().is_empty());
574        assert_eq!(images.get(&b.uri).unwrap().bytes(), &[7]);
575    }
576}