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::{Following, FollowingFrame, 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        Some(upload_key(source.as_str(), generation))
51    }
52
53    fn following_for(&self, source: &SourceId, time: MediaTime) -> Following<'_> {
54        let key = (source.as_str().to_owned(), time.ticks());
55        match self.following.get(&key) {
56            Some(Followed::Last) => Following::Last,
57            Some(Followed::Frame {
58                entry,
59                presented_at,
60                at,
61            }) => Following::Frame(FollowingFrame {
62                view: entry.value.view(),
63                key: Some(upload_key(source.as_str(), entry.generation)),
64                pending: entry.value.pending_work(),
65                presented_at: MediaTime(*presented_at),
66                at: MediaTime(*at),
67            }),
68            None if !self.frames.contains_key(&key) && self.images.contains_key(&key.0) => {
69                Following::Last
70            }
71            None => Following::Pending,
72        }
73    }
74
75    fn pending_source_work(
76        &self,
77        source: &SourceId,
78        time: MediaTime,
79    ) -> Option<&PendingSourceWork> {
80        self.get(source.as_str(), time.ticks())
81            .and_then(StoredFrame::pending_work)
82    }
83}
84
85fn upload_key(source: &str, generation: u64) -> RenderCacheKey {
86    let mut hash = std::hash::DefaultHasher::new();
87    std::hash::Hash::hash(&(source, generation), &mut hash);
88    RenderCacheKey::source(std::hash::Hasher::finish(&hash))
89}
90
91struct Entry<T> {
92    value: Arc<T>,
93    generation: u64,
94}
95
96enum Followed<T> {
97    Last,
98    Frame {
99        entry: Entry<T>,
100        presented_at: i64,
101        at: i64,
102    },
103}
104
105impl<T> Followed<T> {
106    const fn entry(&self) -> Option<&Entry<T>> {
107        match self {
108            Self::Last => None,
109            Self::Frame { entry, .. } => Some(entry),
110        }
111    }
112}
113
114/// Which of the two frames a key holds.
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
116pub enum KeptFrame {
117    /// The frame presented at the key's time.
118    Presented,
119    /// The frame after it.
120    Following,
121}
122
123/// The presentation times of a key's frame and of the frame after it, in ticks.
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub struct FramePair {
126    /// When the key's frame is presented.
127    pub presented_at: i64,
128    /// When the frame after it is presented.
129    pub at: i64,
130}
131
132impl<T> Entry<T> {
133    fn shared(&self) -> Self {
134        Self {
135            value: Arc::clone(&self.value),
136            generation: self.generation,
137        }
138    }
139}
140
141/// Most timestamped frame keys kept, aliases included.
142const MAX_VIDEO_FRAMES: usize = 512;
143/// Most time-independent images kept.
144const MAX_IMAGES: usize = 128;
145/// Most replaced entries kept for the host to release.
146const MAX_RETIRED: usize = 128;
147/// Default byte budget across live, image, and retired generations: 64 `Rgba16Float` frames at
148/// 1080p, 16 at 4K. The count limit alone would allow about 8.5 GB at 1080p.
149pub const DEFAULT_VIDEO_FRAME_BYTES: u64 = 1 << 30;
150
151/// An upload refused because the pinned working set would outgrow the byte budget
152/// ([`FrameStore::pin`]). The store is unchanged.
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub struct WorkingSetOverBudget {
155    /// Bytes of the other pinned frames the store holds.
156    pub held: u64,
157    /// Bytes of the refused frame.
158    pub requested: u64,
159    /// The store's byte budget.
160    pub budget: u64,
161}
162
163impl WorkingSetOverBudget {
164    /// Minimum the working set needs: the pinned frames held plus this one.
165    #[must_use]
166    pub const fn needed(&self) -> u64 {
167        self.held.saturating_add(self.requested)
168    }
169}
170
171/// Timestamped video frames and explicitly registered, time-independent images.
172pub struct FrameStore<T> {
173    frames: HashMap<(String, i64), Entry<T>>,
174    following: HashMap<(String, i64), Followed<T>>,
175    images: HashMap<String, Entry<T>>,
176    retired: HashMap<u64, Entry<T>>,
177    /// Keys (source, time) of the pinned working set ([`Self::pin`]).
178    pinned_frames: HashSet<(String, i64)>,
179    /// Bytes of the working set the last [`Self::unpin`] released.
180    last_working_set: u64,
181    next_generation: u64,
182    size: fn(&T) -> u64,
183    video_byte_budget: u64,
184}
185
186impl<T> Default for FrameStore<T> {
187    fn default() -> Self {
188        Self::sized(|_| 0, u64::MAX)
189    }
190}
191
192impl<T> FrameStore<T> {
193    /// A store that measures each value with `size` and keeps at most `video_byte_budget` bytes.
194    ///
195    /// The budget counts every retained generation once, retired entries and images included.
196    /// Eviction releases only cache ownership; submitted work owns its GPU resources.
197    ///
198    /// A newly inserted frame may exceed the budget alone so it can be presented, in which case
199    /// no other unpinned generation is kept. A pinned working set may not ([`Self::pin`]).
200    #[must_use]
201    pub fn sized(size: fn(&T) -> u64, video_byte_budget: u64) -> Self {
202        Self {
203            frames: HashMap::new(),
204            following: HashMap::new(),
205            images: HashMap::new(),
206            retired: HashMap::new(),
207            pinned_frames: HashSet::new(),
208            last_working_set: 0,
209            next_generation: 1,
210            size,
211            video_byte_budget,
212        }
213    }
214
215    /// Changes the byte budget, evicting oldest generations at once to fit.
216    pub fn set_video_byte_budget(&mut self, bytes: u64) {
217        self.video_byte_budget = bytes;
218        self.enforce_video_budget(None);
219    }
220
221    #[cfg(test)]
222    pub(crate) fn video_bytes(&self) -> u64 {
223        let mut counted = HashSet::new();
224        self.frames
225            .values()
226            .chain(self.following.values().filter_map(Followed::entry))
227            .filter(|entry| counted.insert(entry.generation))
228            .fold(0_u64, |total, entry| {
229                total.saturating_add((self.size)(entry.value.as_ref()))
230            })
231    }
232
233    /// Pins the working set of the frame being made: the frames at `keys` (source and time), the
234    /// frames after them the keys hold, and each source's image, which answers a time with no
235    /// exact frame. Replaces earlier pins.
236    ///
237    /// Until [`Self::unpin`], the budget never evicts a pinned generation, and an upload or
238    /// alias that would push the pinned set over budget is refused. A one-frame working set may
239    /// exceed the budget, as any newest upload may.
240    pub fn pin(&mut self, keys: impl IntoIterator<Item = (String, i64)>) {
241        self.pinned_frames.clear();
242        self.pinned_frames.extend(keys);
243    }
244
245    /// Drops the pins, leaving every generation to the budget again.
246    pub fn unpin(&mut self) {
247        self.last_working_set = self.generation_bytes(&self.pinned_generations(None, None));
248        self.pinned_frames.clear();
249    }
250
251    /// Bytes of the working set the last [`Self::unpin`] released: what one output frame needed,
252    /// which a host lowering the budget under memory pressure keeps room for.
253    #[must_use]
254    pub const fn last_working_set_bytes(&self) -> u64 {
255        self.last_working_set
256    }
257
258    /// The generations the pinned working set looks up, as [`Self::get`] would answer, except
259    /// for what an upload is about to replace (the frame at `frame` or the image of `image`).
260    fn pinned_generations(
261        &self,
262        frame: Option<&(String, i64)>,
263        image: Option<&str>,
264    ) -> HashSet<u64> {
265        let mut pinned: HashSet<u64> = self
266            .pinned_frames
267            .iter()
268            .filter(|key| Some(*key) != frame)
269            .filter_map(|key| match self.frames.get(key) {
270                Some(entry) => Some(entry.generation),
271                None if Some(key.0.as_str()) == image => None,
272                None => self.images.get(&key.0).map(|entry| entry.generation),
273            })
274            .collect();
275        if !self.following.is_empty() {
276            pinned.extend(
277                self.pinned_frames
278                    .iter()
279                    .filter_map(|key| self.following.get(key)?.entry())
280                    .map(|entry| entry.generation),
281            );
282        }
283        pinned
284    }
285
286    /// Whether `source`'s image is pinned, because a pinned key of that source has no exact
287    /// frame.
288    fn image_pinned(&self, source: &str) -> bool {
289        self.pinned_frames
290            .iter()
291            .any(|key| key.0 == source && !self.frames.contains_key(key))
292    }
293
294    /// Bytes of the generations in `generations`, each counted once.
295    fn generation_bytes(&self, generations: &HashSet<u64>) -> u64 {
296        let mut counted = HashSet::new();
297        self.frames
298            .values()
299            .chain(self.images.values())
300            .chain(self.following.values().filter_map(Followed::entry))
301            .filter(|entry| generations.contains(&entry.generation))
302            .filter(|entry| counted.insert(entry.generation))
303            .fold(0_u64, |total, entry| {
304                total.saturating_add((self.size)(entry.value.as_ref()))
305            })
306    }
307
308    /// Refuses `requested` bytes joining the pinned set when it and `others` would exceed the
309    /// budget, unless it is the working set's only frame or already one of `others`.
310    fn admit_pinned(
311        &self,
312        others: &HashSet<u64>,
313        generation: Option<u64>,
314        requested: u64,
315    ) -> Result<(), WorkingSetOverBudget> {
316        if others.is_empty() || generation.is_some_and(|generation| others.contains(&generation)) {
317            return Ok(());
318        }
319        let held = self.generation_bytes(others);
320        if held.saturating_add(requested) > self.video_byte_budget {
321            return Err(WorkingSetOverBudget {
322                held,
323                requested,
324                budget: self.video_byte_budget,
325            });
326        }
327        Ok(())
328    }
329
330    /// Evicts whole generations, aliases included, oldest first and never pinned ones. Only the
331    /// newly inserted generation and the pinned set can exceed the budget.
332    fn enforce_video_budget(&mut self, keep: Option<u64>) {
333        let pinned = self.pinned_generations(None, None);
334        while self.retained_bytes(self.size) > self.video_byte_budget {
335            let oldest = self
336                .generations()
337                .into_iter()
338                .filter(|generation| Some(*generation) != keep && !pinned.contains(generation))
339                .min();
340            let Some(oldest) = oldest else {
341                break;
342            };
343            self.release_generation(oldest);
344        }
345    }
346    fn entry(&mut self, value: T) -> Entry<T> {
347        let generation = self.next_generation;
348        self.next_generation = generation.checked_add(1).unwrap_or(1);
349        if self.next_generation == 1 {
350            self.clear();
351        }
352        Entry {
353            value: Arc::new(value),
354            generation,
355        }
356    }
357
358    /// Stores a frame at `key` and returns its new generation. A frame already at `key` is
359    /// retired with the frame after it the key held, and older unpinned generations are evicted
360    /// to fit the budget.
361    ///
362    /// # Errors
363    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
364    /// store unchanged.
365    pub fn insert(&mut self, key: (String, i64), value: T) -> Result<u64, WorkingSetOverBudget> {
366        if self.pinned_frames.contains(&key) {
367            let others = self.pinned_generations(Some(&key), None);
368            self.admit_pinned(&others, None, (self.size)(&value))?;
369        }
370        if !self.frames.contains_key(&key) && self.frames.len() >= MAX_VIDEO_FRAMES {
371            self.evict_oldest_frame();
372        }
373        let entry = self.entry(value);
374        let generation = entry.generation;
375        self.retire_following(&key);
376        if let Some(old) = self.frames.insert(key, entry) {
377            self.retire(old);
378        }
379        self.enforce_video_budget(Some(generation));
380        Ok(generation)
381    }
382
383    fn retire_following(&mut self, key: &(String, i64)) {
384        if self.following.is_empty() {
385            return;
386        }
387        if let Some(Followed::Frame { entry, .. }) = self.following.remove(key) {
388            self.retire(entry);
389        }
390    }
391
392    /// Stores the frame after the one at `key`, with both frames' presentation times, and
393    /// returns its new generation; `None`, storing nothing, when `key` holds no frame. The frame
394    /// is pinned with its key and dropped when the key's frame is replaced or dropped.
395    ///
396    /// # Errors
397    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
398    /// store unchanged.
399    pub fn insert_following(
400        &mut self,
401        key: (String, i64),
402        value: T,
403        times: FramePair,
404    ) -> Result<Option<u64>, WorkingSetOverBudget> {
405        if !self.frames.contains_key(&key) {
406            return Ok(None);
407        }
408        if self.pinned_frames.contains(&key) {
409            let others = self.pinned_generations(None, None);
410            self.admit_pinned(&others, None, (self.size)(&value))?;
411        }
412        let entry = self.entry(value);
413        let generation = entry.generation;
414        self.follow(key, entry, times);
415        self.enforce_video_budget(Some(generation));
416        Ok(Some(generation))
417    }
418
419    /// Makes the frame after the one at `requested` the frame `existing` holds as `kept`, sharing
420    /// its generation and bytes. Returns `false`, changing nothing, when either key holds no
421    /// such frame.
422    ///
423    /// # Errors
424    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
425    /// store unchanged.
426    pub fn alias_following(
427        &mut self,
428        existing: (&(String, i64), KeptFrame),
429        requested: (String, i64),
430        times: FramePair,
431    ) -> Result<bool, WorkingSetOverBudget> {
432        let Some(entry) = self.kept(existing.0, existing.1).map(Entry::shared) else {
433            return Ok(false);
434        };
435        if !self.frames.contains_key(&requested) {
436            return Ok(false);
437        }
438        if self.pinned_frames.contains(&requested) {
439            let others = self.pinned_generations(None, None);
440            self.admit_pinned(
441                &others,
442                Some(entry.generation),
443                (self.size)(entry.value.as_ref()),
444            )?;
445        }
446        self.follow(requested, entry, times);
447        Ok(true)
448    }
449
450    /// Records that no frame follows the one at `key`: it is its source's last, or the host
451    /// cannot name the next. Returns `false`, changing nothing, when `key` holds no frame.
452    pub fn set_last(&mut self, key: (String, i64)) -> bool {
453        if !self.frames.contains_key(&key) {
454            return false;
455        }
456        if let Some(Followed::Frame { entry, .. }) = self.following.insert(key, Followed::Last) {
457            self.retire(entry);
458        }
459        true
460    }
461
462    /// Whether `key` holds the frame after its own, or the record that there is none.
463    #[must_use]
464    pub fn follows(&self, source: &str, time: i64) -> bool {
465        !self.following.is_empty() && self.following.contains_key(&(source.to_owned(), time))
466    }
467
468    /// A key of `source` that keeps the frame presented at `pts` ticks and which of its two frames
469    /// that is. Only keys holding the frame after their own are looked at.
470    #[must_use]
471    pub fn kept_at(&self, source: &str, pts: i64) -> Option<((String, i64), KeptFrame)> {
472        self.following.iter().find_map(|(key, followed)| {
473            let Followed::Frame {
474                presented_at, at, ..
475            } = followed
476            else {
477                return None;
478            };
479            let kept = if *presented_at == pts {
480                KeptFrame::Presented
481            } else if *at == pts {
482                KeptFrame::Following
483            } else {
484                return None;
485            };
486            (key.0 == source).then(|| (key.clone(), kept))
487        })
488    }
489
490    fn follow(&mut self, key: (String, i64), entry: Entry<T>, times: FramePair) {
491        let generation = entry.generation;
492        let old = self.following.insert(
493            key,
494            Followed::Frame {
495                entry,
496                presented_at: times.presented_at,
497                at: times.at,
498            },
499        );
500        if let Some(Followed::Frame { entry: old, .. }) = old
501            && old.generation != generation
502        {
503            self.retire(old);
504        }
505    }
506
507    fn kept(&self, key: &(String, i64), kept: KeptFrame) -> Option<&Entry<T>> {
508        match kept {
509            KeptFrame::Presented => self.frames.get(key),
510            KeptFrame::Following => self.following.get(key)?.entry(),
511        }
512    }
513
514    /// Makes `requested` answer with the frame `existing` holds as `kept`, as [`Self::alias`]
515    /// does for a presented frame.
516    ///
517    /// # Errors
518    /// As [`Self::alias`].
519    pub fn alias_kept(
520        &mut self,
521        existing: (&(String, i64), KeptFrame),
522        requested: (String, i64),
523    ) -> Result<bool, WorkingSetOverBudget> {
524        if existing.1 == KeptFrame::Presented {
525            return self.alias(existing.0, requested);
526        }
527        let Some(entry) = self.kept(existing.0, existing.1).map(Entry::shared) else {
528            return Ok(false);
529        };
530        self.share(entry, requested)
531    }
532
533    /// Makes `requested` answer with the frame at `existing`, sharing its generation and bytes.
534    /// Returns `false` when `existing` holds no frame.
535    ///
536    /// # Errors
537    /// Refuses an alias into a pinned key that would push the working set over budget, keeping
538    /// the store unchanged.
539    pub fn alias(
540        &mut self,
541        existing: &(String, i64),
542        requested: (String, i64),
543    ) -> Result<bool, WorkingSetOverBudget> {
544        let Some(entry) = self.frames.get(existing).map(Entry::shared) else {
545            return Ok(false);
546        };
547        if existing == &requested {
548            return Ok(true);
549        }
550        self.share(entry, requested)
551    }
552
553    fn share(
554        &mut self,
555        entry: Entry<T>,
556        requested: (String, i64),
557    ) -> Result<bool, WorkingSetOverBudget> {
558        let generation = entry.generation;
559        if self.pinned_frames.contains(&requested) {
560            let others = self.pinned_generations(Some(&requested), None);
561            self.admit_pinned(&others, Some(generation), (self.size)(entry.value.as_ref()))?;
562        }
563        if !self.frames.contains_key(&requested) && self.frames.len() >= MAX_VIDEO_FRAMES {
564            self.evict_oldest_frame();
565        }
566        let replaced = !self.following.is_empty()
567            && self
568                .frames
569                .get(&requested)
570                .is_some_and(|old| old.generation != generation);
571        if replaced {
572            self.retire_following(&requested);
573        }
574        if let Some(old) = self.frames.insert(requested, entry)
575            && old.generation != generation
576        {
577            self.retire(old);
578        }
579        Ok(true)
580    }
581
582    /// Stores `source`'s time-independent image and returns its new generation; the image
583    /// answers every time with no exact frame.
584    ///
585    /// # Errors
586    /// Refuses a pinned source's image that would push the working set over budget, keeping the
587    /// store unchanged.
588    pub fn insert_image(&mut self, source: String, value: T) -> Result<u64, WorkingSetOverBudget> {
589        if self.image_pinned(&source) {
590            let others = self.pinned_generations(None, Some(&source));
591            self.admit_pinned(&others, None, (self.size)(&value))?;
592        }
593        if !self.images.contains_key(&source) && self.images.len() >= MAX_IMAGES {
594            self.evict_oldest_image();
595        }
596        let entry = self.entry(value);
597        let generation = entry.generation;
598        if let Some(old) = self.images.insert(source, entry) {
599            self.retire(old);
600        }
601        self.enforce_video_budget(Some(generation));
602        Ok(generation)
603    }
604
605    /// Whether `source`'s image is still the upload `generation` names. The store evicts images
606    /// on its own, so a host checks before relying on an earlier upload.
607    #[must_use]
608    pub fn holds_image(&self, source: &str, generation: u64) -> bool {
609        self.images
610            .get(source)
611            .is_some_and(|entry| entry.generation == generation)
612    }
613
614    /// The frame stored at `source` and `time`, else the source's image.
615    #[must_use]
616    pub fn get(&self, source: &str, time: i64) -> Option<&T> {
617        self.lookup(source, time).map(|entry| entry.value.as_ref())
618    }
619
620    /// The upload generation `get` would answer from. A store never reuses generations.
621    #[must_use]
622    pub fn generation(&self, source: &str, time: i64) -> Option<u64> {
623        self.lookup(source, time).map(|entry| entry.generation)
624    }
625
626    fn lookup(&self, source: &str, time: i64) -> Option<&Entry<T>> {
627        self.frames
628            .get(&(source.to_owned(), time))
629            .or_else(|| self.images.get(source))
630    }
631
632    /// Drops the frame at `source` and `time`; returns whether there was one.
633    pub fn remove(&mut self, source: &str, time: i64) -> bool {
634        let key = (source.to_owned(), time);
635        if !self.following.is_empty() {
636            self.following.remove(&key);
637        }
638        self.frames.remove(&key).is_some()
639    }
640
641    /// Generations held, retired ones included.
642    #[must_use]
643    pub fn len(&self) -> usize {
644        self.generations().len()
645    }
646
647    /// Whether nothing is held.
648    #[must_use]
649    pub fn is_empty(&self) -> bool {
650        self.len() == 0
651    }
652
653    /// Retired entries held for release.
654    #[must_use]
655    pub fn retired_len(&self) -> usize {
656        self.retired.len()
657    }
658
659    /// Bytes every generation holds, measured by `bytes`, each counted once.
660    pub fn retained_bytes(&self, bytes: impl Fn(&T) -> u64) -> u64 {
661        let mut counted = HashSet::new();
662        self.frames
663            .values()
664            .chain(self.images.values())
665            .chain(self.retired.values())
666            .chain(self.following.values().filter_map(Followed::entry))
667            .filter(|entry| counted.insert(entry.generation))
668            .fold(0_u64, |total, entry| {
669                total.saturating_add(bytes(entry.value.as_ref()))
670            })
671    }
672
673    /// Drops every frame, alias, image, and retired entry of `generation`. Returns whether
674    /// anything was dropped.
675    pub fn release_generation(&mut self, generation: u64) -> bool {
676        let retired = self.retired.remove(&generation).is_some();
677        let before_frames = self.frames.len();
678        self.frames
679            .retain(|_, entry| entry.generation != generation);
680        let before_images = self.images.len();
681        self.images
682            .retain(|_, entry| entry.generation != generation);
683        let before_following = self.following.len();
684        if before_following != 0 {
685            self.following.retain(|_, followed| {
686                followed
687                    .entry()
688                    .is_none_or(|entry| entry.generation != generation)
689            });
690            self.drop_unpresented();
691        }
692        retired
693            || before_frames != self.frames.len()
694            || before_images != self.images.len()
695            || before_following != self.following.len()
696    }
697
698    fn drop_unpresented(&mut self) {
699        if !self.following.is_empty() {
700            self.following
701                .retain(|key, _| self.frames.contains_key(key));
702        }
703    }
704
705    /// Drops everything.
706    pub fn clear(&mut self) {
707        self.frames.clear();
708        self.following.clear();
709        self.images.clear();
710        self.retired.clear();
711    }
712
713    /// Invalidates derived values everywhere, including aliases and retirees.
714    pub fn retain_values(&mut self, keep: impl Fn(&T) -> bool) {
715        self.frames.retain(|_, entry| keep(&entry.value));
716        self.images.retain(|_, entry| keep(&entry.value));
717        self.retired.retain(|_, entry| keep(&entry.value));
718        if !self.following.is_empty() {
719            self.following
720                .retain(|_, followed| followed.entry().is_none_or(|entry| keep(&entry.value)));
721            self.drop_unpresented();
722        }
723    }
724
725    /// Keeps only the frames and images `keep` accepts, given their source. Retired entries
726    /// stay.
727    pub fn retain_entries(&mut self, keep: impl Fn(&str, &T) -> bool) {
728        self.frames
729            .retain(|(source, _), entry| keep(source, &entry.value));
730        self.images
731            .retain(|source, entry| keep(source, &entry.value));
732        if !self.following.is_empty() {
733            self.following.retain(|(source, _), followed| {
734                followed
735                    .entry()
736                    .is_none_or(|entry| keep(source, &entry.value))
737            });
738            self.drop_unpresented();
739        }
740    }
741
742    /// Keeps only the frames and images of sources `keep` accepts. Retired entries stay until
743    /// released or evicted.
744    pub fn retain_sources(&mut self, keep: impl Fn(&str) -> bool) {
745        self.frames.retain(|(source, _), _| keep(source));
746        self.images.retain(|source, _| keep(source));
747        self.drop_unpresented();
748    }
749
750    /// Drops one source's frames and image after its media changed. Retired entries stay until
751    /// released.
752    pub fn release_source(&mut self, source: &str) -> bool {
753        let before = self.frames.len() + self.images.len();
754        self.retain_sources(|kept| kept != source);
755        before != self.frames.len() + self.images.len()
756    }
757
758    /// Drops `source`'s frames before `before`, a time on that source's own timeline.
759    pub fn trim_before(&mut self, source: &str, before: i64) {
760        self.frames
761            .retain(|(kept, time), _| kept != source || *time >= before);
762        self.drop_unpresented();
763    }
764
765    fn retire(&mut self, entry: Entry<T>) {
766        while self.retired.len() >= MAX_RETIRED {
767            let Some(oldest) = self.retired.keys().min().copied() else {
768                break;
769            };
770            self.retired.remove(&oldest);
771        }
772        self.retired.insert(entry.generation, entry);
773    }
774
775    fn generations(&self) -> HashSet<u64> {
776        self.frames
777            .values()
778            .chain(self.images.values())
779            .chain(self.retired.values())
780            .chain(self.following.values().filter_map(Followed::entry))
781            .map(|entry| entry.generation)
782            .collect()
783    }
784
785    fn evict_oldest_frame(&mut self) {
786        let pinned = self.pinned_generations(None, None);
787        let key = self
788            .frames
789            .iter()
790            .filter(|(_, entry)| !pinned.contains(&entry.generation))
791            .min_by_key(|(_, entry)| entry.generation)
792            .map(|(key, _)| key.clone());
793        if let Some(key) = key {
794            if !self.following.is_empty() {
795                self.following.remove(&key);
796            }
797            self.frames.remove(&key);
798        }
799    }
800
801    fn evict_oldest_image(&mut self) {
802        let pinned = self.pinned_generations(None, None);
803        let key = self
804            .images
805            .iter()
806            .filter(|(_, entry)| !pinned.contains(&entry.generation))
807            .min_by_key(|(_, entry)| entry.generation)
808            .map(|(key, _)| key.clone());
809        if let Some(key) = key {
810            self.images.remove(&key);
811        }
812    }
813}
814
815#[cfg(test)]
816#[path = "frame_store_tests.rs"]
817mod tests;