Skip to main content

adk_surface/camera/
facts.rs

1//! What a camera source reports (spec 3.7 §7.13, §8.2): the facts the live camera surface
2//! projects into words. Numbers and times, never sentences, so a pipeline reports what it
3//! measured and the surface says it the same way on every screen.
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7
8/// One camera as its source reports it.
9///
10/// # Example
11///
12/// ```rust
13/// use adk_surface::camera::{CameraFacts, GovernorFacts, Ingest, StreamState};
14///
15/// let facts = CameraFacts::new("line-2", "Line 2 camera", "inspector", "s-line")
16///     .with_place("line 2")
17///     .with_ingest(Ingest::rtsp(1920, 1080, "the line 2 server"))
18///     .with_governor(GovernorFacts::new(5.0, 300_000, chrono::Utc::now()));
19/// assert_eq!(facts.state, StreamState::Live);
20/// ```
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct CameraFacts {
24    /// The camera's id, as routes name it: `line-2`.
25    pub id: String,
26    /// The name people know it by: "Line 2 camera".
27    pub name: String,
28    /// What it looks at, as a sentence names it: "line 2" ("Nothing on line 2 is being checked").
29    pub place: String,
30    /// The agent that watches it, by its name in the runtime.
31    pub agent: String,
32    /// The agent's session the camera belongs to: only that session's owner sees or acts on
33    /// the camera (spec 3.3 §11 S-I8).
34    pub session: String,
35    /// How frames arrive.
36    pub ingest: Ingest,
37    /// The stream's state as the pipeline sees it; a person's switch and stop are the hub's.
38    pub state: StreamState,
39    /// The frame governor (spec 3.7 §7.9).
40    pub governor: GovernorFacts,
41    /// The tracks now, anonymous (V-I8).
42    #[serde(default)]
43    pub tracks: Vec<TrackFacts>,
44    /// The watch conditions on this camera.
45    #[serde(default)]
46    pub watches: Vec<WatchFacts>,
47    /// The zones on this camera, in its pixels.
48    #[serde(default)]
49    pub zones: Vec<ZoneFacts>,
50    /// The switch when the camera is first seen: on unless the source says otherwise.
51    #[serde(default = "on")]
52    pub on: bool,
53    /// Where the camera comes from when it is not a stream the agent watches, such as "from the
54    /// voice screen".
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub from: Option<String>,
57    /// What passes the camera, plural, for the warning when nothing checks it: "parts" ("Parts on
58    /// line 2 are passing without inspection").
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub passing: Option<String>,
61}
62
63fn on() -> bool {
64    true
65}
66
67impl CameraFacts {
68    /// A live camera with no tracks, watches or zones, watched by `agent` in `session`.
69    pub fn new(
70        id: impl Into<String>,
71        name: impl Into<String>,
72        agent: impl Into<String>,
73        session: impl Into<String>,
74    ) -> Self {
75        let name = name.into();
76        Self {
77            id: id.into(),
78            place: name.to_lowercase(),
79            name,
80            agent: agent.into(),
81            session: session.into(),
82            ingest: Ingest::rtsp(1920, 1080, ""),
83            state: StreamState::Live,
84            governor: GovernorFacts::new(1.0, 0, Utc::now()),
85            tracks: Vec::new(),
86            watches: Vec::new(),
87            zones: Vec::new(),
88            on: true,
89            from: None,
90            passing: None,
91        }
92    }
93
94    /// What sentences call it: "line 2".
95    #[must_use]
96    pub fn with_place(mut self, place: impl Into<String>) -> Self {
97        self.place = place.into();
98        self
99    }
100
101    /// How frames arrive.
102    #[must_use]
103    pub fn with_ingest(mut self, ingest: Ingest) -> Self {
104        self.ingest = ingest;
105        self
106    }
107
108    /// The stream's state.
109    #[must_use]
110    pub fn with_state(mut self, state: StreamState) -> Self {
111        self.state = state;
112        self
113    }
114
115    /// The frame governor.
116    #[must_use]
117    pub fn with_governor(mut self, governor: GovernorFacts) -> Self {
118        self.governor = governor;
119        self
120    }
121
122    /// The tracks now.
123    #[must_use]
124    pub fn with_tracks(mut self, tracks: Vec<TrackFacts>) -> Self {
125        self.tracks = tracks;
126        self
127    }
128
129    /// The watch conditions.
130    #[must_use]
131    pub fn with_watches(mut self, watches: Vec<WatchFacts>) -> Self {
132        self.watches = watches;
133        self
134    }
135
136    /// The zones.
137    #[must_use]
138    pub fn with_zones(mut self, zones: Vec<ZoneFacts>) -> Self {
139        self.zones = zones;
140        self
141    }
142
143    /// The switch when the camera is first seen.
144    #[must_use]
145    pub fn switched(mut self, on: bool) -> Self {
146        self.on = on;
147        self
148    }
149
150    /// Where the camera comes from, such as "from the voice screen".
151    #[must_use]
152    pub fn from(mut self, from: impl Into<String>) -> Self {
153        self.from = Some(from.into());
154        self
155    }
156
157    /// What passes the camera, plural: "parts".
158    #[must_use]
159    pub fn passing(mut self, what: impl Into<String>) -> Self {
160        self.passing = Some(what.into());
161        self
162    }
163}
164
165/// How a camera's frames arrive (spec 3.7 §7.13's sources).
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "camelCase")]
168pub struct Ingest {
169    /// `RTSP`, `File`, `Screen`, `Browser` or `This computer`.
170    pub kind: String,
171    /// Frame width in pixels.
172    pub width: u32,
173    /// Frame height in pixels.
174    pub height: u32,
175    /// Where it is decoded, such as "the line 2 server"; empty when it says nothing.
176    #[serde(default)]
177    pub at: String,
178}
179
180impl Ingest {
181    /// An RTSP camera of `width` × `height`, decoded `at`.
182    pub fn rtsp(width: u32, height: u32, at: impl Into<String>) -> Self {
183        Self { kind: "RTSP".into(), width, height, at: at.into() }
184    }
185
186    /// The web home's own camera (spec 3.7 §7.13 `SurfaceCameraSource`).
187    pub fn this_computer(width: u32, height: u32) -> Self {
188        Self { kind: "This computer".into(), width, height, at: String::new() }
189    }
190}
191
192/// A stream's state as the pipeline sees it. Off and stopped are a person's, kept by the hub.
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
195pub enum StreamState {
196    /// Frames arrive and are looked at.
197    Live,
198    /// The governor paused the camera until its budget renews (board choice C5).
199    Paused {
200        /// When it paused.
201        since: DateTime<Utc>,
202    },
203    /// The source cannot be reached and is retried (board choice C6).
204    Lost {
205        /// When the last frame arrived.
206        since: DateTime<Utc>,
207        /// The next attempt.
208        retry_at: DateTime<Utc>,
209        /// The attempts so far.
210        attempt: u32,
211        /// What went wrong, credentials already replaced by the source (spec 3.7 §9.1).
212        error: String,
213    },
214}
215
216/// The frame governor's state for one camera (spec 3.7 §7.9, board choice C3): how often it
217/// looks, whether it asks a cloud model about unclear tracks, and today's frames.
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[serde(rename_all = "camelCase")]
220pub struct GovernorFacts {
221    /// Frames looked at a second now.
222    pub rate: f64,
223    /// Frames a second as set.
224    pub set_rate: f64,
225    /// Escalation of unclear tracks, when this camera escalates.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub escalation: Option<EscalationFacts>,
228    /// Frames looked at today.
229    pub frames_today: u64,
230    /// The daily frame limit.
231    pub frames_limit: u64,
232    /// When the budget renews.
233    pub renews_at: DateTime<Utc>,
234    /// The share of the limit at which the governor looks less often.
235    pub look_less_at: f64,
236    /// The share at which it stops escalating.
237    pub stop_asking_at: f64,
238    /// The lowest rate the governor looks at before it stops escalating and pauses, when it
239    /// steps by whether the frames left can last rather than at fixed shares (spec 3.7 §7.9's
240    /// `FrameGovernor`).
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub min_rate: Option<f64>,
243    /// Today's steps, oldest first.
244    #[serde(default)]
245    pub steps: Vec<GovernorStep>,
246}
247
248impl GovernorFacts {
249    /// Looking `rate` times a second, as set, against `frames_limit` frames a day renewing at
250    /// `renews_at`, with the steps at 90% and 95%.
251    pub fn new(rate: f64, frames_limit: u64, renews_at: DateTime<Utc>) -> Self {
252        Self {
253            rate,
254            set_rate: rate,
255            escalation: None,
256            frames_today: 0,
257            frames_limit,
258            renews_at,
259            look_less_at: 0.9,
260            stop_asking_at: 0.95,
261            min_rate: None,
262            steps: Vec::new(),
263        }
264    }
265
266    /// Escalation of unclear tracks.
267    #[must_use]
268    pub fn with_escalation(mut self, escalation: EscalationFacts) -> Self {
269        self.escalation = Some(escalation);
270        self
271    }
272
273    /// Frames looked at today.
274    #[must_use]
275    pub fn with_frames_today(mut self, frames: u64) -> Self {
276        self.frames_today = frames;
277        self
278    }
279
280    /// The rate now, after the governor lowered it.
281    #[must_use]
282    pub fn with_rate(mut self, rate: f64) -> Self {
283        self.rate = rate;
284        self
285    }
286
287    /// A step the governor took.
288    #[must_use]
289    pub fn with_step(mut self, step: GovernorStep) -> Self {
290        self.steps.push(step);
291        self
292    }
293
294    /// The share of today's frames used, `0.0..=1.0`; `0.0` without a limit.
295    pub fn used(&self) -> f64 {
296        if self.frames_limit == 0 {
297            return 0.0;
298        }
299        (self.frames_today as f64 / self.frames_limit as f64).min(1.0)
300    }
301
302    /// Whether the governor stepped down today and has not paused.
303    pub fn stepped_down(&self) -> bool {
304        self.steps.iter().any(|step| !matches!(step.kind, GovernorStepKind::Pause))
305    }
306}
307
308/// Escalation of unclear tracks to a cloud model (spec 3.7 §7.13 "Tracking").
309#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311pub struct EscalationFacts {
312    /// The model asked, such as `sam-3.1`.
313    pub backend: String,
314    /// Requests in the last minute.
315    pub last_minute: u32,
316    /// The most a minute.
317    pub max_per_minute: u32,
318    /// Requests today.
319    pub today: u32,
320    /// What today's requests cost, in micro-USD.
321    pub cost_today_micros: u64,
322    /// When the governor stopped escalating, while it is stopped.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub stopped_at: Option<DateTime<Utc>>,
325}
326
327/// One step the governor took (spec 3.7 §9.3 `vision.governor.step`).
328#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329#[serde(rename_all = "camelCase")]
330pub struct GovernorStep {
331    /// When.
332    pub at: DateTime<Utc>,
333    /// What it did.
334    pub kind: GovernorStepKind,
335    /// The share of the limit used when it did, when known.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub used: Option<f64>,
338}
339
340/// What a governor step did, in the fixed order it steps down (board choice C3).
341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
342#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
343pub enum GovernorStepKind {
344    /// Looked less often.
345    LookLessOften {
346        /// Frames a second before.
347        from: f64,
348        /// Frames a second after.
349        to: f64,
350    },
351    /// Stopped escalating unclear tracks.
352    StopAsking,
353    /// Paused the camera until the budget renews.
354    Pause,
355}
356
357/// One anonymous track (spec 3.7 V-I8): its id resets with its source session.
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359#[serde(rename_all = "camelCase")]
360pub struct TrackFacts {
361    /// The track's number: `43` shows as `T43`.
362    pub id: u64,
363    /// What it is: "part".
364    pub label: String,
365    /// Where it is.
366    pub phase: TrackPhase,
367    /// A defect a watch condition looks for, seen on it.
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub finding: Option<Finding>,
370}
371
372/// Where a track is.
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
374#[serde(rename_all = "camelCase")]
375pub enum TrackPhase {
376    /// Coming into view.
377    Entering,
378    /// Inside a zone.
379    InZone,
380    /// Leaving the view.
381    Leaving,
382    /// In view, outside every zone.
383    InView,
384}
385
386/// What a detector found on a track, such as a seal tear.
387#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
388#[serde(rename_all = "camelCase")]
389pub struct Finding {
390    /// "seal tear".
391    pub label: String,
392    /// Its score.
393    pub score: f64,
394    /// Frames in a row it was seen.
395    pub frames: u32,
396}
397
398/// A watch condition (spec 3.7 §7.10): what wakes the agent.
399#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401pub struct WatchFacts {
402    /// Its id.
403    pub id: String,
404    /// "Seal tear".
405    pub name: String,
406    /// The label it looks for: "seal tear".
407    pub label: String,
408    /// The least score.
409    pub min_score: f64,
410    /// Frames in a row.
411    pub frames: u32,
412    /// The zone it looks inside, by id.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub zone: Option<String>,
415    /// Seconds before it wakes again for the same track.
416    pub cooldown_secs: u32,
417    /// Times it woke the agent today.
418    pub woke_today: u32,
419    /// What the agent sleeps until, as its line says: "a defect" ("Asleep until a defect");
420    /// "a seal tear" when unset.
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub wakes_for: Option<String>,
423}
424
425/// A zone, in the camera's pixels (board choice C12).
426#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
427#[serde(rename_all = "camelCase")]
428pub struct ZoneFacts {
429    /// Its id.
430    pub id: String,
431    /// "Inspection window".
432    pub name: String,
433    /// `[x0, y0, x1, y1]` in the camera's pixels.
434    pub corners: [f64; 4],
435}
436
437/// One frame offered to the hub: the encoded picture, in the camera's pixels, with what was
438/// found on it (spec 3.7 §7.13: frames stay ephemeral).
439#[derive(Debug, Clone, PartialEq)]
440pub struct CameraFrame {
441    /// The encoded picture: `image/jpeg` or `image/png`.
442    pub bytes: Vec<u8>,
443    /// Its media type.
444    pub mime_type: String,
445    /// Width in pixels.
446    pub width: u32,
447    /// Height in pixels.
448    pub height: u32,
449    /// When it was captured.
450    pub at: DateTime<Utc>,
451    /// How long after capture its overlays were ready, in milliseconds (board choice C10).
452    pub latency_ms: u32,
453    /// What was found on it, in its pixels.
454    pub overlays: Vec<Overlay>,
455}
456
457impl CameraFrame {
458    /// A JPEG or PNG frame of `width` × `height` captured `at`, nothing found on it yet.
459    pub fn new(
460        bytes: Vec<u8>,
461        mime_type: impl Into<String>,
462        width: u32,
463        height: u32,
464        at: DateTime<Utc>,
465    ) -> Self {
466        Self {
467            bytes,
468            mime_type: mime_type.into(),
469            width,
470            height,
471            at,
472            latency_ms: 0,
473            overlays: Vec::new(),
474        }
475    }
476
477    /// What was found on it.
478    #[must_use]
479    pub fn with_overlays(mut self, overlays: Vec<Overlay>) -> Self {
480        self.overlays = overlays;
481        self
482    }
483
484    /// How long after capture its overlays were ready.
485    #[must_use]
486    pub fn with_latency_ms(mut self, latency_ms: u32) -> Self {
487        self.latency_ms = latency_ms;
488        self
489    }
490}
491
492/// Something found on a frame, in the frame's pixels.
493#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
494#[serde(rename_all = "camelCase")]
495pub struct Overlay {
496    /// "part", "seal tear", "fiducial", "person".
497    pub label: String,
498    /// `[x0, y0, x1, y1]`; absent for a mask drawn without its box.
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub bbox: Option<[f64; 4]>,
501    /// Its score.
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub score: Option<f64>,
504    /// The anonymous track it belongs to.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub track: Option<u64>,
507    /// A mask's outline, as a polygon.
508    #[serde(default, skip_serializing_if = "Vec::is_empty")]
509    pub outline: Vec<[f64; 2]>,
510    /// A measured length.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub measurement: Option<Measurement>,
513    /// Frames in a row it was seen.
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub frames: Option<u32>,
516    /// A person covered before the frame was shown (board choice C9).
517    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
518    pub blurred: bool,
519}
520
521impl Overlay {
522    /// A box labelled `label`.
523    pub fn boxed(label: impl Into<String>, bbox: [f64; 4]) -> Self {
524        Self {
525            label: label.into(),
526            bbox: Some(bbox),
527            score: None,
528            track: None,
529            outline: Vec::new(),
530            measurement: None,
531            frames: None,
532            blurred: false,
533        }
534    }
535
536    /// Of track `track`.
537    #[must_use]
538    pub fn on_track(mut self, track: u64) -> Self {
539        self.track = Some(track);
540        self
541    }
542
543    /// With its score.
544    #[must_use]
545    pub fn scored(mut self, score: f64) -> Self {
546        self.score = Some(score);
547        self
548    }
549
550    /// With a mask's outline.
551    #[must_use]
552    pub fn outlined(mut self, outline: Vec<[f64; 2]>) -> Self {
553        self.outline = outline;
554        self
555    }
556
557    /// With a measured length.
558    #[must_use]
559    pub fn measured(mut self, measurement: Measurement) -> Self {
560        self.measurement = Some(measurement);
561        self
562    }
563
564    /// Seen `frames` frames in a row.
565    #[must_use]
566    pub fn for_frames(mut self, frames: u32) -> Self {
567        self.frames = Some(frames);
568        self
569    }
570
571    /// A person, covered before the frame was shown.
572    #[must_use]
573    pub fn blurred(mut self) -> Self {
574        self.blurred = true;
575        self
576    }
577}
578
579/// A length measured on a frame, valid in the calibrated plane (spec 3.7 §7.13).
580#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
581#[serde(rename_all = "camelCase")]
582pub struct Measurement {
583    /// One end, in the frame's pixels.
584    pub from: [f64; 2],
585    /// The other end.
586    pub to: [f64; 2],
587    /// The length in millimetres.
588    pub millimetres: f64,
589}
590
591/// A frame the hub holds in memory, with its digest: what a card keeps (board choice C11).
592#[derive(Debug, Clone, PartialEq)]
593pub struct HeldFrame {
594    /// `sha256:` of its bytes.
595    pub digest: String,
596    /// The frame.
597    pub frame: CameraFrame,
598}