1use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
34use std::time::{Duration, Instant};
35
36use kessel_video::{Facing, VideoFrame};
37use serde::Serialize;
38
39fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
40 m.lock().unwrap_or_else(PoisonError::into_inner)
41}
42
43#[derive(Clone, Debug)]
45#[non_exhaustive]
46pub struct CameraFrame {
47 pub frame: VideoFrame,
51 pub facing: Facing,
53 pub rotation: u32,
56}
57
58impl CameraFrame {
59 pub fn new(frame: VideoFrame, facing: Facing) -> CameraFrame {
61 CameraFrame {
62 frame,
63 facing,
64 rotation: 0,
65 }
66 }
67
68 pub fn mirror(&self) -> bool {
71 self.facing == Facing::Front
72 }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
77#[serde(rename_all = "snake_case")]
78#[non_exhaustive]
79pub enum CameraFeed {
80 #[default]
82 Off,
83 Live,
85 Paused,
88}
89
90#[derive(Clone, Debug)]
92#[non_exhaustive]
93pub enum CameraTapItem {
94 Feed(CameraFeed),
96 Frame(CameraFrame),
98}
99
100struct Slot {
101 feed: CameraFeed,
102 feed_new: bool,
104 frame: Option<CameraFrame>,
105 closed: bool,
106 taken: u64,
107 dropped: u64,
108}
109
110struct Shared {
111 slot: Mutex<Slot>,
112 ready: Condvar,
113}
114
115pub struct CameraTap {
119 shared: Arc<Shared>,
120}
121
122#[derive(Clone)]
124pub struct CameraTapSender {
125 shared: Arc<Shared>,
126}
127
128impl std::fmt::Debug for CameraTap {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 let s = lock(&self.shared.slot);
131 f.debug_struct("CameraTap")
132 .field("feed", &s.feed)
133 .field("closed", &s.closed)
134 .finish_non_exhaustive()
135 }
136}
137
138impl std::fmt::Debug for CameraTapSender {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 f.debug_struct("CameraTapSender").finish_non_exhaustive()
141 }
142}
143
144impl CameraTap {
145 pub fn channel() -> (CameraTapSender, CameraTap) {
147 let shared = Arc::new(Shared {
148 slot: Mutex::new(Slot {
149 feed: CameraFeed::Off,
150 feed_new: true,
151 frame: None,
152 closed: false,
153 taken: 0,
154 dropped: 0,
155 }),
156 ready: Condvar::new(),
157 });
158 (
159 CameraTapSender {
160 shared: Arc::clone(&shared),
161 },
162 CameraTap { shared },
163 )
164 }
165
166 fn take(s: &mut Slot) -> Option<CameraTapItem> {
167 if s.closed {
168 return None;
169 }
170 if std::mem::take(&mut s.feed_new) {
171 return Some(CameraTapItem::Feed(s.feed));
172 }
173 let f = s.frame.take()?;
174 s.taken += 1;
175 Some(CameraTapItem::Frame(f))
176 }
177
178 pub fn try_recv(&self) -> Option<CameraTapItem> {
180 Self::take(&mut lock(&self.shared.slot))
181 }
182
183 pub fn recv_timeout(&self, wait: Duration) -> Option<CameraTapItem> {
186 let until = Instant::now() + wait;
187 let mut s = lock(&self.shared.slot);
188 loop {
189 if let Some(item) = Self::take(&mut s) {
190 return Some(item);
191 }
192 if s.closed {
193 return None;
194 }
195 let left = until.saturating_duration_since(Instant::now());
196 if left.is_zero() {
197 return None;
198 }
199 s = self
200 .shared
201 .ready
202 .wait_timeout(s, left)
203 .unwrap_or_else(PoisonError::into_inner)
204 .0;
205 }
206 }
207
208 pub fn feed(&self) -> CameraFeed {
210 lock(&self.shared.slot).feed
211 }
212
213 pub fn taken(&self) -> u64 {
215 lock(&self.shared.slot).taken
216 }
217
218 pub fn dropped(&self) -> u64 {
221 lock(&self.shared.slot).dropped
222 }
223
224 pub fn close(&self) {
227 let stale = {
228 let mut s = lock(&self.shared.slot);
229 s.closed = true;
230 s.frame.take()
231 };
232 drop(stale);
233 self.shared.ready.notify_all();
234 }
235
236 pub fn is_closed(&self) -> bool {
238 lock(&self.shared.slot).closed
239 }
240}
241
242impl Drop for CameraTap {
243 fn drop(&mut self) {
244 self.close();
245 }
246}
247
248impl CameraTapSender {
249 pub fn send(&self, frame: CameraFrame) -> bool {
252 let stale = {
253 let mut s = lock(&self.shared.slot);
254 if s.closed {
255 return false;
256 }
257 if s.feed != CameraFeed::Live {
258 s.feed = CameraFeed::Live;
259 s.feed_new = true;
260 }
261 let stale = s.frame.replace(frame);
262 if stale.is_some() {
263 s.dropped += 1;
264 }
265 stale
266 };
267 drop(stale);
269 self.shared.ready.notify_one();
270 true
271 }
272
273 pub fn set_feed(&self, feed: CameraFeed) -> bool {
276 let stale = {
277 let mut s = lock(&self.shared.slot);
278 if s.closed {
279 return false;
280 }
281 if s.feed == feed {
282 return true;
283 }
284 s.feed = feed;
285 s.feed_new = true;
286 if feed == CameraFeed::Live {
287 None
288 } else {
289 s.frame.take()
290 }
291 };
292 drop(stale);
293 self.shared.ready.notify_one();
294 true
295 }
296
297 pub fn is_closed(&self) -> bool {
299 lock(&self.shared.slot).closed
300 }
301}
302
303#[derive(Clone, Default)]
306pub(crate) struct CameraTaps(Arc<Mutex<Hub>>);
307
308#[derive(Default)]
309struct Hub {
310 taps: Vec<CameraTapSender>,
311 feed: CameraFeed,
312}
313
314impl CameraTaps {
315 pub(crate) fn open(&self) -> CameraTap {
317 let (tx, rx) = CameraTap::channel();
318 let mut h = lock(&self.0);
319 tx.set_feed(h.feed);
320 h.taps.retain(|t| !t.is_closed());
321 h.taps.push(tx);
322 rx
323 }
324
325 pub(crate) fn any(&self) -> bool {
327 let mut h = lock(&self.0);
328 h.taps.retain(|t| !t.is_closed());
329 !h.taps.is_empty()
330 }
331
332 pub(crate) fn frame(&self, frame: &VideoFrame, facing: Facing) {
334 let mut h = lock(&self.0);
335 h.feed = CameraFeed::Live;
336 if h.taps.is_empty() {
337 return;
338 }
339 h.taps
340 .retain(|t| t.send(CameraFrame::new(frame.clone(), facing)));
341 }
342
343 pub(crate) fn feed(&self, feed: CameraFeed) {
345 let mut h = lock(&self.0);
346 h.feed = feed;
347 h.taps.retain(|t| t.set_feed(feed));
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 #![allow(clippy::expect_used, clippy::unwrap_used)]
354 use super::*;
355
356 fn frame(n: u32) -> VideoFrame {
357 kessel_video::fake::pattern_frame(16, 16, n, u64::from(n)).expect("a frame")
358 }
359
360 fn capture_us(item: Option<CameraTapItem>) -> u64 {
361 match item {
362 Some(CameraTapItem::Frame(f)) => f.frame.capture_us,
363 other => panic!("a frame, got {other:?}"),
364 }
365 }
366
367 #[test]
368 fn a_slow_reader_gets_the_newest_frame_and_the_rest_are_counted_dropped() {
369 let taps = CameraTaps::default();
370 let tap = taps.open();
371 assert!(matches!(
372 tap.try_recv(),
373 Some(CameraTapItem::Feed(CameraFeed::Off))
374 ));
375 assert!(tap.try_recv().is_none());
376 for n in 1..=5 {
377 taps.frame(&frame(n), Facing::Front);
378 }
379 assert!(matches!(
380 tap.try_recv(),
381 Some(CameraTapItem::Feed(CameraFeed::Live))
382 ));
383 assert_eq!(capture_us(tap.try_recv()), 5, "the newest frame");
384 assert!(tap.try_recv().is_none(), "never a queue");
385 assert_eq!(tap.dropped(), 4);
386 assert_eq!(tap.taken(), 1);
387 }
388
389 #[test]
390 fn a_pause_drops_the_waiting_frame_and_comes_first() {
391 let taps = CameraTaps::default();
392 taps.frame(&frame(1), Facing::Back);
393 let tap = taps.open();
394 assert!(matches!(
395 tap.try_recv(),
396 Some(CameraTapItem::Feed(CameraFeed::Live))
397 ));
398 taps.frame(&frame(2), Facing::Back);
399 taps.feed(CameraFeed::Paused);
400 assert!(matches!(
401 tap.try_recv(),
402 Some(CameraTapItem::Feed(CameraFeed::Paused))
403 ));
404 assert!(
405 tap.try_recv().is_none(),
406 "the frame before the pause is gone"
407 );
408 taps.frame(&frame(3), Facing::Back);
409 assert!(matches!(
410 tap.try_recv(),
411 Some(CameraTapItem::Feed(CameraFeed::Live))
412 ));
413 match tap.try_recv() {
414 Some(CameraTapItem::Frame(f)) => {
415 assert_eq!(f.facing, Facing::Back);
416 assert_eq!(f.rotation, 0);
417 assert!(!f.mirror());
418 }
419 other => panic!("a frame, got {other:?}"),
420 }
421 }
422
423 #[test]
424 fn a_closed_tap_is_forgotten_and_wakes_its_reader() {
425 let taps = CameraTaps::default();
426 let tap = Arc::new(taps.open());
427 assert!(taps.any());
428 let _ = tap.try_recv();
429 let reader = {
430 let tap = Arc::clone(&tap);
431 std::thread::spawn(move || tap.recv_timeout(Duration::from_secs(30)))
432 };
433 std::thread::sleep(Duration::from_millis(50));
434 tap.close();
435 assert!(
436 reader.join().expect("the reader").is_none(),
437 "closed: nothing"
438 );
439 assert!(!taps.any(), "forgotten");
440 taps.frame(&frame(1), Facing::Front);
441 assert!(tap.try_recv().is_none());
442 }
443
444 #[test]
445 fn a_waiting_reader_wakes_on_a_frame() {
446 let (tx, tap) = CameraTap::channel();
447 assert!(matches!(
448 tap.recv_timeout(Duration::from_millis(1)),
449 Some(CameraTapItem::Feed(CameraFeed::Off))
450 ));
451 let sender = std::thread::spawn(move || {
452 std::thread::sleep(Duration::from_millis(50));
453 tx.send(CameraFrame::new(frame(7), Facing::Front))
454 });
455 assert!(matches!(
456 tap.recv_timeout(Duration::from_secs(10)),
457 Some(CameraTapItem::Feed(CameraFeed::Live))
458 ));
459 assert_eq!(capture_us(tap.recv_timeout(Duration::from_secs(10))), 7);
460 assert!(sender.join().expect("the sender"));
461 drop(tap);
462 }
463}