adk_surface/camera/hub.rs
1//! The hub every camera frame passes before anyone sees it (spec 3.7 §8.2, §7.13).
2//!
3//! The browser stops a track when its switch goes off and a pipeline stops sampling, but the
4//! server does not rely on either: [`Cameras::offer`] drops every frame of a camera that is off
5//! or stopped, whatever arrives, as `voice::VisualInputs` does for the voice screen. A frame
6//! that passes is held in memory only — the latest few, so a person can freeze one and raise a
7//! card from it — and never written anywhere. The one way a frame is kept is
8//! [`CameraSource::keep_frame`], from a card, blurred first.
9
10use std::collections::{HashMap, VecDeque};
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13
14use adk_core::GovernanceControl;
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17use tokio::sync::{RwLock, broadcast};
18
19use super::facts::{CameraFacts, CameraFrame, HeldFrame, ZoneFacts};
20use crate::error::{Result, SurfaceError};
21
22/// How many frames of each camera the hub holds, newest last: about two seconds at five a
23/// second, enough to freeze the frame on screen and draw each track's trail.
24pub const HELD_FRAMES: usize = 10;
25
26/// How many frozen frames of each camera the hub holds while people write their cards.
27pub const FROZEN_FRAMES: usize = 4;
28
29/// How long a frozen frame is held for its card, in minutes.
30pub const FROZEN_MINUTES: i64 = 15;
31
32/// The most frames a second a screen hands one camera through [`Cameras::ingest`]: twice the
33/// rate a camera's pipeline looks by default. A frame sooner after the last one taken is
34/// dropped ([`DropReason::TooSoon`]).
35pub const MAX_SCREEN_FPS: u32 = 10;
36
37/// Where the live camera surface reads cameras and acts on them (spec 3.7 §8.2): the seam
38/// between the surface and a frame pipeline.
39///
40/// The pipeline reports facts — the stream's state, the governor's numbers, tracks, watches,
41/// zones — and offers frames to the [`Cameras`] hub; the surface turns them into words. A
42/// person's switch and stop reach the source after the hub has already closed its gate, so a
43/// source that keeps sending sends to nobody.
44///
45/// # Example
46///
47/// ```rust
48/// use std::sync::Arc;
49/// use adk_surface::camera::{CameraFacts, CameraSource, Cameras, HeldFrame, ZoneFacts};
50///
51/// struct OneCamera;
52///
53/// #[async_trait::async_trait]
54/// impl CameraSource for OneCamera {
55/// async fn cameras(&self) -> adk_surface::Result<Vec<CameraFacts>> {
56/// Ok(vec![CameraFacts::new("line-2", "Line 2 camera", "inspector", "s-line")])
57/// }
58/// async fn keep_frame(
59/// &self,
60/// camera: &CameraFacts,
61/// frame: &HeldFrame,
62/// ) -> adk_surface::Result<adk_core::ImageEvidence> {
63/// let _ = (camera, frame);
64/// Err(adk_surface::SurfaceError::unsupported("keeping frames"))
65/// }
66/// }
67///
68/// let cameras = Cameras::new(Arc::new(OneCamera));
69/// # let _ = cameras;
70/// ```
71#[async_trait]
72pub trait CameraSource: Send + Sync {
73 /// Every camera this source serves, with its facts now.
74 ///
75 /// # Errors
76 ///
77 /// The source's error.
78 async fn cameras(&self) -> Result<Vec<CameraFacts>>;
79
80 /// Turns `camera` on or off at the source: off, it captures and sends nothing. The hub has
81 /// already closed or opened its gate. The default does nothing more.
82 ///
83 /// # Errors
84 ///
85 /// The source's error.
86 async fn switch(&self, camera: &str, on: bool) -> Result<()> {
87 let _ = (camera, on);
88 Ok(())
89 }
90
91 /// Ends `camera`'s stream. The default does nothing more than the hub's gate.
92 ///
93 /// # Errors
94 ///
95 /// The source's error.
96 async fn stop(&self, camera: &str) -> Result<()> {
97 let _ = camera;
98 Ok(())
99 }
100
101 /// Tries a lost source again now (board choice C6).
102 ///
103 /// # Errors
104 ///
105 /// `surface.unsupported` by default.
106 async fn retry(&self, camera: &str) -> Result<()> {
107 let _ = camera;
108 Err(SurfaceError::unsupported("trying a camera again"))
109 }
110
111 /// Changes zone `zone` of `camera`: every watch that uses it reads the new corners from its
112 /// next frame (board choice C12).
113 ///
114 /// # Errors
115 ///
116 /// `surface.unsupported` by default.
117 async fn save_zone(&self, camera: &str, zone: &ZoneFacts) -> Result<()> {
118 let _ = (camera, zone);
119 Err(SurfaceError::unsupported("changing a camera's zones"))
120 }
121
122 /// Pauses (`true`) or resumes (`false`) every camera at the source: Stop all, or Resume all
123 /// (spec 3.7 V-I17). The hub has already closed or opened its gate. The default does nothing
124 /// more.
125 ///
126 /// # Errors
127 ///
128 /// The source's error.
129 async fn freeze(&self, frozen: bool) -> Result<()> {
130 let _ = frozen;
131 Ok(())
132 }
133
134 /// Where the frames a screen captures for `camera` go once they pass the hub's gate
135 /// ([`Cameras::ingest`]): the frame pipeline's push side. `None`, the default, for a camera
136 /// whose source reads its own frames.
137 fn intake(&self, camera: &str) -> Option<Arc<dyn FrameIntake>> {
138 let _ = camera;
139 None
140 }
141
142 /// The camera the voice screen's camera feeds, when this source serves one: the voice view
143 /// hands that camera's frames to [`Cameras::ingest`] and mirrors its switch.
144 fn voice_camera(&self) -> Option<String> {
145 None
146 }
147
148 /// Keeps `frame` of `camera` as evidence: everyone in it blurred first, then written once,
149 /// kept [`EVIDENCE_RETENTION_DAYS`](crate::EVIDENCE_RETENTION_DAYS) (board choice C11, spec
150 /// 3.7 V-I9). Returns the evidence a card and a held call carry: the kept copy's digest, its
151 /// artifact and its regions.
152 ///
153 /// # Errors
154 ///
155 /// The source's error; nothing is kept then.
156 async fn keep_frame(
157 &self,
158 camera: &CameraFacts,
159 frame: &HeldFrame,
160 ) -> Result<adk_core::ImageEvidence>;
161}
162
163/// The push side of a frame pipeline: where [`Cameras::ingest`] hands a screen's frames once
164/// they passed the gate (spec 3.7 §7.13 `SurfaceCameraSource`).
165///
166/// # Example
167///
168/// ```rust
169/// use std::sync::Mutex;
170/// use adk_surface::camera::FrameIntake;
171///
172/// #[derive(Default)]
173/// struct Count(Mutex<usize>);
174///
175/// impl FrameIntake for Count {
176/// fn push(&self, _bytes: Vec<u8>, _at: chrono::DateTime<chrono::Utc>) -> bool {
177/// *self.0.lock().unwrap() += 1;
178/// true
179/// }
180/// }
181/// ```
182pub trait FrameIntake: Send + Sync {
183 /// Takes one encoded frame captured `at`; `false` when the pipeline dropped it.
184 fn push(&self, bytes: Vec<u8>, at: DateTime<Utc>) -> bool;
185}
186
187/// Who did something to a camera, and when.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Acted {
190 /// The person's user id.
191 pub by: String,
192 /// When.
193 pub at: DateTime<Utc>,
194}
195
196/// One camera's gate and the frames held for it.
197#[derive(Debug, Default)]
198struct Feed {
199 on: bool,
200 /// The person's last switch, when there was one.
201 switched: Option<Acted>,
202 /// The person stopped the stream.
203 stopped: Option<Acted>,
204 /// The latest frames, newest last; memory only.
205 recent: VecDeque<HeldFrame>,
206 /// Frames a person froze to raise a card from, with when; memory only.
207 frozen: VecDeque<(HeldFrame, DateTime<Utc>)>,
208 /// Frames dropped at the gate.
209 dropped: u64,
210 /// When a screen last handed this camera a frame that was taken.
211 last_ingest: Option<DateTime<Utc>>,
212}
213
214/// What became of a frame offered to the hub.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub enum Offered {
217 /// Held in memory and shown, under this digest.
218 Shown {
219 /// `sha256:` of its bytes.
220 digest: String,
221 },
222 /// Handed to the camera's frame pipeline ([`Cameras::ingest`]), which shows what it makes
223 /// of it.
224 Forwarded,
225 /// Dropped at the gate, and why.
226 Dropped(DropReason),
227}
228
229/// Why the hub dropped a frame.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum DropReason {
232 /// The camera is switched off: a source switched off sends nothing.
233 Off,
234 /// The stream was stopped.
235 Stopped,
236 /// Stop all paused every camera (spec 3.7 V-I17).
237 Frozen,
238 /// No source serves a camera of that id, or none takes its frames.
239 Unknown,
240 /// A screen sent it within a [`MAX_SCREEN_FPS`] interval of the last frame taken.
241 TooSoon,
242}
243
244/// What the hub tells the surfaces watching a camera.
245#[derive(Debug, Clone)]
246pub enum CameraUpdate {
247 /// A frame passed the gate.
248 Frame {
249 /// The camera.
250 camera: String,
251 /// The frame.
252 frame: Arc<HeldFrame>,
253 },
254 /// Something other than the frame changed: the switch, a stop, a zone.
255 Changed {
256 /// The camera.
257 camera: String,
258 },
259}
260
261impl CameraUpdate {
262 /// The camera it is about.
263 pub fn camera(&self) -> &str {
264 match self {
265 Self::Frame { camera, .. } | Self::Changed { camera } => camera,
266 }
267 }
268}
269
270/// A camera's switch and stop as the hub keeps them.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub(crate) struct Gate {
273 pub(crate) on: bool,
274 pub(crate) switched: Option<Acted>,
275 pub(crate) stopped: Option<Acted>,
276 /// Stop all paused every camera.
277 pub(crate) frozen: bool,
278}
279
280/// The cameras of a home and their gate (spec 3.7 §8.2): every frame passes [`Cameras::offer`],
281/// which drops what a switched-off or stopped camera sends and holds the rest in memory only.
282///
283/// # Example
284///
285/// ```rust
286/// # use std::sync::Arc;
287/// # use adk_surface::camera::{CameraFacts, CameraFrame, CameraSource, Cameras, DropReason, HeldFrame, Offered};
288/// # struct OneCamera;
289/// # #[async_trait::async_trait]
290/// # impl CameraSource for OneCamera {
291/// # async fn cameras(&self) -> adk_surface::Result<Vec<CameraFacts>> {
292/// # Ok(vec![CameraFacts::new("line-2", "Line 2 camera", "inspector", "s-line")])
293/// # }
294/// # async fn keep_frame(&self, _: &CameraFacts, _: &HeldFrame) -> adk_surface::Result<adk_core::ImageEvidence> {
295/// # Err(adk_surface::SurfaceError::unsupported("keeping frames"))
296/// # }
297/// # }
298/// # #[tokio::main(flavor = "current_thread")]
299/// # async fn main() {
300/// let cameras = Cameras::new(Arc::new(OneCamera));
301/// let frame = || CameraFrame::new(b"jpeg".to_vec(), "image/jpeg", 1920, 1080, chrono::Utc::now());
302/// assert!(matches!(cameras.offer("line-2", frame()).await, Offered::Shown { .. }));
303/// cameras.switch("line-2", false, "ana", chrono::Utc::now()).await.unwrap();
304/// assert_eq!(cameras.offer("line-2", frame()).await, Offered::Dropped(DropReason::Off));
305/// assert!(cameras.latest("line-2").await.is_none());
306/// # }
307/// ```
308#[derive(Clone)]
309pub struct Cameras {
310 inner: Arc<HubInner>,
311}
312
313struct HubInner {
314 source: Arc<dyn CameraSource>,
315 feeds: RwLock<HashMap<String, Feed>>,
316 updates: broadcast::Sender<CameraUpdate>,
317 /// Stop all: every camera paused until Resume all.
318 frozen: AtomicBool,
319 /// The kill switch the hub follows besides Stop all, when it follows one.
320 governance: std::sync::RwLock<Option<GovernanceControl>>,
321}
322
323/// A [`Cameras`] that does not keep the hub alive: what a frame pipeline holds, so the hub and
324/// its source do not own each other.
325#[cfg(feature = "vision-camera")]
326#[derive(Clone)]
327pub(crate) struct WeakCameras(std::sync::Weak<HubInner>);
328
329#[cfg(feature = "vision-camera")]
330impl WeakCameras {
331 /// The hub, while anything else holds it.
332 pub(crate) fn upgrade(&self) -> Option<Cameras> {
333 self.0.upgrade().map(|inner| Cameras { inner })
334 }
335}
336
337impl std::fmt::Debug for Cameras {
338 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339 f.debug_struct("Cameras").finish_non_exhaustive()
340 }
341}
342
343impl Cameras {
344 /// The hub over `source`. Each camera's switch starts as its facts say.
345 pub fn new(source: Arc<dyn CameraSource>) -> Self {
346 let (updates, _) = broadcast::channel(64);
347 Self {
348 inner: Arc::new(HubInner {
349 source,
350 feeds: RwLock::new(HashMap::new()),
351 updates,
352 frozen: AtomicBool::new(false),
353 governance: std::sync::RwLock::new(None),
354 }),
355 }
356 }
357
358 /// Follows `control` as well as Stop all: while it is frozen the gate drops every frame of
359 /// every camera, wherever the freeze came from (spec 3.7 V-I17).
360 #[must_use]
361 pub fn with_governance(self, control: GovernanceControl) -> Self {
362 *self.inner.governance.write().unwrap_or_else(std::sync::PoisonError::into_inner) =
363 Some(control);
364 self
365 }
366
367 #[cfg(feature = "vision-camera")]
368 pub(crate) fn downgrade(&self) -> WeakCameras {
369 WeakCameras(Arc::downgrade(&self.inner))
370 }
371
372 /// Whether every camera is paused: by Stop all, or by the kill switch the hub follows.
373 pub fn is_frozen(&self) -> bool {
374 self.inner.frozen.load(Ordering::SeqCst)
375 || self
376 .inner
377 .governance
378 .read()
379 .unwrap_or_else(std::sync::PoisonError::into_inner)
380 .as_ref()
381 .is_some_and(GovernanceControl::is_frozen)
382 }
383
384 /// Stop all (spec 3.7 V-I17): the gate drops every frame of every camera from now on, then
385 /// the source is told to pause its streams. The frames held stay, so a card can still be
386 /// raised from one.
387 ///
388 /// # Errors
389 ///
390 /// The source's error, after the gate closed.
391 pub async fn freeze_all(&self) -> Result<()> {
392 self.inner.frozen.store(true, Ordering::SeqCst);
393 self.changed_all().await;
394 self.inner.source.freeze(true).await
395 }
396
397 /// Resume all: the gate opens again for every camera a person has not switched off or
398 /// stopped, then the source is told.
399 ///
400 /// # Errors
401 ///
402 /// The source's error, after the gate opened.
403 pub async fn thaw_all(&self) -> Result<()> {
404 self.inner.frozen.store(false, Ordering::SeqCst);
405 self.changed_all().await;
406 self.inner.source.freeze(false).await
407 }
408
409 async fn changed_all(&self) {
410 let cameras: Vec<String> = self.inner.feeds.read().await.keys().cloned().collect();
411 for camera in cameras {
412 self.changed(&camera);
413 }
414 }
415
416 /// The camera the voice screen's camera feeds, when the source serves one.
417 pub fn voice_camera(&self) -> Option<String> {
418 self.inner.source.voice_camera()
419 }
420
421 /// Whether `camera` takes the frames a screen captures ([`ingest`](Self::ingest)): its
422 /// source has a pipeline's push side for it, as the web home's own camera does.
423 pub fn takes_frames(&self, camera: &str) -> bool {
424 self.inner.source.intake(camera).is_some()
425 }
426
427 /// Hands a frame a screen captured for `camera` to the camera's frame pipeline, once it
428 /// passes the gate: dropped when the camera is off, stopped, paused by Stop all or unknown,
429 /// when it comes within a [`MAX_SCREEN_FPS`] interval of the last frame taken, or when no
430 /// pipeline takes its frames. The pipeline offers what it makes of the frame — redacted,
431 /// with what it found — to [`offer`](Self::offer); nothing is held here.
432 pub async fn ingest(&self, camera: &str, bytes: Vec<u8>, at: DateTime<Utc>) -> Offered {
433 if let Err(reason) = self.admit(camera).await {
434 return Offered::Dropped(reason);
435 }
436 {
437 let gap = chrono::Duration::milliseconds(1_000 / i64::from(MAX_SCREEN_FPS));
438 let mut feeds = self.inner.feeds.write().await;
439 if let Some(feed) = feeds.get_mut(camera) {
440 if feed.last_ingest.is_some_and(|last| at >= last && at - last < gap) {
441 feed.dropped += 1;
442 return Offered::Dropped(DropReason::TooSoon);
443 }
444 feed.last_ingest = Some(at);
445 }
446 }
447 match self.inner.source.intake(camera) {
448 Some(intake) if intake.push(bytes, at) => Offered::Forwarded,
449 Some(_) | None => Offered::Dropped(DropReason::Unknown),
450 }
451 }
452
453 /// Whether `camera`'s gate lets a frame through now, counting the frames it drops.
454 async fn admit(&self, camera: &str) -> std::result::Result<(), DropReason> {
455 if !self.inner.feeds.read().await.contains_key(camera) {
456 // A camera seen for the first time: its switch starts as its facts say.
457 if let Err(error) = self.facts().await {
458 tracing::warn!(error = %error, camera.id = %camera, "a frame was dropped: the camera source could not be read");
459 return Err(DropReason::Unknown);
460 }
461 }
462 let frozen = self.is_frozen();
463 let mut feeds = self.inner.feeds.write().await;
464 let Some(feed) = feeds.get_mut(camera) else {
465 return Err(DropReason::Unknown);
466 };
467 let refused = if feed.stopped.is_some() {
468 Some(DropReason::Stopped)
469 } else if !feed.on {
470 Some(DropReason::Off)
471 } else if frozen {
472 Some(DropReason::Frozen)
473 } else {
474 None
475 };
476 match refused {
477 Some(reason) => {
478 feed.dropped += 1;
479 Err(reason)
480 }
481 None => Ok(()),
482 }
483 }
484
485 /// The source.
486 pub fn source(&self) -> &Arc<dyn CameraSource> {
487 &self.inner.source
488 }
489
490 /// Every camera's facts, each camera's gate made the first time it is seen.
491 pub(crate) async fn facts(&self) -> Result<Vec<CameraFacts>> {
492 let facts = self.inner.source.cameras().await?;
493 let mut feeds = self.inner.feeds.write().await;
494 for camera in &facts {
495 feeds
496 .entry(camera.id.clone())
497 .or_insert_with(|| Feed { on: camera.on, ..Feed::default() });
498 }
499 Ok(facts)
500 }
501
502 /// Offers `frame` of `camera`: dropped when the camera is off, stopped, paused by Stop all or
503 /// unknown, else held in memory as its newest frame and shown to whoever watches. Never
504 /// written anywhere.
505 pub async fn offer(&self, camera: &str, frame: CameraFrame) -> Offered {
506 if let Err(reason) = self.admit(camera).await {
507 return Offered::Dropped(reason);
508 }
509 let held = {
510 let mut feeds = self.inner.feeds.write().await;
511 let Some(feed) = feeds.get_mut(camera) else {
512 return Offered::Dropped(DropReason::Unknown);
513 };
514 // The gate may have closed since it was read: a switch or a stop wins the race.
515 if feed.stopped.is_some() || !feed.on {
516 feed.dropped += 1;
517 return Offered::Dropped(if feed.stopped.is_some() {
518 DropReason::Stopped
519 } else {
520 DropReason::Off
521 });
522 }
523 let held = HeldFrame { digest: crate::evidence::digest_of(&frame.bytes), frame };
524 if feed.recent.len() == HELD_FRAMES {
525 feed.recent.pop_front();
526 }
527 feed.recent.push_back(held.clone());
528 held
529 };
530 let digest = held.digest.clone();
531 let _ = self
532 .inner
533 .updates
534 .send(CameraUpdate::Frame { camera: camera.to_string(), frame: Arc::new(held) });
535 Offered::Shown { digest }
536 }
537
538 /// Turns `camera` on or off for `by` at `at`. The gate changes first, so no frame passes
539 /// after an off, and off forgets every frame held; then the source is told.
540 ///
541 /// # Errors
542 ///
543 /// `surface.not_found` for an unknown camera; the source's error, after the gate changed.
544 pub async fn switch(&self, camera: &str, on: bool, by: &str, at: DateTime<Utc>) -> Result<()> {
545 {
546 let mut feeds = self.inner.feeds.write().await;
547 let feed = feeds
548 .get_mut(camera)
549 .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))?;
550 feed.on = on;
551 feed.switched = Some(Acted { by: by.to_string(), at });
552 if !on {
553 feed.recent.clear();
554 feed.frozen.clear();
555 }
556 }
557 self.changed(camera);
558 self.inner.source.switch(camera, on).await
559 }
560
561 /// Ends `camera`'s stream for `by` at `at`: the gate closes for good and every frame held is
562 /// forgotten; then the source is told.
563 ///
564 /// # Errors
565 ///
566 /// `surface.not_found` for an unknown camera; the source's error, after the gate closed.
567 pub async fn stop(&self, camera: &str, by: &str, at: DateTime<Utc>) -> Result<()> {
568 {
569 let mut feeds = self.inner.feeds.write().await;
570 let feed = feeds
571 .get_mut(camera)
572 .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))?;
573 feed.on = false;
574 feed.stopped = Some(Acted { by: by.to_string(), at });
575 feed.recent.clear();
576 feed.frozen.clear();
577 }
578 self.changed(camera);
579 self.inner.source.stop(camera).await
580 }
581
582 /// The pipeline started `camera`'s stream again after a stop: its gate opens.
583 pub async fn started(&self, camera: &str) {
584 if let Some(feed) = self.inner.feeds.write().await.get_mut(camera) {
585 feed.stopped = None;
586 feed.on = true;
587 }
588 self.changed(camera);
589 }
590
591 /// Tells whoever watches `camera` to read it again: a zone, a watch or the governor changed.
592 pub fn changed(&self, camera: &str) {
593 let _ = self.inner.updates.send(CameraUpdate::Changed { camera: camera.to_string() });
594 }
595
596 /// The newest frame held for `camera`.
597 pub async fn latest(&self, camera: &str) -> Option<HeldFrame> {
598 self.inner.feeds.read().await.get(camera)?.recent.back().cloned()
599 }
600
601 /// The frame of `camera` with `digest`, while the hub still holds it: among the latest, or
602 /// frozen for a card.
603 pub async fn held(&self, camera: &str, digest: &str) -> Option<HeldFrame> {
604 let feeds = self.inner.feeds.read().await;
605 let feed = feeds.get(camera)?;
606 // Newest first: a still scene repeats its bytes, and the newest copy is the one shown.
607 feed.recent
608 .iter()
609 .rev()
610 .find(|held| held.digest == digest)
611 .or_else(|| feed.frozen.iter().map(|(held, _)| held).find(|held| held.digest == digest))
612 .cloned()
613 }
614
615 /// Freezes frame `digest` of `camera` at `at` for a card (board choice C11): held in memory
616 /// for [`FROZEN_MINUTES`], the newest [`FROZEN_FRAMES`] of them, and forgotten when the camera
617 /// is switched off. Nothing is written. Returns the frames up to it, oldest first, for its
618 /// trails; `None` when the hub no longer holds it.
619 pub async fn freeze(
620 &self,
621 camera: &str,
622 digest: &str,
623 at: DateTime<Utc>,
624 ) -> Option<Vec<HeldFrame>> {
625 let mut feeds = self.inner.feeds.write().await;
626 let feed = feeds.get_mut(camera)?;
627 feed.frozen.retain(|(_, frozen)| at - *frozen < chrono::Duration::minutes(FROZEN_MINUTES));
628 let upto: Vec<HeldFrame> = match feed.recent.iter().rposition(|held| held.digest == digest)
629 {
630 Some(index) => feed.recent.iter().take(index + 1).cloned().collect(),
631 None => vec![feed.frozen.iter().find(|(held, _)| held.digest == digest)?.0.clone()],
632 };
633 let frame = upto.last()?.clone();
634 feed.frozen.retain(|(held, _)| held.digest != digest);
635 if feed.frozen.len() == FROZEN_FRAMES {
636 feed.frozen.pop_front();
637 }
638 feed.frozen.push_back((frame, at));
639 Some(upto)
640 }
641
642 /// The frames held for `camera`, oldest first.
643 pub(crate) async fn recent(&self, camera: &str) -> Vec<HeldFrame> {
644 self.inner
645 .feeds
646 .read()
647 .await
648 .get(camera)
649 .map(|feed| feed.recent.iter().cloned().collect())
650 .unwrap_or_default()
651 }
652
653 /// How many frames of `camera` the gate dropped.
654 pub async fn dropped(&self, camera: &str) -> u64 {
655 self.inner.feeds.read().await.get(camera).map_or(0, |feed| feed.dropped)
656 }
657
658 /// Whether `camera` is on: switched on, not stopped and not paused by Stop all.
659 pub async fn is_on(&self, camera: &str) -> bool {
660 !self.is_frozen()
661 && self
662 .inner
663 .feeds
664 .read()
665 .await
666 .get(camera)
667 .is_some_and(|feed| feed.on && feed.stopped.is_none())
668 }
669
670 /// `camera`'s gate, as the views show it.
671 pub(crate) async fn gate(&self, camera: &str) -> Option<Gate> {
672 let frozen = self.is_frozen();
673 self.inner.feeds.read().await.get(camera).map(|feed| Gate {
674 on: feed.on,
675 switched: feed.switched.clone(),
676 stopped: feed.stopped.clone(),
677 frozen,
678 })
679 }
680
681 /// Every frame that passes the gate and every change, as it happens.
682 pub fn subscribe(&self) -> broadcast::Receiver<CameraUpdate> {
683 self.inner.updates.subscribe()
684 }
685}