Skip to main content

adk_kernel/
vision.rs

1//! Visual wake sources (spec 3.7 §7.10).
2//!
3//! A camera, screen or browser stream evaluates its watch conditions on the device; the
4//! kernel sees only the events that pass. [`VisionWakeSource`] turns each into a
5//! [`WakeEvent`] and needs no new [`Wake`](crate::Wake) variant:
6//!
7//! | Part | How |
8//! |------|-----|
9//! | Name | The stream's source name, such as `conveyor-1`: a sleeper waits on `Wake::Queue { source: "conveyor-1" }` |
10//! | Key | [`keys::vision`]: `queue:<source>:<session>:<track>:<condition>:<event>`, so one track seen for forty frames wakes one process once, and a redelivery wakes nothing |
11//! | Fallback | With no sleeper, a [`Trigger`](crate::Trigger) on the same `Wake::Queue` starts a `Triggered` process |
12//! | Payload | The event, label, score, track, frame (index, capture time, digest, size, artifact and version) and the top regions with a count of the rest, within [`WAKE_PAYLOAD_LIMIT`] ([`vision_payload`]) |
13//! | Delivery | The woken turn reads the payload as delimited data, not instructions ([`WakeReason::notice`](crate::WakeReason::notice)), and loads the frame through the vision tools on the governed path |
14//!
15//! The payload carries digests and artifact references, never pixels (spec 3.7 V-I15). No
16//! principal is set, so standing rules and Auto stay inert for the run a camera starts: a
17//! consequential call it makes is held for a person.
18//!
19//! The kernel takes the source's events through its own types ([`VisualWake`]), so a default
20//! build compiles no perception code. Feature `vision` adds the bridge from `adk-vision`:
21//! `VisualWake: From<&adk_vision::WatchEvent>`, and `VisionWakeSource` as an
22//! `adk_vision::WatchSink`.
23//!
24//! # Example
25//!
26//! ```rust
27//! use adk_kernel::{VisionWakeSource, VisualFrame, VisualRegion, VisualWake, WakeSource};
28//!
29//! let source = VisionWakeSource::new("conveyor-1").unwrap();
30//! let frame = VisualFrame::new(1203, chrono::Utc::now(), "sha256:0f3a", 1280, 720);
31//! let wake = VisualWake::new("shift-1", "torn-seal", "detected", 7, "torn seal", 0.91, frame)
32//!     .with_frames(3)
33//!     .with_regions([VisualRegion::new([412.0, 220.5, 448.0, 251.0]).with_label("torn seal").with_track(7)]);
34//! let event = source.event(&wake).unwrap();
35//! assert_eq!(event.source, "conveyor-1");
36//! assert_eq!(event.key, "queue:conveyor-1:shift-1:7:torn-seal:detected");
37//! assert_eq!(event.payload["track"], 7);
38//! assert_eq!(event.payload["regions"][0]["box"][0], 412.0);
39//! assert!(event.payload.to_string().len() <= adk_kernel::WAKE_PAYLOAD_LIMIT);
40//! assert_eq!(source.name(), "conveyor-1");
41//! ```
42
43use adk_core::ArtifactLocator;
44use async_trait::async_trait;
45use chrono::{DateTime, SecondsFormat, Utc};
46use futures::stream::BoxStream;
47use serde::{Deserialize, Serialize};
48use serde_json::{Value, json};
49
50use crate::error::{KernelError, Result};
51use crate::wake::{WAKE_PAYLOAD_LIMIT, WakeEvent, WakeHub, WakeSource, keys};
52
53/// The `kind` of every visual wake payload.
54pub const VISION_PAYLOAD_KIND: &str = "vision";
55
56/// The most characters of any text a payload carries, so the payload's fixed part stays far
57/// below [`WAKE_PAYLOAD_LIMIT`] whatever a detector names its labels.
58const PAYLOAD_TEXT_CHARS: usize = 64;
59
60/// The most characters of the frame's artifact file name: a media-store name,
61/// `vision-<64 hex>.png`, is 75, and a cut name would name no artifact.
62const PAYLOAD_FILE_CHARS: usize = 128;
63
64/// The most bytes of a source name or a key part.
65const MAX_KEY_PART: usize = 128;
66
67/// The frame a visual wake names: its place in the stream, the digest of its encoded bytes,
68/// its size, and the artifact it is kept as.
69///
70/// # Example
71///
72/// ```rust
73/// use adk_core::ArtifactLocator;
74/// use adk_kernel::VisualFrame;
75///
76/// let frame = VisualFrame::new(1203, chrono::Utc::now(), "sha256:0f3a", 1280, 720)
77///     .with_artifact(ArtifactLocator::new("inspector", "line-1", "shift-1", "frame-1203.jpg", 0));
78/// assert_eq!(frame.artifact.unwrap().file_name, "frame-1203.jpg");
79/// ```
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82#[non_exhaustive]
83pub struct VisualFrame {
84    /// The frame's index in the stream.
85    pub index: u64,
86    /// When it was captured.
87    pub captured_at: DateTime<Utc>,
88    /// `sha256:` of its encoded bytes.
89    pub digest: String,
90    /// Width in source pixels.
91    pub width: u32,
92    /// Height in source pixels.
93    pub height: u32,
94    /// Where it is kept, with its version; `None` while it is not.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub artifact: Option<ArtifactLocator>,
97}
98
99impl VisualFrame {
100    /// A frame not yet kept as an artifact.
101    pub fn new(
102        index: u64,
103        captured_at: DateTime<Utc>,
104        digest: impl Into<String>,
105        width: u32,
106        height: u32,
107    ) -> Self {
108        Self { index, captured_at, digest: digest.into(), width, height, artifact: None }
109    }
110
111    /// Records where the frame is kept.
112    #[must_use]
113    pub fn with_artifact(mut self, artifact: ArtifactLocator) -> Self {
114        self.artifact = Some(artifact);
115        self
116    }
117}
118
119/// One region of a visual wake: its box in source pixels, label, score and track.
120///
121/// # Example
122///
123/// ```rust
124/// use adk_kernel::VisualRegion;
125///
126/// let region = VisualRegion::new([10.0, 20.0, 50.0, 60.0]).with_label("seal").with_score(0.8);
127/// assert_eq!(region.label.as_deref(), Some("seal"));
128/// ```
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131#[non_exhaustive]
132pub struct VisualRegion {
133    /// `[x0, y0, x1, y1]` in source pixels.
134    #[serde(rename = "box")]
135    pub bbox: [f32; 4],
136    /// The class or concept.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub label: Option<String>,
139    /// The detector's confidence.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub score: Option<f32>,
142    /// The anonymous track.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub track: Option<u64>,
145}
146
147impl VisualRegion {
148    /// A region with this box and nothing else.
149    pub fn new(bbox: [f32; 4]) -> Self {
150        Self { bbox, label: None, score: None, track: None }
151    }
152
153    /// Sets the label.
154    #[must_use]
155    pub fn with_label(mut self, label: impl Into<String>) -> Self {
156        self.label = Some(label.into());
157        self
158    }
159
160    /// Sets the score.
161    #[must_use]
162    pub fn with_score(mut self, score: f32) -> Self {
163        self.score = Some(score);
164        self
165    }
166
167    /// Sets the track.
168    #[must_use]
169    pub fn with_track(mut self, track: u64) -> Self {
170        self.track = Some(track);
171        self
172    }
173}
174
175/// A watch condition that passed on a stream, as the kernel takes it: the condition, what
176/// happened, the track with its label and score, the frame, and the regions that met the
177/// condition in it, the track's first.
178///
179/// `session` is the source session the anonymous track identifiers belong to; it is part of
180/// the key, since identifiers reset with it.
181///
182/// See the [module documentation](self) for an example.
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185#[non_exhaustive]
186pub struct VisualWake {
187    /// The source session.
188    pub session: String,
189    /// The watch condition's name.
190    pub condition: String,
191    /// What happened, such as `detected`.
192    pub event: String,
193    /// The anonymous track.
194    pub track: u64,
195    /// The track's label.
196    pub label: String,
197    /// The track's score.
198    pub score: f32,
199    /// The consecutive frames the track met the condition in.
200    pub frames: u32,
201    /// The frame.
202    pub frame: VisualFrame,
203    /// The regions that met the condition, the track's first, then by score.
204    pub regions: Vec<VisualRegion>,
205}
206
207impl VisualWake {
208    /// A wake for `track` under `condition`, with one frame counted and no regions.
209    pub fn new(
210        session: impl Into<String>,
211        condition: impl Into<String>,
212        event: impl Into<String>,
213        track: u64,
214        label: impl Into<String>,
215        score: f32,
216        frame: VisualFrame,
217    ) -> Self {
218        Self {
219            session: session.into(),
220            condition: condition.into(),
221            event: event.into(),
222            track,
223            label: label.into(),
224            score,
225            frames: 1,
226            frame,
227            regions: Vec::new(),
228        }
229    }
230
231    /// Sets the consecutive frames the track met the condition in.
232    #[must_use]
233    pub fn with_frames(mut self, frames: u32) -> Self {
234        self.frames = frames;
235        self
236    }
237
238    /// Sets the regions, the track's first.
239    #[must_use]
240    pub fn with_regions(mut self, regions: impl IntoIterator<Item = VisualRegion>) -> Self {
241        self.regions = regions.into_iter().collect();
242        self
243    }
244}
245
246/// A [`WakeSource`] for one camera, screen or browser stream (spec 3.7 §7.10): each
247/// [`VisualWake`] published becomes a [`WakeEvent`] named after the stream and keyed
248/// [`keys::vision`], which `Wake::Queue { source }` matches.
249///
250/// Register it with `KernelBuilder::wake_source`. Events published while no subscriber is
251/// attached are held, up to 1024, for the first subscriber.
252///
253/// See the [module documentation](self) for an example.
254#[derive(Debug)]
255pub struct VisionWakeSource {
256    name: String,
257    hub: WakeHub,
258}
259
260impl VisionWakeSource {
261    /// A source for the stream named `source`.
262    ///
263    /// # Errors
264    ///
265    /// [`KernelError::Config`] for a name that is empty, longer than 128 bytes, or holds
266    /// whitespace, a control character, `:` or `#`: the name is the start of every key, and
267    /// the kernel reads a key's source up to its first `:`.
268    pub fn new(source: impl Into<String>) -> Result<Self> {
269        let name = source.into();
270        key_part("source name", &name)?;
271        if name.contains(':') {
272            return Err(KernelError::Config {
273                reason: format!(
274                    "the visual wake source name `{name}` holds `:`; name the stream without \
275                     one, since a key's source ends at its first `:`"
276                ),
277            });
278        }
279        Ok(Self { name, hub: WakeHub::default() })
280    }
281
282    /// The wake event `wake` makes, without publishing it.
283    ///
284    /// # Errors
285    ///
286    /// [`KernelError::Config`] for a session, condition or event that is empty, longer than
287    /// 128 bytes, or holds whitespace, a control character or `#`.
288    pub fn event(&self, wake: &VisualWake) -> Result<WakeEvent> {
289        key_part("session", &wake.session)?;
290        key_part("condition", &wake.condition)?;
291        key_part("event", &wake.event)?;
292        let key = keys::vision(&self.name, &wake.session, wake.track, &wake.condition, &wake.event);
293        Ok(WakeEvent::new(self.name.clone(), key, vision_payload(&self.name, wake))
294            .with_at(wake.frame.captured_at))
295    }
296
297    /// Publishes `wake` to the source's subscribers and returns its event.
298    ///
299    /// # Errors
300    ///
301    /// [`event`](Self::event)'s errors; nothing is published then.
302    pub fn publish(&self, wake: &VisualWake) -> Result<WakeEvent> {
303        let event = self.event(wake)?;
304        tracing::debug!(wake.source = %self.name, wake.key = %event.key, "visual wake published");
305        self.hub.publish(event.clone());
306        Ok(event)
307    }
308}
309
310#[async_trait]
311impl WakeSource for VisionWakeSource {
312    fn name(&self) -> &str {
313        &self.name
314    }
315
316    async fn subscribe(&self) -> Result<BoxStream<'static, WakeEvent>> {
317        Ok(self.hub.subscribe())
318    }
319}
320
321fn key_part(what: &str, text: &str) -> Result<()> {
322    let ok = !text.is_empty()
323        && text.len() <= MAX_KEY_PART
324        && !text.chars().any(|c| c.is_whitespace() || c.is_control() || c == '#');
325    if ok {
326        return Ok(());
327    }
328    Err(KernelError::Config {
329        reason: format!(
330            "a visual wake's {what} `{}` cannot be part of a key: use 1 to {MAX_KEY_PART} bytes \
331             with no whitespace, control character or `#`",
332            clip(text, PAYLOAD_TEXT_CHARS)
333        ),
334    })
335}
336
337/// `text` cut to `chars` characters, control characters replaced, so a payload's size is
338/// bounded however a detector names things.
339fn clip(text: &str, chars: usize) -> String {
340    text.chars().take(chars).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect()
341}
342
343fn rounded(value: f32, decimals: i32) -> Value {
344    let scale = 10f64.powi(decimals);
345    json!((f64::from(value) * scale).round() / scale)
346}
347
348fn region_json(region: &VisualRegion) -> Value {
349    let mut entry = json!({ "box": region.bbox.map(|edge| rounded(edge, 1)) });
350    if let Some(label) = &region.label {
351        entry["label"] = json!(clip(label, PAYLOAD_TEXT_CHARS));
352    }
353    if let Some(score) = region.score {
354        entry["score"] = rounded(score, 2);
355    }
356    if let Some(track) = region.track {
357        entry["track"] = json!(track);
358    }
359    entry
360}
361
362/// The payload of `wake` from the stream `source`, as compact JSON within
363/// [`WAKE_PAYLOAD_LIMIT`] bytes: `kind` (`vision`), `source`, `session`, `condition`,
364/// `event`, `label`, `score`, `track`, `frames`, `frame` (`index`, `capturedAt`, `digest`,
365/// `width`, `height`, `artifact`), `regions` (each `box`, `label`, `score`, `track`) and
366/// `moreRegions`, the count of regions left out.
367///
368/// Texts are cut to 64 characters (the digest to 80, the frame's file name to 128) and boxes
369/// rounded to a tenth of a pixel, so the fixed part stays under 3.5 KiB; the regions kept are
370/// the longest prefix of
371/// `wake.regions` that fits.
372///
373/// # Example
374///
375/// ```rust
376/// use adk_kernel::{VisualFrame, VisualRegion, VisualWake, WAKE_PAYLOAD_LIMIT, vision_payload};
377///
378/// let frame = VisualFrame::new(9, chrono::Utc::now(), "sha256:0f3a", 1280, 720);
379/// let many = (0..500).map(|i| VisualRegion::new([i as f32, 0.0, i as f32 + 10.0, 10.0]).with_label("scratch"));
380/// let wake = VisualWake::new("s1", "scratch", "detected", 1, "scratch", 0.7, frame).with_regions(many);
381/// let payload = vision_payload("conveyor-1", &wake);
382/// assert!(payload.to_string().len() <= WAKE_PAYLOAD_LIMIT);
383/// let kept = payload["regions"].as_array().unwrap().len() as u64;
384/// assert_eq!(kept + payload["moreRegions"].as_u64().unwrap(), 500);
385/// ```
386pub fn vision_payload(source: &str, wake: &VisualWake) -> Value {
387    let text = |value: &str| json!(clip(value, PAYLOAD_TEXT_CHARS));
388    let frame = &wake.frame;
389    let mut frame_json = json!({
390        "index": frame.index,
391        "capturedAt": frame.captured_at.to_rfc3339_opts(SecondsFormat::Millis, true),
392        "digest": clip(&frame.digest, 80),
393        "width": frame.width,
394        "height": frame.height,
395    });
396    if let Some(artifact) = &frame.artifact {
397        frame_json["artifact"] = json!({
398            "appName": text(&artifact.app_name),
399            "userId": text(&artifact.user_id),
400            "sessionId": text(&artifact.session_id),
401            "fileName": clip(&artifact.file_name, PAYLOAD_FILE_CHARS),
402            "version": artifact.version,
403        });
404    }
405    let regions: Vec<Value> = wake.regions.iter().map(region_json).collect();
406    let total = regions.len();
407    let build = |kept: usize| {
408        json!({
409            "kind": VISION_PAYLOAD_KIND,
410            "source": text(source),
411            "session": text(&wake.session),
412            "condition": text(&wake.condition),
413            "event": text(&wake.event),
414            "label": text(&wake.label),
415            "score": rounded(wake.score, 2),
416            "track": wake.track,
417            "frames": wake.frames,
418            "frame": frame_json,
419            "regions": regions[..kept],
420            "moreRegions": total - kept,
421        })
422    };
423    let fits = |kept: usize| build(kept).to_string().len() <= WAKE_PAYLOAD_LIMIT;
424    // Each region adds more bytes than `moreRegions` loses digits, so the size grows with
425    // every region kept: the longest prefix that fits is found by bisection.
426    let (mut low, mut high) = (0, total);
427    while low < high {
428        let mid = (low + high).div_ceil(2);
429        if fits(mid) {
430            low = mid;
431        } else {
432            high = mid - 1;
433        }
434    }
435    build(low)
436}
437
438#[cfg(feature = "vision")]
439mod bridge {
440    use adk_vision::{VisionError, WatchEvent, WatchSink};
441    use async_trait::async_trait;
442
443    use super::{VisionWakeSource, VisualFrame, VisualRegion, VisualWake};
444
445    impl From<&WatchEvent> for VisualWake {
446        /// The kernel's form of a watch event; regions without a box are left out, and
447        /// masks travel as their boxes (spec 3.7 V-I15).
448        fn from(event: &WatchEvent) -> Self {
449            let frame = &event.frame;
450            let mut visual = VisualFrame::new(
451                frame.index,
452                frame.captured_at,
453                frame.digest.to_string(),
454                frame.width,
455                frame.height,
456            );
457            visual.artifact = frame.artifact.clone();
458            let regions = event.regions.iter().filter_map(|region| {
459                let b = region.shape.bbox()?;
460                Some(VisualRegion {
461                    bbox: [b.x0, b.y0, b.x1, b.y1],
462                    label: region.label.clone(),
463                    score: region.score,
464                    track: region.track.map(|track| track.0),
465                })
466            });
467            VisualWake::new(
468                event.session.clone(),
469                event.condition.clone(),
470                event.kind.as_str(),
471                event.track.0,
472                event.label.clone(),
473                event.score,
474                visual,
475            )
476            .with_frames(event.frames)
477            .with_regions(regions)
478        }
479    }
480
481    #[async_trait]
482    impl WatchSink for VisionWakeSource {
483        /// Publishes the event as a wake.
484        ///
485        /// # Errors
486        ///
487        /// [`VisionError::InvalidInput`] for an event from another stream than the source's,
488        /// or one whose session, condition or event cannot key a wake.
489        async fn deliver(&self, event: &WatchEvent) -> adk_vision::Result<()> {
490            if event.source.0 != self.name {
491                return Err(VisionError::InvalidInput(format!(
492                    "a watch event from stream `{}` reached the wake source of `{}`; register \
493                     one VisionWakeSource per stream",
494                    event.source.0, self.name
495                )));
496            }
497            self.publish(&VisualWake::from(event))
498                .map(|_| ())
499                .map_err(|error| VisionError::InvalidInput(error.to_string()))
500        }
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    fn frame() -> VisualFrame {
509        VisualFrame::new(4, Utc::now(), "sha256:0f3a", 640, 480)
510    }
511
512    #[test]
513    fn names_and_key_parts_that_cannot_key_a_wake_are_refused() {
514        for name in ["", "rtsp://cam", "two words", "a#b"] {
515            assert!(VisionWakeSource::new(name).is_err(), "{name:?}");
516        }
517        let source = VisionWakeSource::new("cam-1").unwrap();
518        for (session, condition) in [("", "seal"), ("s 1", "seal"), ("s1", "se#al")] {
519            let wake = VisualWake::new(session, condition, "detected", 1, "seal", 0.9, frame());
520            assert!(source.event(&wake).is_err(), "{session:?} {condition:?}");
521        }
522    }
523
524    #[test]
525    fn a_published_wake_reaches_a_later_subscriber_once() {
526        use futures::StreamExt;
527
528        let source = VisionWakeSource::new("cam-1").unwrap();
529        let wake = VisualWake::new("s1", "seal", "detected", 3, "seal", 0.9, frame());
530        let published = source.publish(&wake).unwrap();
531        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
532        let received = runtime.block_on(async {
533            let mut events = source.subscribe().await.unwrap();
534            events.next().await.unwrap()
535        });
536        assert_eq!(received, published);
537        assert_eq!(received.key, "queue:cam-1:s1:3:seal:detected");
538    }
539
540    #[test]
541    fn a_media_store_file_name_reaches_the_payload_whole() {
542        let file = format!("vision-{}.png", "0f".repeat(32));
543        let frame =
544            frame().with_artifact(ArtifactLocator::new("inspector", "line-1", "s1", &file, 0));
545        let wake = VisualWake::new("s1", "seal", "detected", 1, "seal", 0.9, frame);
546        let payload = vision_payload("cam-1", &wake);
547        assert_eq!(payload["frame"]["artifact"]["fileName"], json!(file));
548    }
549
550    #[test]
551    fn hostile_labels_stay_within_the_limit() {
552        let label = "\u{0}\"\\\u{10ffff}".repeat(400);
553        let region = VisualRegion::new([0.0, 0.0, 1.0, 1.0]).with_label(label.clone());
554        let mut frame = frame();
555        frame.digest = label.clone();
556        frame.artifact = Some(ArtifactLocator::new(&label, &label, &label, &label, 1));
557        let wake = VisualWake::new("s1", "seal", "detected", 1, label, 0.5, frame)
558            .with_regions(vec![region; 100]);
559        let payload = vision_payload(&"\u{1F600}".repeat(200), &wake);
560        assert!(payload.to_string().len() <= WAKE_PAYLOAD_LIMIT, "{}", payload.to_string().len());
561        assert!(payload["regions"].as_array().is_some_and(|kept| !kept.is_empty()));
562    }
563}