Skip to main content

viva_u3v/
event.rs

1//! USB3 Vision events: GenCP `EVENT_CMD` packets on the event endpoint
2//! (backlog TC-27 (4)).
3//!
4//! An event command is GenCP's (GenCP 1.3.1 §4.4.10, Table 17), framed as
5//! USB3 Vision frames every GenCP packet, little-endian:
6//!
7//! ```text
8//! [ "U3VE" ][ flags ][ 0x0C00 ][ length ][ request_id ][ event … ]
9//! event:    [ event_size ][ event_id ][ timestamp (ns) ][ data … ]
10//! ```
11//!
12//! With the device's MultiEvent mode on, one command carries several events,
13//! each `event_size` bytes; otherwise `event_size` is 0 and the one event
14//! fills the command. The `U3VE` prefix is Wireshark's (`packet-u3v.c`,
15//! `U3V_EVENT_PREFIX`); the event layout is GenCP's, and the Grasshopper3's
16//! XML addresses it on its event ports as GenCP lays it out: the event ID at
17//! 0x2, the timestamp at 0x4 and the frame ID, its data, at 0xC
18//! (`PGR_GS3_U3_23S6M.xml`). No camera has sent us one.
19
20use std::collections::VecDeque;
21use std::time::Duration;
22
23use bytes::Bytes;
24
25use crate::U3vError;
26use crate::usb::{BulkIn, GONE_GRACE, unless_gone};
27
28/// `U3VE` read as a little-endian `u32`: the prefix of an event command.
29const EVENT_PREFIX: u32 = 0x4556_3355;
30
31/// Prefix plus common command data.
32const HEADER_SIZE: usize = 12;
33
34/// `event_size`, `event_id` and the timestamp: what every event carries.
35const EVENT_HEADER_SIZE: usize = 12;
36
37/// GenCP's `EVENT_CMD`.
38const EVENT_CMD: u16 = viva_gencp::command_id::EVENT_CMD;
39
40/// Event commands queued on the endpoint.
41const EVENTS_IN_FLIGHT: usize = 4;
42
43/// Transfer errors in a row after which the event stream gives up.
44const MAX_CONSECUTIVE_FAILURES: u32 = 8;
45
46/// One event a USB3 Vision device sent.
47#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct U3vEvent {
50    /// The event's ID: what the XML's event port names in its `<EventID>`.
51    pub id: u16,
52    /// Device time of the event, in ns (GenCP 1.3.1 Table 17).
53    pub timestamp: u64,
54    /// The data after the event's 12-byte header.
55    pub data: Bytes,
56    /// The event as the device laid it out, from its `event_size` field on:
57    /// what the camera's event port addresses.
58    pub raw: Bytes,
59}
60
61/// The events in one event command.
62///
63/// A packet that is not an event command, or whose events do not tile its
64/// length, is an error; a command carrying no event is an empty list.
65pub fn parse_event_command(packet: &[u8]) -> Result<Vec<U3vEvent>, U3vError> {
66    let malformed = |problem| U3vError::Malformed {
67        packet: "event command",
68        problem,
69    };
70    let header = packet
71        .get(..HEADER_SIZE)
72        .ok_or(malformed("is shorter than its header"))?;
73    if u32::from_le_bytes(header[..4].try_into().unwrap()) != EVENT_PREFIX {
74        return Err(malformed("lacks the U3VE prefix"));
75    }
76    if u16::from_le_bytes([header[6], header[7]]) != EVENT_CMD {
77        return Err(malformed("is not an EVENT_CMD"));
78    }
79    let length = usize::from(u16::from_le_bytes([header[8], header[9]]));
80    let scd = packet
81        .get(HEADER_SIZE..HEADER_SIZE + length)
82        .ok_or(malformed("is shorter than its length field"))?;
83    let shared = Bytes::copy_from_slice(scd);
84
85    let mut events = Vec::new();
86    let mut offset = 0;
87    while offset < scd.len() {
88        let rest = &scd[offset..];
89        if rest.len() < EVENT_HEADER_SIZE {
90            return Err(malformed("ends inside an event header"));
91        }
92        let size = match usize::from(u16::from_le_bytes([rest[0], rest[1]])) {
93            // MultiEvent off: one event, the whole command.
94            0 => rest.len(),
95            size if size < EVENT_HEADER_SIZE => {
96                return Err(malformed("declares an event shorter than its header"));
97            }
98            size if size > rest.len() => {
99                return Err(malformed("declares an event longer than the command"));
100            }
101            size => size,
102        };
103        let raw = shared.slice(offset..offset + size);
104        events.push(U3vEvent {
105            id: u16::from_le_bytes([rest[2], rest[3]]),
106            timestamp: u64::from_le_bytes(rest[4..12].try_into().unwrap()),
107            data: raw.slice(EVENT_HEADER_SIZE..),
108            raw,
109        });
110        offset += size;
111    }
112    Ok(events)
113}
114
115/// The events a device sends, read from its event endpoint with a few event
116/// commands' transfers queued.
117pub struct U3vEventStream {
118    queue: Box<dyn BulkIn>,
119    transfer: usize,
120    events: VecDeque<U3vEvent>,
121    failures: u32,
122    skipped: u64,
123    warned_ack: bool,
124}
125
126impl U3vEventStream {
127    /// Events from `queue`, each command at most `max_transfer` bytes (the
128    /// EIRM's Maximum Event Transfer Length; 1024 when it says 0), every
129    /// transfer a whole number of `packet`-byte packets.
130    pub fn new(queue: Box<dyn BulkIn>, max_transfer: u32, packet: Option<usize>) -> Self {
131        let packet = packet.unwrap_or(1).max(1);
132        let max = match max_transfer {
133            0 => 1024,
134            bytes => bytes as usize,
135        };
136        Self {
137            queue,
138            transfer: max.div_ceil(packet) * packet,
139            events: VecDeque::new(),
140            failures: 0,
141            skipped: 0,
142            warned_ack: false,
143        }
144    }
145
146    /// Event transfers that did not parse as event commands, skipped.
147    pub fn skipped(&self) -> u64 {
148        self.skipped
149    }
150
151    /// The next event, or `Ok(None)` when none arrived within `idle`. A
152    /// failed transfer resets the endpoint and the stream goes on;
153    /// [`U3vError::Disconnected`], or transfers that keep failing, end it.
154    pub fn next_event_within(&mut self, idle: Duration) -> Result<Option<U3vEvent>, U3vError> {
155        loop {
156            if let Some(event) = self.events.pop_front() {
157                return Ok(Some(event));
158            }
159            while self.queue.pending() < EVENTS_IN_FLIGHT {
160                self.queue.submit(self.transfer);
161            }
162            let Some(completion) = self.queue.wait_next(idle) else {
163                return Ok(None);
164            };
165            match completion.status {
166                Ok(()) => self.take(&completion.data),
167                Err(U3vError::Disconnected) => return Err(U3vError::Disconnected),
168                // Any other failure — a transfer the host cancelled too,
169                // which the reader cancels only while recovering, below, and
170                // an unplug on macOS does (UV-03) — is counted, and the
171                // endpoint reset, as the stream does: cancellations that
172                // never stop end the reader rather than spin it (Codex review
173                // of #205).
174                Err(error) => {
175                    let error = unless_gone(error, || self.queue.is_present(), Duration::ZERO);
176                    if matches!(error, U3vError::Disconnected) {
177                        return Err(error);
178                    }
179                    self.failures += 1;
180                    tracing::warn!(%error, "an event transfer failed; resetting the endpoint");
181                    if self.failures > MAX_CONSECUTIVE_FAILURES {
182                        return Err(unless_gone(error, || self.queue.is_present(), GONE_GRACE));
183                    }
184                    self.queue.cancel_all();
185                    while self.queue.pending() > 0 && self.queue.wait_next(idle).is_some() {}
186                    self.queue
187                        .reset()
188                        .map_err(|e| unless_gone(e, || self.queue.is_present(), GONE_GRACE))?;
189                }
190            }
191        }
192    }
193
194    fn take(&mut self, packet: &[u8]) {
195        match parse_event_command(packet) {
196            Ok(events) => {
197                self.failures = 0;
198                // GenCP's RequestAck flag: the device wants an EVENT_ACK,
199                // which the event interface, an IN endpoint, cannot carry
200                // (backlog UV-06).
201                let flags = u16::from_le_bytes([packet[4], packet[5]]);
202                if flags & viva_gencp::ccd_flags::REQUEST_ACK != 0 && !self.warned_ack {
203                    self.warned_ack = true;
204                    tracing::warn!(
205                        "the camera asks for event acknowledges, which are not sent: \
206                         please report this camera (backlog UV-06)"
207                    );
208                }
209                self.events.extend(events);
210            }
211            Err(error) => {
212                self.skipped += 1;
213                tracing::debug!(%error, bytes = packet.len(), "skipping an event transfer");
214            }
215        }
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    /// An event command written out by hand from GenCP 1.3.1 Table 17.
224    fn command(flags: u16, scd: &[u8]) -> Vec<u8> {
225        let mut packet = b"U3VE".to_vec();
226        packet.extend_from_slice(&flags.to_le_bytes());
227        packet.extend_from_slice(&0x0C00u16.to_le_bytes());
228        packet.extend_from_slice(&(scd.len() as u16).to_le_bytes());
229        packet.extend_from_slice(&7u16.to_le_bytes());
230        packet.extend_from_slice(scd);
231        packet
232    }
233
234    #[test]
235    fn one_event_fills_a_command_without_multievent() {
236        #[rustfmt::skip]
237        let scd = [
238            0x00, 0x00,                                     // event_size 0
239            0x43, 0x9C,                                     // event_id 0x9C43
240            0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, // timestamp
241            0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // frame id 5
242        ];
243        let events = parse_event_command(&command(0, &scd)).unwrap();
244        assert_eq!(events.len(), 1);
245        let event = &events[0];
246        assert_eq!(event.id, 0x9C43);
247        assert_eq!(event.timestamp, 0x1122_3344_5566_7788);
248        assert_eq!(&event.data[..], &scd[12..]);
249        assert_eq!(&event.raw[..], &scd[..]);
250    }
251
252    #[test]
253    fn multievent_commands_carry_sized_events() {
254        let mut scd = Vec::new();
255        for (id, extra) in [(0x9001u16, 8usize), (0x9002, 0)] {
256            scd.extend_from_slice(&((12 + extra) as u16).to_le_bytes());
257            scd.extend_from_slice(&id.to_le_bytes());
258            scd.extend_from_slice(&u64::from(id).to_le_bytes());
259            scd.extend(std::iter::repeat_n(0xAB, extra));
260        }
261        let events = parse_event_command(&command(0, &scd)).unwrap();
262        assert_eq!(
263            events
264                .iter()
265                .map(|e| (e.id, e.data.len()))
266                .collect::<Vec<_>>(),
267            [(0x9001, 8), (0x9002, 0)]
268        );
269        assert_eq!(events[1].raw.len(), 12);
270    }
271
272    #[test]
273    fn malformed_commands_are_refused() {
274        assert!(parse_event_command(b"U3VE").is_err());
275        let mut wrong_prefix = command(0, &[0; 12]);
276        wrong_prefix[3] = b'C';
277        assert!(parse_event_command(&wrong_prefix).is_err());
278        let mut too_long = vec![0u8; 12];
279        too_long[0] = 40;
280        assert!(parse_event_command(&command(0, &too_long)).is_err());
281        let mut short_header = command(0, &[0; 12]);
282        short_header.truncate(20);
283        assert!(parse_event_command(&short_header).is_err());
284    }
285
286    /// UV-03 on macOS: an event transfer that fails with an unknown error on
287    /// a device the operating system no longer lists ends the event stream
288    /// with a disconnect; on a device still listed the stream goes on.
289    #[test]
290    fn an_unknown_failure_is_a_disconnect_only_once_the_device_is_unlisted() {
291        use crate::usb::{MockUsbTransfer, UsbTransfer};
292        use std::sync::Arc;
293        const EP: u8 = 0x83;
294        let not_responding = || U3vError::usb("unknown (error 0xe00002ed)");
295        let idle = Duration::from_millis(1);
296
297        let mock = Arc::new(MockUsbTransfer::new());
298        mock.set_present(Some(true));
299        mock.enqueue_error(EP, not_responding());
300        mock.enqueue_read(EP, command(0, &[0, 0, 0x01, 0x90, 1, 0, 0, 0, 0, 0, 0, 0]));
301        let mut events = U3vEventStream::new(mock.bulk_in(EP).unwrap(), 0, None);
302        let event = events.next_event_within(idle).unwrap().expect("an event");
303        assert_eq!(event.id, 0x9001);
304
305        mock.set_present(Some(false));
306        mock.enqueue_error(EP, not_responding());
307        let result = events.next_event_within(idle);
308        assert!(matches!(result, Err(U3vError::Disconnected)), "{result:?}");
309    }
310
311    /// Codex review of #205: a transfer the host cancelled, on a device still
312    /// listed, is a failure like any other — counted, and the endpoint reset —
313    /// so that cancellations that never stop end the reader instead of
314    /// spinning it. A good event in between starts the count again.
315    #[test]
316    fn transfers_the_host_keeps_cancelling_end_the_event_reader() {
317        use crate::usb::{MockUsbTransfer, UsbTransfer};
318        use std::sync::Arc;
319        const EP: u8 = 0x83;
320        let idle = Duration::from_millis(1);
321
322        let mock = Arc::new(MockUsbTransfer::new());
323        mock.set_present(Some(true));
324        mock.enqueue_error(EP, U3vError::Cancelled);
325        mock.enqueue_read(EP, command(0, &[0, 0, 0x01, 0x90, 1, 0, 0, 0, 0, 0, 0, 0]));
326        for _ in 0..=MAX_CONSECUTIVE_FAILURES {
327            mock.enqueue_error(EP, U3vError::Cancelled);
328        }
329        let mut events = U3vEventStream::new(mock.bulk_in(EP).unwrap(), 0, None);
330        let event = events.next_event_within(idle).unwrap().expect("an event");
331        assert_eq!(event.id, 0x9001);
332        let result = events.next_event_within(idle);
333        assert!(matches!(result, Err(U3vError::Cancelled)), "{result:?}");
334    }
335}