Skip to main content

viva_genicam/stream/
stats.rs

1//! Counters for one stream (SR-07), written by its receive engine: GVSP's,
2//! or a USB3 Vision stream's reader (API-11).
3
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::{Duration, Instant};
7
8const EWMA_ALPHA: f64 = 0.2;
9
10/// Snapshot of one stream's counters (backlog SR-07).
11///
12/// **USB3 Vision** streams fill the frame counters the same way, and of the
13/// packet counters: `packets_received` counts bulk transfers,
14/// `packets_ignored_malformed` the transfers that were not the leader,
15/// payload or trailer due, and `transfer_errors` the failed transfers the
16/// stream recovered from. The other packet and resend counters stay 0.
17///
18/// **Frames.** Every block the camera sends is counted exactly once, when its
19/// fate is decided, so that
20///
21/// ```text
22/// blocks sent = frames_complete + frames_incomplete + frames_missed
23///             + frames_backpressure + frames_unsupported
24/// ```
25///
26/// once nothing is in flight and the delivery queue is drained. A frame
27/// waiting in the queue is in none of them yet.
28///
29/// **Packets.** `packets_received` counts every datagram read from the socket;
30/// the other packet counters say what became of the ones that were not used.
31///
32/// **Resend.** Each packet asked for again counts once in `resend_requested`,
33/// however many requests it took, and then at most once more: in
34/// `resend_recovered` if it arrived, in `resend_unavailable` if the camera
35/// said it no longer has it. What is left was neither — lost again, or its
36/// frame closed first.
37#[derive(Debug, Clone, Copy, PartialEq, Default)]
38#[non_exhaustive]
39pub struct StreamStats {
40    /// Frames handed to the application with every packet present.
41    pub frames_complete: u64,
42    /// Frames closed without that: packets missing, no trailer, or an error
43    /// status from the device. Counted whether or not the stream delivers
44    /// incomplete frames.
45    pub frames_incomplete: u64,
46    /// Blocks never seen at all: gaps in the block-id sequence.
47    pub frames_missed: u64,
48    /// Frames assembled and then discarded because the application did not
49    /// take them before the delivery queue filled.
50    pub frames_backpressure: u64,
51    /// Blocks whose payload type the engine does not assemble.
52    pub frames_unsupported: u64,
53    /// Datagrams read from the socket.
54    pub packets_received: u64,
55    /// Packets received more than once.
56    pub packets_duplicate: u64,
57    /// Packets never received, of frames closed incomplete. A lower bound when
58    /// a trailer is missing, since the trailer is what says how many there were.
59    pub packets_missing: u64,
60    /// Datagrams that are not GVSP.
61    pub packets_ignored_malformed: u64,
62    /// Packets of a format or payload type the engine does not assemble.
63    pub packets_ignored_unsupported: u64,
64    /// Data packets beyond the end of the frame buffer.
65    pub packets_ignored_out_of_range: u64,
66    /// Packets for a block already closed or older than the ones in flight.
67    pub packets_ignored_late: u64,
68    /// Leader or data packets whose status reports an error.
69    pub packets_ignored_error_status: u64,
70    /// Datagrams from an address other than the camera's.
71    pub packets_ignored_foreign: u64,
72    /// Data packets, other than a block's last, whose length is not the
73    /// stride the packet size implies. They are not used: a frame that had
74    /// one closes incomplete.
75    pub packets_size_mismatch: u64,
76    /// Packets asked for again, each counted once however often it was asked.
77    pub resend_requested: u64,
78    /// Packets asked for again that then arrived.
79    pub resend_recovered: u64,
80    /// Packets asked for again that the camera answered it no longer has.
81    pub resend_unavailable: u64,
82    /// USB3 Vision: transfers that failed — a stall, a fault — and that the
83    /// stream recovered from by resetting its endpoint, at the cost of the
84    /// block in progress. 0 on GigE Vision.
85    pub transfer_errors: u64,
86    /// Payload bytes of complete frames handed to the application.
87    pub bytes: u64,
88    /// Time between the last two complete frames.
89    pub last_frame_dt: Duration,
90    /// Smoothed rate of complete frames.
91    pub avg_fps: f64,
92    /// Smoothed payload throughput of complete frames, in megabits a second.
93    pub avg_mbps: f64,
94    /// Smoothed delay from the device timestamp to delivery, when the stream
95    /// can map device time to host time.
96    pub avg_latency_ms: Option<f64>,
97    /// Time since the stream started.
98    pub elapsed: Duration,
99    /// Average datagram rate since the stream started.
100    pub packets_per_second: f64,
101}
102
103impl StreamStats {
104    /// Frames the application did not receive complete: incomplete, missed
105    /// and dropped to backpressure.
106    pub fn frames_lost(&self) -> u64 {
107        self.frames_incomplete + self.frames_missed + self.frames_backpressure
108    }
109
110    /// Packets received and not used, for any reason.
111    pub fn packets_ignored(&self) -> u64 {
112        self.packets_ignored_malformed
113            + self.packets_ignored_unsupported
114            + self.packets_ignored_out_of_range
115            + self.packets_ignored_late
116            + self.packets_ignored_error_status
117            + self.packets_ignored_foreign
118    }
119}
120
121/// Why a received packet was not used.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123#[non_exhaustive]
124pub(crate) enum IgnoredPacket {
125    /// Not a GVSP packet.
126    Malformed,
127    /// A packet format or payload type the engine does not assemble.
128    Unsupported,
129    /// A data packet beyond the end of the frame buffer.
130    OutOfRange,
131    /// For a block already closed, or older than the blocks in flight.
132    Late,
133    /// A leader or data packet whose status reports an error, or a resend
134    /// answer that carries no data.
135    ErrorStatus,
136    /// From an address other than the camera's.
137    Foreign,
138}
139
140#[derive(Debug)]
141struct Rates {
142    last_frame_dt: Duration,
143    avg_fps: f64,
144    avg_mbps: f64,
145    avg_latency_ms: Option<f64>,
146    last_frame_instant: Option<Instant>,
147}
148
149#[derive(Debug)]
150struct StatsInner {
151    start: Instant,
152    frames_complete: AtomicU64,
153    frames_incomplete: AtomicU64,
154    frames_missed: AtomicU64,
155    frames_backpressure: AtomicU64,
156    frames_unsupported: AtomicU64,
157    packets_received: AtomicU64,
158    packets_duplicate: AtomicU64,
159    packets_missing: AtomicU64,
160    ignored_malformed: AtomicU64,
161    ignored_unsupported: AtomicU64,
162    ignored_out_of_range: AtomicU64,
163    ignored_late: AtomicU64,
164    ignored_error_status: AtomicU64,
165    ignored_foreign: AtomicU64,
166    packets_size_mismatch: AtomicU64,
167    resend_requested: AtomicU64,
168    resend_recovered: AtomicU64,
169    resend_unavailable: AtomicU64,
170    transfer_errors: AtomicU64,
171    bytes: AtomicU64,
172    rates: Mutex<Rates>,
173}
174
175/// Shared, cloneable handle to one stream's counters.
176///
177/// The receive engine writes them, packet by packet, from its own thread; any
178/// clone can [`snapshot`](Self::snapshot) them, from any thread.
179#[derive(Debug, Clone)]
180pub struct StreamStatsAccumulator {
181    inner: Arc<StatsInner>,
182}
183
184fn add(counter: &AtomicU64, n: u64) {
185    counter.fetch_add(n, Ordering::Relaxed);
186}
187
188impl StreamStatsAccumulator {
189    /// Create a new statistics accumulator.
190    pub(crate) fn new() -> Self {
191        let zero = || AtomicU64::new(0);
192        Self {
193            inner: Arc::new(StatsInner {
194                start: Instant::now(),
195                frames_complete: zero(),
196                frames_incomplete: zero(),
197                frames_missed: zero(),
198                frames_backpressure: zero(),
199                frames_unsupported: zero(),
200                packets_received: zero(),
201                packets_duplicate: zero(),
202                packets_missing: zero(),
203                ignored_malformed: zero(),
204                ignored_unsupported: zero(),
205                ignored_out_of_range: zero(),
206                ignored_late: zero(),
207                ignored_error_status: zero(),
208                ignored_foreign: zero(),
209                packets_size_mismatch: zero(),
210                resend_requested: zero(),
211                resend_recovered: zero(),
212                resend_unavailable: zero(),
213                transfer_errors: zero(),
214                bytes: zero(),
215                rates: Mutex::new(Rates {
216                    last_frame_dt: Duration::ZERO,
217                    avg_fps: 0.0,
218                    avg_mbps: 0.0,
219                    avg_latency_ms: None,
220                    last_frame_instant: None,
221                }),
222            }),
223        }
224    }
225
226    /// A datagram was read from the socket.
227    pub(crate) fn record_packet_received(&self) {
228        add(&self.inner.packets_received, 1);
229    }
230
231    /// `count` transfers were read from a USB3 Vision stream.
232    #[cfg(feature = "u3v")]
233    pub(crate) fn record_packets_received(&self, count: u64) {
234        add(&self.inner.packets_received, count);
235    }
236
237    /// `count` transfers were neither the leader, payload nor trailer due.
238    #[cfg(feature = "u3v")]
239    pub(crate) fn record_malformed_packets(&self, count: u64) {
240        add(&self.inner.ignored_malformed, count);
241    }
242
243    /// `count` transfers failed and the stream recovered.
244    #[cfg(feature = "u3v")]
245    pub(crate) fn record_transfer_errors(&self, count: u64) {
246        add(&self.inner.transfer_errors, count);
247    }
248
249    /// A packet arrived that had already been received.
250    pub(crate) fn record_duplicate_packet(&self) {
251        add(&self.inner.packets_duplicate, 1);
252    }
253
254    /// A packet was received and not used.
255    pub(crate) fn record_ignored_packet(&self, reason: IgnoredPacket) {
256        let counter = match reason {
257            IgnoredPacket::Malformed => &self.inner.ignored_malformed,
258            IgnoredPacket::Unsupported => &self.inner.ignored_unsupported,
259            IgnoredPacket::OutOfRange => &self.inner.ignored_out_of_range,
260            IgnoredPacket::Late => &self.inner.ignored_late,
261            IgnoredPacket::ErrorStatus => &self.inner.ignored_error_status,
262            IgnoredPacket::Foreign => &self.inner.ignored_foreign,
263        };
264        add(counter, 1);
265    }
266
267    /// A data packet other than a block's last did not fill the stride.
268    pub(crate) fn record_size_mismatch(&self) {
269        add(&self.inner.packets_size_mismatch, 1);
270    }
271
272    /// `count` packets were asked for again for the first time.
273    pub(crate) fn record_resend_requested(&self, count: u64) {
274        add(&self.inner.resend_requested, count);
275    }
276
277    /// A packet asked for again arrived.
278    pub(crate) fn record_resend_recovered(&self) {
279        add(&self.inner.resend_recovered, 1);
280    }
281
282    /// The camera answered that it no longer has `count` packets asked for.
283    pub(crate) fn record_resend_unavailable(&self, count: u64) {
284        add(&self.inner.resend_unavailable, count);
285    }
286
287    /// A frame closed incomplete without `count` of its packets.
288    pub(crate) fn record_missing_packets(&self, count: u64) {
289        add(&self.inner.packets_missing, count);
290    }
291
292    /// A complete frame of `bytes`, finished arriving at `completed`, was
293    /// handed to the application. The rates count from `completed`, not from
294    /// the hand-over: frames held back behind an older one, or read late,
295    /// leave in a burst that says nothing about the camera's rate.
296    pub(crate) fn record_frame(&self, bytes: usize, latency: Option<Duration>, completed: Instant) {
297        add(&self.inner.frames_complete, 1);
298        add(&self.inner.bytes, bytes as u64);
299        let now = completed;
300        let mut rates = self.inner.rates.lock().expect("stats mutex poisoned");
301        if let Some(prev) = rates.last_frame_instant.replace(now) {
302            let dt = now.saturating_duration_since(prev);
303            if dt > Duration::ZERO {
304                rates.last_frame_dt = dt;
305                let fps = 1.0 / dt.as_secs_f64();
306                rates.avg_fps = if rates.avg_fps == 0.0 {
307                    fps
308                } else {
309                    rates.avg_fps + EWMA_ALPHA * (fps - rates.avg_fps)
310                };
311                let mbps = (bytes as f64 * 8.0) / 1_000_000.0 / dt.as_secs_f64();
312                rates.avg_mbps = if rates.avg_mbps == 0.0 {
313                    mbps
314                } else {
315                    rates.avg_mbps + EWMA_ALPHA * (mbps - rates.avg_mbps)
316                };
317            }
318        } else {
319            rates.last_frame_dt = Duration::ZERO;
320        }
321        if let Some(latency) = latency {
322            let ms = latency.as_secs_f64() * 1_000.0;
323            rates.avg_latency_ms = Some(match rates.avg_latency_ms {
324                Some(prev) => prev + EWMA_ALPHA * (ms - prev),
325                None => ms,
326            });
327        }
328    }
329
330    /// A frame closed without every packet, or with an error status.
331    pub(crate) fn record_incomplete_frame(&self) {
332        add(&self.inner.frames_incomplete, 1);
333    }
334
335    /// `count` block ids were skipped.
336    pub(crate) fn record_missed_frames(&self, count: u64) {
337        add(&self.inner.frames_missed, count);
338    }
339
340    /// An assembled frame was discarded because the delivery queue was full.
341    pub(crate) fn record_backpressure_drop(&self) {
342        add(&self.inner.frames_backpressure, 1);
343    }
344
345    /// A block arrived whose payload type the engine does not assemble.
346    pub(crate) fn record_unsupported_block(&self) {
347        add(&self.inner.frames_unsupported, 1);
348    }
349
350    /// Produce a snapshot of the accumulated statistics.
351    pub fn snapshot(&self) -> StreamStats {
352        let get = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
353        let inner = &*self.inner;
354        let elapsed = inner.start.elapsed();
355        let packets_received = get(&inner.packets_received);
356        let packets_per_second = if elapsed > Duration::ZERO {
357            packets_received as f64 / elapsed.as_secs_f64()
358        } else {
359            0.0
360        };
361        let rates = inner.rates.lock().expect("stats mutex poisoned");
362        StreamStats {
363            frames_complete: get(&inner.frames_complete),
364            frames_incomplete: get(&inner.frames_incomplete),
365            frames_missed: get(&inner.frames_missed),
366            frames_backpressure: get(&inner.frames_backpressure),
367            frames_unsupported: get(&inner.frames_unsupported),
368            packets_received,
369            packets_duplicate: get(&inner.packets_duplicate),
370            packets_missing: get(&inner.packets_missing),
371            packets_ignored_malformed: get(&inner.ignored_malformed),
372            packets_ignored_unsupported: get(&inner.ignored_unsupported),
373            packets_ignored_out_of_range: get(&inner.ignored_out_of_range),
374            packets_ignored_late: get(&inner.ignored_late),
375            packets_ignored_error_status: get(&inner.ignored_error_status),
376            packets_ignored_foreign: get(&inner.ignored_foreign),
377            packets_size_mismatch: get(&inner.packets_size_mismatch),
378            resend_requested: get(&inner.resend_requested),
379            resend_recovered: get(&inner.resend_recovered),
380            resend_unavailable: get(&inner.resend_unavailable),
381            transfer_errors: get(&inner.transfer_errors),
382            bytes: get(&inner.bytes),
383            last_frame_dt: rates.last_frame_dt,
384            avg_fps: rates.avg_fps,
385            avg_mbps: rates.avg_mbps,
386            avg_latency_ms: rates.avg_latency_ms,
387            elapsed,
388            packets_per_second,
389        }
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn counters_are_independent_and_sum_as_documented() {
399        let stats = StreamStatsAccumulator::new();
400        stats.record_frame(100, None, Instant::now());
401        stats.record_frame(100, None, Instant::now());
402        stats.record_incomplete_frame();
403        stats.record_missed_frames(3);
404        stats.record_backpressure_drop();
405        stats.record_ignored_packet(IgnoredPacket::Late);
406        stats.record_ignored_packet(IgnoredPacket::Malformed);
407        stats.record_ignored_packet(IgnoredPacket::Foreign);
408        stats.record_duplicate_packet();
409        stats.record_resend_requested(3);
410        stats.record_resend_recovered();
411        stats.record_resend_unavailable(1);
412        let snap = stats.clone().snapshot();
413        assert_eq!(snap.frames_complete, 2);
414        assert_eq!(snap.bytes, 200);
415        assert_eq!(snap.frames_lost(), 1 + 3 + 1);
416        assert_eq!(snap.packets_ignored(), 3);
417        assert_eq!(snap.packets_ignored_foreign, 1);
418        assert_eq!(
419            (
420                snap.resend_requested,
421                snap.resend_recovered,
422                snap.resend_unavailable
423            ),
424            (3, 1, 1)
425        );
426        assert_eq!(snap.packets_duplicate, 1);
427        assert_eq!(snap.packets_ignored_late, 1);
428    }
429}