nv-view 0.1.0

PTZ/view-state, camera motion modeling, epoch policy, and context validity for the NextVision runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Epoch policy trait and default implementation.

use nv_core::{AffineTransform2D, Duration};

use crate::camera_motion::CameraMotionState;
use crate::provider::MotionReport;
use crate::validity::DegradationReason;
use crate::view_state::ViewState;

/// Decision returned by an [`EpochPolicy`] when camera motion is detected.
#[derive(Clone, Debug)]
pub enum EpochDecision {
    /// No temporal state change. View is continuous despite motion.
    Continue,

    /// Degrade context validity but keep the current epoch.
    Degrade { reason: DegradationReason },

    /// Degrade, but also apply a compensation transform to existing
    /// track positions so they align with the new view.
    Compensate {
        reason: DegradationReason,
        transform: AffineTransform2D,
    },

    /// Full segmentation: increment epoch, close trajectory segments,
    /// notify stages.
    Segment,
}

/// Context passed to [`EpochPolicy::decide`].
pub struct EpochPolicyContext<'a> {
    /// The view state from the previous frame.
    pub previous_view: &'a ViewState,
    /// The motion report for the current frame.
    pub current_report: &'a MotionReport,
    /// The computed motion state for the current frame.
    pub motion_state: CameraMotionState,
    /// How long the camera has been in the current motion state.
    pub state_duration: Duration,
}

/// User-implementable trait: controls the response to detected camera motion.
///
/// The library ships [`DefaultEpochPolicy`] for common threshold-based decisions.
/// Users with complex PTZ deployments can implement custom policies.
pub trait EpochPolicy: Send + Sync + 'static {
    /// Decide what to do in response to detected camera motion.
    fn decide(&self, ctx: &EpochPolicyContext<'_>) -> EpochDecision;
}

/// Default epoch policy based on configurable thresholds.
///
/// Covers the common case: large PTZ jumps → segment, small motions → degrade,
/// high-confidence transforms → compensate.
#[derive(Debug, Clone)]
pub struct DefaultEpochPolicy {
    /// Pan/tilt delta (degrees) above which a PTZ move triggers `Segment`.
    /// Below this, triggers `Degrade`. Default: `15.0`.
    pub segment_angle_threshold: f32,

    /// Zoom ratio change above which a zoom move triggers `Segment`.
    /// Default: `0.3`.
    pub segment_zoom_threshold: f32,

    /// Inferred-motion displacement (normalized coords) above which
    /// triggers `Segment`. Default: `0.25`.
    pub segment_displacement_threshold: f32,

    /// Minimum confidence for a `Compensate` decision (instead of `Segment`)
    /// when a transform is available. Default: `0.8`.
    pub compensate_min_confidence: f32,

    /// If `true`, small motions below segment thresholds produce `Degrade`
    /// instead of `Continue`. Default: `true`.
    pub degrade_on_small_motion: bool,

    /// Minimum PTZ telemetry delta (degrees for pan/tilt, ratio for zoom)
    /// below which changes are treated as sensor noise and ignored.
    /// Prevents floating-point jitter from triggering spurious `Degrade`
    /// events when the camera is at rest. Default: `0.01`.
    pub ptz_deadband: f32,
}

impl Default for DefaultEpochPolicy {
    fn default() -> Self {
        Self {
            segment_angle_threshold: 15.0,
            segment_zoom_threshold: 0.3,
            segment_displacement_threshold: 0.25,
            compensate_min_confidence: 0.8,
            degrade_on_small_motion: true,
            ptz_deadband: 0.01,
        }
    }
}

impl EpochPolicy for DefaultEpochPolicy {
    fn decide(&self, ctx: &EpochPolicyContext<'_>) -> EpochDecision {
        // A preset recall is always a full discontinuity.
        for event in &ctx.current_report.ptz_events {
            if matches!(event, crate::ptz::PtzEvent::PresetRecall { .. }) {
                return EpochDecision::Segment;
            }
        }

        // Check PTZ telemetry for large moves.
        if let (Some(prev_ptz), Some(curr_ptz)) = (
            ctx.previous_view.ptz.as_ref(),
            ctx.current_report.ptz.as_ref(),
        ) {
            let pan_delta = angular_delta(curr_ptz.pan, prev_ptz.pan);
            let tilt_delta = angular_delta(curr_ptz.tilt, prev_ptz.tilt);
            let zoom_delta = (curr_ptz.zoom - prev_ptz.zoom).abs();

            if pan_delta > self.segment_angle_threshold
                || tilt_delta > self.segment_angle_threshold
                || zoom_delta > self.segment_zoom_threshold
            {
                // Check if compensation is possible.
                if let Some(ref transform) = ctx.current_report.frame_transform
                    && transform.confidence >= self.compensate_min_confidence
                {
                    return EpochDecision::Compensate {
                        reason: DegradationReason::PtzMoving,
                        transform: transform.transform,
                    };
                }
                return EpochDecision::Segment;
            }

            if self.degrade_on_small_motion
                && (pan_delta > self.ptz_deadband
                    || tilt_delta > self.ptz_deadband
                    || zoom_delta > self.ptz_deadband)
            {
                return EpochDecision::Degrade {
                    reason: DegradationReason::PtzMoving,
                };
            }
        }

        // Check inferred displacement.
        if let CameraMotionState::Moving {
            displacement: Some(disp),
            ..
        } = &ctx.motion_state
        {
            if *disp > self.segment_displacement_threshold {
                if let Some(ref transform) = ctx.current_report.frame_transform
                    && transform.confidence >= self.compensate_min_confidence
                {
                    return EpochDecision::Compensate {
                        reason: DegradationReason::LargeJump,
                        transform: transform.transform,
                    };
                }
                return EpochDecision::Segment;
            }
            if self.degrade_on_small_motion && *disp > 0.0 {
                return EpochDecision::Degrade {
                    reason: DegradationReason::InferredMotionLowConfidence,
                };
            }
        }

        EpochDecision::Continue
    }
}

/// Compute the shortest angular delta between two angles in degrees,
/// correctly handling wraparound at the 0°/360° boundary.
fn angular_delta(a: f32, b: f32) -> f32 {
    let raw = (a - b).abs();
    raw.min(360.0 - raw)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ptz::{PtzEvent, PtzTelemetry};
    use crate::transform::{GlobalTransformEstimate, TransformEstimationMethod};
    use crate::view_state::{ViewState, ViewVersion};
    use nv_core::MonotonicTs;

    fn stable_ctx<'a>(prev: &'a ViewState, report: &'a MotionReport) -> EpochPolicyContext<'a> {
        EpochPolicyContext {
            previous_view: prev,
            current_report: report,
            motion_state: CameraMotionState::Stable,
            state_duration: Duration::from_secs(10),
        }
    }

    fn moving_ctx<'a>(
        prev: &'a ViewState,
        report: &'a MotionReport,
        displacement: f32,
    ) -> EpochPolicyContext<'a> {
        EpochPolicyContext {
            previous_view: prev,
            current_report: report,
            motion_state: CameraMotionState::Moving {
                angular_velocity: None,
                displacement: Some(displacement),
            },
            state_duration: Duration::from_secs(1),
        }
    }

    // -- Continue --

    #[test]
    fn stable_camera_continues() {
        let policy = DefaultEpochPolicy::default();
        let prev = ViewState::fixed_initial();
        let report = MotionReport::default();
        let ctx = stable_ctx(&prev, &report);
        assert!(matches!(policy.decide(&ctx), EpochDecision::Continue));
    }

    // -- PTZ thresholds --

    #[test]
    fn large_ptz_pan_segments() {
        let policy = DefaultEpochPolicy::default();
        let mut prev = ViewState::observed_initial();
        prev.ptz = Some(PtzTelemetry {
            pan: 0.0,
            tilt: 0.0,
            zoom: 0.5,
            ts: MonotonicTs::from_nanos(0),
        });
        let report = MotionReport {
            ptz: Some(PtzTelemetry {
                pan: 20.0, // > 15.0 threshold
                tilt: 0.0,
                zoom: 0.5,
                ts: MonotonicTs::from_nanos(33_000_000),
            }),
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        assert!(matches!(policy.decide(&ctx), EpochDecision::Segment));
    }

    #[test]
    fn small_ptz_move_degrades() {
        let policy = DefaultEpochPolicy::default();
        let mut prev = ViewState::observed_initial();
        prev.ptz = Some(PtzTelemetry {
            pan: 0.0,
            tilt: 0.0,
            zoom: 0.5,
            ts: MonotonicTs::from_nanos(0),
        });
        let report = MotionReport {
            ptz: Some(PtzTelemetry {
                pan: 2.0, // < 15.0 threshold, > 0
                tilt: 0.0,
                zoom: 0.5,
                ts: MonotonicTs::from_nanos(33_000_000),
            }),
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        let d = policy.decide(&ctx);
        assert!(
            matches!(d, EpochDecision::Degrade { .. }),
            "small PTZ move should degrade, got: {d:?}"
        );
    }

    #[test]
    fn large_ptz_with_high_confidence_transform_compensates() {
        let policy = DefaultEpochPolicy::default();
        let mut prev = ViewState::observed_initial();
        prev.ptz = Some(PtzTelemetry {
            pan: 0.0,
            tilt: 0.0,
            zoom: 0.5,
            ts: MonotonicTs::from_nanos(0),
        });
        let report = MotionReport {
            ptz: Some(PtzTelemetry {
                pan: 20.0,
                tilt: 0.0,
                zoom: 0.5,
                ts: MonotonicTs::from_nanos(33_000_000),
            }),
            frame_transform: Some(GlobalTransformEstimate {
                transform: nv_core::AffineTransform2D::IDENTITY,
                confidence: 0.95, // > 0.8 threshold
                method: TransformEstimationMethod::FeatureMatching,
                computed_at: ViewVersion::INITIAL,
            }),
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        assert!(matches!(
            policy.decide(&ctx),
            EpochDecision::Compensate { .. }
        ));
    }

    // -- Inferred displacement thresholds --

    #[test]
    fn large_inferred_displacement_segments() {
        let policy = DefaultEpochPolicy::default();
        let prev = ViewState::observed_initial();
        let report = MotionReport::default();
        let ctx = moving_ctx(&prev, &report, 0.3); // > 0.25 threshold
        assert!(matches!(policy.decide(&ctx), EpochDecision::Segment));
    }

    #[test]
    fn small_inferred_displacement_degrades() {
        let policy = DefaultEpochPolicy::default();
        let prev = ViewState::observed_initial();
        let report = MotionReport::default();
        let ctx = moving_ctx(&prev, &report, 0.05); // > 0 but < 0.25
        let d = policy.decide(&ctx);
        assert!(
            matches!(d, EpochDecision::Degrade { .. }),
            "small displacement should degrade, got: {d:?}"
        );
    }

    // -- PTZ events --

    #[test]
    fn preset_recall_event_segments() {
        let policy = DefaultEpochPolicy::default();
        let prev = ViewState::observed_initial();
        let report = MotionReport {
            ptz_events: vec![PtzEvent::PresetRecall {
                preset_id: 3,
                ts: MonotonicTs::from_nanos(100_000),
            }],
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        assert!(
            matches!(policy.decide(&ctx), EpochDecision::Segment),
            "preset recall should force segment"
        );
    }

    #[test]
    fn move_start_event_alone_does_not_segment() {
        let policy = DefaultEpochPolicy::default();
        let prev = ViewState::observed_initial();
        let report = MotionReport {
            ptz_events: vec![PtzEvent::MoveStart {
                ts: MonotonicTs::from_nanos(100_000),
            }],
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        // MoveStart alone doesn't change telemetry or displacement,
        // so the policy falls through to Continue.
        assert!(matches!(policy.decide(&ctx), EpochDecision::Continue));
    }

    // -- Configuration --

    #[test]
    fn degrade_on_small_motion_can_be_disabled() {
        let policy = DefaultEpochPolicy {
            degrade_on_small_motion: false,
            ..DefaultEpochPolicy::default()
        };
        let prev = ViewState::observed_initial();
        let report = MotionReport::default();
        let ctx = moving_ctx(&prev, &report, 0.05);
        // With degrade disabled, small motion should continue.
        assert!(matches!(policy.decide(&ctx), EpochDecision::Continue));
    }

    #[test]
    fn ptz_jitter_within_deadband_continues() {
        let policy = DefaultEpochPolicy::default();
        let mut prev = ViewState::observed_initial();
        prev.ptz = Some(PtzTelemetry {
            pan: 10.0,
            tilt: 5.0,
            zoom: 0.5,
            ts: MonotonicTs::from_nanos(0),
        });
        let report = MotionReport {
            ptz: Some(PtzTelemetry {
                // Tiny jitter below the 0.01 deadband
                pan: 10.005,
                tilt: 5.003,
                zoom: 0.5002,
                ts: MonotonicTs::from_nanos(33_000_000),
            }),
            ..Default::default()
        };
        let ctx = stable_ctx(&prev, &report);
        assert!(
            matches!(policy.decide(&ctx), EpochDecision::Continue),
            "floating-point jitter within deadband should not degrade"
        );
    }
}