1use crate::{AnalyticsError, AnalyticsEvent, ZoneAnalyticsConfig};
4use sightloom_core::{ClassId, MediaTime, Point, Polygon, Rect, TrackId, ZoneId};
5
6#[derive(Clone, Copy, Debug)]
7struct TrackAnalytics {
8 track_id: TrackId,
9 class_id: Option<ClassId>,
10 inside_streak: u32,
11 outside_streak: u32,
12 missed: u32,
13 confirmed_inside: bool,
14 dwell_active: bool,
15 dwell_started_at: Option<MediaTime>,
16 visit_count: u32,
17 last_seen_frame: u64,
18}
19
20pub struct ZoneAnalytics<'a, const N: usize> {
22 zone_id: ZoneId,
23 polygon: Polygon<'a>,
24 config: ZoneAnalyticsConfig,
25 slots: [Option<TrackAnalytics>; N],
26 occupancy: u32,
27}
28
29impl<'a, const N: usize> ZoneAnalytics<'a, N> {
30 pub fn new(
36 zone_id: ZoneId,
37 polygon: Polygon<'a>,
38 config: ZoneAnalyticsConfig,
39 ) -> Result<Self, AnalyticsError> {
40 let config = config.validate()?;
41 Ok(Self {
42 zone_id,
43 polygon,
44 config,
45 slots: [None; N],
46 occupancy: 0,
47 })
48 }
49
50 #[must_use]
52 pub const fn occupancy(&self) -> u32 {
53 self.occupancy
54 }
55
56 #[allow(clippy::too_many_arguments, clippy::missing_panics_doc)]
64 pub fn update(
65 &mut self,
66 track_id: TrackId,
67 bbox: Rect,
68 class_id: Option<ClassId>,
69 mask_centroid: Option<Point>,
70 frame_index: u64,
71 now: MediaTime,
72 output: &mut [AnalyticsEvent],
73 ) -> Result<usize, AnalyticsError> {
74 if let Some(filter) = self.config.class_filter
75 && class_id != Some(filter)
76 {
77 return Ok(0);
78 }
79
80 let anchor = self.config.anchor.anchor(bbox, mask_centroid);
81 let raw_inside = self.polygon.contains(anchor);
82 let index = self.find_or_alloc(track_id, class_id, frame_index)?;
83
84 let mut state = self.slots[index].expect("allocated");
86 let previous_occupancy = self.occupancy;
87 let mut events = [None; 4];
88 let mut event_count = 0_usize;
89
90 if raw_inside {
91 state.missed = 0;
92 state.inside_streak = state.inside_streak.saturating_add(1);
93 state.outside_streak = 0;
94 } else {
95 state.outside_streak = state.outside_streak.saturating_add(1);
96 state.inside_streak = 0;
97 }
98 state.last_seen_frame = frame_index;
99 state.class_id = class_id.or(state.class_id);
100
101 if !state.confirmed_inside && state.inside_streak >= self.config.enter_hysteresis {
102 state.confirmed_inside = true;
103 self.occupancy = self.occupancy.saturating_add(1);
104 events[event_count] = Some(AnalyticsEvent::Entered {
105 track_id,
106 zone_id: self.zone_id,
107 class_id: state.class_id,
108 });
109 event_count += 1;
110
111 let debounce_ok = self.config.dwell_start_debounce_ns == 0
112 || state.dwell_started_at.is_none_or(|start| {
113 now.duration_since_ns(start) >= self.config.dwell_start_debounce_ns
114 });
115 if debounce_ok && !state.dwell_active {
116 state.dwell_active = true;
117 state.dwell_started_at = Some(now);
118 events[event_count] = Some(AnalyticsEvent::DwellStarted {
119 track_id,
120 zone_id: self.zone_id,
121 at: now,
122 });
123 event_count += 1;
124 }
125 }
126
127 if state.confirmed_inside && state.outside_streak >= self.config.exit_hysteresis {
128 state.confirmed_inside = false;
129 self.occupancy = self.occupancy.saturating_sub(1);
130 events[event_count] = Some(AnalyticsEvent::Exited {
131 track_id,
132 zone_id: self.zone_id,
133 class_id: state.class_id,
134 });
135 event_count += 1;
136
137 if state.dwell_active {
138 let started = state.dwell_started_at.unwrap_or(now);
139 let duration_ns = now.duration_since_ns(started);
140 state.dwell_active = false;
141 state.visit_count = state.visit_count.saturating_add(1);
142 events[event_count] = Some(AnalyticsEvent::DwellEnded {
143 track_id,
144 zone_id: self.zone_id,
145 duration_ns,
146 visit_count: state.visit_count,
147 });
148 event_count += 1;
149 state.dwell_started_at = None;
150 }
151 }
152
153 if self.occupancy != previous_occupancy {
154 events[event_count] = Some(AnalyticsEvent::OccupancyChanged {
155 zone_id: self.zone_id,
156 occupancy: self.occupancy,
157 });
158 event_count += 1;
159 }
160
161 if event_count > output.len() {
162 self.occupancy = previous_occupancy;
164 return Err(AnalyticsError::InsufficientCapacity);
165 }
166
167 self.slots[index] = Some(state);
168 for (i, event) in events.into_iter().flatten().enumerate() {
169 output[i] = event;
170 }
171 Ok(event_count)
172 }
173
174 #[allow(clippy::missing_panics_doc)]
180 pub fn note_miss(
181 &mut self,
182 track_id: TrackId,
183 now: MediaTime,
184 output: &mut [AnalyticsEvent],
185 ) -> Result<usize, AnalyticsError> {
186 let Some(index) = self.find(track_id) else {
187 return Ok(0);
188 };
189 let mut state = self.slots[index].expect("found");
190 let previous_occupancy = self.occupancy;
191 state.missed = state.missed.saturating_add(1);
192 if state.missed <= self.config.missed_frame_tolerance {
193 self.slots[index] = Some(state);
194 return Ok(0);
195 }
196 state.outside_streak = state.outside_streak.saturating_add(1);
197 state.inside_streak = 0;
198
199 let mut written = 0_usize;
200 if state.confirmed_inside && state.outside_streak >= self.config.exit_hysteresis {
201 if output.len() < 2 {
202 return Err(AnalyticsError::InsufficientCapacity);
203 }
204 state.confirmed_inside = false;
205 self.occupancy = self.occupancy.saturating_sub(1);
206 output[written] = AnalyticsEvent::Exited {
207 track_id,
208 zone_id: self.zone_id,
209 class_id: state.class_id,
210 };
211 written += 1;
212 if state.dwell_active {
213 let started = state.dwell_started_at.unwrap_or(now);
214 state.dwell_active = false;
215 state.visit_count = state.visit_count.saturating_add(1);
216 output[written] = AnalyticsEvent::DwellEnded {
217 track_id,
218 zone_id: self.zone_id,
219 duration_ns: now.duration_since_ns(started),
220 visit_count: state.visit_count,
221 };
222 written += 1;
223 state.dwell_started_at = None;
224 }
225 if written < output.len() && self.occupancy != previous_occupancy {
226 output[written] = AnalyticsEvent::OccupancyChanged {
227 zone_id: self.zone_id,
228 occupancy: self.occupancy,
229 };
230 written += 1;
231 }
232 }
233 self.slots[index] = Some(state);
234 Ok(written)
235 }
236
237 #[must_use]
239 pub fn visit_count(&self, track_id: TrackId) -> Option<u32> {
240 self.find(track_id)
241 .and_then(|i| self.slots[i].map(|s| s.visit_count))
242 }
243
244 #[must_use]
246 pub fn time_in_zone_ns(&self, track_id: TrackId, now: MediaTime) -> Option<i64> {
247 let state = self.find(track_id).and_then(|i| self.slots[i])?;
248 if !state.dwell_active {
249 return None;
250 }
251 Some(now.duration_since_ns(state.dwell_started_at?))
252 }
253
254 fn find(&self, track_id: TrackId) -> Option<usize> {
255 self.slots.iter().position(|slot| {
256 slot.as_ref()
257 .is_some_and(|state| state.track_id == track_id)
258 })
259 }
260
261 fn find_or_alloc(
262 &mut self,
263 track_id: TrackId,
264 class_id: Option<ClassId>,
265 frame_index: u64,
266 ) -> Result<usize, AnalyticsError> {
267 if let Some(index) = self.find(track_id) {
268 return Ok(index);
269 }
270 let free = self
271 .slots
272 .iter()
273 .position(Option::is_none)
274 .ok_or(AnalyticsError::InsufficientCapacity)?;
275 self.slots[free] = Some(TrackAnalytics {
276 track_id,
277 class_id,
278 inside_streak: 0,
279 outside_streak: 0,
280 missed: 0,
281 confirmed_inside: false,
282 dwell_active: false,
283 dwell_started_at: None,
284 visit_count: 0,
285 last_seen_frame: frame_index,
286 });
287 Ok(free)
288 }
289}