Skip to main content

alpha2_host_core/
reverse_window.rs

1//! Decoded frames kept for a backward run, within a byte budget.
2//!
3//! A backward run decodes a stretch forward once and hands its frames out in reverse. The window
4//! keys frames by time; consecutive keys may share one frame, which counts once. While it holds
5//! more than its budget it drops its earliest keys, which the run reaches last and decodes again.
6
7use std::collections::BTreeMap;
8use std::sync::Arc;
9
10use alpha2_time::MediaTime;
11
12/// Frames by time, at most `budget` bytes of distinct frames (always at least one key).
13pub struct ReverseWindow<F> {
14    frames: BTreeMap<MediaTime, Arc<F>>,
15    bytes: u64,
16    budget: u64,
17}
18
19impl<F> ReverseWindow<F> {
20    /// An empty window holding at most `budget` bytes.
21    #[must_use]
22    pub const fn new(budget: u64) -> Self {
23        Self {
24            frames: BTreeMap::new(),
25            bytes: 0,
26            budget,
27        }
28    }
29
30    /// Adds `frame` at `time`, after every key so far, and drops the earliest keys while over
31    /// budget. `bytes` is what `frame` holds; it counts once when the previous key shares it.
32    pub fn push(&mut self, time: MediaTime, frame: Arc<F>, bytes: impl Fn(&F) -> u64) {
33        if !self
34            .frames
35            .last_key_value()
36            .is_some_and(|(_, last)| Arc::ptr_eq(last, &frame))
37        {
38            self.bytes = self.bytes.saturating_add(bytes(&frame));
39        }
40        self.frames.insert(time, frame);
41        while self.bytes > self.budget && self.frames.len() > 1 {
42            if let Some((_, dropped)) = self.frames.pop_first()
43                && !self
44                    .frames
45                    .first_key_value()
46                    .is_some_and(|(_, first)| Arc::ptr_eq(first, &dropped))
47            {
48                self.bytes = self.bytes.saturating_sub(bytes(&dropped));
49            }
50        }
51    }
52
53    /// The frame at exactly `time`.
54    #[must_use]
55    pub fn get(&self, time: MediaTime) -> Option<&Arc<F>> {
56        self.frames.get(&time)
57    }
58
59    /// The latest key.
60    #[must_use]
61    pub fn last_time(&self) -> Option<MediaTime> {
62        self.frames.last_key_value().map(|(time, _)| *time)
63    }
64
65    /// Removes and returns the latest frame keyed before `time`, dropping every key from it on.
66    pub fn take_before(&mut self, time: MediaTime, bytes: impl Fn(&F) -> u64) -> Option<Arc<F>> {
67        let (&key, _) = self.frames.range(..time).next_back()?;
68        let later = self.frames.split_off(&key);
69        let mut previous: Option<&Arc<F>> = self.frames.last_key_value().map(|(_, frame)| frame);
70        for frame in later.values() {
71            if !previous.is_some_and(|before| Arc::ptr_eq(before, frame)) {
72                self.bytes = self.bytes.saturating_sub(bytes(frame));
73            }
74            previous = Some(frame);
75        }
76        later.into_values().next()
77    }
78
79    /// Bytes of the distinct frames held.
80    #[must_use]
81    pub const fn bytes(&self) -> u64 {
82        self.bytes
83    }
84
85    /// Whether it holds no frame.
86    #[must_use]
87    pub fn is_empty(&self) -> bool {
88        self.frames.is_empty()
89    }
90
91    /// How many distinct frames it holds.
92    #[must_use]
93    pub fn distinct(&self) -> usize {
94        let frames = self.frames.values().collect::<Vec<_>>();
95        frames
96            .windows(2)
97            .filter(|pair| !Arc::ptr_eq(pair[0], pair[1]))
98            .count()
99            + usize::from(!frames.is_empty())
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[allow(clippy::trivially_copy_pass_by_ref)]
108    fn size(frame: &u64) -> u64 {
109        *frame
110    }
111
112    #[test]
113    fn a_shared_frame_counts_once_and_the_earliest_keys_go_first() {
114        let mut window = ReverseWindow::new(25);
115        let a = Arc::new(10);
116        window.push(MediaTime(0), Arc::clone(&a), size);
117        window.push(MediaTime(1), a, size);
118        assert_eq!((window.bytes(), window.distinct()), (10, 1));
119        window.push(MediaTime(2), Arc::new(10), size);
120        window.push(MediaTime(3), Arc::new(10), size);
121        // 30 bytes: both keys of the shared frame go, and its bytes once.
122        assert_eq!(window.bytes(), 20);
123        assert!(window.get(MediaTime(1)).is_none());
124        assert_eq!(window.last_time(), Some(MediaTime(3)));
125    }
126
127    #[test]
128    fn taking_before_a_time_answers_the_latest_earlier_frame_and_drops_the_rest() {
129        let mut window = ReverseWindow::new(100);
130        for time in 0..4 {
131            window.push(MediaTime(time * 10), Arc::new(5), size);
132        }
133        assert_eq!(window.take_before(MediaTime(25), size).map(|f| *f), Some(5));
134        assert_eq!(window.last_time(), Some(MediaTime(10)));
135        assert_eq!(window.bytes(), 10);
136        assert!(window.take_before(MediaTime(0), size).is_none());
137        let a = Arc::new(7);
138        let mut shared = ReverseWindow::new(100);
139        shared.push(MediaTime(0), Arc::clone(&a), size);
140        shared.push(MediaTime(1), a, size);
141        assert!(shared.take_before(MediaTime(5), size).is_some());
142        assert_eq!(shared.bytes(), 7);
143    }
144}