viva-gige 0.2.3

GigE Vision transport: GVCP discovery, GenCP over GVCP, and GVSP
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
//! Streaming statistics helpers.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

const EWMA_ALPHA: f64 = 0.2;

/// Immutable view of streaming statistics suitable for UI overlays.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StreamStats {
    pub frames: u64,
    pub bytes: u64,
    pub drops: u64,
    pub resends: u64,
    pub last_frame_dt: Duration,
    pub avg_fps: f64,
    pub avg_mbps: f64,
    pub avg_latency_ms: Option<f64>,
    pub packets: u64,
    pub resend_ranges: u64,
    pub backpressure_drops: u64,
    pub late_frames: u64,
    pub pool_exhaustions: u64,
    pub elapsed: Duration,
    pub packets_per_second: f64,
}

impl Default for StreamStats {
    fn default() -> Self {
        StreamStats {
            frames: 0,
            bytes: 0,
            drops: 0,
            resends: 0,
            last_frame_dt: Duration::ZERO,
            avg_fps: 0.0,
            avg_mbps: 0.0,
            avg_latency_ms: None,
            packets: 0,
            resend_ranges: 0,
            backpressure_drops: 0,
            late_frames: 0,
            pool_exhaustions: 0,
            elapsed: Duration::ZERO,
            packets_per_second: 0.0,
        }
    }
}

#[derive(Debug)]
struct StatsState {
    frames: u64,
    bytes: u64,
    packets: u64,
    resends: u64,
    resend_ranges: u64,
    drops: u64,
    backpressure_drops: u64,
    late_frames: u64,
    pool_exhaustions: u64,
    last_frame_dt: Duration,
    avg_fps: f64,
    avg_mbps: f64,
    avg_latency_ms: Option<f64>,
    last_frame_instant: Option<Instant>,
    start: Instant,
}

impl StatsState {
    fn new() -> Self {
        Self {
            frames: 0,
            bytes: 0,
            packets: 0,
            resends: 0,
            resend_ranges: 0,
            drops: 0,
            backpressure_drops: 0,
            late_frames: 0,
            pool_exhaustions: 0,
            last_frame_dt: Duration::ZERO,
            avg_fps: 0.0,
            avg_mbps: 0.0,
            avg_latency_ms: None,
            last_frame_instant: None,
            start: Instant::now(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct StreamStatsAccumulator {
    inner: Arc<StatsInner>,
}

#[derive(Debug)]
struct StatsInner {
    state: Mutex<StatsState>,
}

impl StreamStatsAccumulator {
    /// Create a new statistics accumulator.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(StatsInner {
                state: Mutex::new(StatsState::new()),
            }),
        }
    }

    /// Record a received packet.
    pub fn record_packet(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.packets += 1;
    }

    /// Record a resend request.
    pub fn record_resend(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.resends += 1;
    }

    /// Record the number of packet ranges covered by a resend request.
    pub fn record_resend_ranges(&self, ranges: u64) {
        if ranges == 0 {
            return;
        }
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.resend_ranges += ranges;
    }

    /// Record a dropped frame event.
    pub fn record_drop(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.drops += 1;
    }

    /// Record a drop caused by application backpressure.
    pub fn record_backpressure_drop(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.backpressure_drops += 1;
    }

    /// Record a frame that missed its presentation deadline.
    pub fn record_late_frame(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.late_frames += 1;
    }

    /// Record an exhausted frame buffer pool event.
    pub fn record_pool_exhaustion(&self) {
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.pool_exhaustions += 1;
    }

    /// Update metrics for a fully received frame.
    pub fn record_frame(&self, bytes: usize, latency: Option<Duration>) {
        let now = Instant::now();
        let mut state = self.inner.state.lock().expect("stats mutex poisoned");
        state.frames += 1;
        state.bytes += bytes as u64;

        if let Some(prev) = state.last_frame_instant.replace(now) {
            let dt = now.saturating_duration_since(prev);
            if dt > Duration::ZERO {
                state.last_frame_dt = dt;
                let fps = 1.0 / dt.as_secs_f64();
                state.avg_fps = if state.avg_fps == 0.0 {
                    fps
                } else {
                    state.avg_fps + EWMA_ALPHA * (fps - state.avg_fps)
                };
                let mbps = (bytes as f64 * 8.0) / 1_000_000.0 / dt.as_secs_f64();
                state.avg_mbps = if state.avg_mbps == 0.0 {
                    mbps
                } else {
                    state.avg_mbps + EWMA_ALPHA * (mbps - state.avg_mbps)
                };
            }
        } else {
            state.last_frame_dt = Duration::ZERO;
        }

        if let Some(latency) = latency {
            let ms = latency.as_secs_f64() * 1_000.0;
            state.avg_latency_ms = Some(match state.avg_latency_ms {
                Some(prev) => prev + EWMA_ALPHA * (ms - prev),
                None => ms,
            });
        }
    }

    /// Produce a snapshot of the accumulated statistics.
    pub fn snapshot(&self) -> StreamStats {
        let state = self.inner.state.lock().expect("stats mutex poisoned");
        let elapsed = state.start.elapsed();
        let packets_per_second = if elapsed > Duration::ZERO {
            state.packets as f64 / elapsed.as_secs_f64()
        } else {
            0.0
        };

        StreamStats {
            frames: state.frames,
            bytes: state.bytes,
            drops: state.drops + state.backpressure_drops,
            resends: state.resends,
            last_frame_dt: state.last_frame_dt,
            avg_fps: state.avg_fps,
            avg_mbps: state.avg_mbps,
            avg_latency_ms: state.avg_latency_ms,
            packets: state.packets,
            resend_ranges: state.resend_ranges,
            backpressure_drops: state.backpressure_drops,
            late_frames: state.late_frames,
            pool_exhaustions: state.pool_exhaustions,
            elapsed,
            packets_per_second,
        }
    }
}

impl Default for StreamStatsAccumulator {
    fn default() -> Self {
        Self::new()
    }
}

/// Event channel statistics.
#[derive(Debug)]
pub struct EventStats {
    received: AtomicU64,
    malformed: AtomicU64,
    filtered: AtomicU64,
    start: Instant,
}

impl EventStats {
    /// Create a new accumulator for GVCP events.
    pub fn new() -> Self {
        Self {
            received: AtomicU64::new(0),
            malformed: AtomicU64::new(0),
            filtered: AtomicU64::new(0),
            start: Instant::now(),
        }
    }

    /// Record a successfully parsed event packet.
    pub fn record_event(&self) {
        self.received.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a dropped or malformed event packet.
    pub fn record_malformed(&self) {
        self.malformed.fetch_add(1, Ordering::Relaxed);
    }

    /// Record an event filtered out by the application.
    pub fn record_filtered(&self) {
        self.filtered.fetch_add(1, Ordering::Relaxed);
    }

    /// Snapshot the collected counters.
    pub fn snapshot(&self) -> EventSnapshot {
        EventSnapshot {
            received: self.received.load(Ordering::Relaxed),
            malformed: self.malformed.load(Ordering::Relaxed),
            filtered: self.filtered.load(Ordering::Relaxed),
            elapsed: self.start.elapsed().as_secs_f32(),
        }
    }
}

impl Default for EventStats {
    fn default() -> Self {
        Self::new()
    }
}

/// Immutable view of event statistics.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EventSnapshot {
    pub received: u64,
    pub malformed: u64,
    pub filtered: u64,
    pub elapsed: f32,
}

/// Action command dispatch statistics.
#[derive(Debug)]
pub struct ActionStats {
    sent: AtomicU64,
    acknowledgements: AtomicU64,
    failures: AtomicU64,
}

impl ActionStats {
    /// Create a new accumulator for action command metrics.
    pub fn new() -> Self {
        Self {
            sent: AtomicU64::new(0),
            acknowledgements: AtomicU64::new(0),
            failures: AtomicU64::new(0),
        }
    }

    /// Record a dispatched action.
    pub fn record_send(&self) {
        self.sent.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a received acknowledgement.
    pub fn record_ack(&self) {
        self.acknowledgements.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a failure while dispatching or waiting for acknowledgements.
    pub fn record_failure(&self) {
        self.failures.fetch_add(1, Ordering::Relaxed);
    }

    /// Snapshot the collected counters.
    pub fn snapshot(&self) -> ActionSnapshot {
        ActionSnapshot {
            sent: self.sent.load(Ordering::Relaxed),
            acknowledgements: self.acknowledgements.load(Ordering::Relaxed),
            failures: self.failures.load(Ordering::Relaxed),
        }
    }
}

impl Default for ActionStats {
    fn default() -> Self {
        Self::new()
    }
}

/// Immutable view of action statistics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActionSnapshot {
    pub sent: u64,
    pub acknowledgements: u64,
    pub failures: u64,
}

/// Timestamp synchronisation statistics.
#[derive(Debug)]
pub struct TimeStats {
    samples: AtomicU64,
    latches: AtomicU64,
    resets: AtomicU64,
}

impl TimeStats {
    /// Create a new accumulator for timestamp operations.
    pub fn new() -> Self {
        Self {
            samples: AtomicU64::new(0),
            latches: AtomicU64::new(0),
            resets: AtomicU64::new(0),
        }
    }

    /// Record a calibration sample.
    pub fn record_sample(&self) {
        self.samples.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a timestamp latch request.
    pub fn record_latch(&self) {
        self.latches.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a timestamp reset operation.
    pub fn record_reset(&self) {
        self.resets.fetch_add(1, Ordering::Relaxed);
    }

    /// Snapshot the current counters.
    pub fn snapshot(&self) -> TimeSnapshot {
        TimeSnapshot {
            samples: self.samples.load(Ordering::Relaxed),
            latches: self.latches.load(Ordering::Relaxed),
            resets: self.resets.load(Ordering::Relaxed),
        }
    }
}

impl Default for TimeStats {
    fn default() -> Self {
        Self::new()
    }
}

/// Immutable view of timestamp statistics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeSnapshot {
    pub samples: u64,
    pub latches: u64,
    pub resets: u64,
}