Skip to main content

adk_vision/stream/
sampler.rs

1//! [`Sampler`]: which decoded frames a source keeps, and at what size.
2
3use std::time::Duration;
4
5use crate::edit::ops;
6use crate::error::{Result, VisionError};
7use crate::media::DecodedImage;
8use crate::traits::Sampling;
9
10/// Keeps frames at most [`Sampling::fps`] apart by presentation time and downscales them to
11/// [`Sampling::max_long_edge`].
12///
13/// Admission follows a grid of one slot per `1 / fps`: the first frame is kept, then the
14/// first frame at or after each next slot, with a slack of an eighth of the interval for
15/// timestamp jitter. A frame kept late moves the grid to itself, so a source that stalls
16/// never bursts to catch up; a timestamp that goes backwards (a restarted stream) restarts
17/// the grid. Kept frames are therefore at least seven eighths of an interval apart, and a
18/// source faster than `fps` yields `fps` frames a second.
19///
20/// # Example
21///
22/// ```
23/// use std::time::Duration;
24/// use adk_vision::Sampling;
25/// use adk_vision::stream::Sampler;
26///
27/// // A 30 fps source sampled at 5 fps keeps every sixth frame.
28/// let mut sampler = Sampler::new(Sampling { fps: 5.0, max_long_edge: Some(640) }).unwrap();
29/// let kept: Vec<u64> = (0..30u64)
30///     .filter(|i| sampler.admit(Duration::from_micros(i * 33_333)))
31///     .collect();
32/// assert_eq!(kept, vec![0, 6, 12, 18, 24]);
33/// assert_eq!(sampler.fitted_size(1920, 1080), (640, 360));
34/// ```
35#[derive(Clone, Debug)]
36pub struct Sampler {
37    interval: Duration,
38    slack: Duration,
39    max_long_edge: Option<u32>,
40    next_due: Option<Duration>,
41    last: Option<Duration>,
42}
43
44impl Sampler {
45    /// A sampler for `sampling`.
46    ///
47    /// # Errors
48    ///
49    /// [`VisionError::InvalidInput`] when `fps` is not a finite positive number, or
50    /// `max_long_edge` is zero.
51    pub fn new(sampling: Sampling) -> Result<Self> {
52        if !sampling.fps.is_finite() || sampling.fps <= 0.0 {
53            return Err(VisionError::InvalidInput(format!(
54                "a sampling rate must be a positive number of frames a second; got {}",
55                sampling.fps
56            )));
57        }
58        if sampling.max_long_edge == Some(0) {
59            return Err(VisionError::InvalidInput(
60                "max_long_edge must be at least 1 pixel; leave it unset to keep the source size"
61                    .into(),
62            ));
63        }
64        let interval = Duration::from_secs_f64(1.0 / f64::from(sampling.fps));
65        Ok(Self {
66            interval,
67            slack: interval / 8,
68            max_long_edge: sampling.max_long_edge,
69            next_due: None,
70            last: None,
71        })
72    }
73
74    /// The time between two kept frames.
75    pub fn interval(&self) -> Duration {
76        self.interval
77    }
78
79    /// Whether to keep the frame presented at `pts`, counted from the start of the stream.
80    pub fn admit(&mut self, pts: Duration) -> bool {
81        let backwards = self.last.is_some_and(|last| pts < last);
82        let keep = match self.next_due {
83            None => true,
84            Some(_) if backwards => true,
85            Some(due) => pts + self.slack >= due,
86        };
87        if keep {
88            let due = self.next_due.filter(|_| !backwards).unwrap_or(pts);
89            // A frame on time keeps the grid; a late one moves it, so the next frame is at
90            // least an interval less the slack after this one and a stalled source never
91            // bursts to catch up.
92            self.next_due = Some((due + self.interval).max(pts + self.interval));
93            self.last = Some(pts);
94        }
95        keep
96    }
97
98    /// The size a `width` × `height` frame is scaled to: unchanged when its long edge is
99    /// within `max_long_edge`, otherwise scaled down to it with the aspect ratio kept.
100    pub fn fitted_size(&self, width: u32, height: u32) -> (u32, u32) {
101        let Some(max) = self.max_long_edge else { return (width, height) };
102        let long = width.max(height);
103        if long <= max {
104            return (width, height);
105        }
106        let scale = f64::from(max) / f64::from(long);
107        let side = |v: u32| ((f64::from(v) * scale).round() as u32).clamp(1, max);
108        (side(width), side(height))
109    }
110
111    /// `pixels` scaled to [`fitted_size`](Self::fitted_size).
112    pub fn fit(&self, pixels: DecodedImage) -> DecodedImage {
113        let (width, height) = pixels.size();
114        let (w, h) = self.fitted_size(width, height);
115        if (w, h) == (width, height) { pixels } else { ops::resize(&pixels, w, h) }
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    fn sampler(fps: f32) -> Sampler {
124        Sampler::new(Sampling { fps, max_long_edge: None }).unwrap()
125    }
126
127    #[test]
128    fn invalid_rates_are_refused() {
129        for fps in [0.0, -1.0, f32::NAN, f32::INFINITY] {
130            assert!(Sampler::new(Sampling { fps, max_long_edge: None }).is_err(), "{fps}");
131        }
132        assert!(Sampler::new(Sampling { fps: 1.0, max_long_edge: Some(0) }).is_err());
133    }
134
135    #[test]
136    fn a_slow_source_is_kept_whole() {
137        let mut s = sampler(10.0);
138        assert!((0..20u64).all(|i| s.admit(Duration::from_millis(i * 500))));
139    }
140
141    #[test]
142    fn a_stall_re_anchors_instead_of_bursting() {
143        let mut s = sampler(10.0);
144        assert!(s.admit(Duration::ZERO));
145        // Five seconds of nothing, then a 30 fps burst: one frame per 100 ms again.
146        let kept: Vec<u64> =
147            (0..9u64).filter(|i| s.admit(Duration::from_millis(5_000 + i * 33))).collect();
148        assert_eq!(kept, vec![0, 3, 6]);
149    }
150
151    #[test]
152    fn backwards_timestamps_restart_the_grid() {
153        let mut s = sampler(1.0);
154        assert!(s.admit(Duration::from_secs(10)));
155        assert!(!s.admit(Duration::from_millis(10_500)));
156        assert!(s.admit(Duration::from_secs(2)));
157        assert!(!s.admit(Duration::from_millis(2_500)));
158        assert!(s.admit(Duration::from_secs(3)));
159    }
160
161    #[test]
162    fn frames_are_only_ever_scaled_down() {
163        let s = Sampler::new(Sampling { fps: 1.0, max_long_edge: Some(320) }).unwrap();
164        assert_eq!(s.fitted_size(640, 360), (320, 180));
165        assert_eq!(s.fitted_size(360, 640), (180, 320));
166        assert_eq!(s.fitted_size(200, 100), (200, 100));
167        let fitted = s.fit(DecodedImage::filled(640, 480, [9; 4]));
168        assert_eq!(fitted.size(), (320, 240));
169    }
170}