1#[cfg(feature = "alloc")]
4extern crate alloc;
5
6#[cfg(feature = "alloc")]
7use alloc::vec::Vec;
8
9#[cfg(feature = "std")]
10use std::collections::HashMap;
11
12use crate::{ByteTrackConfig, ByteTracker, TrackError, TrackerSnapshot};
13use sightloom_core::{Detection, SourceId, TrackKey, TrackUid};
14
15#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct TrackedDetection {
18 pub detection: Detection,
20 pub track_key: TrackKey,
22 pub track_uid: TrackUid,
24}
25
26#[cfg(feature = "std")]
30#[derive(Clone, Debug)]
31pub struct MultiSourceTracker {
32 config: ByteTrackConfig,
33 trackers: HashMap<u32, ByteTracker>,
34 uids: HashMap<(u32, u32), TrackUid>,
36 next_uid: u64,
37}
38
39#[cfg(feature = "std")]
40impl MultiSourceTracker {
41 pub fn new(config: ByteTrackConfig) -> Result<Self, TrackError> {
47 let _ = config.validate()?;
48 Ok(Self {
49 config,
50 trackers: HashMap::new(),
51 uids: HashMap::new(),
52 next_uid: 1,
53 })
54 }
55
56 #[must_use]
58 pub const fn config(&self) -> ByteTrackConfig {
59 self.config
60 }
61
62 #[must_use]
64 pub const fn next_uid(&self) -> u64 {
65 self.next_uid
66 }
67
68 #[must_use]
70 pub fn checkpoint(&self) -> MultiSourceCheckpoint {
71 let mut sources = Vec::new();
72 for (source, tracker) in &self.trackers {
73 sources.push(SourceTrackerCheckpoint {
74 source_id: *source,
75 tracker: tracker.snapshot(),
76 });
77 }
78 sources.sort_by_key(|s| s.source_id);
79 let mut uids = Vec::new();
80 for ((source, local), uid) in &self.uids {
81 uids.push(UidMapEntry {
82 source_id: *source,
83 local_track_id: *local,
84 track_uid: uid.0,
85 });
86 }
87 uids.sort_by_key(|e| (e.source_id, e.local_track_id));
88 MultiSourceCheckpoint {
89 next_uid: self.next_uid,
90 sources,
91 uids,
92 }
93 }
94
95 pub fn restore(
101 config: ByteTrackConfig,
102 checkpoint: MultiSourceCheckpoint,
103 ) -> Result<Self, TrackError> {
104 let mut pool = Self::new(config)?;
105 pool.next_uid = checkpoint.next_uid.max(1);
106 for source in checkpoint.sources {
107 let tracker = ByteTracker::from_snapshot(config, source.tracker)?;
108 pool.trackers.insert(source.source_id, tracker);
109 }
110 for entry in checkpoint.uids {
111 pool.uids.insert(
112 (entry.source_id, entry.local_track_id),
113 TrackUid(entry.track_uid),
114 );
115 pool.next_uid = pool.next_uid.max(entry.track_uid.saturating_add(1));
116 }
117 Ok(pool)
118 }
119
120 pub fn update(
126 &mut self,
127 source_id: SourceId,
128 detections: &[Detection],
129 ) -> Result<Vec<TrackedDetection>, TrackError> {
130 if !self.trackers.contains_key(&source_id.0) {
131 let tracker = ByteTracker::new(self.config)?;
132 self.trackers.insert(source_id.0, tracker);
133 }
134 let tracker = self
135 .trackers
136 .get_mut(&source_id.0)
137 .ok_or(TrackError::InvalidConfig)?;
138 let tracked = tracker.update(detections)?;
139 let mut out = Vec::with_capacity(tracked.len());
140 for detection in tracked {
141 let Some(local) = detection.track_id() else {
142 continue;
143 };
144 let key = TrackKey::new(source_id, local);
145 let uid = *self.uids.entry((source_id.0, local.0)).or_insert_with(|| {
146 let uid = TrackUid(self.next_uid);
147 self.next_uid = self.next_uid.saturating_add(1);
148 uid
149 });
150 out.push(TrackedDetection {
151 detection,
152 track_key: key,
153 track_uid: uid,
154 });
155 }
156 Ok(out)
157 }
158
159 #[must_use]
161 pub fn uid_of(&self, key: TrackKey) -> Option<TrackUid> {
162 self.uids
163 .get(&(key.source_id.0, key.local_track_id.0))
164 .copied()
165 }
166
167 #[must_use]
169 pub fn source_count(&self) -> usize {
170 self.trackers.len()
171 }
172
173 pub fn reset_source(&mut self, source_id: SourceId) {
177 self.trackers.remove(&source_id.0);
178 self.uids.retain(|(sid, _), _| *sid != source_id.0);
179 }
180
181 pub fn remove_source(&mut self, source_id: SourceId) {
183 self.reset_source(source_id);
184 }
185
186 #[must_use]
188 pub fn has_source(&self, source_id: SourceId) -> bool {
189 self.trackers.contains_key(&source_id.0)
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196 use crate::ByteTrackConfig;
197 use sightloom_core::{Detection, Rect, SourceId};
198
199 fn det(left: f32, top: f32, right: f32, bottom: f32) -> Detection {
200 Detection::new(
201 Rect::new(left, top, right, bottom).unwrap(),
202 0.9,
203 None,
204 None,
205 )
206 .unwrap()
207 }
208
209 #[test]
210 fn reset_source_clears_motion_but_keeps_uid_counter() {
211 let cfg = ByteTrackConfig::default();
212 let mut pool = MultiSourceTracker::new(cfg).unwrap();
213 let d = det(0.0, 0.0, 10.0, 10.0);
214 let _ = pool.update(SourceId(1), &[d]).unwrap();
215 assert!(pool.has_source(SourceId(1)));
216 let next_before = pool.next_uid();
217 pool.reset_source(SourceId(1));
218 assert!(!pool.has_source(SourceId(1)));
219 assert_eq!(pool.next_uid(), next_before);
220 }
221
222 #[test]
223 fn distinct_uids_for_same_local_id_across_sources() {
224 let mut pool = MultiSourceTracker::new(ByteTrackConfig {
225 track_high_thresh: 0.5,
226 track_activation_thresh: 0.5,
227 track_low_thresh: 0.1,
228 match_thresh: 0.3,
229 max_time_lost: 30,
230 class_aware: false,
231 })
232 .unwrap();
233 let a = pool
234 .update(SourceId(1), &[det(0.0, 0.0, 10.0, 20.0)])
235 .unwrap();
236 let b = pool
237 .update(SourceId(2), &[det(100.0, 0.0, 110.0, 20.0)])
238 .unwrap();
239 assert_eq!(a[0].track_key.local_track_id.0, 1);
240 assert_eq!(b[0].track_key.local_track_id.0, 1);
241 assert_ne!(a[0].track_uid, b[0].track_uid);
242 assert_eq!(pool.source_count(), 2);
243 }
244}
245
246#[derive(Clone, Debug, PartialEq)]
248pub struct MultiSourceCheckpoint {
249 pub next_uid: u64,
251 pub sources: Vec<SourceTrackerCheckpoint>,
253 pub uids: Vec<UidMapEntry>,
255}
256
257#[derive(Clone, Debug, PartialEq)]
259pub struct SourceTrackerCheckpoint {
260 pub source_id: u32,
262 pub tracker: TrackerSnapshot,
264}
265
266#[derive(Clone, Debug, PartialEq)]
268pub struct UidMapEntry {
269 pub source_id: u32,
271 pub local_track_id: u32,
273 pub track_uid: u64,
275}