Skip to main content

adk_surface/camera/
live.rs

1//! The live camera surface on the frame pipeline (spec 3.7 §7.13, §8.2, S12; feature
2//! `vision-camera`).
3//!
4//! [`PipelineCameras`] runs each camera through adk-vision's
5//! [`StreamPipeline`](adk_vision::stream::StreamPipeline) — source, frame governor, privacy,
6//! detector, tracker — and is the [`CameraSource`] the hub reads: what the surface shows is what
7//! the pipeline measured.
8//!
9//! | The surface shows | From |
10//! |---|---|
11//! | The picture and its overlays | Each observation's frame, after the camera's privacy hook and, with [`LiveCamera::cover_people`], everyone the detector calls a person covered, with its tracked regions; offered to the hub, whose gate drops it while the camera is off, stopped or paused by Stop all |
12//! | "Looking", "Frames today", the steps | The pipeline's [`GovernorHandle`] and the `vision.governor.step`s it took |
13//! | "Asking sam-3.1" | Escalations granted through [`PipelineCameras::escalate`] |
14//! | "Tracks now" | The tracker's anonymous identifiers on the newest frame (V-I8) |
15//! | "Watching for", zones | Each camera's [`WatchCondition`]s, held against every frame here; a zone a person edits becomes the conditions' zone from the next frame |
16//! | "Can't reach the camera" | The source failing, retried with a growing wait or at once from "Try again now" |
17//!
18//! Switching a stream camera off stops capture at its source: the stream is dropped — a
19//! [`DeviceSource`](adk_vision::stream::DeviceSource)'s ffmpeg exits, an RTSP connection
20//! closes — recorded as `vision.source.stopped`, and on opens it again (`vision.source.started`).
21//! Stop all closes every stream camera's source the same way (reason `stopAll`), and Resume all
22//! opens again each one that is on (`resumeAll`), so a freeze leaves no camera capturing
23//! (spec 3.7 V-I17).
24//!
25//! The web home's own camera is a [`LiveCamera::surface`]: frames the voice screen or the camera
26//! page ("Use this browser's camera") capture reach the hub through [`Cameras::ingest`], which
27//! drops them while the camera is off, and enter the pipeline through adk-vision's
28//! [`SurfaceCameraSource`].
29
30use std::collections::{HashMap, VecDeque};
31use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
32use std::sync::{Arc, Mutex};
33use std::time::Duration as StdDuration;
34
35use adk_artifact::ArtifactService;
36use adk_core::ImageEvidence;
37use adk_core::audit_log::{
38    AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
39};
40use adk_vision::stream::{
41    CameraFeed, EscalationVerdict, FrameBudget, FrameKeeper, FramePrivacy, FrameSource,
42    FrameStream, GovernorChange, GovernorHandle, KeepReason, NoRedaction, Observation,
43    ObservationSink, PrivacyHook, RedactedFrame, SourceEvent, StreamPipeline, SurfaceCameraSource,
44    VISION_SOURCE_STARTED, VISION_SOURCE_STOPPED,
45};
46use adk_vision::{
47    BBox, CallOptions, DecodeLimits, DecodedImage, DetectQuery, Frame, FrameMeta, FramePixels,
48    FrameSourceId, MediaScope, Region, Sampling, Shape, Tracker, VisionCx, VisionError,
49    VisionRuntime, WatchCondition, WatchEvaluator, WatchSink, Zone, watch_registered_draft,
50};
51use async_trait::async_trait;
52use chrono::{DateTime, NaiveDate, Utc};
53use futures::StreamExt;
54use serde_json::json;
55use tokio::sync::{Notify, watch};
56use tokio_util::sync::CancellationToken;
57
58use super::facts::{
59    CameraFacts, EscalationFacts, Finding, GovernorFacts, GovernorStep, GovernorStepKind,
60    HeldFrame, Overlay, StreamState, TrackFacts, TrackPhase, WatchFacts, ZoneFacts,
61};
62use super::hub::{CameraSource, Cameras, FrameIntake, WeakCameras};
63use crate::error::{Result, SurfaceError};
64
65/// How good a shown frame's JPEG is.
66const SHOWN_QUALITY: u8 = 82;
67
68/// The labels a frame's people go by: covered before a frame is shown or kept under
69/// [`LiveCamera::cover_people`], the whole box of every detected person.
70const PEOPLE: [&str; 2] = ["person", "face"];
71
72/// How long a camera waits before trying a lost source again, at first and at most.
73const RETRY_FIRST: StdDuration = StdDuration::from_secs(2);
74const RETRY_MOST: StdDuration = StdDuration::from_secs(30);
75
76/// How long switching a stream camera off waits for its source to close before answering.
77const STOP_WAIT: StdDuration = StdDuration::from_secs(3);
78
79fn vision(error: VisionError) -> SurfaceError {
80    SurfaceError::Source(error.into())
81}
82
83/// A watch condition on a live camera (spec 3.7 §7.10), as the surface names it.
84///
85/// # Example
86///
87/// ```rust
88/// use adk_surface::camera::LiveWatch;
89/// use adk_vision::WatchCondition;
90///
91/// let watch = LiveWatch::new(
92///     "crack",
93///     "Crack",
94///     WatchCondition::new("crack", ["crack"]).with_min_score(0.6).with_min_frames(3),
95/// )
96/// .in_zone("inspection-window")
97/// .wakes_for("a defect");
98/// # let _ = watch;
99/// ```
100#[derive(Debug, Clone)]
101pub struct LiveWatch {
102    id: String,
103    name: String,
104    condition: WatchCondition,
105    zone: Option<String>,
106    wakes_for: Option<String>,
107}
108
109impl LiveWatch {
110    /// The watch `id`, shown as `name`, holding `condition`. Its zone, when it has one, is a
111    /// zone of the camera ([`in_zone`](Self::in_zone)), never the condition's own.
112    pub fn new(id: impl Into<String>, name: impl Into<String>, condition: WatchCondition) -> Self {
113        Self { id: id.into(), name: name.into(), condition, zone: None, wakes_for: None }
114    }
115
116    /// Looks only inside the camera's zone `zone`.
117    #[must_use]
118    pub fn in_zone(mut self, zone: impl Into<String>) -> Self {
119        self.zone = Some(zone.into());
120        self
121    }
122
123    /// What the agent sleeps until, as its line says: "a defect" ("Asleep until a defect").
124    #[must_use]
125    pub fn wakes_for(mut self, what: impl Into<String>) -> Self {
126        self.wakes_for = Some(what.into());
127        self
128    }
129}
130
131/// What a camera's pipeline did with its frames since it started, for a test or a probe.
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
133#[serde(rename_all = "camelCase")]
134pub struct FrameCounts {
135    /// Frames the source delivered.
136    pub arrived: u64,
137    /// Frames dropped before the pipeline looked at them: the camera off, or Stop all.
138    pub dropped: u64,
139    /// Frames the pipeline looked at and offered to the hub.
140    pub observed: u64,
141    /// Watch events.
142    pub fired: u64,
143}
144
145/// Builds a fresh tracker for each run of a camera's pipeline.
146type TrackerFactory = Arc<dyn Fn() -> Box<dyn Tracker> + Send + Sync>;
147
148enum Input {
149    Stream(Arc<dyn FrameSource>),
150    Screen { source: Arc<SurfaceCameraSource>, feed: CameraFeed },
151}
152
153/// One camera on the frame pipeline: its facts, its source, and the pipeline's stages.
154///
155/// Frames are shown and kept as the camera sends them. Two opt-ins restrict that: a privacy
156/// hook ([`with_privacy`](Self::with_privacy)) redacts every frame before any other stage
157/// sees it, and [`cover_people`](Self::cover_people) covers every region the detector labels
158/// `person` or `face` before a frame is shown or kept.
159///
160/// # Example
161///
162/// ```rust
163/// use std::sync::Arc;
164/// use adk_surface::camera::{CameraFacts, Ingest, LiveCamera, LiveWatch, ZoneFacts};
165/// use adk_vision::stream::{FrameBudget, SurfaceCameraSource};
166/// use adk_vision::{FrameSourceId, GreedyIouTracker, WatchCondition};
167///
168/// let (source, _feed) = SurfaceCameraSource::new(FrameSourceId("line-2".into()));
169/// let camera = LiveCamera::stream(
170///     CameraFacts::new("line-2", "Line 2 camera", "inspector", "s-line")
171///         .with_ingest(Ingest::rtsp(640, 360, "the line 2 server")),
172///     Arc::new(source),
173/// )
174/// .tracker(|| Box::new(GreedyIouTracker::new(0.3, 4)))
175/// .budget(FrameBudget::new(5.0).with_min_local_fps(1.0).with_local_quota(200_000))
176/// .zone(ZoneFacts {
177///     id: "inspection-window".into(),
178///     name: "Inspection window".into(),
179///     corners: [200.0, 140.0, 440.0, 280.0],
180/// })
181/// .watch(LiveWatch::new("crack", "Crack", WatchCondition::new("crack", ["crack"])).in_zone("inspection-window"));
182/// # let _ = camera;
183/// ```
184pub struct LiveCamera {
185    facts: CameraFacts,
186    input: Input,
187    privacy: Arc<dyn PrivacyHook>,
188    cover_people: bool,
189    detection: Option<(Arc<VisionRuntime>, DetectQuery, CallOptions)>,
190    tracker: Option<TrackerFactory>,
191    budget: Option<FrameBudget>,
192    sampling: Option<Sampling>,
193    watches: Vec<LiveWatch>,
194    escalation: Option<(String, u64)>,
195}
196
197impl std::fmt::Debug for LiveCamera {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.debug_struct("LiveCamera").field("id", &self.facts.id).finish_non_exhaustive()
200    }
201}
202
203impl LiveCamera {
204    /// A camera whose frames `source` reads: an RTSP camera, a file, a screen. It starts on
205    /// unless `facts` says otherwise.
206    pub fn stream(facts: CameraFacts, source: Arc<dyn FrameSource>) -> Self {
207        Self::with_input(facts, Input::Stream(source))
208    }
209
210    /// The web home's own camera (spec 3.7 §7.13 `SurfaceCameraSource`): frames the voice
211    /// screen or the camera page captures reach it through [`Cameras::ingest`] — the camera
212    /// page sends them to `POST /surface/cameras/{camera}/frames` — with no realtime model. It
213    /// starts off, says it comes "from the web home", and takes nothing until a person
214    /// switches it on.
215    pub fn surface(facts: CameraFacts) -> Self {
216        let (source, feed) = SurfaceCameraSource::new(FrameSourceId(facts.id.clone()));
217        let facts = match facts.from {
218            Some(_) => facts,
219            None => facts.from("from the web home"),
220        }
221        .switched(false);
222        Self::with_input(facts, Input::Screen { source: Arc::new(source), feed })
223    }
224
225    fn with_input(facts: CameraFacts, input: Input) -> Self {
226        let zones = facts.zones.clone();
227        Self {
228            facts: CameraFacts { zones, ..facts },
229            input,
230            privacy: Arc::new(NoRedaction),
231            cover_people: false,
232            detection: None,
233            tracker: None,
234            budget: None,
235            sampling: None,
236            watches: Vec::new(),
237            escalation: None,
238        }
239    }
240
241    /// Passes every frame through `hook` before any other stage sees it, such as
242    /// `RedactorPrivacy::blur_faces`; a frame the hook fails on is dropped.
243    #[must_use]
244    pub fn with_privacy(mut self, hook: Arc<dyn PrivacyHook>) -> Self {
245        self.privacy = hook;
246        self
247    }
248
249    /// Covers every region the detector labels `person` or `face`, its whole box, before a
250    /// frame is shown or kept.
251    #[must_use]
252    pub fn cover_people(mut self) -> Self {
253        self.cover_people = true;
254        self
255    }
256
257    /// Detects `query` on every frame through `runtime`'s detection route.
258    #[must_use]
259    pub fn detector(mut self, runtime: Arc<VisionRuntime>, query: DetectQuery) -> Self {
260        self.detection = Some((runtime, query, CallOptions::default()));
261        self
262    }
263
264    /// The detection call's options: a route, a region of interest.
265    #[must_use]
266    pub fn detect_options(mut self, options: CallOptions) -> Self {
267        if let Some((_, _, current)) = &mut self.detection {
268            *current = options;
269        }
270        self
271    }
272
273    /// Tracks detections across frames with a tracker `make` builds for each run of the
274    /// pipeline, so identifiers start again with each source session (V-I8).
275    #[must_use]
276    pub fn tracker(mut self, make: impl Fn() -> Box<dyn Tracker> + Send + Sync + 'static) -> Self {
277        self.tracker = Some(Arc::new(make));
278        self
279    }
280
281    /// Holds the camera to `budget` through a frame governor (spec 3.7 §7.9).
282    #[must_use]
283    pub fn budget(mut self, budget: FrameBudget) -> Self {
284        self.budget = Some(budget);
285        self
286    }
287
288    /// Samples the source at `sampling`; the budget's local rate by default.
289    #[must_use]
290    pub fn sampling(mut self, sampling: Sampling) -> Self {
291        self.sampling = Some(sampling);
292        self
293    }
294
295    /// Adds zone `zone`, in the camera's pixels.
296    #[must_use]
297    pub fn zone(mut self, zone: ZoneFacts) -> Self {
298        self.facts.zones.retain(|existing| existing.id != zone.id);
299        self.facts.zones.push(zone);
300        self
301    }
302
303    /// Adds watch condition `watch`.
304    #[must_use]
305    pub fn watch(mut self, watch: LiveWatch) -> Self {
306        self.watches.push(watch);
307        self
308    }
309
310    /// Escalates unclear tracks to `backend`, such as `sam-3.1`, each billed frame costing
311    /// `micros_per_frame` micro-USD: [`PipelineCameras::escalate`] asks the governor first.
312    #[must_use]
313    pub fn escalation(mut self, backend: impl Into<String>, micros_per_frame: u64) -> Self {
314        self.escalation = Some((backend.into(), micros_per_frame));
315        self
316    }
317}
318
319/// The share of a camera's frames the surface needs back from the pipeline, behind one lock.
320struct RunState {
321    stream: StreamState,
322    /// The camera's size in pixels: the frames' when they are not downscaled.
323    size: (u32, u32),
324    governor: Option<GovernorHandle>,
325    steps: Vec<GovernorStep>,
326    paused_since: Option<DateTime<Utc>>,
327    escalation_stopped_at: Option<DateTime<Utc>>,
328    /// Escalations granted: when, and the frames billed.
329    grants: VecDeque<(DateTime<Utc>, u64)>,
330    tracks: Vec<TrackFacts>,
331    /// Each track's centre on the frame before, for which way it moves.
332    centres: HashMap<u64, f64>,
333    zones: Vec<ZoneFacts>,
334    evaluator: WatchEvaluator,
335    /// Frames in a row each (watch, track) met its condition.
336    streaks: HashMap<(usize, u64), u32>,
337    woke: Vec<u32>,
338    woke_on: Option<NaiveDate>,
339    last_frame: Option<DateTime<Utc>>,
340    attempt: u32,
341}
342
343/// One camera and the task running its pipeline.
344struct Run {
345    base: CameraFacts,
346    id: FrameSourceId,
347    input: Input,
348    privacy: Arc<dyn PrivacyHook>,
349    cover_people: bool,
350    detection: Option<(Arc<VisionRuntime>, DetectQuery, CallOptions)>,
351    tracker: Option<TrackerFactory>,
352    budget: Option<FrameBudget>,
353    sampling: Option<Sampling>,
354    watches: Vec<LiveWatch>,
355    escalation: Option<(String, u64)>,
356    /// The camera's switch: a stream camera's source captures only while it is on.
357    switch: watch::Sender<bool>,
358    /// Whether the camera's source holds an open stream: a device captures, a connection reads.
359    capturing: watch::Sender<bool>,
360    stopped: AtomicBool,
361    arrived: AtomicU64,
362    dropped: AtomicU64,
363    observed: AtomicU64,
364    fired: AtomicU64,
365    cancel: CancellationToken,
366    retry_now: Notify,
367    state: Mutex<RunState>,
368}
369
370impl Run {
371    fn lock(&self) -> std::sync::MutexGuard<'_, RunState> {
372        self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
373    }
374
375    fn is_on(&self) -> bool {
376        *self.switch.borrow()
377    }
378
379    fn feed(&self) -> Option<&CameraFeed> {
380        match &self.input {
381            Input::Screen { feed, .. } => Some(feed),
382            Input::Stream(_) => None,
383        }
384    }
385
386    /// The watches' conditions, each zone the camera's zone of that id now.
387    fn conditions(&self, zones: &[ZoneFacts]) -> Vec<WatchCondition> {
388        self.watches
389            .iter()
390            .map(|watch| {
391                let zone = watch
392                    .zone
393                    .as_deref()
394                    .and_then(|id| zones.iter().find(|zone| zone.id == id))
395                    .and_then(|zone| {
396                        let [x0, y0, x1, y1] = zone.corners.map(|value| value as f32);
397                        Zone::new(vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).ok()
398                    });
399                let mut condition = watch.condition.clone();
400                condition.zone = zone;
401                condition
402            })
403            .collect()
404    }
405
406    fn facts(&self, now: DateTime<Utc>) -> CameraFacts {
407        let state = self.lock();
408        let mut facts = self.base.clone();
409        facts.ingest.width = state.size.0;
410        facts.ingest.height = state.size.1;
411        facts.state = match state.paused_since {
412            Some(since) => StreamState::Paused { since },
413            None => state.stream.clone(),
414        };
415        facts.governor = self.governor_facts(&state, now);
416        facts.tracks = match facts.state {
417            StreamState::Live if self.is_on() => state.tracks.clone(),
418            StreamState::Live | StreamState::Paused { .. } | StreamState::Lost { .. } => Vec::new(),
419        };
420        let today = now.date_naive();
421        facts.watches = self
422            .watches
423            .iter()
424            .enumerate()
425            .map(|(index, watch)| WatchFacts {
426                id: watch.id.clone(),
427                name: watch.name.clone(),
428                label: watch.condition.labels.first().cloned().unwrap_or_default(),
429                min_score: f64::from(watch.condition.min_score),
430                frames: watch.condition.min_frames,
431                zone: watch.zone.clone(),
432                cooldown_secs: u32::try_from(watch.condition.cooldown.as_secs())
433                    .unwrap_or(u32::MAX),
434                woke_today: if state.woke_on == Some(today) {
435                    state.woke.get(index).copied().unwrap_or(0)
436                } else {
437                    0
438                },
439                wakes_for: watch.wakes_for.clone(),
440            })
441            .collect();
442        facts.zones = state.zones.clone();
443        facts
444    }
445
446    fn governor_facts(&self, state: &RunState, now: DateTime<Utc>) -> GovernorFacts {
447        let Some(budget) = &self.budget else {
448            let rate = self.sampling.map_or(1.0, |sampling| f64::from(sampling.fps));
449            return GovernorFacts::new(rate, 0, now);
450        };
451        let (rate, frames_today, renews_at) = match &state.governor {
452            Some(governor) => {
453                let now = governor.state();
454                (f64::from(now.fps), now.local_frames, now.period_ends_at)
455            }
456            None => {
457                let period = i64::try_from(budget.period_secs).unwrap_or(i64::MAX).max(1);
458                let end = (now.timestamp().div_euclid(period) + 1).saturating_mul(period);
459                (f64::from(budget.local_fps), 0, DateTime::from_timestamp(end, 0).unwrap_or(now))
460            }
461        };
462        let mut facts = GovernorFacts::new(
463            f64::from(budget.local_fps),
464            budget.local_frames_per_period.unwrap_or(0),
465            renews_at,
466        )
467        .with_rate(rate)
468        .with_frames_today(frames_today);
469        facts.min_rate = Some(f64::from(budget.min_local_fps));
470        facts.look_less_at = state.steps.iter().find_map(|step| step.used).unwrap_or(0.9);
471        facts.steps = state.steps.clone();
472        if let Some((backend, micros)) = &self.escalation {
473            let minute_ago = now - chrono::Duration::seconds(60);
474            let billed: u64 = state.grants.iter().map(|(_, frames)| frames).sum();
475            facts.escalation = Some(EscalationFacts {
476                backend: backend.clone(),
477                last_minute: u32::try_from(
478                    state.grants.iter().filter(|(at, _)| *at > minute_ago).count(),
479                )
480                .unwrap_or(u32::MAX),
481                max_per_minute: budget.escalations_per_minute.unwrap_or(0),
482                today: u32::try_from(state.grants.len()).unwrap_or(u32::MAX),
483                cost_today_micros: billed.saturating_mul(*micros),
484                stopped_at: state.escalation_stopped_at,
485            });
486        }
487        facts
488    }
489}
490
491struct Shared {
492    app: String,
493    user: String,
494    artifacts: Option<Arc<dyn ArtifactService>>,
495    cx: VisionCx,
496    audit: Option<(AuditTrail, AuditActor)>,
497    wakes: Option<Arc<dyn WatchSink>>,
498    /// Stop all, as the hub told the source: while it is in force every stream camera's source
499    /// is closed.
500    frozen: watch::Sender<bool>,
501}
502
503impl Shared {
504    async fn audit(&self, draft: AuditRecordDraft) {
505        if let Some((trail, actor)) = &self.audit
506            && let Err(error) = trail.record(draft.actor(actor.clone())).await
507        {
508            tracing::warn!(error = %error, "a camera's audit record was not written");
509        }
510    }
511}
512
513/// The cameras of a home on the frame pipeline (spec 3.7 §7.13, §8.2): the [`CameraSource`]
514/// that reports what each camera's pipeline measured.
515///
516/// [`start`](Self::start) makes the hub over it and starts every camera's pipeline; each runs
517/// until its camera is stopped or the hub is dropped. A camera switched off has its frames
518/// dropped before the pipeline looks at them, and the hub's gate drops anything still on its
519/// way; Stop all does the same for every camera (V-I17), and a frozen kill switch in the
520/// context pauses each pipeline at its next frame with a `vision.source.paused` record.
521///
522/// # Example
523///
524/// ```rust,no_run
525/// use std::sync::Arc;
526/// use adk_surface::camera::{CameraFacts, LiveCamera, PipelineCameras};
527/// use adk_vision::VisionCx;
528///
529/// # async fn example(source: Arc<dyn adk_vision::stream::FrameSource>) {
530/// let live = PipelineCameras::builder("inspector", "ana")
531///     .cx(VisionCx::new())
532///     .camera(LiveCamera::stream(
533///         CameraFacts::new("line-2", "Line 2 camera", "inspector", "s-line"),
534///         source,
535///     ))
536///     .build()
537///     .unwrap();
538/// let cameras = live.start();
539/// # let _ = cameras;
540/// # }
541/// ```
542pub struct PipelineCameras {
543    shared: Arc<Shared>,
544    runs: Vec<Arc<Run>>,
545    governance: Option<adk_core::GovernanceControl>,
546}
547
548impl std::fmt::Debug for PipelineCameras {
549    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
550        f.debug_struct("PipelineCameras")
551            .field("cameras", &self.runs.iter().map(|run| &run.base.id).collect::<Vec<_>>())
552            .finish_non_exhaustive()
553    }
554}
555
556impl Drop for PipelineCameras {
557    fn drop(&mut self) {
558        for run in &self.runs {
559            run.cancel.cancel();
560        }
561    }
562}
563
564/// Builds [`PipelineCameras`].
565pub struct PipelineCamerasBuilder {
566    app: String,
567    user: String,
568    artifacts: Option<Arc<dyn ArtifactService>>,
569    cx: VisionCx,
570    governance: Option<adk_core::GovernanceControl>,
571    audit: Option<(AuditTrail, AuditActor)>,
572    wakes: Option<Arc<dyn WatchSink>>,
573    cameras: Vec<LiveCamera>,
574}
575
576impl PipelineCamerasBuilder {
577    /// Keeps card evidence and wake payloads in `artifacts`, in each camera's session of the
578    /// builder's app and user; without it, raising a card is refused.
579    #[must_use]
580    pub fn artifacts(mut self, artifacts: Arc<dyn ArtifactService>) -> Self {
581        self.artifacts = Some(artifacts);
582        self
583    }
584
585    /// Runs every pipeline under `cx`: its meter, its audit trail, its cancellation.
586    #[must_use]
587    pub fn cx(mut self, cx: VisionCx) -> Self {
588        self.cx = cx;
589        self
590    }
591
592    /// The kill switch every pipeline and the hub follow (spec 3.7 V-I17): while it is frozen,
593    /// each pipeline drops its frames unprocessed and the hub's gate drops every frame.
594    #[must_use]
595    pub fn governance(mut self, control: adk_core::GovernanceControl) -> Self {
596        self.cx = self.cx.with_governance(control.clone());
597        self.governance = Some(control);
598        self
599    }
600
601    /// Writes the cameras' `vision.*` records — the pipelines' and each watch's
602    /// `vision.watch.registered` and `.fired` — to `trail` as `actor`.
603    #[must_use]
604    pub fn audit(mut self, trail: AuditTrail, actor: AuditActor) -> Self {
605        self.cx = self.cx.with_audit(trail.clone(), actor.clone());
606        self.audit = Some((trail, actor));
607        self
608    }
609
610    /// Hands every watch event to `wakes`, such as the kernel's `VisionWakeSource`, with its
611    /// frame kept redacted as the wake payload (needs [`artifacts`](Self::artifacts)).
612    #[must_use]
613    pub fn wakes(mut self, wakes: Arc<dyn WatchSink>) -> Self {
614        self.wakes = Some(wakes);
615        self
616    }
617
618    /// Adds `camera`.
619    #[must_use]
620    pub fn camera(mut self, camera: LiveCamera) -> Self {
621        self.cameras.push(camera);
622        self
623    }
624
625    /// The cameras, not yet started.
626    ///
627    /// # Errors
628    ///
629    /// `surface.invalid` for two cameras with one id, a watch on a zone the camera does not
630    /// have, or conditions the watch evaluator refuses.
631    pub fn build(self) -> Result<Arc<PipelineCameras>> {
632        let shared = Arc::new(Shared {
633            app: self.app,
634            user: self.user,
635            artifacts: self.artifacts,
636            cx: self.cx,
637            audit: self.audit,
638            wakes: self.wakes,
639            frozen: watch::Sender::new(false),
640        });
641        let mut runs: Vec<Arc<Run>> = Vec::with_capacity(self.cameras.len());
642        for camera in self.cameras {
643            if runs.iter().any(|run| run.base.id == camera.facts.id) {
644                return Err(SurfaceError::Invalid(format!(
645                    "two cameras are named '{}'; each id names one camera's routes",
646                    camera.facts.id
647                )));
648            }
649            for watch in &camera.watches {
650                if let Some(zone) = &watch.zone
651                    && !camera.facts.zones.iter().any(|candidate| &candidate.id == zone)
652                {
653                    return Err(SurfaceError::Invalid(format!(
654                        "watch '{}' of camera '{}' looks inside zone '{zone}', which the camera does not have",
655                        watch.id, camera.facts.id
656                    )));
657                }
658            }
659            let cancel = shared.cx.cancellation().child_token();
660            let size = (camera.facts.ingest.width, camera.facts.ingest.height);
661            let zones = camera.facts.zones.clone();
662            let mut run = Run {
663                id: FrameSourceId(camera.facts.id.clone()),
664                switch: watch::Sender::new(camera.facts.on),
665                capturing: watch::Sender::new(false),
666                base: camera.facts,
667                input: camera.input,
668                privacy: camera.privacy,
669                cover_people: camera.cover_people,
670                detection: camera.detection,
671                tracker: camera.tracker,
672                budget: camera.budget,
673                sampling: camera.sampling,
674                escalation: camera.escalation,
675                stopped: AtomicBool::new(false),
676                arrived: AtomicU64::new(0),
677                dropped: AtomicU64::new(0),
678                observed: AtomicU64::new(0),
679                fired: AtomicU64::new(0),
680                cancel,
681                retry_now: Notify::new(),
682                state: Mutex::new(RunState {
683                    stream: StreamState::Live,
684                    size,
685                    governor: None,
686                    steps: Vec::new(),
687                    paused_since: None,
688                    escalation_stopped_at: None,
689                    grants: VecDeque::new(),
690                    tracks: Vec::new(),
691                    centres: HashMap::new(),
692                    zones: Vec::new(),
693                    evaluator: WatchEvaluator::new(Vec::new()).map_err(vision)?,
694                    streaks: HashMap::new(),
695                    woke: vec![0; camera.watches.len()],
696                    woke_on: None,
697                    last_frame: None,
698                    attempt: 0,
699                }),
700                watches: camera.watches,
701            };
702            let conditions = run.conditions(&zones);
703            let state = run.state.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner);
704            state.evaluator = WatchEvaluator::new(conditions).map_err(vision)?;
705            state.zones = zones;
706            if let Some(feed) = run.feed() {
707                feed.switch(run.is_on());
708            }
709            runs.push(Arc::new(run));
710        }
711        Ok(Arc::new(PipelineCameras { shared, runs, governance: self.governance }))
712    }
713}
714
715impl PipelineCameras {
716    /// A builder of the cameras of `user` in `app`.
717    pub fn builder(app: impl Into<String>, user: impl Into<String>) -> PipelineCamerasBuilder {
718        PipelineCamerasBuilder {
719            app: app.into(),
720            user: user.into(),
721            artifacts: None,
722            cx: VisionCx::new(),
723            governance: None,
724            audit: None,
725            wakes: None,
726            cameras: Vec::new(),
727        }
728    }
729
730    /// The hub over these cameras, following the kill switch they were built with, and every
731    /// camera's pipeline started. A pipeline holds the hub weakly: dropping every clone of the
732    /// hub and of these cameras stops them.
733    pub fn start(self: &Arc<Self>) -> Cameras {
734        let mut hub = Cameras::new(Arc::clone(self) as Arc<dyn CameraSource>);
735        if let Some(control) = &self.governance {
736            hub = hub.with_governance(control.clone());
737        }
738        for run in &self.runs {
739            tokio::spawn(drive(Arc::clone(run), Arc::clone(&self.shared), hub.downgrade()));
740        }
741        hub
742    }
743
744    fn run(&self, camera: &str) -> Result<&Arc<Run>> {
745        self.runs
746            .iter()
747            .find(|run| run.base.id == camera)
748            .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))
749    }
750
751    /// What camera `camera`'s pipeline did with its frames so far.
752    pub fn counts(&self, camera: &str) -> Option<FrameCounts> {
753        let run = self.run(camera).ok()?;
754        Some(FrameCounts {
755            arrived: run.arrived.load(Ordering::SeqCst),
756            dropped: run.dropped.load(Ordering::SeqCst),
757            observed: run.observed.load(Ordering::SeqCst),
758            fired: run.fired.load(Ordering::SeqCst),
759        })
760    }
761
762    /// Whether camera `camera`'s source holds an open stream now: a device capturing, a
763    /// connection reading. A stream camera switched off holds none.
764    pub fn is_capturing(&self, camera: &str) -> Option<bool> {
765        Some(*self.run(camera).ok()?.capturing.borrow())
766    }
767
768    /// Camera `camera`'s frame governor, once its pipeline runs.
769    pub fn governor(&self, camera: &str) -> Option<GovernorHandle> {
770        self.run(camera).ok()?.lock().governor.clone()
771    }
772
773    /// Asks camera `camera`'s governor to escalate `frames` frames of an unclear track now:
774    /// granted with the frames billed, or refused with the reason. A grant counts in "Asking …
775    /// about unclear tracks".
776    ///
777    /// # Errors
778    ///
779    /// `surface.not_found` for an unknown camera, `surface.unsupported` before its pipeline
780    /// runs or without a budget, and the audit trail's error when it fails closed.
781    pub async fn escalate(&self, camera: &str, frames: u64) -> Result<EscalationVerdict> {
782        self.escalate_at(camera, Utc::now(), frames).await
783    }
784
785    /// As [`escalate`](Self::escalate), asked at `at`: for a replayed stream, whose governor
786    /// runs on the frames' capture times.
787    ///
788    /// # Errors
789    ///
790    /// As [`escalate`](Self::escalate).
791    pub async fn escalate_at(
792        &self,
793        camera: &str,
794        at: DateTime<Utc>,
795        frames: u64,
796    ) -> Result<EscalationVerdict> {
797        let run = self.run(camera)?;
798        let governor = run.lock().governor.clone().ok_or_else(|| {
799            SurfaceError::unsupported("escalating before the camera's governor runs")
800        })?;
801        let verdict =
802            governor.request_escalation_at(&self.shared.cx, at, frames).await.map_err(vision)?;
803        if let EscalationVerdict::Granted { billed_frames } = verdict {
804            let period = governor.state();
805            let length = run.budget.as_ref().map_or(86_400, |budget| budget.period_secs);
806            let period_start = period.period_ends_at
807                - chrono::Duration::seconds(i64::try_from(length).unwrap_or(86_400));
808            let mut state = run.lock();
809            state.grants.retain(|(granted, _)| *granted >= period_start);
810            state.grants.push_back((at, billed_frames));
811        }
812        Ok(verdict)
813    }
814}
815
816#[async_trait]
817impl CameraSource for PipelineCameras {
818    async fn cameras(&self) -> Result<Vec<CameraFacts>> {
819        let now = Utc::now();
820        Ok(self.runs.iter().map(|run| run.facts(now)).collect())
821    }
822
823    /// Off stops a stream camera's capture at its source: its stream is dropped — a
824    /// [`DeviceSource`](adk_vision::stream::DeviceSource)'s ffmpeg exits, a connection closes —
825    /// and nothing opens it until the camera is on again; the answer comes once the stream is
826    /// closed, or after [`STOP_WAIT`] whatever the source does. On opens it again. The hub's
827    /// gate and the pipeline's own check still drop any frame on its way.
828    async fn switch(&self, camera: &str, on: bool) -> Result<()> {
829        let run = self.run(camera)?;
830        run.switch.send_replace(on);
831        if let Some(feed) = run.feed() {
832            feed.switch(on);
833        }
834        if !on {
835            {
836                let mut state = run.lock();
837                state.tracks.clear();
838                state.centres.clear();
839                state.streaks.clear();
840            }
841            if run.feed().is_none() {
842                let mut capturing = run.capturing.subscribe();
843                if tokio::time::timeout(STOP_WAIT, capturing.wait_for(|open| !*open)).await.is_err()
844                {
845                    tracing::warn!(camera.id = %camera, "the camera's source did not close in time; its frames are still dropped");
846                }
847            }
848        }
849        Ok(())
850    }
851
852    async fn stop(&self, camera: &str) -> Result<()> {
853        let run = self.run(camera)?;
854        run.stopped.store(true, Ordering::SeqCst);
855        run.switch.send_replace(false);
856        if let Some(feed) = run.feed() {
857            feed.switch(false);
858        }
859        run.cancel.cancel();
860        run.lock().tracks.clear();
861        Ok(())
862    }
863
864    async fn retry(&self, camera: &str) -> Result<()> {
865        self.run(camera)?.retry_now.notify_one();
866        Ok(())
867    }
868
869    async fn save_zone(&self, camera: &str, zone: &ZoneFacts) -> Result<()> {
870        let run = self.run(camera)?;
871        let changed: Vec<WatchCondition> = {
872            let mut state = run.lock();
873            let entry = state
874                .zones
875                .iter_mut()
876                .find(|candidate| candidate.id == zone.id)
877                .ok_or_else(|| SurfaceError::not_found(format!("zone '{}'", zone.id)))?;
878            *entry = zone.clone();
879            let conditions = run.conditions(&state.zones);
880            // Counting starts again with the new corners: a track met the old zone, not this one.
881            state.evaluator = WatchEvaluator::new(conditions.clone()).map_err(vision)?;
882            state.streaks.clear();
883            run.watches
884                .iter()
885                .zip(conditions)
886                .filter(|(watch, _)| watch.zone.as_deref() == Some(zone.id.as_str()))
887                .map(|(_, condition)| condition)
888                .collect()
889        };
890        for condition in &changed {
891            self.shared.audit(watch_registered_draft(&run.id, condition)).await;
892        }
893        tracing::info!(camera.id = %camera, zone.id = %zone.id, watches = changed.len(), "zone changed");
894        Ok(())
895    }
896
897    /// Stop all closes each stream camera's source as off does — a device's ffmpeg exits, a
898    /// connection closes — and answers once each has closed, or after [`STOP_WAIT`] whatever a
899    /// source does; Resume all opens again each one that is on. The voice screen's camera
900    /// captures in the browser, which stops its own track: its frames are dropped.
901    async fn freeze(&self, frozen: bool) -> Result<()> {
902        self.shared.frozen.send_replace(frozen);
903        if frozen {
904            let closing = self.runs.iter().filter(|run| run.feed().is_none()).map(|run| async move {
905                let mut capturing = run.capturing.subscribe();
906                if tokio::time::timeout(STOP_WAIT, capturing.wait_for(|open| !*open)).await.is_err()
907                {
908                    tracing::warn!(camera.id = %run.base.id, "the camera's source did not close in time after Stop all; its frames are still dropped");
909                }
910            });
911            futures::future::join_all(closing).await;
912        }
913        Ok(())
914    }
915
916    fn intake(&self, camera: &str) -> Option<Arc<dyn FrameIntake>> {
917        let feed = self.run(camera).ok()?.feed()?.clone();
918        Some(Arc::new(FeedIntake(feed)))
919    }
920
921    fn voice_camera(&self) -> Option<String> {
922        self.runs.iter().find(|run| run.feed().is_some()).map(|run| run.base.id.clone())
923    }
924
925    async fn keep_frame(&self, camera: &CameraFacts, frame: &HeldFrame) -> Result<ImageEvidence> {
926        let run = self.run(&camera.id)?;
927        let artifacts = self
928            .shared
929            .artifacts
930            .clone()
931            .ok_or_else(|| SurfaceError::unsupported("keeping a camera's frames"))?;
932        let shown = &frame.frame;
933        let (pixels, _) =
934            DecodedImage::decode(&shown.bytes, &DecodeLimits::default()).map_err(vision)?;
935        let (width, height) = pixels.size();
936        let scale = (
937            f64::from(width) / f64::from(shown.width.max(1)),
938            f64::from(height) / f64::from(shown.height.max(1)),
939        );
940        // What the hook redacted, and under `cover_people` everyone on the frame, is covered
941        // again before it is written, whatever was shown.
942        let people: Vec<BBox> = shown
943            .overlays
944            .iter()
945            .filter(|overlay| {
946                overlay.blurred || (run.cover_people && PEOPLE.contains(&overlay.label.as_str()))
947            })
948            .filter_map(|overlay| overlay.bbox)
949            .map(|[x0, y0, x1, y1]| {
950                BBox::new(
951                    (x0 * scale.0) as f32,
952                    (y0 * scale.1) as f32,
953                    (x1 * scale.0) as f32,
954                    (y1 * scale.1) as f32,
955                )
956            })
957            .collect();
958        let redacted =
959            cover(&self.shared.cx, &run.id, shown.at, pixels, people.clone(), "camera-card")
960                .await
961                .map_err(vision)?;
962        let keeper = FrameKeeper::new(
963            artifacts,
964            MediaScope::new(
965                self.shared.app.clone(),
966                self.shared.user.clone(),
967                camera.session.clone(),
968            ),
969            run.id.clone(),
970        );
971        let kept = keeper
972            .keep(&self.shared.cx, &redacted, KeepReason::CardEvidence)
973            .await
974            .map_err(vision)?;
975        let digest = kept.image.digest.to_string();
976        let regions: Vec<serde_json::Value> = people
977            .iter()
978            .map(|bbox| {
979                json!({
980                    "image": digest,
981                    "shape": { "kind": "box", "x0": bbox.x0, "y0": bbox.y0, "x1": bbox.x1, "y1": bbox.y1 },
982                    "label": "person",
983                    "origin": { "backend": "camera", "frame": "sourcePixels" },
984                })
985            })
986            .collect();
987        Ok(ImageEvidence::new(
988            digest.clone(),
989            kept.image.artifact.clone(),
990            kept.image.mime_type.clone(),
991            kept.image.width,
992            kept.image.height,
993        )
994        .with_regions(json!({
995            "image": digest,
996            "width": kept.image.width,
997            "height": kept.image.height,
998            "regions": regions,
999        }))
1000        .with_caption(format!("{} at {}", camera.name, shown.at.format("%H:%M:%S"))))
1001    }
1002}
1003
1004/// The push side of the voice screen's camera, behind the hub's gate.
1005struct FeedIntake(CameraFeed);
1006
1007impl FrameIntake for FeedIntake {
1008    fn push(&self, bytes: Vec<u8>, at: DateTime<Utc>) -> bool {
1009        self.0.push_frame(bytes, at)
1010    }
1011}
1012
1013/// A privacy step that fills boxes solid, for people the detector found after the camera's own
1014/// privacy hook ran.
1015struct Cover {
1016    name: String,
1017    boxes: Vec<BBox>,
1018}
1019
1020#[async_trait]
1021impl PrivacyHook for Cover {
1022    fn name(&self) -> &str {
1023        &self.name
1024    }
1025
1026    async fn redact(
1027        &self,
1028        _cx: &VisionCx,
1029        _frame: &FrameMeta,
1030        pixels: &mut DecodedImage,
1031    ) -> adk_vision::Result<Vec<BBox>> {
1032        if self.boxes.is_empty() {
1033            return Ok(Vec::new());
1034        }
1035        let (width, height) = pixels.size();
1036        let mut rgba = pixels.rgba().to_vec();
1037        for bbox in &self.boxes {
1038            let clamp = |value: f32, max: u32| (value.max(0.0) as u32).min(max);
1039            let (x0, y0) = (clamp(bbox.x0.floor(), width), clamp(bbox.y0.floor(), height));
1040            let (x1, y1) = (clamp(bbox.x1.ceil(), width), clamp(bbox.y1.ceil(), height));
1041            for y in y0..y1 {
1042                for x in x0..x1 {
1043                    let at = ((y * width + x) * 4) as usize;
1044                    rgba[at..at + 3].copy_from_slice(&[0, 0, 0]);
1045                    rgba[at + 3] = 255;
1046                }
1047            }
1048        }
1049        *pixels = DecodedImage::from_rgba(width, height, rgba)?;
1050        Ok(self.boxes.clone())
1051    }
1052}
1053
1054/// `pixels` of `source` captured `at`, `people` filled, as the only kind of frame a
1055/// [`FrameKeeper`] stores.
1056async fn cover(
1057    cx: &VisionCx,
1058    source: &FrameSourceId,
1059    at: DateTime<Utc>,
1060    pixels: DecodedImage,
1061    people: Vec<BBox>,
1062    name: &str,
1063) -> adk_vision::Result<RedactedFrame> {
1064    let frame = Frame {
1065        source: source.clone(),
1066        index: 0,
1067        pts: StdDuration::ZERO,
1068        captured_at: at,
1069        pixels: FramePixels::Ephemeral(Arc::new(pixels)),
1070    };
1071    FramePrivacy::new(Arc::new(Cover { name: name.to_string(), boxes: people }))
1072        .apply(cx, frame)
1073        .await
1074}
1075
1076/// A JPEG of `image` for the screen.
1077fn jpeg(image: &DecodedImage) -> std::result::Result<Vec<u8>, String> {
1078    let (width, height) = image.size();
1079    let rgba = image::RgbaImage::from_raw(width, height, image.rgba().to_vec())
1080        .ok_or_else(|| "a frame's pixels do not match its size".to_string())?;
1081    let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
1082    let mut out = Vec::new();
1083    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, SHOWN_QUALITY)
1084        .encode_image(&rgb)
1085        .map_err(|error| error.to_string())?;
1086    Ok(out)
1087}
1088
1089/// Replaces the user and password of any URL in `text`: an error a source reports never shows
1090/// a credential (spec 3.7 §9.1).
1091fn without_credentials(text: &str) -> String {
1092    let mut out = String::with_capacity(text.len());
1093    let mut rest = text;
1094    while let Some(scheme) = rest.find("://") {
1095        let (head, tail) = rest.split_at(scheme + 3);
1096        out.push_str(head);
1097        let end = tail.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(tail.len());
1098        match tail[..end].rfind('@') {
1099            Some(at) => {
1100                out.push_str("[credentials hidden]");
1101                rest = &tail[at..];
1102            }
1103            None => rest = tail,
1104        }
1105    }
1106    out.push_str(rest);
1107    out
1108}
1109
1110/// Runs camera `run`'s pipeline until it is stopped or the hub goes, building it again after a
1111/// stage fails.
1112async fn drive(run: Arc<Run>, shared: Arc<Shared>, hub: WeakCameras) {
1113    let conditions = run.lock().evaluator.conditions().to_vec();
1114    for condition in &conditions {
1115        shared.audit(watch_registered_draft(&run.id, condition)).await;
1116    }
1117    let source: Arc<dyn FrameSource> = match &run.input {
1118        Input::Stream(source) => Arc::clone(source),
1119        Input::Screen { source, .. } => Arc::clone(source) as Arc<dyn FrameSource>,
1120    };
1121    let watched: Arc<dyn FrameSource> = Arc::new(Watched {
1122        id: run.id.clone(),
1123        stops: matches!(run.input, Input::Stream(_)),
1124        inner: source,
1125        run: Arc::clone(&run),
1126        shared: Arc::clone(&shared),
1127        hub: hub.clone(),
1128    });
1129    let sink =
1130        Arc::new(Sink { run: Arc::clone(&run), shared: Arc::clone(&shared), hub: hub.clone() });
1131    let cx = shared.cx.clone().with_cancellation(run.cancel.clone());
1132    loop {
1133        if run.cancel.is_cancelled() || hub.upgrade().is_none() {
1134            return;
1135        }
1136        // A frozen kill switch refuses a run at its start: wait for the thaw rather than
1137        // building a pipeline whose governor would start its count again.
1138        if let Err(VisionError::Cancelled) = cx.check() {
1139            return;
1140        }
1141        if cx.check().is_err() {
1142            tokio::select! {
1143                () = run.cancel.cancelled() => return,
1144                () = tokio::time::sleep(StdDuration::from_millis(500)) => continue,
1145            }
1146        }
1147        let mut builder = StreamPipeline::builder(Arc::clone(&watched))
1148            .with_privacy(Arc::clone(&run.privacy))
1149            .sink(Arc::clone(&sink) as Arc<dyn ObservationSink>);
1150        if let Some(sampling) = run.sampling {
1151            builder = builder.sampling(sampling);
1152        }
1153        if let Some(budget) = &run.budget {
1154            builder = builder.budget(budget.clone());
1155        }
1156        if let Some((runtime, query, options)) = &run.detection {
1157            builder = builder
1158                .detector(Arc::clone(runtime), query.clone())
1159                .detect_options(options.clone());
1160        }
1161        if let Some(make) = &run.tracker {
1162            builder = builder.tracker(make());
1163        }
1164        let pipeline = match builder.build() {
1165            Ok(pipeline) => pipeline,
1166            Err(error) => {
1167                tracing::error!(camera.id = %run.id.0, error = %error, "the camera's pipeline cannot be built");
1168                lost(&run, &hub, &error.to_string()).await;
1169                return;
1170            }
1171        };
1172        {
1173            let mut state = run.lock();
1174            state.governor = pipeline.governor();
1175            state.steps.clear();
1176            state.paused_since = None;
1177            state.escalation_stopped_at = None;
1178        }
1179        match pipeline.run(&cx).await {
1180            Ok(summary) => {
1181                tracing::info!(camera.id = %run.id.0, frames.received = summary.received, frames.observed = summary.observations, "camera stream ended");
1182            }
1183            Err(error) => {
1184                tracing::warn!(camera.id = %run.id.0, error = %error, "camera stream failed");
1185                if run.cancel.is_cancelled() {
1186                    return;
1187                }
1188                let wait = lost(&run, &hub, &error.to_string()).await;
1189                tokio::select! {
1190                    () = run.cancel.cancelled() => return,
1191                    () = run.retry_now.notified() => {}
1192                    () = tokio::time::sleep(wait) => {}
1193                }
1194            }
1195        }
1196    }
1197}
1198
1199/// Marks `run` lost with `error` and tells the hub; returns how long to wait before trying
1200/// again.
1201async fn lost(run: &Run, hub: &WeakCameras, error: &str) -> StdDuration {
1202    let now = Utc::now();
1203    let wait = {
1204        let mut state = run.lock();
1205        state.attempt = state.attempt.saturating_add(1);
1206        let wait =
1207            RETRY_FIRST.saturating_mul(1 << state.attempt.saturating_sub(1).min(5)).min(RETRY_MOST);
1208        state.stream = StreamState::Lost {
1209            since: state.last_frame.unwrap_or(now),
1210            retry_at: now + chrono::Duration::from_std(wait).unwrap_or_default(),
1211            attempt: state.attempt,
1212            error: without_credentials(error),
1213        };
1214        state.tracks.clear();
1215        state.centres.clear();
1216        wait
1217    };
1218    if let Some(hub) = hub.upgrade() {
1219        hub.changed(&run.base.id);
1220    }
1221    wait
1222}
1223
1224/// The `vision.source.stopped` or `.started` record of a person's switch closing or opening a
1225/// camera's source (spec 3.7 §9.3); the person's own act is `surface.camera.switch`.
1226fn switch_draft(action: &str, source: &FrameSourceId, reason: &str) -> AuditRecordDraft {
1227    AuditRecordDraft::new(
1228        AuditRecordKind::Other(adk_vision::audit::VISION_AUDIT_KIND.to_string()),
1229        action,
1230    )
1231    .outcome(AuditRecordOutcome::Succeeded)
1232    .ext("source", json!(source.0))
1233    .ext("reason", json!(reason))
1234}
1235
1236/// A camera's source as its pipeline reads it: reopened with a growing wait when it fails or
1237/// ends, so the pipeline — and its governor's count — outlives a lost connection; closed while
1238/// a stream camera is off and opened again when it is on; frames dropped while the camera is
1239/// off or Stop all is in force, before anything looks at them; and numbered on across
1240/// reconnections, so watch conditions keep counting.
1241struct Watched {
1242    id: FrameSourceId,
1243    /// Off closes the source: a stream camera's. The voice screen's camera captures in the
1244    /// browser, which stops its own track; its source only queues what the browser sends.
1245    stops: bool,
1246    inner: Arc<dyn FrameSource>,
1247    run: Arc<Run>,
1248    shared: Arc<Shared>,
1249    hub: WeakCameras,
1250}
1251
1252struct Reading {
1253    inner: Arc<dyn FrameSource>,
1254    stops: bool,
1255    switch: watch::Receiver<bool>,
1256    /// Stop all: in force, it closes the source as off does.
1257    frozen: watch::Receiver<bool>,
1258    /// The switch or Stop all closed the source; opening it again is recorded, with what
1259    /// opened it: `switchedOn` or `resumeAll`.
1260    reopened_by: Option<&'static str>,
1261    sampling: Sampling,
1262    current: Option<FrameStream>,
1263    next_index: u64,
1264    pts_base: StdDuration,
1265    last_pts: StdDuration,
1266    run: Arc<Run>,
1267    shared: Arc<Shared>,
1268    hub: WeakCameras,
1269}
1270
1271#[async_trait]
1272impl FrameSource for Watched {
1273    fn id(&self) -> &FrameSourceId {
1274        &self.id
1275    }
1276
1277    async fn frames(&self, sampling: Sampling) -> adk_vision::Result<FrameStream> {
1278        adk_vision::stream::Sampler::new(sampling)?;
1279        let reading = Reading {
1280            inner: Arc::clone(&self.inner),
1281            stops: self.stops,
1282            switch: self.run.switch.subscribe(),
1283            frozen: self.shared.frozen.subscribe(),
1284            reopened_by: None,
1285            sampling,
1286            current: None,
1287            next_index: 0,
1288            pts_base: StdDuration::ZERO,
1289            last_pts: StdDuration::ZERO,
1290            run: Arc::clone(&self.run),
1291            shared: Arc::clone(&self.shared),
1292            hub: self.hub.clone(),
1293        };
1294        let frames = futures::stream::unfold(reading, |mut reading| async move {
1295            loop {
1296                // Off and Stop all stop capture at the source: the stream is dropped, and with
1297                // it any process or connection it holds, until the camera is on and nothing is
1298                // stopped.
1299                let off = !*reading.switch.borrow_and_update();
1300                let frozen = *reading.frozen.borrow_and_update();
1301                if reading.stops && (off || frozen) {
1302                    reading.close(Some(if off { "switchedOff" } else { "stopAll" })).await;
1303                    tokio::select! {
1304                        () = reading.run.cancel.cancelled() => return None,
1305                        changed = reading.switch.changed() => {
1306                            if changed.is_err() {
1307                                return None;
1308                            }
1309                            if *reading.switch.borrow() && reading.reopened_by.is_some() {
1310                                reading.reopened_by = Some("switchedOn");
1311                            }
1312                        }
1313                        changed = reading.frozen.changed() => {
1314                            if changed.is_err() {
1315                                return None;
1316                            }
1317                            if !*reading.frozen.borrow() && reading.reopened_by.is_some() {
1318                                reading.reopened_by = Some("resumeAll");
1319                            }
1320                        }
1321                    }
1322                    continue;
1323                }
1324                if reading.current.is_none() {
1325                    match reading.inner.frames(reading.sampling).await {
1326                        Ok(stream) => {
1327                            reading.current = Some(stream);
1328                            reading.pts_base = reading.last_pts;
1329                            reading.run.capturing.send_replace(true);
1330                            reading.opened().await;
1331                        }
1332                        Err(error) => {
1333                            wait_after(&reading.run, &reading.hub, &error.to_string()).await;
1334                            continue;
1335                        }
1336                    }
1337                }
1338                let next = match reading.current.as_mut() {
1339                    Some(stream) if reading.stops => tokio::select! {
1340                        next = stream.next() => next,
1341                        // Switched off or stopped while waiting for a frame: closed at the top.
1342                        _ = reading.switch.wait_for(|on| !*on) => continue,
1343                        _ = reading.frozen.wait_for(|frozen| *frozen) => continue,
1344                    },
1345                    Some(stream) => stream.next().await,
1346                    None => continue,
1347                };
1348                match next {
1349                    Some(Ok(mut frame)) => {
1350                        reading.arrived(frame.captured_at);
1351                        reading.run.arrived.fetch_add(1, Ordering::SeqCst);
1352                        if !reading.run.is_on() || *reading.shared.frozen.borrow() {
1353                            reading.run.dropped.fetch_add(1, Ordering::SeqCst);
1354                            continue;
1355                        }
1356                        frame.index = reading.next_index;
1357                        reading.next_index += 1;
1358                        frame.pts = reading.pts_base + frame.pts;
1359                        reading.last_pts = frame.pts;
1360                        return Some((Ok(frame), reading));
1361                    }
1362                    Some(Err(error)) => {
1363                        reading.close(None).await;
1364                        wait_after(&reading.run, &reading.hub, &error.to_string()).await;
1365                    }
1366                    None => {
1367                        reading.close(None).await;
1368                        wait_after(&reading.run, &reading.hub, "the camera's stream ended").await;
1369                    }
1370                }
1371            }
1372        });
1373        Ok(frames.boxed())
1374    }
1375}
1376
1377impl Drop for Reading {
1378    fn drop(&mut self) {
1379        self.run.capturing.send_replace(false);
1380    }
1381}
1382
1383impl Reading {
1384    /// Drops the source's stream, if one is open; `reason`, when a person closed it — the
1385    /// switch (`switchedOff`) or Stop all (`stopAll`) — which is recorded as
1386    /// `vision.source.stopped`.
1387    async fn close(&mut self, reason: Option<&'static str>) {
1388        let Some(stream) = self.current.take() else { return };
1389        drop(stream);
1390        self.run.capturing.send_replace(false);
1391        if let Some(reason) = reason {
1392            self.reopened_by = Some(if reason == "stopAll" { "resumeAll" } else { "switchedOn" });
1393            tracing::info!(camera.id = %self.run.base.id, close.reason = reason, "camera source stopped capturing");
1394            self.shared.audit(switch_draft(VISION_SOURCE_STOPPED, &self.run.id, reason)).await;
1395        }
1396    }
1397
1398    /// The source opened: after a person closed it, that is recorded as
1399    /// `vision.source.started` with what opened it again.
1400    async fn opened(&mut self) {
1401        if let Some(reason) = self.reopened_by.take() {
1402            tracing::info!(camera.id = %self.run.base.id, open.reason = reason, "camera source captures again");
1403            self.shared.audit(switch_draft(VISION_SOURCE_STARTED, &self.run.id, reason)).await;
1404        }
1405    }
1406
1407    /// A frame arrived: the camera is live again.
1408    fn arrived(&self, at: DateTime<Utc>) {
1409        let was_lost = {
1410            let mut state = self.run.lock();
1411            state.last_frame = Some(at);
1412            state.attempt = 0;
1413            let was_lost = matches!(state.stream, StreamState::Lost { .. });
1414            state.stream = StreamState::Live;
1415            was_lost
1416        };
1417        if was_lost && let Some(hub) = self.hub.upgrade() {
1418            tracing::info!(camera.id = %self.run.base.id, "camera back");
1419            hub.changed(&self.run.base.id);
1420        }
1421    }
1422}
1423
1424/// `run`'s source failed: marks the camera lost, then waits — less if a person asks to try
1425/// again.
1426async fn wait_after(run: &Run, hub: &WeakCameras, error: &str) {
1427    tracing::warn!(camera.id = %run.base.id, error = %without_credentials(error), "camera lost");
1428    let wait = lost(run, hub, error).await;
1429    tokio::select! {
1430        () = run.retry_now.notified() => {}
1431        () = tokio::time::sleep(wait) => {}
1432    }
1433}
1434
1435/// What a camera's pipeline hands the surface: each observation as a shown frame, the tracks
1436/// and watch counts on it, and the governor's steps.
1437struct Sink {
1438    run: Arc<Run>,
1439    shared: Arc<Shared>,
1440    hub: WeakCameras,
1441}
1442
1443fn is_person(region: &Region) -> bool {
1444    region.label.as_deref().is_some_and(|label| PEOPLE.contains(&label))
1445}
1446
1447/// What a privacy hook's boxes are called on screen, from its name: `redactor:faces` → `face`.
1448fn hidden_label(hook: &str) -> &'static str {
1449    if hook.contains("face") { "face" } else { "person" }
1450}
1451
1452#[async_trait]
1453impl ObservationSink for Sink {
1454    async fn observe(&self, cx: &VisionCx, observation: Observation) -> adk_vision::Result<()> {
1455        let Some(hub) = self.hub.upgrade() else { return Ok(()) };
1456        let run = &self.run;
1457        let captured = observation.frame.captured_at;
1458        let pixels = observation.image.pixels();
1459        let (frame_width, frame_height) = pixels.size();
1460        let (width, height) = {
1461            let mut state = run.lock();
1462            // Regions are in source pixels: without downscaling the frame's size is the camera's.
1463            if run.sampling.is_none_or(|sampling| sampling.max_long_edge.is_none()) {
1464                state.size = (frame_width, frame_height);
1465            }
1466            state.size
1467        };
1468        let to_frame = (
1469            f64::from(frame_width) / f64::from(width.max(1)),
1470            f64::from(frame_height) / f64::from(height.max(1)),
1471        );
1472        let people: Vec<BBox> = observation
1473            .regions
1474            .iter()
1475            .filter(|region| run.cover_people && is_person(region))
1476            .filter_map(|region| region.shape.bbox())
1477            .map(|bbox| {
1478                BBox::new(
1479                    (f64::from(bbox.x0) * to_frame.0) as f32,
1480                    (f64::from(bbox.y0) * to_frame.1) as f32,
1481                    (f64::from(bbox.x1) * to_frame.0) as f32,
1482                    (f64::from(bbox.y1) * to_frame.1) as f32,
1483                )
1484            })
1485            .collect();
1486        // Under `cover_people`, everyone the detector found is covered before the frame is
1487        // shown or kept.
1488        let image: Arc<RedactedFrame> = if people.is_empty() {
1489            Arc::clone(&observation.image)
1490        } else {
1491            let name = format!("{}+people", observation.image.hook());
1492            Arc::new(cover(cx, &observation.source, captured, pixels.clone(), people, &name).await?)
1493        };
1494
1495        // Watch conditions, with each (watch, track)'s frames in a row.
1496        let tracked = observation.tracked();
1497        let (events, conditions) = {
1498            let mut state = run.lock();
1499            let events = state.evaluator.observe(&tracked);
1500            let conditions = state.evaluator.conditions().to_vec();
1501            let mut seen = Vec::new();
1502            for (index, condition) in conditions.iter().enumerate() {
1503                for region in observation.regions.iter().filter(|region| condition.matches(region))
1504                {
1505                    if let Some(track) = region.track {
1506                        let key = (index, track.0);
1507                        if !seen.contains(&key) {
1508                            *state.streaks.entry(key).or_insert(0) += 1;
1509                            seen.push(key);
1510                        }
1511                    }
1512                }
1513            }
1514            state.streaks.retain(|key, _| seen.contains(key));
1515            if !events.is_empty() {
1516                let today = captured.date_naive();
1517                if state.woke_on != Some(today) {
1518                    state.woke_on = Some(today);
1519                    state.woke.iter_mut().for_each(|count| *count = 0);
1520                }
1521                for event in &events {
1522                    if let Some(index) =
1523                        conditions.iter().position(|condition| condition.name == event.condition)
1524                        && let Some(count) = state.woke.get_mut(index)
1525                    {
1526                        *count += 1;
1527                    }
1528                }
1529            }
1530            (events, conditions)
1531        };
1532        for event in &events {
1533            tracing::info!(camera.id = %run.base.id, watch = %event.condition, track = event.track.0, score = event.score, frames = event.frames, "watch fired");
1534            if let Some(condition) = conditions.iter().find(|c| c.name == event.condition) {
1535                self.shared.audit(event.audit_draft(condition.digest())).await;
1536            }
1537            if let (Some(wakes), Some(artifacts)) = (&self.shared.wakes, &self.shared.artifacts) {
1538                let keeper = FrameKeeper::new(
1539                    Arc::clone(artifacts),
1540                    MediaScope::new(
1541                        self.shared.app.clone(),
1542                        self.shared.user.clone(),
1543                        run.base.session.clone(),
1544                    ),
1545                    run.id.clone(),
1546                );
1547                let kept = keeper.keep(cx, &image, KeepReason::WakePayload).await?;
1548                if let Err(error) =
1549                    wakes.deliver(&event.clone().with_frame_artifact(kept.image.artifact)).await
1550                {
1551                    tracing::warn!(camera.id = %run.base.id, error = %error, "a watch event was not delivered");
1552                }
1553            }
1554        }
1555
1556        // The overlays, in the camera's pixels.
1557        let streak_of = |state: &RunState, region: &Region| -> Option<u32> {
1558            let track = region.track?.0;
1559            conditions
1560                .iter()
1561                .enumerate()
1562                .filter(|(_, condition)| condition.matches(region))
1563                .filter_map(|(index, _)| state.streaks.get(&(index, track)).copied())
1564                .max()
1565        };
1566        let to_camera = (1.0 / to_frame.0, 1.0 / to_frame.1);
1567        let overlays: Vec<Overlay>;
1568        {
1569            let mut state = run.lock();
1570            let zones = state.zones.clone();
1571            let mut centres = HashMap::new();
1572            let mut rows: Vec<TrackFacts> = Vec::new();
1573            let mut drawn = Vec::with_capacity(observation.regions.len());
1574            for region in &observation.regions {
1575                let Some(bbox) = region.shape.bbox() else { continue };
1576                let corners = [
1577                    f64::from(bbox.x0),
1578                    f64::from(bbox.y0),
1579                    f64::from(bbox.x1),
1580                    f64::from(bbox.y1),
1581                ];
1582                let label = region.label.clone().unwrap_or_else(|| "object".into());
1583                let mut overlay = Overlay::boxed(label.clone(), corners);
1584                overlay.score = region.score.map(f64::from);
1585                overlay.track = region.track.map(|track| track.0);
1586                if let Shape::Polygon(polygon) = &region.shape {
1587                    overlay.outline = polygon
1588                        .points
1589                        .iter()
1590                        .map(|[x, y]| [f64::from(*x), f64::from(*y)])
1591                        .collect();
1592                }
1593                let streak = streak_of(&state, region);
1594                overlay.frames = streak;
1595                if run.cover_people && is_person(region) {
1596                    overlay.blurred = true;
1597                } else if let Some(track) = region.track {
1598                    let centre = f64::midpoint(corners[0], corners[2]);
1599                    let inside = zones.iter().any(|zone| {
1600                        let [x0, y0, x1, y1] = zone.corners;
1601                        let cy = f64::midpoint(corners[1], corners[3]);
1602                        centre >= x0 && centre < x1 && cy >= y0 && cy < y1
1603                    });
1604                    let moving = state.centres.get(&track.0).map(|before| centre - before);
1605                    let edge = f64::from(width) * 0.04;
1606                    let phase = if inside {
1607                        TrackPhase::InZone
1608                    } else if corners[0] <= edge {
1609                        if moving.is_some_and(|dx| dx < 0.0) {
1610                            TrackPhase::Leaving
1611                        } else {
1612                            TrackPhase::Entering
1613                        }
1614                    } else if corners[2] >= f64::from(width) - edge {
1615                        if moving.is_some_and(|dx| dx < 0.0) {
1616                            TrackPhase::Entering
1617                        } else {
1618                            TrackPhase::Leaving
1619                        }
1620                    } else {
1621                        TrackPhase::InView
1622                    };
1623                    centres.insert(track.0, centre);
1624                    let finding = streak.map(|frames| Finding {
1625                        label: label.clone(),
1626                        score: region.score.map_or(0.0, f64::from),
1627                        frames,
1628                    });
1629                    match rows.iter_mut().find(|row| row.id == track.0) {
1630                        Some(row) => {
1631                            if row.finding.is_none() {
1632                                row.finding = finding;
1633                            }
1634                        }
1635                        None => rows.push(TrackFacts {
1636                            id: track.0,
1637                            label: label.clone(),
1638                            phase,
1639                            finding,
1640                        }),
1641                    }
1642                }
1643                drawn.push(overlay);
1644            }
1645            // What the camera's privacy hook covered, in the camera's pixels.
1646            let hidden = hidden_label(observation.image.hook());
1647            for bbox in observation.image.redacted() {
1648                drawn.push(
1649                    Overlay::boxed(
1650                        hidden,
1651                        [
1652                            f64::from(bbox.x0) * to_camera.0,
1653                            f64::from(bbox.y0) * to_camera.1,
1654                            f64::from(bbox.x1) * to_camera.0,
1655                            f64::from(bbox.y1) * to_camera.1,
1656                        ],
1657                    )
1658                    .blurred(),
1659                );
1660            }
1661            state.centres = centres;
1662            state.tracks = rows;
1663            overlays = drawn;
1664        }
1665
1666        let shown_pixels = image.pixels().clone();
1667        let bytes = tokio::task::spawn_blocking(move || jpeg(&shown_pixels))
1668            .await
1669            .map_err(|error| {
1670                VisionError::Decode(format!("a shown frame's encoder panicked: {error}"))
1671            })?
1672            .map_err(VisionError::Decode)?;
1673        let latency = (Utc::now() - captured).num_milliseconds().clamp(0, i64::from(u32::MAX));
1674        let frame = super::facts::CameraFrame::new(bytes, "image/jpeg", width, height, captured)
1675            .with_overlays(overlays)
1676            .with_latency_ms(u32::try_from(latency).unwrap_or(u32::MAX));
1677        hub.offer(&run.base.id, frame).await;
1678        run.observed.fetch_add(1, Ordering::SeqCst);
1679        run.fired.fetch_add(events.len() as u64, Ordering::SeqCst);
1680        if !events.is_empty() {
1681            hub.changed(&run.base.id);
1682        }
1683        Ok(())
1684    }
1685
1686    async fn source_event(&self, _cx: &VisionCx, event: &SourceEvent) -> adk_vision::Result<()> {
1687        let run = &self.run;
1688        {
1689            let mut state = run.lock();
1690            match event {
1691                SourceEvent::Governor { step } => {
1692                    let used = step
1693                        .state
1694                        .local_quota
1695                        .filter(|quota| *quota > 0)
1696                        .map(|quota| step.state.local_frames as f64 / quota as f64);
1697                    let mut push =
1698                        |kind| state.steps.push(GovernorStep { at: step.at, kind, used });
1699                    match &step.change {
1700                        GovernorChange::RateLowered { from_fps, to_fps } => {
1701                            push(GovernorStepKind::LookLessOften {
1702                                from: f64::from(*from_fps),
1703                                to: f64::from(*to_fps),
1704                            });
1705                        }
1706                        GovernorChange::EscalationStopped { .. } => {
1707                            push(GovernorStepKind::StopAsking);
1708                            state.escalation_stopped_at = Some(step.at);
1709                        }
1710                        GovernorChange::Paused { .. } => {
1711                            push(GovernorStepKind::Pause);
1712                            state.paused_since = Some(step.at);
1713                            state.tracks.clear();
1714                        }
1715                        // A new period: today's steps start again.
1716                        GovernorChange::Resumed => {
1717                            state.paused_since = None;
1718                            state.steps.clear();
1719                        }
1720                        GovernorChange::RateRestored { .. } => state.steps.clear(),
1721                        GovernorChange::EscalationResumed => {
1722                            state.escalation_stopped_at = None;
1723                            state.steps.clear();
1724                        }
1725                        _ => {}
1726                    }
1727                    tracing::info!(camera.id = %run.base.id, change = ?step.change, frames.today = step.state.local_frames, "governor step");
1728                }
1729                SourceEvent::Stopped { .. } => {
1730                    state.tracks.clear();
1731                    state.centres.clear();
1732                }
1733                _ => {}
1734            }
1735        }
1736        if let Some(hub) = self.hub.upgrade() {
1737            hub.changed(&run.base.id);
1738        }
1739        Ok(())
1740    }
1741}
1742
1743#[cfg(test)]
1744mod tests {
1745    use super::*;
1746
1747    #[test]
1748    fn a_source_error_never_shows_a_credential() {
1749        assert_eq!(
1750            without_credentials("connection refused · rtsp://admin:hunter2@10.0.4.21:554/stream1"),
1751            "connection refused · rtsp://[credentials hidden]@10.0.4.21:554/stream1"
1752        );
1753        assert_eq!(without_credentials("rtsp://10.0.4.21/s"), "rtsp://10.0.4.21/s");
1754        assert_eq!(without_credentials("no url here"), "no url here");
1755    }
1756
1757    #[test]
1758    fn a_privacy_hooks_boxes_are_named_for_what_it_hides() {
1759        assert_eq!(hidden_label("redactor:faces"), "face");
1760        assert_eq!(hidden_label("redactor:people"), "person");
1761        assert_eq!(hidden_label("none"), "person");
1762    }
1763}