Skip to main content

alpha2_engine/
frame_store.rs

1//! A cache of prepared source frames, keyed by source and time, bounded by count and bytes: what
2//! a player or an exporter renders from ([`FrameProvider`] for entries that are [`StoredFrame`]s).
3//!
4//! A frame is found only under the request time the host inserted or aliased it at, so the
5//! presented-at rule of [`FrameProvider::texture_for`] holds only for times the host stored.
6//!
7//! Every upload gets a generation number. Aliases share their target's generation, and a
8//! replaced entry is retired, still counted, until the host releases it or the budget evicts it.
9//!
10//! An export pins the frames its current output frame shows. The budget never evicts them, and
11//! an upload that would push the pinned set over budget is refused, so an oversized frame fails
12//! at once instead of evicting its own sources.
13
14use std::collections::HashMap;
15use std::collections::HashSet;
16use std::sync::Arc;
17
18use alpha2_media::SourceId;
19use alpha2_render::{CpuSource, PendingSourceWork, RenderCacheKey, SourceView};
20use alpha2_time::MediaTime;
21
22use crate::FrameProvider;
23
24/// A store entry the renderer can sample.
25pub trait StoredFrame {
26    /// The picture, for the renderer.
27    fn view(&self) -> SourceView<'_>;
28
29    /// Work that must run before the picture is read; `None` for a ready one.
30    fn pending_work(&self) -> Option<&PendingSourceWork> {
31        None
32    }
33}
34
35impl StoredFrame for CpuSource {
36    fn view(&self) -> SourceView<'_> {
37        SourceView::cpu(self)
38    }
39}
40
41impl<T: StoredFrame> FrameProvider for FrameStore<T> {
42    fn texture_for(&self, source: &SourceId, time: MediaTime) -> Option<SourceView<'_>> {
43        self.get(source.as_str(), time.ticks())
44            .map(StoredFrame::view)
45    }
46
47    /// Keyed by source and upload generation, since an upload's picture never changes.
48    fn source_key(&self, source: &SourceId, time: MediaTime) -> Option<RenderCacheKey> {
49        let generation = self.generation(source.as_str(), time.ticks())?;
50        let mut hash = std::hash::DefaultHasher::new();
51        std::hash::Hash::hash(&(source.as_str(), generation), &mut hash);
52        Some(RenderCacheKey::source(std::hash::Hasher::finish(&hash)))
53    }
54
55    fn pending_source_work(
56        &self,
57        source: &SourceId,
58        time: MediaTime,
59    ) -> Option<&PendingSourceWork> {
60        self.get(source.as_str(), time.ticks())
61            .and_then(StoredFrame::pending_work)
62    }
63}
64
65struct Entry<T> {
66    value: Arc<T>,
67    generation: u64,
68}
69
70impl<T> Entry<T> {
71    fn shared(&self) -> Self {
72        Self {
73            value: Arc::clone(&self.value),
74            generation: self.generation,
75        }
76    }
77}
78
79/// Most timestamped frame keys kept, aliases included.
80const MAX_VIDEO_FRAMES: usize = 512;
81/// Most time-independent images kept.
82const MAX_IMAGES: usize = 128;
83/// Most replaced entries kept for the host to release.
84const MAX_RETIRED: usize = 128;
85/// Default byte budget across live, image, and retired generations: 64 `Rgba16Float` frames at
86/// 1080p, 16 at 4K. The count limit alone would allow about 8.5 GB at 1080p.
87pub const DEFAULT_VIDEO_FRAME_BYTES: u64 = 1 << 30;
88
89/// An upload refused because the pinned working set would outgrow the byte budget
90/// ([`FrameStore::pin`]). The store is unchanged.
91#[derive(Clone, Copy, Debug, Eq, PartialEq)]
92pub struct WorkingSetOverBudget {
93    /// Bytes of the other pinned frames the store holds.
94    pub held: u64,
95    /// Bytes of the refused frame.
96    pub requested: u64,
97    /// The store's byte budget.
98    pub budget: u64,
99}
100
101impl WorkingSetOverBudget {
102    /// Minimum the working set needs: the pinned frames held plus this one.
103    #[must_use]
104    pub const fn needed(&self) -> u64 {
105        self.held.saturating_add(self.requested)
106    }
107}
108
109/// Timestamped video frames and explicitly registered, time-independent images.
110pub struct FrameStore<T> {
111    frames: HashMap<(String, i64), Entry<T>>,
112    images: HashMap<String, Entry<T>>,
113    retired: HashMap<u64, Entry<T>>,
114    /// Keys (source, time) of the pinned working set ([`Self::pin`]).
115    pinned_frames: HashSet<(String, i64)>,
116    /// Bytes of the working set the last [`Self::unpin`] released.
117    last_working_set: u64,
118    next_generation: u64,
119    size: fn(&T) -> u64,
120    video_byte_budget: u64,
121}
122
123impl<T> Default for FrameStore<T> {
124    fn default() -> Self {
125        Self::sized(|_| 0, u64::MAX)
126    }
127}
128
129impl<T> FrameStore<T> {
130    /// A store that measures each value with `size` and keeps at most `video_byte_budget` bytes.
131    ///
132    /// The budget counts every retained generation once, retired entries and images included.
133    /// Eviction releases only cache ownership; submitted work owns its GPU resources.
134    ///
135    /// A newly inserted frame may exceed the budget alone so it can be presented, in which case
136    /// no other unpinned generation is kept. A pinned working set may not ([`Self::pin`]).
137    #[must_use]
138    pub fn sized(size: fn(&T) -> u64, video_byte_budget: u64) -> Self {
139        Self {
140            frames: HashMap::new(),
141            images: HashMap::new(),
142            retired: HashMap::new(),
143            pinned_frames: HashSet::new(),
144            last_working_set: 0,
145            next_generation: 1,
146            size,
147            video_byte_budget,
148        }
149    }
150
151    /// Changes the byte budget, evicting oldest generations at once to fit.
152    pub fn set_video_byte_budget(&mut self, bytes: u64) {
153        self.video_byte_budget = bytes;
154        self.enforce_video_budget(None);
155    }
156
157    #[cfg(test)]
158    pub(crate) fn video_bytes(&self) -> u64 {
159        let mut counted = HashSet::new();
160        self.frames
161            .values()
162            .filter(|entry| counted.insert(entry.generation))
163            .fold(0_u64, |total, entry| {
164                total.saturating_add((self.size)(entry.value.as_ref()))
165            })
166    }
167
168    /// Pins the working set of the frame being made: the frames at `keys` (source and time) and
169    /// each source's image, which answers a time with no exact frame. Replaces earlier pins.
170    ///
171    /// Until [`Self::unpin`], the budget never evicts a pinned generation, and an upload or
172    /// alias that would push the pinned set over budget is refused. A one-frame working set may
173    /// exceed the budget, as any newest upload may.
174    pub fn pin(&mut self, keys: impl IntoIterator<Item = (String, i64)>) {
175        self.pinned_frames.clear();
176        self.pinned_frames.extend(keys);
177    }
178
179    /// Drops the pins, leaving every generation to the budget again.
180    pub fn unpin(&mut self) {
181        self.last_working_set = self.generation_bytes(&self.pinned_generations(None, None));
182        self.pinned_frames.clear();
183    }
184
185    /// Bytes of the working set the last [`Self::unpin`] released: what one output frame needed,
186    /// which a host lowering the budget under memory pressure keeps room for.
187    #[must_use]
188    pub const fn last_working_set_bytes(&self) -> u64 {
189        self.last_working_set
190    }
191
192    /// The generations the pinned working set looks up, as [`Self::get`] would answer, except
193    /// for what an upload is about to replace (the frame at `frame` or the image of `image`).
194    fn pinned_generations(
195        &self,
196        frame: Option<&(String, i64)>,
197        image: Option<&str>,
198    ) -> HashSet<u64> {
199        self.pinned_frames
200            .iter()
201            .filter(|key| Some(*key) != frame)
202            .filter_map(|key| match self.frames.get(key) {
203                Some(entry) => Some(entry.generation),
204                None if Some(key.0.as_str()) == image => None,
205                None => self.images.get(&key.0).map(|entry| entry.generation),
206            })
207            .collect()
208    }
209
210    /// Whether `source`'s image is pinned, because a pinned key of that source has no exact
211    /// frame.
212    fn image_pinned(&self, source: &str) -> bool {
213        self.pinned_frames
214            .iter()
215            .any(|key| key.0 == source && !self.frames.contains_key(key))
216    }
217
218    /// Bytes of the generations in `generations`, each counted once.
219    fn generation_bytes(&self, generations: &HashSet<u64>) -> u64 {
220        let mut counted = HashSet::new();
221        self.frames
222            .values()
223            .chain(self.images.values())
224            .filter(|entry| generations.contains(&entry.generation))
225            .filter(|entry| counted.insert(entry.generation))
226            .fold(0_u64, |total, entry| {
227                total.saturating_add((self.size)(entry.value.as_ref()))
228            })
229    }
230
231    /// Refuses `requested` bytes joining the pinned set when it and `others` would exceed the
232    /// budget, unless it is the working set's only frame or already one of `others`.
233    fn admit_pinned(
234        &self,
235        others: &HashSet<u64>,
236        generation: Option<u64>,
237        requested: u64,
238    ) -> Result<(), WorkingSetOverBudget> {
239        if others.is_empty() || generation.is_some_and(|generation| others.contains(&generation)) {
240            return Ok(());
241        }
242        let held = self.generation_bytes(others);
243        if held.saturating_add(requested) > self.video_byte_budget {
244            return Err(WorkingSetOverBudget {
245                held,
246                requested,
247                budget: self.video_byte_budget,
248            });
249        }
250        Ok(())
251    }
252
253    /// Evicts whole generations, aliases included, oldest first and never pinned ones. Only the
254    /// newly inserted generation and the pinned set can exceed the budget.
255    fn enforce_video_budget(&mut self, keep: Option<u64>) {
256        let pinned = self.pinned_generations(None, None);
257        while self.retained_bytes(self.size) > self.video_byte_budget {
258            let oldest = self
259                .generations()
260                .into_iter()
261                .filter(|generation| Some(*generation) != keep && !pinned.contains(generation))
262                .min();
263            let Some(oldest) = oldest else {
264                break;
265            };
266            self.release_generation(oldest);
267        }
268    }
269    fn entry(&mut self, value: T) -> Entry<T> {
270        let generation = self.next_generation;
271        self.next_generation = generation.checked_add(1).unwrap_or(1);
272        if self.next_generation == 1 {
273            self.frames.clear();
274            self.images.clear();
275            self.retired.clear();
276        }
277        Entry {
278            value: Arc::new(value),
279            generation,
280        }
281    }
282
283    /// Stores a frame at `key` and returns its new generation. A frame already at `key` is
284    /// retired, and older unpinned generations are evicted to fit the budget.
285    ///
286    /// # Errors
287    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
288    /// store unchanged.
289    pub fn insert(&mut self, key: (String, i64), value: T) -> Result<u64, WorkingSetOverBudget> {
290        if self.pinned_frames.contains(&key) {
291            let others = self.pinned_generations(Some(&key), None);
292            self.admit_pinned(&others, None, (self.size)(&value))?;
293        }
294        if !self.frames.contains_key(&key) && self.frames.len() >= MAX_VIDEO_FRAMES {
295            self.evict_oldest_frame();
296        }
297        let entry = self.entry(value);
298        let generation = entry.generation;
299        if let Some(old) = self.frames.insert(key, entry) {
300            self.retire(old);
301        }
302        self.enforce_video_budget(Some(generation));
303        Ok(generation)
304    }
305
306    /// Makes `requested` answer with the frame at `existing`, sharing its generation and bytes.
307    /// Returns `false` when `existing` holds no frame.
308    ///
309    /// # Errors
310    /// Refuses an alias into a pinned key that would push the working set over budget, keeping
311    /// the store unchanged.
312    pub fn alias(
313        &mut self,
314        existing: &(String, i64),
315        requested: (String, i64),
316    ) -> Result<bool, WorkingSetOverBudget> {
317        let Some(entry) = self.frames.get(existing).map(Entry::shared) else {
318            return Ok(false);
319        };
320        if existing == &requested {
321            return Ok(true);
322        }
323        let generation = entry.generation;
324        if self.pinned_frames.contains(&requested) {
325            let others = self.pinned_generations(Some(&requested), None);
326            self.admit_pinned(&others, Some(generation), (self.size)(entry.value.as_ref()))?;
327        }
328        if !self.frames.contains_key(&requested) && self.frames.len() >= MAX_VIDEO_FRAMES {
329            self.evict_oldest_frame();
330        }
331        if let Some(old) = self.frames.insert(requested, entry)
332            && old.generation != generation
333        {
334            self.retire(old);
335        }
336        Ok(true)
337    }
338
339    /// Stores `source`'s time-independent image and returns its new generation; the image
340    /// answers every time with no exact frame.
341    ///
342    /// # Errors
343    /// Refuses a pinned source's image that would push the working set over budget, keeping the
344    /// store unchanged.
345    pub fn insert_image(&mut self, source: String, value: T) -> Result<u64, WorkingSetOverBudget> {
346        if self.image_pinned(&source) {
347            let others = self.pinned_generations(None, Some(&source));
348            self.admit_pinned(&others, None, (self.size)(&value))?;
349        }
350        if !self.images.contains_key(&source) && self.images.len() >= MAX_IMAGES {
351            self.evict_oldest_image();
352        }
353        let entry = self.entry(value);
354        let generation = entry.generation;
355        if let Some(old) = self.images.insert(source, entry) {
356            self.retire(old);
357        }
358        self.enforce_video_budget(Some(generation));
359        Ok(generation)
360    }
361
362    /// Whether `source`'s image is still the upload `generation` names. The store evicts images
363    /// on its own, so a host checks before relying on an earlier upload.
364    #[must_use]
365    pub fn holds_image(&self, source: &str, generation: u64) -> bool {
366        self.images
367            .get(source)
368            .is_some_and(|entry| entry.generation == generation)
369    }
370
371    /// The frame stored at `source` and `time`, else the source's image.
372    #[must_use]
373    pub fn get(&self, source: &str, time: i64) -> Option<&T> {
374        self.lookup(source, time).map(|entry| entry.value.as_ref())
375    }
376
377    /// The upload generation `get` would answer from. A store never reuses generations.
378    #[must_use]
379    pub fn generation(&self, source: &str, time: i64) -> Option<u64> {
380        self.lookup(source, time).map(|entry| entry.generation)
381    }
382
383    fn lookup(&self, source: &str, time: i64) -> Option<&Entry<T>> {
384        self.frames
385            .get(&(source.to_owned(), time))
386            .or_else(|| self.images.get(source))
387    }
388
389    /// Drops the frame at `source` and `time`; returns whether there was one.
390    pub fn remove(&mut self, source: &str, time: i64) -> bool {
391        self.frames.remove(&(source.to_owned(), time)).is_some()
392    }
393
394    /// Generations held, retired ones included.
395    #[must_use]
396    pub fn len(&self) -> usize {
397        self.generations().len()
398    }
399
400    /// Whether nothing is held.
401    #[must_use]
402    pub fn is_empty(&self) -> bool {
403        self.len() == 0
404    }
405
406    /// Retired entries held for release.
407    #[must_use]
408    pub fn retired_len(&self) -> usize {
409        self.retired.len()
410    }
411
412    /// Bytes every generation holds, measured by `bytes`, each counted once.
413    pub fn retained_bytes(&self, bytes: impl Fn(&T) -> u64) -> u64 {
414        let mut counted = HashSet::new();
415        self.frames
416            .values()
417            .chain(self.images.values())
418            .chain(self.retired.values())
419            .filter(|entry| counted.insert(entry.generation))
420            .fold(0_u64, |total, entry| {
421                total.saturating_add(bytes(entry.value.as_ref()))
422            })
423    }
424
425    /// Drops every frame, alias, image, and retired entry of `generation`. Returns whether
426    /// anything was dropped.
427    pub fn release_generation(&mut self, generation: u64) -> bool {
428        let retired = self.retired.remove(&generation).is_some();
429        let before_frames = self.frames.len();
430        self.frames
431            .retain(|_, entry| entry.generation != generation);
432        let before_images = self.images.len();
433        self.images
434            .retain(|_, entry| entry.generation != generation);
435        retired || before_frames != self.frames.len() || before_images != self.images.len()
436    }
437
438    /// Drops everything.
439    pub fn clear(&mut self) {
440        self.frames.clear();
441        self.images.clear();
442        self.retired.clear();
443    }
444
445    /// Invalidates derived values everywhere, including aliases and retirees.
446    pub fn retain_values(&mut self, keep: impl Fn(&T) -> bool) {
447        self.frames.retain(|_, entry| keep(&entry.value));
448        self.images.retain(|_, entry| keep(&entry.value));
449        self.retired.retain(|_, entry| keep(&entry.value));
450    }
451
452    /// Keeps only the frames and images `keep` accepts, given their source. Retired entries
453    /// stay.
454    pub fn retain_entries(&mut self, keep: impl Fn(&str, &T) -> bool) {
455        self.frames
456            .retain(|(source, _), entry| keep(source, &entry.value));
457        self.images
458            .retain(|source, entry| keep(source, &entry.value));
459    }
460
461    /// Keeps only the frames and images of sources `keep` accepts. Retired entries stay until
462    /// released or evicted.
463    pub fn retain_sources(&mut self, keep: impl Fn(&str) -> bool) {
464        self.frames.retain(|(source, _), _| keep(source));
465        self.images.retain(|source, _| keep(source));
466    }
467
468    /// Drops one source's frames and image after its media changed. Retired entries stay until
469    /// released.
470    pub fn release_source(&mut self, source: &str) -> bool {
471        let before = self.frames.len() + self.images.len();
472        self.retain_sources(|kept| kept != source);
473        before != self.frames.len() + self.images.len()
474    }
475
476    /// Drops `source`'s frames before `before`, a time on that source's own timeline.
477    pub fn trim_before(&mut self, source: &str, before: i64) {
478        self.frames
479            .retain(|(kept, time), _| kept != source || *time >= before);
480    }
481
482    fn retire(&mut self, entry: Entry<T>) {
483        while self.retired.len() >= MAX_RETIRED {
484            let Some(oldest) = self.retired.keys().min().copied() else {
485                break;
486            };
487            self.retired.remove(&oldest);
488        }
489        self.retired.insert(entry.generation, entry);
490    }
491
492    fn generations(&self) -> HashSet<u64> {
493        self.frames
494            .values()
495            .chain(self.images.values())
496            .chain(self.retired.values())
497            .map(|entry| entry.generation)
498            .collect()
499    }
500
501    fn evict_oldest_frame(&mut self) {
502        let pinned = self.pinned_generations(None, None);
503        let key = self
504            .frames
505            .iter()
506            .filter(|(_, entry)| !pinned.contains(&entry.generation))
507            .min_by_key(|(_, entry)| entry.generation)
508            .map(|(key, _)| key.clone());
509        if let Some(key) = key {
510            self.frames.remove(&key);
511        }
512    }
513
514    fn evict_oldest_image(&mut self) {
515        let pinned = self.pinned_generations(None, None);
516        let key = self
517            .images
518            .iter()
519            .filter(|(_, entry)| !pinned.contains(&entry.generation))
520            .min_by_key(|(_, entry)| entry.generation)
521            .map(|(key, _)| key.clone());
522        if let Some(key) = key {
523            self.images.remove(&key);
524        }
525    }
526}
527
528#[cfg(test)]
529#[path = "frame_store_tests.rs"]
530mod tests;