Skip to main content

spatialrust_web/
camera_tracking.rs

1//! Bounded image-space background flow; not metric camera pose or SLAM.
2
3use serde::Serialize;
4use spatialrust_image::Image;
5use spatialrust_math::Vec2;
6use spatialrust_vision::{
7    detect_fast, select_keypoints_grid, track_points_forward_backward, FastOptions,
8    GridSelectionOptions, LucasKanadeOptions, RobustTrackOptions,
9};
10
11use crate::{WebError, WebResult};
12
13const MAX_AXIS: usize = 320;
14const MAX_POINTS: usize = 80;
15const PATCH_MARGIN: usize = 22;
16
17#[derive(Default)]
18enum MaskSupport {
19    #[default]
20    Empty,
21    Full,
22    Prefix {
23        stride: usize,
24        sums: Vec<u32>,
25    },
26}
27
28impl MaskSupport {
29    // Dimensions and binary labels are validated before construction. With at
30    // most 320*320 pixels, both prefix entries and query sums fit in u32.
31    fn from_validated(mask: &[u8], width: usize, height: usize, person_pixels: usize) -> Self {
32        if person_pixels == 0 {
33            return Self::Empty;
34        }
35        if person_pixels == width * height {
36            return Self::Full;
37        }
38        let stride = width + 1;
39        let mut sums = vec![0; stride * (height + 1)];
40        for row in 0..height {
41            let mut row_sum = 0;
42            for column in 0..width {
43                row_sum += u32::from(mask[row * width + column]);
44                sums[(row + 1) * stride + column + 1] = sums[row * stride + column + 1] + row_sum;
45            }
46        }
47        Self::Prefix { stride, sums }
48    }
49}
50
51/// Whether a frame pair provides usable image-space motion.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
53#[serde(rename_all = "snake_case")]
54pub enum CameraTrackingStatus {
55    /// First frame supplies features but no displacement.
56    Warming,
57    /// At least eight background tracks survived consistency checks.
58    Tracking,
59    /// Insufficient texture, visible background, or consistent tracks.
60    Lost,
61    /// A gap over 500ms starts a new frame pair.
62    Reseeded,
63}
64
65/// One forward/backward-consistent background track, in processing pixels.
66#[derive(Clone, Debug, PartialEq, Serialize)]
67pub struct CameraTrack {
68    /// Previous-frame pixel coordinate.
69    pub from: [f64; 2],
70    /// Current-frame pixel coordinate.
71    pub to: [f64; 2],
72}
73
74/// Bounded visualization report; contains no image bytes or metric pose.
75#[derive(Clone, Debug, PartialEq, Serialize)]
76pub struct CameraTrackReport {
77    /// Report schema version.
78    pub schema: u8,
79    /// Processing width.
80    pub width: usize,
81    /// Processing height.
82    pub height: usize,
83    /// Caller-supplied monotonic timestamp in milliseconds.
84    pub timestamp_ms: f64,
85    /// Current tracking state.
86    pub status: CameraTrackingStatus,
87    /// Component-wise median background displacement, absent when unqualified.
88    pub background_flow_px: Option<[f64; 2]>,
89    /// At most 80 accepted tracks.
90    pub tracks: Vec<CameraTrack>,
91    /// Features selected for the next frame pair.
92    pub seeded_features: usize,
93    /// Fraction of current pixels explicitly marked as person.
94    pub person_fraction: f64,
95}
96
97/// Small owned frame-pair tracker for an opt-in camera playground.
98///
99/// Reuses FAST, grid selection and forward/backward LK. It retains one previous
100/// gray frame and owned mask support; `track_gray_copy` retains no caller storage.
101/// This estimates 2D background flow, not camera translation, distance or 6DoF.
102pub struct CameraTracker {
103    width: usize,
104    height: usize,
105    previous: Option<Image<u8, 1>>,
106    previous_mask: MaskSupport,
107    points: Vec<Vec2<f64>>,
108    timestamp: Option<f64>,
109}
110
111impl CameraTracker {
112    /// Creates a tracker bounded to 64..=320 pixels on each axis.
113    pub fn try_new(width: usize, height: usize) -> WebResult<Self> {
114        if !(64..=MAX_AXIS).contains(&width) || !(64..=MAX_AXIS).contains(&height) {
115            return Err(invalid("camera frame axes must be in 64..=320"));
116        }
117        Ok(Self {
118            width,
119            height,
120            previous: None,
121            previous_mask: MaskSupport::Empty,
122            points: Vec::new(),
123            timestamp: None,
124        })
125    }
126
127    /// Returns the exact accepted gray/mask shape.
128    pub fn dimensions(&self) -> [usize; 2] {
129        [self.width, self.height]
130    }
131
132    /// Drops retained pixels, mask, features and clock state.
133    pub fn reset(&mut self) {
134        self.previous = None;
135        self.previous_mask = MaskSupport::Empty;
136        self.points.clear();
137        self.timestamp = None;
138    }
139
140    /// Copies a packed gray frame and derives owned binary-mask support.
141    ///
142    /// An empty mask disables exclusion; otherwise `1` marks person and `0`
143    /// background at the exact frame resolution. Both endpoints and their
144    /// 22-pixel neighborhoods must be background. Invalid shape, labels or
145    /// non-monotonic/non-finite timestamps reject before retained state changes.
146    pub fn track_gray_copy(
147        &mut self,
148        gray: &[u8],
149        mask: &[u8],
150        timestamp_ms: f64,
151    ) -> WebResult<CameraTrackReport> {
152        let pixels = self.width * self.height;
153        if gray.len() != pixels || (!mask.is_empty() && mask.len() != pixels) {
154            return Err(invalid("gray/mask lengths must match processing dimensions"));
155        }
156        let mut person_pixels = 0;
157        for &value in mask {
158            if value > 1 {
159                return Err(invalid("person mask must contain only 0 or 1"));
160            }
161            person_pixels += usize::from(value);
162        }
163        if !timestamp_ms.is_finite()
164            || timestamp_ms < 0.
165            || self.timestamp.is_some_and(|old| timestamp_ms <= old)
166        {
167            return Err(invalid(
168                "frame timestamps must be finite, non-negative and strictly increasing",
169            ));
170        }
171        let current_mask =
172            MaskSupport::from_validated(mask, self.width, self.height, person_pixels);
173        let current = Image::try_new(self.width, self.height, gray.to_vec()).map_err(invalid)?;
174        let gap = self.timestamp.is_some_and(|old| timestamp_ms - old > 500.);
175        let mut tracks = Vec::with_capacity(MAX_POINTS);
176        if let Some(previous) = self.previous.as_ref().filter(|_| !gap && !self.points.is_empty()) {
177            let options = RobustTrackOptions {
178                lucas_kanade: LucasKanadeOptions {
179                    window_radius: 5,
180                    pyramid_levels: 3,
181                    max_iterations: 30,
182                    epsilon: 0.001,
183                    min_eigenvalue: 1e-4,
184                },
185                max_forward_backward_error: 1.,
186            };
187            let result = track_points_forward_backward(
188                previous.view(),
189                current.view(),
190                &self.points,
191                options,
192            )
193            .map_err(invalid)?;
194            for (i, from) in self.points.iter().enumerate() {
195                let to = result.next_points()[i];
196                if result.status()[i]
197                    && self.background(&self.previous_mask, from.x, from.y)
198                    && self.background(&current_mask, to.x, to.y)
199                {
200                    tracks.push(CameraTrack { from: [from.x, from.y], to: [to.x, to.y] });
201                }
202            }
203        }
204        let candidates =
205            detect_fast(current.view(), FastOptions { threshold: 12, nonmax_suppression: true })
206                .map_err(invalid)?;
207        let candidates: Vec<_> = candidates
208            .into_iter()
209            .filter(|p| self.background(&current_mask, f64::from(p.x()), f64::from(p.y())))
210            .collect();
211        let candidates = select_keypoints_grid(
212            &candidates,
213            self.width,
214            self.height,
215            GridSelectionOptions { cell_width: 24, cell_height: 24, max_per_cell: 2 },
216        )
217        .map_err(invalid)?;
218        let next_points: Vec<_> = candidates
219            .into_iter()
220            .take(MAX_POINTS)
221            .map(|p| Vec2 { x: f64::from(p.x()), y: f64::from(p.y()) })
222            .collect();
223        let status = if self.previous.is_none() {
224            CameraTrackingStatus::Warming
225        } else if gap {
226            CameraTrackingStatus::Reseeded
227        } else if tracks.len() >= 8 {
228            CameraTrackingStatus::Tracking
229        } else {
230            CameraTrackingStatus::Lost
231        };
232        let background_flow_px = if status == CameraTrackingStatus::Tracking {
233            Some(std::array::from_fn(|axis| {
234                let mut values: Vec<_> = tracks.iter().map(|p| p.to[axis] - p.from[axis]).collect();
235                values.sort_by(f64::total_cmp);
236                let middle = values.len() / 2;
237                if values.len() % 2 == 0 {
238                    (values[middle - 1] + values[middle]) * 0.5
239                } else {
240                    values[middle]
241                }
242            }))
243        } else {
244            None
245        };
246        let report = CameraTrackReport {
247            schema: 1,
248            width: self.width,
249            height: self.height,
250            timestamp_ms,
251            status,
252            background_flow_px,
253            tracks,
254            seeded_features: next_points.len(),
255            person_fraction: person_pixels as f64 / pixels as f64,
256        };
257        self.previous = Some(current);
258        self.previous_mask = current_mask;
259        self.points = next_points;
260        self.timestamp = Some(timestamp_ms);
261        Ok(report)
262    }
263
264    fn background(&self, mask: &MaskSupport, x: f64, y: f64) -> bool {
265        let margin = PATCH_MARGIN as f64;
266        if !x.is_finite()
267            || !y.is_finite()
268            || x < margin
269            || y < margin
270            || x >= (self.width - PATCH_MARGIN) as f64
271            || y >= (self.height - PATCH_MARGIN) as f64
272        {
273            return false;
274        }
275        match mask {
276            MaskSupport::Empty => true,
277            MaskSupport::Full => false,
278            MaskSupport::Prefix { stride, sums } => {
279                let (x, y) = (x as usize, y as usize);
280                let (left, right) = (x - PATCH_MARGIN, x + PATCH_MARGIN + 1);
281                let (top, bottom) = (y - PATCH_MARGIN, y + PATCH_MARGIN + 1);
282                // Equal diagonals mean no person pixel in the inclusive square.
283                // Addition avoids unsigned underflow in a subtraction chain.
284                sums[bottom * stride + right] + sums[top * stride + left]
285                    == sums[top * stride + right] + sums[bottom * stride + left]
286            }
287        }
288    }
289}
290
291fn invalid(error: impl std::fmt::Display) -> WebError {
292    WebError::InvalidState(error.to_string())
293}
294
295#[cfg(test)]
296#[path = "camera_tracking_tests.rs"]
297mod tests;