Skip to main content

kitchen_views/video/
cache.rs

1//! Decoded frames kept for scrubbing back and forth: least recently used first out, within a
2//! byte budget (a 1080p RGBA frame is 8 MB: 64 of them is half a gigabyte).
3
4use std::collections::VecDeque;
5
6use crate::video::Frame;
7
8/// Frames by index, newest use last.
9#[derive(Debug)]
10pub struct FrameCache {
11    frames: VecDeque<Frame>,
12    budget: usize,
13    used: usize,
14}
15
16impl FrameCache {
17    /// A cache of up to `budget` bytes.
18    pub fn new(budget: usize) -> Self {
19        Self { frames: VecDeque::new(), budget, used: 0 }
20    }
21
22    /// Frame `index`, when kept (it becomes the most recently used).
23    pub fn get(&mut self, index: usize) -> Option<Frame> {
24        let at = self.frames.iter().position(|f| f.index == index)?;
25        let frame = self.frames.remove(at)?;
26        self.frames.push_back(frame.clone());
27        Some(frame)
28    }
29
30    /// Whether frame `index` is kept.
31    pub fn contains(&self, index: usize) -> bool {
32        self.frames.iter().any(|f| f.index == index)
33    }
34
35    /// Keeps `frame`, dropping the least recently used to stay within the budget (a frame larger
36    /// than the budget is kept alone).
37    pub fn put(&mut self, frame: Frame) {
38        if let Some(at) = self.frames.iter().position(|f| f.index == frame.index) {
39            let old = self.frames.remove(at).expect("found");
40            self.used -= old.bytes();
41        }
42        self.used += frame.bytes();
43        self.frames.push_back(frame);
44        while self.used > self.budget && self.frames.len() > 1 {
45            let old = self.frames.pop_front().expect("more than one");
46            self.used -= old.bytes();
47        }
48    }
49
50    /// Bytes held.
51    pub fn used(&self) -> usize {
52        self.used
53    }
54
55    pub fn clear(&mut self) {
56        self.frames.clear();
57        self.used = 0;
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use std::sync::Arc;
64
65    use super::*;
66
67    fn frame(index: usize) -> Frame {
68        Frame { index, time: index as f64, width: 2, height: 2, rgba: Arc::new(vec![0; 16]) }
69    }
70
71    #[test]
72    fn keeps_the_recently_used_within_its_budget() {
73        let mut c = FrameCache::new(48);
74        for i in 0..3 {
75            c.put(frame(i));
76        }
77        assert!(c.get(0).is_some(), "0 is now the most recent");
78        c.put(frame(3));
79        assert!(!c.contains(1), "the least recently used went");
80        assert!(c.contains(0) && c.contains(2) && c.contains(3));
81        assert_eq!(c.used(), 48);
82    }
83}