1use 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
53pub const VISION_PAYLOAD_KIND: &str = "vision";
55
56const PAYLOAD_TEXT_CHARS: usize = 64;
59
60const PAYLOAD_FILE_CHARS: usize = 128;
63
64const MAX_KEY_PART: usize = 128;
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82#[non_exhaustive]
83pub struct VisualFrame {
84 pub index: u64,
86 pub captured_at: DateTime<Utc>,
88 pub digest: String,
90 pub width: u32,
92 pub height: u32,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub artifact: Option<ArtifactLocator>,
97}
98
99impl VisualFrame {
100 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 #[must_use]
113 pub fn with_artifact(mut self, artifact: ArtifactLocator) -> Self {
114 self.artifact = Some(artifact);
115 self
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131#[non_exhaustive]
132pub struct VisualRegion {
133 #[serde(rename = "box")]
135 pub bbox: [f32; 4],
136 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub label: Option<String>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub score: Option<f32>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub track: Option<u64>,
145}
146
147impl VisualRegion {
148 pub fn new(bbox: [f32; 4]) -> Self {
150 Self { bbox, label: None, score: None, track: None }
151 }
152
153 #[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 #[must_use]
162 pub fn with_score(mut self, score: f32) -> Self {
163 self.score = Some(score);
164 self
165 }
166
167 #[must_use]
169 pub fn with_track(mut self, track: u64) -> Self {
170 self.track = Some(track);
171 self
172 }
173}
174
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185#[non_exhaustive]
186pub struct VisualWake {
187 pub session: String,
189 pub condition: String,
191 pub event: String,
193 pub track: u64,
195 pub label: String,
197 pub score: f32,
199 pub frames: u32,
201 pub frame: VisualFrame,
203 pub regions: Vec<VisualRegion>,
205}
206
207impl VisualWake {
208 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 #[must_use]
233 pub fn with_frames(mut self, frames: u32) -> Self {
234 self.frames = frames;
235 self
236 }
237
238 #[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#[derive(Debug)]
255pub struct VisionWakeSource {
256 name: String,
257 hub: WakeHub,
258}
259
260impl VisionWakeSource {
261 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 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 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
337fn 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) = ®ion.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
362pub 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 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 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 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}