adk_vision/watch/condition.rs
1//! [`WatchCondition`] and its [`Zone`].
2
3use std::time::Duration;
4
5use serde::{Deserialize, Serialize};
6
7use crate::digest::Digest;
8use crate::error::{Result, VisionError};
9use crate::geometry::{Polygon, Region};
10
11/// The longest condition name, in characters.
12const MAX_NAME_CHARS: usize = 64;
13
14/// Which point of a region must lie in a [`Zone`].
15///
16/// # Example
17///
18/// ```
19/// use adk_vision::ZoneAnchor;
20///
21/// assert_eq!(ZoneAnchor::default(), ZoneAnchor::Center);
22/// assert_eq!(serde_json::to_value(ZoneAnchor::BottomCenter).unwrap(), "bottomCenter");
23/// ```
24#[non_exhaustive]
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27pub enum ZoneAnchor {
28 /// The centre of the region's box.
29 #[default]
30 Center,
31 /// The middle of the box's bottom edge: where an object meets the floor or the belt.
32 BottomCenter,
33}
34
35/// An area of the frame a [`WatchCondition`] is limited to: a polygon in source pixels and
36/// the point of each region that must lie inside it.
37///
38/// Containment is even-odd ray casting with half-open edges, so a zone drawn as an
39/// axis-aligned rectangle holds exactly the points [`BBox::contains`](crate::BBox::contains)
40/// holds.
41///
42/// # Example
43///
44/// ```
45/// use adk_vision::{Zone, ZoneAnchor};
46///
47/// // The left half of a 1280x720 frame.
48/// let zone = Zone::new(vec![[0.0, 0.0], [640.0, 0.0], [640.0, 720.0], [0.0, 720.0]]).unwrap();
49/// assert!(zone.contains([100.0, 300.0]));
50/// assert!(!zone.contains([700.0, 300.0]));
51/// assert_eq!(zone.with_anchor(ZoneAnchor::BottomCenter).anchor, ZoneAnchor::BottomCenter);
52/// assert!(Zone::new(vec![[0.0, 0.0], [1.0, 1.0]]).is_err());
53/// ```
54#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct Zone {
57 /// The polygon, vertices in order, in source pixels.
58 pub polygon: Polygon,
59 /// The point of each region that must lie inside.
60 #[serde(default)]
61 pub anchor: ZoneAnchor,
62}
63
64impl Zone {
65 /// A zone over the polygon with these vertices, anchored at each region's centre.
66 ///
67 /// # Errors
68 ///
69 /// [`VisionError::InvalidInput`] for fewer than three vertices or a coordinate that is
70 /// not finite.
71 pub fn new(points: Vec<[f32; 2]>) -> Result<Self> {
72 let zone = Self { polygon: Polygon { points }, anchor: ZoneAnchor::default() };
73 zone.validate()?;
74 Ok(zone)
75 }
76
77 /// Sets the point of each region that must lie inside.
78 #[must_use]
79 pub fn with_anchor(mut self, anchor: ZoneAnchor) -> Self {
80 self.anchor = anchor;
81 self
82 }
83
84 /// Checks the polygon: three vertices or more, every coordinate finite.
85 ///
86 /// # Errors
87 ///
88 /// [`VisionError::InvalidInput`] naming what is wrong.
89 pub fn validate(&self) -> Result<()> {
90 let points = &self.polygon.points;
91 if points.len() < 3 {
92 return Err(VisionError::InvalidInput(format!(
93 "a zone is a polygon of three vertices or more, not {}",
94 points.len()
95 )));
96 }
97 if points.iter().flatten().any(|c| !c.is_finite()) {
98 return Err(VisionError::InvalidInput(
99 "a zone's vertices must be finite pixel coordinates".into(),
100 ));
101 }
102 Ok(())
103 }
104
105 /// Whether `point` lies inside the polygon (even-odd rule, half-open edges).
106 pub fn contains(&self, [x, y]: [f32; 2]) -> bool {
107 let points = &self.polygon.points;
108 let mut inside = false;
109 let mut previous = match points.last() {
110 Some(last) => *last,
111 None => return false,
112 };
113 for ¤t in points {
114 let ([xi, yi], [xj, yj]) = (current, previous);
115 if (yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi {
116 inside = !inside;
117 }
118 previous = current;
119 }
120 inside
121 }
122
123 /// Whether the region's anchor point lies inside; a region with no extent is outside.
124 pub fn holds(&self, region: &Region) -> bool {
125 let Some(bbox) = region.shape.bbox() else { return false };
126 let point = match self.anchor {
127 ZoneAnchor::Center => bbox.center(),
128 ZoneAnchor::BottomCenter => [(bbox.x0 + bbox.x1) / 2.0, bbox.y1],
129 };
130 self.contains(point)
131 }
132}
133
134/// What a stream watches for, evaluated on the device so the kernel sees only the events
135/// that pass (spec 3.7 ยง7.10).
136///
137/// A region meets the condition when its label is one of `labels` (compared ignoring ASCII
138/// case; an empty list takes any label), its score is at least `min_score` (a region with no
139/// score has none), and, with a zone, its anchor point lies in the zone. A track fires once
140/// it has met the condition in `min_frames` consecutive observations. After a firing, the
141/// condition fires again no sooner than `cooldown` later, by the frames' capture times.
142///
143/// | Field | Default |
144/// |-------|---------|
145/// | `min_score` | `0.5` |
146/// | `min_frames` | `3` |
147/// | `zone` | none: the whole frame |
148/// | `cooldown` | zero |
149///
150/// # Example
151///
152/// ```
153/// use std::time::Duration;
154/// use adk_vision::WatchCondition;
155///
156/// let seal = WatchCondition::new("torn-seal", ["torn seal"])
157/// .with_min_score(0.6)
158/// .with_min_frames(3)
159/// .with_cooldown(Duration::from_secs(2));
160/// assert!(seal.validate().is_ok());
161/// let json = serde_json::to_value(&seal).unwrap();
162/// assert_eq!(json["cooldownMs"], 2000);
163/// assert!(WatchCondition::new("torn seal", ["seal"]).validate().is_err(), "names are keys");
164/// ```
165#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase")]
167pub struct WatchCondition {
168 /// The condition's name: part of every event key, so `[A-Za-z0-9._-]`, at most 64.
169 pub name: String,
170 /// The labels that count; empty for any.
171 #[serde(default)]
172 pub labels: Vec<String>,
173 /// The lowest score that counts, in `[0, 1]`.
174 pub min_score: f32,
175 /// How many consecutive observations a track must meet the condition in, at least 1.
176 pub min_frames: u32,
177 /// The area of the frame the condition is limited to.
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub zone: Option<Zone>,
180 /// The least time between two firings of the condition.
181 #[serde(default, rename = "cooldownMs", with = "millis")]
182 pub cooldown: Duration,
183}
184
185impl WatchCondition {
186 /// A condition named `name` over `labels`, with the defaults in the table above.
187 pub fn new<L: Into<String>>(
188 name: impl Into<String>,
189 labels: impl IntoIterator<Item = L>,
190 ) -> Self {
191 Self {
192 name: name.into(),
193 labels: labels.into_iter().map(Into::into).collect(),
194 min_score: 0.5,
195 min_frames: 3,
196 zone: None,
197 cooldown: Duration::ZERO,
198 }
199 }
200
201 /// Sets the lowest score that counts.
202 #[must_use]
203 pub fn with_min_score(mut self, min_score: f32) -> Self {
204 self.min_score = min_score;
205 self
206 }
207
208 /// Sets how many consecutive observations a track must meet the condition in.
209 #[must_use]
210 pub fn with_min_frames(mut self, min_frames: u32) -> Self {
211 self.min_frames = min_frames;
212 self
213 }
214
215 /// Limits the condition to `zone`.
216 #[must_use]
217 pub fn with_zone(mut self, zone: Zone) -> Self {
218 self.zone = Some(zone);
219 self
220 }
221
222 /// Sets the least time between two firings.
223 #[must_use]
224 pub fn with_cooldown(mut self, cooldown: Duration) -> Self {
225 self.cooldown = cooldown;
226 self
227 }
228
229 /// Checks the condition.
230 ///
231 /// # Errors
232 ///
233 /// [`VisionError::InvalidInput`] for a name outside `[A-Za-z0-9._-]` or longer than 64
234 /// characters, a `min_score` outside `[0, 1]`, a `min_frames` of zero, or an invalid
235 /// zone.
236 pub fn validate(&self) -> Result<()> {
237 let name_ok = !self.name.is_empty()
238 && self.name.chars().count() <= MAX_NAME_CHARS
239 && self.name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
240 if !name_ok {
241 return Err(VisionError::InvalidInput(format!(
242 "watch condition name `{}` must be 1 to {MAX_NAME_CHARS} characters of \
243 [A-Za-z0-9._-]: it is part of every event key",
244 self.name
245 )));
246 }
247 if !(0.0..=1.0).contains(&self.min_score) {
248 return Err(VisionError::InvalidInput(format!(
249 "watch condition `{}` has min_score {}; use a score in [0, 1]",
250 self.name, self.min_score
251 )));
252 }
253 if self.min_frames == 0 {
254 return Err(VisionError::InvalidInput(format!(
255 "watch condition `{}` needs min_frames of at least 1",
256 self.name
257 )));
258 }
259 if let Some(zone) = &self.zone {
260 zone.validate()?;
261 }
262 Ok(())
263 }
264
265 /// Whether `region` meets the condition in this one frame: label, score and zone.
266 ///
267 /// # Example
268 ///
269 /// ```
270 /// use adk_vision::{BBox, BackendId, CoordFrame, Digest, Region, RegionOrigin, Shape, TransformChain, WatchCondition};
271 ///
272 /// let region = Region {
273 /// image: Digest::of(b"frame"),
274 /// shape: Shape::Box(BBox::new(10.0, 10.0, 50.0, 30.0)),
275 /// label: Some("Torn Seal".into()),
276 /// score: Some(0.8),
277 /// track: None,
278 /// origin: RegionOrigin {
279 /// backend: BackendId::new("rf-detr"),
280 /// manifest: None,
281 /// frame: CoordFrame::SentPixels,
282 /// chain: TransformChain::new(640, 480),
283 /// escalated_from: None,
284 /// },
285 /// };
286 /// assert!(WatchCondition::new("seal", ["torn seal"]).matches(®ion));
287 /// assert!(!WatchCondition::new("seal", ["torn seal"]).with_min_score(0.9).matches(®ion));
288 /// ```
289 pub fn matches(&self, region: &Region) -> bool {
290 let label_ok = self.labels.is_empty()
291 || region.label.as_deref().is_some_and(|label| {
292 self.labels.iter().any(|wanted| wanted.eq_ignore_ascii_case(label))
293 });
294 label_ok
295 && region.score.is_some_and(|score| score >= self.min_score)
296 && self.zone.as_ref().is_none_or(|zone| zone.holds(region))
297 }
298
299 /// The digest of the condition's canonical JSON, which the `vision.watch.*` audit records
300 /// name.
301 pub fn digest(&self) -> Digest {
302 Digest::of_json(self)
303 }
304}
305
306/// A `Duration` as whole milliseconds.
307mod millis {
308 use std::time::Duration;
309
310 use serde::{Deserialize, Deserializer, Serializer};
311
312 pub(super) fn serialize<S: Serializer>(
313 value: &Duration,
314 serializer: S,
315 ) -> Result<S::Ok, S::Error> {
316 serializer.serialize_u64(u64::try_from(value.as_millis()).unwrap_or(u64::MAX))
317 }
318
319 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
320 deserializer: D,
321 ) -> Result<Duration, D::Error> {
322 u64::deserialize(deserializer).map(Duration::from_millis)
323 }
324}