alpha2-engine 0.9.0

Player and exporter facade for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! A cache of prepared source frames, keyed by source and time, bounded by count and bytes: what
//! a player or an exporter renders from ([`FrameProvider`] for entries that are [`StoredFrame`]s).
//!
//! A frame is found only under the request time the host inserted or aliased it at, so the
//! presented-at rule of [`FrameProvider::texture_for`] holds only for times the host stored.
//!
//! Every upload gets a generation number. Aliases share their target's generation, and a
//! replaced entry is retired, still counted, until the host releases it or the budget evicts it.
//!
//! An export pins the frames its current output frame shows. The budget never evicts them, and
//! an upload that would push the pinned set over budget is refused, so an oversized frame fails
//! at once instead of evicting its own sources.

use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;

use alpha2_media::SourceId;
use alpha2_render::{CpuSource, PendingSourceWork, RenderCacheKey, SourceView};
use alpha2_time::MediaTime;

use crate::{Following, FollowingFrame, FrameProvider};

/// A store entry the renderer can sample.
pub trait StoredFrame {
    /// The picture, for the renderer.
    fn view(&self) -> SourceView<'_>;

    /// Work that must run before the picture is read; `None` for a ready one.
    fn pending_work(&self) -> Option<&PendingSourceWork> {
        None
    }
}

impl StoredFrame for CpuSource {
    fn view(&self) -> SourceView<'_> {
        SourceView::cpu(self)
    }
}

impl<T: StoredFrame> FrameProvider for FrameStore<T> {
    fn texture_for(&self, source: &SourceId, time: MediaTime) -> Option<SourceView<'_>> {
        self.get(source.as_str(), time.ticks())
            .map(StoredFrame::view)
    }

    /// Keyed by source and upload generation, since an upload's picture never changes.
    fn source_key(&self, source: &SourceId, time: MediaTime) -> Option<RenderCacheKey> {
        let generation = self.generation(source.as_str(), time.ticks())?;
        Some(upload_key(source.as_str(), generation))
    }

    fn following_for(&self, source: &SourceId, time: MediaTime) -> Following<'_> {
        let key = (source.as_str().to_owned(), time.ticks());
        match self.following.get(&key) {
            Some(Followed::Last) => Following::Last,
            Some(Followed::Frame {
                entry,
                presented_at,
                at,
            }) => Following::Frame(FollowingFrame {
                view: entry.value.view(),
                key: Some(upload_key(source.as_str(), entry.generation)),
                pending: entry.value.pending_work(),
                presented_at: MediaTime(*presented_at),
                at: MediaTime(*at),
            }),
            None if !self.frames.contains_key(&key) && self.images.contains_key(&key.0) => {
                Following::Last
            }
            None => Following::Pending,
        }
    }

    fn pending_source_work(
        &self,
        source: &SourceId,
        time: MediaTime,
    ) -> Option<&PendingSourceWork> {
        self.get(source.as_str(), time.ticks())
            .and_then(StoredFrame::pending_work)
    }
}

fn upload_key(source: &str, generation: u64) -> RenderCacheKey {
    let mut hash = std::hash::DefaultHasher::new();
    std::hash::Hash::hash(&(source, generation), &mut hash);
    RenderCacheKey::source(std::hash::Hasher::finish(&hash))
}

struct Entry<T> {
    value: Arc<T>,
    generation: u64,
}

enum Followed<T> {
    Last,
    Frame {
        entry: Entry<T>,
        presented_at: i64,
        at: i64,
    },
}

impl<T> Followed<T> {
    const fn entry(&self) -> Option<&Entry<T>> {
        match self {
            Self::Last => None,
            Self::Frame { entry, .. } => Some(entry),
        }
    }
}

/// Which of the two frames a key holds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KeptFrame {
    /// The frame presented at the key's time.
    Presented,
    /// The frame after it.
    Following,
}

/// The presentation times of a key's frame and of the frame after it, in ticks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FramePair {
    /// When the key's frame is presented.
    pub presented_at: i64,
    /// When the frame after it is presented.
    pub at: i64,
}

impl<T> Entry<T> {
    fn shared(&self) -> Self {
        Self {
            value: Arc::clone(&self.value),
            generation: self.generation,
        }
    }
}

/// Most timestamped frame keys kept, aliases included.
const MAX_VIDEO_FRAMES: usize = 512;
/// Most time-independent images kept.
const MAX_IMAGES: usize = 128;
/// Most replaced entries kept for the host to release.
const MAX_RETIRED: usize = 128;
/// Default byte budget across live, image, and retired generations: 64 `Rgba16Float` frames at
/// 1080p, 16 at 4K. The count limit alone would allow about 8.5 GB at 1080p.
pub const DEFAULT_VIDEO_FRAME_BYTES: u64 = 1 << 30;

/// An upload refused because the pinned working set would outgrow the byte budget
/// ([`FrameStore::pin`]). The store is unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WorkingSetOverBudget {
    /// Bytes of the other pinned frames the store holds.
    pub held: u64,
    /// Bytes of the refused frame.
    pub requested: u64,
    /// The store's byte budget.
    pub budget: u64,
}

impl WorkingSetOverBudget {
    /// Minimum the working set needs: the pinned frames held plus this one.
    #[must_use]
    pub const fn needed(&self) -> u64 {
        self.held.saturating_add(self.requested)
    }
}

/// Timestamped video frames and explicitly registered, time-independent images.
pub struct FrameStore<T> {
    frames: HashMap<(String, i64), Entry<T>>,
    following: HashMap<(String, i64), Followed<T>>,
    images: HashMap<String, Entry<T>>,
    retired: HashMap<u64, Entry<T>>,
    /// Keys (source, time) of the pinned working set ([`Self::pin`]).
    pinned_frames: HashSet<(String, i64)>,
    /// Bytes of the working set the last [`Self::unpin`] released.
    last_working_set: u64,
    next_generation: u64,
    size: fn(&T) -> u64,
    video_byte_budget: u64,
}

impl<T> Default for FrameStore<T> {
    fn default() -> Self {
        Self::sized(|_| 0, u64::MAX)
    }
}

impl<T> FrameStore<T> {
    /// A store that measures each value with `size` and keeps at most `video_byte_budget` bytes.
    ///
    /// The budget counts every retained generation once, retired entries and images included.
    /// Eviction releases only cache ownership; submitted work owns its GPU resources.
    ///
    /// A newly inserted frame may exceed the budget alone so it can be presented, in which case
    /// no other unpinned generation is kept. A pinned working set may not ([`Self::pin`]).
    #[must_use]
    pub fn sized(size: fn(&T) -> u64, video_byte_budget: u64) -> Self {
        Self {
            frames: HashMap::new(),
            following: HashMap::new(),
            images: HashMap::new(),
            retired: HashMap::new(),
            pinned_frames: HashSet::new(),
            last_working_set: 0,
            next_generation: 1,
            size,
            video_byte_budget,
        }
    }

    /// Changes the byte budget, evicting oldest generations at once to fit.
    pub fn set_video_byte_budget(&mut self, bytes: u64) {
        self.video_byte_budget = bytes;
        self.enforce_video_budget(None);
    }

    #[cfg(test)]
    pub(crate) fn video_bytes(&self) -> u64 {
        let mut counted = HashSet::new();
        self.frames
            .values()
            .chain(self.following.values().filter_map(Followed::entry))
            .filter(|entry| counted.insert(entry.generation))
            .fold(0_u64, |total, entry| {
                total.saturating_add((self.size)(entry.value.as_ref()))
            })
    }

    /// Pins the working set of the frame being made: the frames at `keys` (source and time), the
    /// frames after them the keys hold, and each source's image, which answers a time with no
    /// exact frame. Replaces earlier pins.
    ///
    /// Until [`Self::unpin`], the budget never evicts a pinned generation, and an upload or
    /// alias that would push the pinned set over budget is refused. A one-frame working set may
    /// exceed the budget, as any newest upload may.
    pub fn pin(&mut self, keys: impl IntoIterator<Item = (String, i64)>) {
        self.pinned_frames.clear();
        self.pinned_frames.extend(keys);
    }

    /// Drops the pins, leaving every generation to the budget again.
    pub fn unpin(&mut self) {
        self.last_working_set = self.generation_bytes(&self.pinned_generations(None, None));
        self.pinned_frames.clear();
    }

    /// Bytes of the working set the last [`Self::unpin`] released: what one output frame needed,
    /// which a host lowering the budget under memory pressure keeps room for.
    #[must_use]
    pub const fn last_working_set_bytes(&self) -> u64 {
        self.last_working_set
    }

    /// The generations the pinned working set looks up, as [`Self::get`] would answer, except
    /// for what an upload is about to replace (the frame at `frame` or the image of `image`).
    fn pinned_generations(
        &self,
        frame: Option<&(String, i64)>,
        image: Option<&str>,
    ) -> HashSet<u64> {
        let mut pinned: HashSet<u64> = self
            .pinned_frames
            .iter()
            .filter(|key| Some(*key) != frame)
            .filter_map(|key| match self.frames.get(key) {
                Some(entry) => Some(entry.generation),
                None if Some(key.0.as_str()) == image => None,
                None => self.images.get(&key.0).map(|entry| entry.generation),
            })
            .collect();
        if !self.following.is_empty() {
            pinned.extend(
                self.pinned_frames
                    .iter()
                    .filter_map(|key| self.following.get(key)?.entry())
                    .map(|entry| entry.generation),
            );
        }
        pinned
    }

    /// Whether `source`'s image is pinned, because a pinned key of that source has no exact
    /// frame.
    fn image_pinned(&self, source: &str) -> bool {
        self.pinned_frames
            .iter()
            .any(|key| key.0 == source && !self.frames.contains_key(key))
    }

    /// Bytes of the generations in `generations`, each counted once.
    fn generation_bytes(&self, generations: &HashSet<u64>) -> u64 {
        let mut counted = HashSet::new();
        self.frames
            .values()
            .chain(self.images.values())
            .chain(self.following.values().filter_map(Followed::entry))
            .filter(|entry| generations.contains(&entry.generation))
            .filter(|entry| counted.insert(entry.generation))
            .fold(0_u64, |total, entry| {
                total.saturating_add((self.size)(entry.value.as_ref()))
            })
    }

    /// Refuses `requested` bytes joining the pinned set when it and `others` would exceed the
    /// budget, unless it is the working set's only frame or already one of `others`.
    fn admit_pinned(
        &self,
        others: &HashSet<u64>,
        generation: Option<u64>,
        requested: u64,
    ) -> Result<(), WorkingSetOverBudget> {
        if others.is_empty() || generation.is_some_and(|generation| others.contains(&generation)) {
            return Ok(());
        }
        let held = self.generation_bytes(others);
        if held.saturating_add(requested) > self.video_byte_budget {
            return Err(WorkingSetOverBudget {
                held,
                requested,
                budget: self.video_byte_budget,
            });
        }
        Ok(())
    }

    /// Evicts whole generations, aliases included, oldest first and never pinned ones. Only the
    /// newly inserted generation and the pinned set can exceed the budget.
    fn enforce_video_budget(&mut self, keep: Option<u64>) {
        let pinned = self.pinned_generations(None, None);
        while self.retained_bytes(self.size) > self.video_byte_budget {
            let oldest = self
                .generations()
                .into_iter()
                .filter(|generation| Some(*generation) != keep && !pinned.contains(generation))
                .min();
            let Some(oldest) = oldest else {
                break;
            };
            self.release_generation(oldest);
        }
    }
    fn entry(&mut self, value: T) -> Entry<T> {
        let generation = self.next_generation;
        self.next_generation = generation.checked_add(1).unwrap_or(1);
        if self.next_generation == 1 {
            self.clear();
        }
        Entry {
            value: Arc::new(value),
            generation,
        }
    }

    /// Stores a frame at `key` and returns its new generation. A frame already at `key` is
    /// retired with the frame after it the key held, and older unpinned generations are evicted
    /// to fit the budget.
    ///
    /// # Errors
    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
    /// store unchanged.
    pub fn insert(&mut self, key: (String, i64), value: T) -> Result<u64, WorkingSetOverBudget> {
        if self.pinned_frames.contains(&key) {
            let others = self.pinned_generations(Some(&key), None);
            self.admit_pinned(&others, None, (self.size)(&value))?;
        }
        if !self.frames.contains_key(&key) && self.frames.len() >= MAX_VIDEO_FRAMES {
            self.evict_oldest_frame();
        }
        let entry = self.entry(value);
        let generation = entry.generation;
        self.retire_following(&key);
        if let Some(old) = self.frames.insert(key, entry) {
            self.retire(old);
        }
        self.enforce_video_budget(Some(generation));
        Ok(generation)
    }

    fn retire_following(&mut self, key: &(String, i64)) {
        if self.following.is_empty() {
            return;
        }
        if let Some(Followed::Frame { entry, .. }) = self.following.remove(key) {
            self.retire(entry);
        }
    }

    /// Stores the frame after the one at `key`, with both frames' presentation times, and
    /// returns its new generation; `None`, storing nothing, when `key` holds no frame. The frame
    /// is pinned with its key and dropped when the key's frame is replaced or dropped.
    ///
    /// # Errors
    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
    /// store unchanged.
    pub fn insert_following(
        &mut self,
        key: (String, i64),
        value: T,
        times: FramePair,
    ) -> Result<Option<u64>, WorkingSetOverBudget> {
        if !self.frames.contains_key(&key) {
            return Ok(None);
        }
        if self.pinned_frames.contains(&key) {
            let others = self.pinned_generations(None, None);
            self.admit_pinned(&others, None, (self.size)(&value))?;
        }
        let entry = self.entry(value);
        let generation = entry.generation;
        self.follow(key, entry, times);
        self.enforce_video_budget(Some(generation));
        Ok(Some(generation))
    }

    /// Makes the frame after the one at `requested` the frame `existing` holds as `kept`, sharing
    /// its generation and bytes. Returns `false`, changing nothing, when either key holds no
    /// such frame.
    ///
    /// # Errors
    /// Refuses a frame at a pinned key that would push the working set over budget, keeping the
    /// store unchanged.
    pub fn alias_following(
        &mut self,
        existing: (&(String, i64), KeptFrame),
        requested: (String, i64),
        times: FramePair,
    ) -> Result<bool, WorkingSetOverBudget> {
        let Some(entry) = self.kept(existing.0, existing.1).map(Entry::shared) else {
            return Ok(false);
        };
        if !self.frames.contains_key(&requested) {
            return Ok(false);
        }
        if self.pinned_frames.contains(&requested) {
            let others = self.pinned_generations(None, None);
            self.admit_pinned(
                &others,
                Some(entry.generation),
                (self.size)(entry.value.as_ref()),
            )?;
        }
        self.follow(requested, entry, times);
        Ok(true)
    }

    /// Records that no frame follows the one at `key`: it is its source's last, or the host
    /// cannot name the next. Returns `false`, changing nothing, when `key` holds no frame.
    pub fn set_last(&mut self, key: (String, i64)) -> bool {
        if !self.frames.contains_key(&key) {
            return false;
        }
        if let Some(Followed::Frame { entry, .. }) = self.following.insert(key, Followed::Last) {
            self.retire(entry);
        }
        true
    }

    /// Whether `key` holds the frame after its own, or the record that there is none.
    #[must_use]
    pub fn follows(&self, source: &str, time: i64) -> bool {
        !self.following.is_empty() && self.following.contains_key(&(source.to_owned(), time))
    }

    /// A key of `source` that keeps the frame presented at `pts` ticks and which of its two frames
    /// that is. Only keys holding the frame after their own are looked at.
    #[must_use]
    pub fn kept_at(&self, source: &str, pts: i64) -> Option<((String, i64), KeptFrame)> {
        self.following.iter().find_map(|(key, followed)| {
            let Followed::Frame {
                presented_at, at, ..
            } = followed
            else {
                return None;
            };
            let kept = if *presented_at == pts {
                KeptFrame::Presented
            } else if *at == pts {
                KeptFrame::Following
            } else {
                return None;
            };
            (key.0 == source).then(|| (key.clone(), kept))
        })
    }

    fn follow(&mut self, key: (String, i64), entry: Entry<T>, times: FramePair) {
        let generation = entry.generation;
        let old = self.following.insert(
            key,
            Followed::Frame {
                entry,
                presented_at: times.presented_at,
                at: times.at,
            },
        );
        if let Some(Followed::Frame { entry: old, .. }) = old
            && old.generation != generation
        {
            self.retire(old);
        }
    }

    fn kept(&self, key: &(String, i64), kept: KeptFrame) -> Option<&Entry<T>> {
        match kept {
            KeptFrame::Presented => self.frames.get(key),
            KeptFrame::Following => self.following.get(key)?.entry(),
        }
    }

    /// Makes `requested` answer with the frame `existing` holds as `kept`, as [`Self::alias`]
    /// does for a presented frame.
    ///
    /// # Errors
    /// As [`Self::alias`].
    pub fn alias_kept(
        &mut self,
        existing: (&(String, i64), KeptFrame),
        requested: (String, i64),
    ) -> Result<bool, WorkingSetOverBudget> {
        if existing.1 == KeptFrame::Presented {
            return self.alias(existing.0, requested);
        }
        let Some(entry) = self.kept(existing.0, existing.1).map(Entry::shared) else {
            return Ok(false);
        };
        self.share(entry, requested)
    }

    /// Makes `requested` answer with the frame at `existing`, sharing its generation and bytes.
    /// Returns `false` when `existing` holds no frame.
    ///
    /// # Errors
    /// Refuses an alias into a pinned key that would push the working set over budget, keeping
    /// the store unchanged.
    pub fn alias(
        &mut self,
        existing: &(String, i64),
        requested: (String, i64),
    ) -> Result<bool, WorkingSetOverBudget> {
        let Some(entry) = self.frames.get(existing).map(Entry::shared) else {
            return Ok(false);
        };
        if existing == &requested {
            return Ok(true);
        }
        self.share(entry, requested)
    }

    fn share(
        &mut self,
        entry: Entry<T>,
        requested: (String, i64),
    ) -> Result<bool, WorkingSetOverBudget> {
        let generation = entry.generation;
        if self.pinned_frames.contains(&requested) {
            let others = self.pinned_generations(Some(&requested), None);
            self.admit_pinned(&others, Some(generation), (self.size)(entry.value.as_ref()))?;
        }
        if !self.frames.contains_key(&requested) && self.frames.len() >= MAX_VIDEO_FRAMES {
            self.evict_oldest_frame();
        }
        let replaced = !self.following.is_empty()
            && self
                .frames
                .get(&requested)
                .is_some_and(|old| old.generation != generation);
        if replaced {
            self.retire_following(&requested);
        }
        if let Some(old) = self.frames.insert(requested, entry)
            && old.generation != generation
        {
            self.retire(old);
        }
        Ok(true)
    }

    /// Stores `source`'s time-independent image and returns its new generation; the image
    /// answers every time with no exact frame.
    ///
    /// # Errors
    /// Refuses a pinned source's image that would push the working set over budget, keeping the
    /// store unchanged.
    pub fn insert_image(&mut self, source: String, value: T) -> Result<u64, WorkingSetOverBudget> {
        if self.image_pinned(&source) {
            let others = self.pinned_generations(None, Some(&source));
            self.admit_pinned(&others, None, (self.size)(&value))?;
        }
        if !self.images.contains_key(&source) && self.images.len() >= MAX_IMAGES {
            self.evict_oldest_image();
        }
        let entry = self.entry(value);
        let generation = entry.generation;
        if let Some(old) = self.images.insert(source, entry) {
            self.retire(old);
        }
        self.enforce_video_budget(Some(generation));
        Ok(generation)
    }

    /// Whether `source`'s image is still the upload `generation` names. The store evicts images
    /// on its own, so a host checks before relying on an earlier upload.
    #[must_use]
    pub fn holds_image(&self, source: &str, generation: u64) -> bool {
        self.images
            .get(source)
            .is_some_and(|entry| entry.generation == generation)
    }

    /// The frame stored at `source` and `time`, else the source's image.
    #[must_use]
    pub fn get(&self, source: &str, time: i64) -> Option<&T> {
        self.lookup(source, time).map(|entry| entry.value.as_ref())
    }

    /// The upload generation `get` would answer from. A store never reuses generations.
    #[must_use]
    pub fn generation(&self, source: &str, time: i64) -> Option<u64> {
        self.lookup(source, time).map(|entry| entry.generation)
    }

    fn lookup(&self, source: &str, time: i64) -> Option<&Entry<T>> {
        self.frames
            .get(&(source.to_owned(), time))
            .or_else(|| self.images.get(source))
    }

    /// Drops the frame at `source` and `time`; returns whether there was one.
    pub fn remove(&mut self, source: &str, time: i64) -> bool {
        let key = (source.to_owned(), time);
        if !self.following.is_empty() {
            self.following.remove(&key);
        }
        self.frames.remove(&key).is_some()
    }

    /// Generations held, retired ones included.
    #[must_use]
    pub fn len(&self) -> usize {
        self.generations().len()
    }

    /// Whether nothing is held.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Retired entries held for release.
    #[must_use]
    pub fn retired_len(&self) -> usize {
        self.retired.len()
    }

    /// Bytes every generation holds, measured by `bytes`, each counted once.
    pub fn retained_bytes(&self, bytes: impl Fn(&T) -> u64) -> u64 {
        let mut counted = HashSet::new();
        self.frames
            .values()
            .chain(self.images.values())
            .chain(self.retired.values())
            .chain(self.following.values().filter_map(Followed::entry))
            .filter(|entry| counted.insert(entry.generation))
            .fold(0_u64, |total, entry| {
                total.saturating_add(bytes(entry.value.as_ref()))
            })
    }

    /// Drops every frame, alias, image, and retired entry of `generation`. Returns whether
    /// anything was dropped.
    pub fn release_generation(&mut self, generation: u64) -> bool {
        let retired = self.retired.remove(&generation).is_some();
        let before_frames = self.frames.len();
        self.frames
            .retain(|_, entry| entry.generation != generation);
        let before_images = self.images.len();
        self.images
            .retain(|_, entry| entry.generation != generation);
        let before_following = self.following.len();
        if before_following != 0 {
            self.following.retain(|_, followed| {
                followed
                    .entry()
                    .is_none_or(|entry| entry.generation != generation)
            });
            self.drop_unpresented();
        }
        retired
            || before_frames != self.frames.len()
            || before_images != self.images.len()
            || before_following != self.following.len()
    }

    fn drop_unpresented(&mut self) {
        if !self.following.is_empty() {
            self.following
                .retain(|key, _| self.frames.contains_key(key));
        }
    }

    /// Drops everything.
    pub fn clear(&mut self) {
        self.frames.clear();
        self.following.clear();
        self.images.clear();
        self.retired.clear();
    }

    /// Invalidates derived values everywhere, including aliases and retirees.
    pub fn retain_values(&mut self, keep: impl Fn(&T) -> bool) {
        self.frames.retain(|_, entry| keep(&entry.value));
        self.images.retain(|_, entry| keep(&entry.value));
        self.retired.retain(|_, entry| keep(&entry.value));
        if !self.following.is_empty() {
            self.following
                .retain(|_, followed| followed.entry().is_none_or(|entry| keep(&entry.value)));
            self.drop_unpresented();
        }
    }

    /// Keeps only the frames and images `keep` accepts, given their source. Retired entries
    /// stay.
    pub fn retain_entries(&mut self, keep: impl Fn(&str, &T) -> bool) {
        self.frames
            .retain(|(source, _), entry| keep(source, &entry.value));
        self.images
            .retain(|source, entry| keep(source, &entry.value));
        if !self.following.is_empty() {
            self.following.retain(|(source, _), followed| {
                followed
                    .entry()
                    .is_none_or(|entry| keep(source, &entry.value))
            });
            self.drop_unpresented();
        }
    }

    /// Keeps only the frames and images of sources `keep` accepts. Retired entries stay until
    /// released or evicted.
    pub fn retain_sources(&mut self, keep: impl Fn(&str) -> bool) {
        self.frames.retain(|(source, _), _| keep(source));
        self.images.retain(|source, _| keep(source));
        self.drop_unpresented();
    }

    /// Drops one source's frames and image after its media changed. Retired entries stay until
    /// released.
    pub fn release_source(&mut self, source: &str) -> bool {
        let before = self.frames.len() + self.images.len();
        self.retain_sources(|kept| kept != source);
        before != self.frames.len() + self.images.len()
    }

    /// Drops `source`'s frames before `before`, a time on that source's own timeline.
    pub fn trim_before(&mut self, source: &str, before: i64) {
        self.frames
            .retain(|(kept, time), _| kept != source || *time >= before);
        self.drop_unpresented();
    }

    fn retire(&mut self, entry: Entry<T>) {
        while self.retired.len() >= MAX_RETIRED {
            let Some(oldest) = self.retired.keys().min().copied() else {
                break;
            };
            self.retired.remove(&oldest);
        }
        self.retired.insert(entry.generation, entry);
    }

    fn generations(&self) -> HashSet<u64> {
        self.frames
            .values()
            .chain(self.images.values())
            .chain(self.retired.values())
            .chain(self.following.values().filter_map(Followed::entry))
            .map(|entry| entry.generation)
            .collect()
    }

    fn evict_oldest_frame(&mut self) {
        let pinned = self.pinned_generations(None, None);
        let key = self
            .frames
            .iter()
            .filter(|(_, entry)| !pinned.contains(&entry.generation))
            .min_by_key(|(_, entry)| entry.generation)
            .map(|(key, _)| key.clone());
        if let Some(key) = key {
            if !self.following.is_empty() {
                self.following.remove(&key);
            }
            self.frames.remove(&key);
        }
    }

    fn evict_oldest_image(&mut self) {
        let pinned = self.pinned_generations(None, None);
        let key = self
            .images
            .iter()
            .filter(|(_, entry)| !pinned.contains(&entry.generation))
            .min_by_key(|(_, entry)| entry.generation)
            .map(|(key, _)| key.clone());
        if let Some(key) = key {
            self.images.remove(&key);
        }
    }
}

#[cfg(test)]
#[path = "frame_store_tests.rs"]
mod tests;