adk_vision/watch/mod.rs
1//! Watch conditions: what a stream wakes an agent for (spec 3.7 §7.10).
2//!
3//! A stream's pipeline runs source, sampler, privacy, detector and tracker, then hands each
4//! frame's tracked regions to a [`WatchEvaluator`] as a [`TrackedObservation`]. The
5//! evaluator holds each [`WatchCondition`] against every track, on the device, and returns a
6//! [`WatchEvent`] only when one passes — a track that met the condition in enough consecutive
7//! frames, outside the condition's cooldown. A [`WatchSink`] takes the events on; the
8//! kernel's `VisionWakeSource` (`adk-kernel`, feature `vision`) is one, turning each into a
9//! wake.
10//!
11//! | Property | Holds by |
12//! |----------|----------|
13//! | One track, one event | A track fires once per condition and session, however long it stays in view |
14//! | Idempotent | An observation delivered twice, or out of order, changes nothing; each event's [`key`](WatchEvent::key) is its source, session, track, condition and kind |
15//! | Bounded | State is kept only for the tracks the tracker still holds |
16//! | Pure | No clock, no I/O: time is each frame's capture time |
17//!
18//! Events carry digests and artifact references, never pixels (V-I15).
19//!
20//! # Example
21//!
22//! ```
23//! use adk_vision::{
24//! BBox, BackendId, CoordFrame, Digest, FrameRef, FrameSourceId, Region, RegionOrigin,
25//! Shape, TrackId, TrackedObservation, TransformChain, WatchCondition, WatchEvaluator,
26//! };
27//!
28//! let mut watch = WatchEvaluator::new(vec![
29//! WatchCondition::new("torn-seal", ["torn seal"]).with_min_frames(3),
30//! ])
31//! .unwrap();
32//! let seal = |index: u64| {
33//! let frame = Digest::of(&index.to_be_bytes());
34//! let region = Region {
35//! image: frame,
36//! shape: Shape::Box(BBox::new(400.0, 200.0, 440.0, 230.0)),
37//! label: Some("torn seal".into()),
38//! score: Some(0.9),
39//! track: Some(TrackId(7)),
40//! origin: RegionOrigin {
41//! backend: BackendId::new("rf-detr"),
42//! manifest: None,
43//! frame: CoordFrame::SentPixels,
44//! chain: TransformChain::new(1280, 720),
45//! escalated_from: None,
46//! },
47//! };
48//! TrackedObservation::new(
49//! FrameSourceId("conveyor-1".into()),
50//! "shift-1",
51//! FrameRef::new(index, chrono::Utc::now(), frame, 1280, 720),
52//! vec![region],
53//! )
54//! };
55//! // Forty frames of one torn seal: one event, on the third frame.
56//! let events: Vec<_> = (0..40).flat_map(|i| watch.observe(&seal(i))).collect();
57//! assert_eq!(events.len(), 1);
58//! assert_eq!(events[0].frame.index, 2);
59//! assert_eq!(events[0].key(), "shift-1:7:torn-seal:detected");
60//! ```
61
62mod condition;
63mod evaluator;
64
65use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
66use async_trait::async_trait;
67use chrono::{DateTime, Utc};
68use serde::{Deserialize, Serialize};
69use serde_json::json;
70
71pub use condition::{WatchCondition, Zone, ZoneAnchor};
72pub use evaluator::WatchEvaluator;
73
74use crate::audit::VISION_AUDIT_KIND;
75use crate::digest::Digest;
76use crate::error::Result;
77use crate::geometry::{Region, TrackId};
78use crate::media::{ArtifactLocator, FrameSourceId, ImageRef};
79
80/// Action of the record a watch condition registered on a source writes.
81pub const VISION_WATCH_REGISTERED: &str = "vision.watch.registered";
82/// Action of the record a watch event writes.
83pub const VISION_WATCH_FIRED: &str = "vision.watch.fired";
84/// Action of the record a watch condition removed from a source writes.
85pub const VISION_WATCH_STOPPED: &str = "vision.watch.stopped";
86
87/// The frame an observation was made on: its place in the stream, the digest of its encoded
88/// bytes, its size, and the artifact it is stored as once it is kept.
89///
90/// Frames stay in memory unless they become evidence (spec 3.7 §7.13), so `artifact` is
91/// `None` until the pipeline keeps the frame; a pipeline keeps the frame of each event and
92/// attaches its locator ([`WatchEvent::with_frame_artifact`]) before delivering the event.
93///
94/// # Example
95///
96/// ```
97/// use adk_vision::{ArtifactLocator, Digest, FrameRef};
98///
99/// let frame = FrameRef::new(1203, chrono::Utc::now(), Digest::of(b"jpeg"), 1280, 720);
100/// assert!(frame.artifact.is_none());
101/// let kept = frame.with_artifact(ArtifactLocator::new("inspector", "line-1", "shift-1", "frame-1203.jpg", 0));
102/// assert_eq!(kept.artifact.unwrap().version, 0);
103/// ```
104#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "camelCase")]
106pub struct FrameRef {
107 /// The frame's index in the stream.
108 pub index: u64,
109 /// When the frame was captured.
110 pub captured_at: DateTime<Utc>,
111 /// `sha256:` of the frame's encoded bytes, the digest its regions name.
112 pub digest: Digest,
113 /// Width in source pixels.
114 pub width: u32,
115 /// Height in source pixels.
116 pub height: u32,
117 /// Where the frame is stored, with its version; `None` while it is ephemeral.
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub artifact: Option<ArtifactLocator>,
120}
121
122impl FrameRef {
123 /// An ephemeral frame.
124 pub fn new(
125 index: u64,
126 captured_at: DateTime<Utc>,
127 digest: Digest,
128 width: u32,
129 height: u32,
130 ) -> Self {
131 Self { index, captured_at, digest, width, height, artifact: None }
132 }
133
134 /// A frame kept as `image`.
135 pub fn stored(index: u64, captured_at: DateTime<Utc>, image: &ImageRef) -> Self {
136 Self {
137 index,
138 captured_at,
139 digest: image.digest,
140 width: image.width,
141 height: image.height,
142 artifact: Some(image.artifact.clone()),
143 }
144 }
145
146 /// Records where the frame is stored.
147 #[must_use]
148 pub fn with_artifact(mut self, artifact: ArtifactLocator) -> Self {
149 self.artifact = Some(artifact);
150 self
151 }
152}
153
154/// One frame's tracked regions, as the stream pipeline hands them to a [`WatchEvaluator`].
155///
156/// `session` names the source session the track identifiers belong to: they are anonymous
157/// and reset with it (V-I8), so a new session starts every condition afresh and its events
158/// have their own keys. Within a session a tracker never reuses an identifier.
159///
160/// # Example
161///
162/// ```
163/// use adk_vision::{Digest, FrameRef, FrameSourceId, TrackId, TrackedObservation};
164///
165/// let frame = FrameRef::new(0, chrono::Utc::now(), Digest::of(b"frame"), 640, 480);
166/// let empty = TrackedObservation::new(FrameSourceId("cam".into()), "s1", frame, Vec::new())
167/// .with_tracks([TrackId(3)]);
168/// assert_eq!(empty.tracks, vec![TrackId(3)]);
169/// ```
170#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
171#[serde(rename_all = "camelCase")]
172pub struct TrackedObservation {
173 /// The frame source.
174 pub source: FrameSourceId,
175 /// The source session the track identifiers belong to.
176 pub session: String,
177 /// The frame.
178 pub frame: FrameRef,
179 /// The frame's regions, in source pixels; the tracker set each one's `track`. Regions
180 /// without a track are not watched.
181 pub regions: Vec<Region>,
182 /// The tracks the tracker still holds after this frame, seen in it or briefly missed.
183 /// The evaluator forgets a track that is neither listed nor seen in the frame.
184 pub tracks: Vec<TrackId>,
185}
186
187impl TrackedObservation {
188 /// An observation whose live tracks are the ones its regions carry.
189 pub fn new(
190 source: FrameSourceId,
191 session: impl Into<String>,
192 frame: FrameRef,
193 regions: Vec<Region>,
194 ) -> Self {
195 let mut tracks: Vec<TrackId> = regions.iter().filter_map(|r| r.track).collect();
196 tracks.sort_unstable();
197 tracks.dedup();
198 Self { source, session: session.into(), frame, regions, tracks }
199 }
200
201 /// Sets the tracks the tracker still holds, such as tracks missed in this frame that it
202 /// keeps alive; the tracks of the regions stay listed.
203 #[must_use]
204 pub fn with_tracks(mut self, tracks: impl IntoIterator<Item = TrackId>) -> Self {
205 self.tracks.extend(tracks);
206 self.tracks.sort_unstable();
207 self.tracks.dedup();
208 self
209 }
210}
211
212/// What happened to a track under a condition.
213///
214/// # Example
215///
216/// ```
217/// use adk_vision::WatchEventKind;
218///
219/// assert_eq!(WatchEventKind::Detected.as_str(), "detected");
220/// assert_eq!(serde_json::to_value(WatchEventKind::Detected).unwrap(), "detected");
221/// ```
222#[non_exhaustive]
223#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub enum WatchEventKind {
226 /// The track met the condition in its minimum number of consecutive frames.
227 Detected,
228}
229
230impl WatchEventKind {
231 /// The kind as it appears in event keys and payloads.
232 pub fn as_str(self) -> &'static str {
233 match self {
234 Self::Detected => "detected",
235 }
236 }
237}
238
239/// A condition that passed: the track, its label and score, the frame and the regions that
240/// met the condition in it.
241///
242/// `regions` lists the firing track's region first, then the frame's other regions that met
243/// the condition, tracked or not, highest score first.
244#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
245#[serde(rename_all = "camelCase")]
246pub struct WatchEvent {
247 /// The frame source.
248 pub source: FrameSourceId,
249 /// The source session.
250 pub session: String,
251 /// The condition's name.
252 pub condition: String,
253 /// What happened.
254 pub kind: WatchEventKind,
255 /// The track.
256 pub track: TrackId,
257 /// The track's label in this frame.
258 pub label: String,
259 /// The track's score in this frame.
260 pub score: f32,
261 /// The consecutive frames the track had met the condition in.
262 pub frames: u32,
263 /// The frame.
264 pub frame: FrameRef,
265 /// The regions that met the condition in the frame, the track's first.
266 pub regions: Vec<Region>,
267}
268
269impl WatchEvent {
270 /// The event's identity within its source: `<session>:<track>:<condition>:<kind>`. The
271 /// kernel keys the wake `queue:<source>:<key>`, so a redelivered event wakes nothing.
272 pub fn key(&self) -> String {
273 format!("{}:{}:{}:{}", self.session, self.track.0, self.condition, self.kind.as_str())
274 }
275
276 /// Records where the event's frame is stored, once the pipeline has kept it.
277 #[must_use]
278 pub fn with_frame_artifact(mut self, artifact: ArtifactLocator) -> Self {
279 self.frame.artifact = Some(artifact);
280 self
281 }
282
283 /// The `vision.watch.fired` audit record of the event: source, condition, track, frame
284 /// digest and artifact, by reference only (V-I15).
285 ///
286 /// `condition` is the digest of the condition that fired ([`WatchCondition::digest`]).
287 pub fn audit_draft(&self, condition: Digest) -> AuditRecordDraft {
288 let mut draft = AuditRecordDraft::new(
289 AuditRecordKind::Other(VISION_AUDIT_KIND.to_string()),
290 VISION_WATCH_FIRED,
291 )
292 .outcome(AuditRecordOutcome::Succeeded)
293 .payload_ref(self.frame.digest.to_string())
294 .ext("source", json!(self.source))
295 .ext("session", json!(self.session))
296 .ext("condition", json!(self.condition))
297 .ext("conditionDigest", json!(condition))
298 .ext("event", json!(self.kind))
299 .ext("track", json!(self.track))
300 .ext("frameDigest", json!(self.frame.digest))
301 .ext("frameIndex", json!(self.frame.index));
302 if let Some(artifact) = &self.frame.artifact {
303 draft = draft.ext("artifact", json!(artifact));
304 }
305 draft
306 }
307}
308
309/// The `vision.watch.registered` audit record of `condition` registered on `source`.
310///
311/// # Example
312///
313/// ```
314/// use adk_vision::{FrameSourceId, VISION_WATCH_REGISTERED, WatchCondition, watch_registered_draft};
315///
316/// let condition = WatchCondition::new("torn-seal", ["torn seal"]);
317/// let draft = watch_registered_draft(&FrameSourceId("conveyor-1".into()), &condition);
318/// assert_eq!(draft.action, VISION_WATCH_REGISTERED);
319/// ```
320pub fn watch_registered_draft(
321 source: &FrameSourceId,
322 condition: &WatchCondition,
323) -> AuditRecordDraft {
324 AuditRecordDraft::new(
325 AuditRecordKind::Other(VISION_AUDIT_KIND.to_string()),
326 VISION_WATCH_REGISTERED,
327 )
328 .outcome(AuditRecordOutcome::Succeeded)
329 .payload_ref(condition.digest().to_string())
330 .ext("source", json!(source))
331 .ext("condition", json!(condition.name))
332 .ext("conditionDigest", json!(condition.digest()))
333 .ext("labels", json!(condition.labels))
334 .ext("minScore", json!(condition.min_score))
335 .ext("minFrames", json!(condition.min_frames))
336 .ext("zone", json!(condition.zone.is_some()))
337 .ext("cooldownMs", json!(u64::try_from(condition.cooldown.as_millis()).unwrap_or(u64::MAX)))
338}
339
340/// Takes the events a [`WatchEvaluator`] passes, such as the kernel's `VisionWakeSource`
341/// (`adk-kernel`, feature `vision`), which turns each into a wake.
342///
343/// # Example
344///
345/// ```
346/// use std::sync::Mutex;
347/// use adk_vision::{WatchEvent, WatchSink};
348///
349/// #[derive(Default)]
350/// struct Collect(Mutex<Vec<String>>);
351///
352/// #[async_trait::async_trait]
353/// impl WatchSink for Collect {
354/// async fn deliver(&self, event: &WatchEvent) -> adk_vision::Result<()> {
355/// self.0.lock().unwrap().push(event.key());
356/// Ok(())
357/// }
358/// }
359/// ```
360#[async_trait]
361pub trait WatchSink: Send + Sync {
362 /// Takes one event.
363 ///
364 /// # Errors
365 ///
366 /// Returns the sink's error, such as an event for a source it does not serve.
367 async fn deliver(&self, event: &WatchEvent) -> Result<()>;
368}