adk_vision/stream/
sampler.rs1use std::time::Duration;
4
5use crate::edit::ops;
6use crate::error::{Result, VisionError};
7use crate::media::DecodedImage;
8use crate::traits::Sampling;
9
10#[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 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 pub fn interval(&self) -> Duration {
76 self.interval
77 }
78
79 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 self.next_due = Some((due + self.interval).max(pts + self.interval));
93 self.last = Some(pts);
94 }
95 keep
96 }
97
98 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 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 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}