Skip to main content

ultrafast_render/
images.rs

1//! Image resources: decoded off the render thread, uploaded once, converted
2//! to the working space once, then shared by every node that references them.
3
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::mpsc::{Receiver, channel};
7use std::time::SystemTime;
8use ultrafast_gpu::{Device, PixelFormat, Texture, TextureDesc};
9
10/// What a media file was when it was read (modified time and length): a
11/// different stamp later means it was rewritten.
12pub type FileStamp = (SystemTime, u64);
13
14/// The file's stamp now (None for a URL or a missing file).
15pub fn file_stamp(path: &Path) -> Option<FileStamp> {
16    if path.to_string_lossy().contains("://") {
17        return None;
18    }
19    let m = std::fs::metadata(path).ok()?;
20    Some((m.modified().ok()?, m.len()))
21}
22
23pub use ultrafast_geom::f32_to_f16;
24
25pub enum ImageState {
26    Loading(Receiver<Result<Decoded, String>>),
27    /// Decoded and uploaded as RGBA8; waiting for the working-space pass.
28    Uploaded(Texture),
29    Ready(Texture),
30    Failed(String),
31}
32
33pub struct Decoded {
34    pub width: u32,
35    pub height: u32,
36    pub rgba: Vec<u8>,
37    /// The RGBA8 pixels decoded straight into GPU-visible memory instead
38    /// (then `rgba` is empty): the render thread copies nothing.
39    pub staged: Option<ultrafast_gpu::Buffer>,
40    /// Already in its final format (LUTs: RGBA16F data); no prep pass.
41    pub final_format: Option<PixelFormat>,
42}
43
44/// Parses a `.cube` 3D LUT into an RGBA16F texture of N*N x N texels: blue
45/// slices side by side, red along x within a slice, green along y.
46pub fn parse_cube(text: &str) -> Result<Decoded, String> {
47    let mut n = 0usize;
48    let mut values: Vec<[f32; 3]> = Vec::new();
49    for line in text.lines() {
50        let line = line.trim();
51        if line.is_empty() || line.starts_with('#') || line.starts_with("TITLE") || line.starts_with("DOMAIN_") {
52            continue;
53        }
54        let mut it = line.split_whitespace();
55        match it.next().unwrap_or("") {
56            "LUT_3D_SIZE" => n = it.next().and_then(|v| v.parse().ok()).ok_or("bad LUT_3D_SIZE")?,
57            "LUT_1D_SIZE" => return Err("1D LUTs are not supported (use a 3D .cube)".into()),
58            _ => values.push(parse3(line.split_whitespace()).ok_or_else(|| format!("bad LUT line `{line}`"))?),
59        }
60    }
61    if n < 2 || values.len() != n * n * n {
62        return Err(format!("LUT has {} entries, expected {n}^3", values.len()));
63    }
64    let (w, h) = (n * n, n);
65    let mut rgba = Vec::with_capacity(w * h * 8);
66    // .cube order: red fastest, then green, then blue.
67    for g in 0..n {
68        for b in 0..n {
69            for r in 0..n {
70                let v = values[r + g * n + b * n * n];
71                for c in [v[0], v[1], v[2], 1.0] {
72                    rgba.extend(f32_to_f16(c).to_le_bytes());
73                }
74            }
75        }
76    }
77    Ok(Decoded {
78        width: w as u32,
79        height: h as u32,
80        rgba,
81        staged: None,
82        final_format: Some(PixelFormat::Rgba16Float),
83    })
84}
85
86fn parse3<'a>(mut it: impl Iterator<Item = &'a str>) -> Option<[f32; 3]> {
87    Some([
88        it.next()?.parse().ok()?,
89        it.next()?.parse().ok()?,
90        it.next()?.parse().ok()?,
91    ])
92}
93
94type Job = Box<dyn FnOnce() + Send>;
95
96/// Runs image decodes on a fixed pool of threads (all cores but two, which
97/// render and encode), in request order: a sequence's frames prefetched
98/// ahead decode in parallel without oversubscribing the CPU.
99fn decode_pool(job: Job) {
100    static POOL: std::sync::OnceLock<std::sync::Mutex<std::sync::mpsc::Sender<Job>>> = std::sync::OnceLock::new();
101    let tx = POOL.get_or_init(|| {
102        let (tx, rx) = channel::<Job>();
103        let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));
104        let n = std::thread::available_parallelism()
105            .map_or(4, |n| n.get())
106            .saturating_sub(2)
107            .max(2);
108        for i in 0..n {
109            let rx = rx.clone();
110            let _ = std::thread::Builder::new()
111                .name(format!("ultrafast-image-{i}"))
112                .spawn(move || {
113                    loop {
114                        let job = match rx.lock().unwrap().recv() {
115                            Ok(job) => job,
116                            Err(_) => return,
117                        };
118                        job();
119                    }
120                });
121        }
122        std::sync::Mutex::new(tx)
123    });
124    let _ = tx.lock().unwrap().send(job);
125}
126
127/// A still WebP through libwebp (SIMD; animated files and other formats
128/// return None and go through `image`), decoded straight into a
129/// GPU-visible buffer when `device` is given.
130fn decode_webp(path: &Path, device: Option<&Device>) -> Option<Decoded> {
131    if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("webp")) {
132        return None;
133    }
134    let data = std::fs::read(path).ok()?;
135    let (mut w, mut h) = (0, 0);
136    // SAFETY: libwebp reads `data` and writes at most `len` bytes into the
137    // destination, which nothing else uses yet.
138    unsafe {
139        if libwebp_sys::WebPGetInfo(data.as_ptr(), data.len(), &mut w, &mut h) == 0 || w <= 0 || h <= 0 {
140            return None;
141        }
142        let len = w as usize * h as usize * 4;
143        let decode = |dst: &mut [u8]| {
144            !libwebp_sys::WebPDecodeRGBAInto(data.as_ptr(), data.len(), dst.as_mut_ptr(), len, w * 4).is_null()
145        };
146        let (rgba, staged) = match device {
147            Some(device) => {
148                let buf = device.create_buffer(len, None);
149                if !decode(&mut buf.mapped()[..len]) {
150                    return None;
151                }
152                (Vec::new(), Some(buf))
153            }
154            None => {
155                let mut rgba = vec![0u8; len];
156                if !decode(&mut rgba) {
157                    return None;
158                }
159                (rgba, None)
160            }
161        };
162        Some(Decoded {
163            width: w as u32,
164            height: h as u32,
165            rgba,
166            staged,
167            final_format: None,
168        })
169    }
170}
171
172pub struct ImageCache {
173    entries: HashMap<String, ImageState>,
174    /// Last use (in `tick`s) of each entry, for LRU eviction.
175    used: HashMap<String, u64>,
176    tick: u64,
177    base_dir: PathBuf,
178    /// Requested ahead of need (the next frames of a sequence): decoded on
179    /// their own threads meanwhile, and not waited for until asked for.
180    ahead: std::collections::HashSet<String>,
181    /// Decoders write straight into GPU-visible buffers on this device.
182    device: Option<Device>,
183    /// Each entry's file as it was when it was read.
184    stamps: HashMap<String, Option<FileStamp>>,
185}
186
187/// Decoded images kept on the GPU; older ones are evicted (sequences would
188/// otherwise grow without bound).
189const MAX_IMAGES: usize = 96;
190
191impl ImageCache {
192    pub fn new() -> Self {
193        Self {
194            entries: HashMap::new(),
195            used: HashMap::new(),
196            tick: 0,
197            base_dir: PathBuf::from("."),
198            ahead: Default::default(),
199            device: None,
200            stamps: HashMap::new(),
201        }
202    }
203
204    /// Reads again the images whose files changed since they were read (a
205    /// sheet rebuilt, a frame re-rendered in place): their old copies are
206    /// dropped and they decode anew, as on first use. Returns how many; costs
207    /// a stat each.
208    pub fn drop_changed(&mut self) -> usize {
209        let changed: Vec<String> = self
210            .stamps
211            .iter()
212            .filter(|(src, was)| !src.contains("://") && file_stamp(&crate::media_path(&self.base_dir, src)) != **was)
213            .map(|(src, _)| src.clone())
214            .collect();
215        for src in &changed {
216            self.entries.remove(src);
217            self.used.remove(src);
218            self.ahead.remove(src);
219            self.stamps.remove(src);
220            self.request_now(src);
221        }
222        changed.len()
223    }
224
225    pub fn set_base_dir(&mut self, dir: &Path) {
226        self.base_dir = dir.to_path_buf();
227    }
228
229    /// Decode into buffers `device` reads (sparing the render thread the
230    /// upload copy).
231    pub fn set_device(&mut self, device: &Device) {
232        self.device = Some(device.clone());
233    }
234
235    /// Starts decoding `src` ahead of need (a sequence's coming frames).
236    pub fn prefetch(&mut self, src: &str) {
237        if !self.entries.contains_key(src) {
238            self.ahead.insert(src.to_string());
239            self.request_now(src);
240        }
241    }
242
243    /// Starts decoding `src` if it is not known yet; an exact render waits
244    /// for it.
245    pub fn request(&mut self, src: &str) {
246        self.ahead.remove(src);
247        self.request_now(src);
248    }
249
250    fn request_now(&mut self, src: &str) {
251        if self.entries.contains_key(src) {
252            return;
253        }
254        let path = crate::media_path(&self.base_dir, src);
255        self.stamps.insert(src.to_string(), file_stamp(&path));
256        let (tx, rx) = channel();
257        let device = self.device.clone();
258        decode_pool(Box::new(move || {
259            let is_cube = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("cube"));
260            let r = if is_cube {
261                std::fs::read_to_string(&path)
262                    .map_err(|e| format!("{}: {e}", path.display()))
263                    .and_then(|t| parse_cube(&t).map_err(|e| format!("{}: {e}", path.display())))
264            } else {
265                decode_webp(&path, device.as_ref()).map(Ok).unwrap_or_else(|| {
266                    image::open(&path)
267                        .map(|img| {
268                            let rgba = img.to_rgba8();
269                            Decoded {
270                                width: rgba.width(),
271                                height: rgba.height(),
272                                rgba: rgba.into_raw(),
273                                staged: None,
274                                final_format: None,
275                            }
276                        })
277                        .map_err(|e| format!("{}: {e}", path.display()))
278                })
279            };
280            let _ = tx.send(r);
281        }));
282        self.entries.insert(src.to_string(), ImageState::Loading(rx));
283    }
284
285    /// Advances loading images. Newly decoded images are uploaded (counted as
286    /// uploads); the returned textures still need the working-space pass,
287    /// which the caller encodes and then reports with `mark_ready`.
288    pub fn poll(&mut self, device: &Device, block: bool) -> Vec<(String, Texture)> {
289        let mut uploaded = Vec::new();
290        for (src, st) in self.entries.iter_mut() {
291            if let ImageState::Loading(rx) = st {
292                let r = if block && !self.ahead.contains(src) {
293                    rx.recv().ok()
294                } else {
295                    rx.try_recv().ok()
296                };
297                match r {
298                    None => {}
299                    Some(Ok(d)) => {
300                        let desc = TextureDesc {
301                            width: d.width,
302                            height: d.height,
303                            format: d.final_format.unwrap_or(PixelFormat::Rgba8Unorm),
304                            cpu_readable: false,
305                        };
306                        let tex = match &d.staged {
307                            Some(buf) => device.upload_texture_from(desc, buf),
308                            None => device.upload_texture(desc, &d.rgba),
309                        };
310                        if d.final_format.is_some() {
311                            *st = ImageState::Ready(tex);
312                        } else {
313                            uploaded.push((src.clone(), tex.clone()));
314                            *st = ImageState::Uploaded(tex);
315                        }
316                    }
317                    Some(Err(e)) => *st = ImageState::Failed(e),
318                }
319            }
320        }
321        uploaded
322    }
323
324    pub fn mark_ready(&mut self, src: &str, tex: Texture) {
325        self.entries.insert(src.to_string(), ImageState::Ready(tex));
326    }
327
328    pub fn get(&mut self, src: &str) -> Option<&ImageState> {
329        self.used.insert(src.to_string(), self.tick);
330        self.entries.get(src)
331    }
332
333    /// Advances the LRU clock and evicts the least recently used ready
334    /// images beyond the cap (never ones used in the last few frames, which
335    /// in-flight GPU work may still read).
336    pub fn end_frame(&mut self) {
337        self.tick += 1;
338        // Frames fetched ahead that were never asked for (a seek) become
339        // ordinary entries the LRU may drop.
340        if self.ahead.len() > 64 {
341            self.ahead.clear();
342        }
343        if self.entries.len() <= MAX_IMAGES {
344            return;
345        }
346        let mut ready: Vec<(u64, String)> = self
347            .entries
348            .iter()
349            .filter(|(_, s)| matches!(s, ImageState::Ready(_) | ImageState::Failed(_)))
350            .filter(|(k, _)| !self.ahead.contains(*k))
351            .map(|(k, _)| (self.used.get(k).copied().unwrap_or(0), k.clone()))
352            .filter(|(u, _)| *u + 4 < self.tick)
353            .collect();
354        ready.sort();
355        for (_, k) in ready.into_iter().take(self.entries.len() - MAX_IMAGES) {
356            self.entries.remove(&k);
357            self.used.remove(&k);
358            self.stamps.remove(&k);
359        }
360    }
361
362    /// Whether `src` is loading, loaded or failed (not dropped or never asked for).
363    pub fn is_known(&self, src: &str) -> bool {
364        self.entries.contains_key(src)
365    }
366
367    pub fn ready(&self, src: &str) -> Option<&Texture> {
368        match self.entries.get(src) {
369            Some(ImageState::Ready(t)) => Some(t),
370            _ => None,
371        }
372    }
373
374    /// GPU bytes of the images held.
375    pub fn bytes(&self) -> u64 {
376        self.entries
377            .values()
378            .filter_map(|s| match s {
379                ImageState::Ready(t) | ImageState::Uploaded(t) => Some(t.desc()),
380                _ => None,
381            })
382            .map(|d| d.width as u64 * d.height as u64 * d.format.bytes_per_pixel() as u64)
383            .sum()
384    }
385
386    pub fn loading(&self) -> usize {
387        self.entries
388            .values()
389            .filter(|s| matches!(s, ImageState::Loading(_) | ImageState::Uploaded(_)))
390            .count()
391    }
392}
393
394impl Default for ImageCache {
395    fn default() -> Self {
396        Self::new()
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn half_conversion() {
406        assert_eq!(f32_to_f16(1.0), 0x3c00);
407        assert_eq!(f32_to_f16(0.5), 0x3800);
408        assert_eq!(f32_to_f16(0.0), 0);
409        assert_eq!(f32_to_f16(-2.0), 0xc000);
410    }
411
412    #[test]
413    fn identity_cube_parses() {
414        let mut s = String::from("LUT_3D_SIZE 2\n");
415        for b in 0..2 {
416            for g in 0..2 {
417                for r in 0..2 {
418                    s += &format!("{r} {g} {b}\n");
419                }
420            }
421        }
422        let d = parse_cube(&s).unwrap();
423        assert_eq!((d.width, d.height), (4, 2));
424    }
425}