Skip to main content

sightloom_tracking/
multi_source.rs

1//! Per-source tracker pool with globally unique track uids.
2
3#[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/// One detection result annotated with multi-source identity keys.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct TrackedDetection {
18    /// Detection with local [`TrackId`] set by the per-source tracker.
19    pub detection: Detection,
20    /// Composite source-local key.
21    pub track_key: TrackKey,
22    /// Globally unique track uid for the session.
23    pub track_uid: TrackUid,
24}
25
26/// Multi-source tracker: one independent motion model per [`SourceId`].
27///
28/// Local track ids may collide across sources; [`TrackUid`] values do not.
29#[cfg(feature = "std")]
30#[derive(Clone, Debug)]
31pub struct MultiSourceTracker {
32    config: ByteTrackConfig,
33    trackers: HashMap<u32, ByteTracker>,
34    /// `(source_id, local_track_id) -> TrackUid`
35    uids: HashMap<(u32, u32), TrackUid>,
36    next_uid: u64,
37}
38
39#[cfg(feature = "std")]
40impl MultiSourceTracker {
41    /// Creates an empty multi-source tracker pool.
42    ///
43    /// # Errors
44    ///
45    /// Returns invalid config errors.
46    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    /// Tracker configuration shared by every source.
57    #[must_use]
58    pub const fn config(&self) -> ByteTrackConfig {
59        self.config
60    }
61
62    /// Next global track uid counter.
63    #[must_use]
64    pub const fn next_uid(&self) -> u64 {
65        self.next_uid
66    }
67
68    /// Snapshot of uid map and per-source trackers for checkpoints.
69    #[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    /// Restores multi-source state from a checkpoint.
96    ///
97    /// # Errors
98    ///
99    /// Propagates tracker restore errors.
100    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    /// Updates only the tracker for `source_id`.
121    ///
122    /// # Errors
123    ///
124    /// Propagates single-source tracker errors.
125    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    /// Looks up the global uid for a track key.
160    #[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    /// Number of independent source trackers currently allocated.
168    #[must_use]
169    pub fn source_count(&self) -> usize {
170        self.trackers.len()
171    }
172
173    /// Drops motion state for one source (local tracks + uid map entries).
174    ///
175    /// Global [`TrackUid`] counter is **not** rewound so historical uids stay unique.
176    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    /// Alias for [`Self::reset_source`] (host reconnect wording).
182    pub fn remove_source(&mut self, source_id: SourceId) {
183        self.reset_source(source_id);
184    }
185
186    /// True when a per-source tracker is currently allocated.
187    #[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/// Checkpoint payload for multi-source tracking.
247#[derive(Clone, Debug, PartialEq)]
248pub struct MultiSourceCheckpoint {
249    /// Next global uid.
250    pub next_uid: u64,
251    /// Per-source tracker snapshots.
252    pub sources: Vec<SourceTrackerCheckpoint>,
253    /// Composite key to uid map.
254    pub uids: Vec<UidMapEntry>,
255}
256
257/// One source tracker inside a multi-source checkpoint.
258#[derive(Clone, Debug, PartialEq)]
259pub struct SourceTrackerCheckpoint {
260    /// Source id.
261    pub source_id: u32,
262    /// Tracker snapshot.
263    pub tracker: TrackerSnapshot,
264}
265
266/// One uid map row.
267#[derive(Clone, Debug, PartialEq)]
268pub struct UidMapEntry {
269    /// Source id.
270    pub source_id: u32,
271    /// Local track id.
272    pub local_track_id: u32,
273    /// Global uid.
274    pub track_uid: u64,
275}