Skip to main content

viva_zenoh_api/
evs_header.rs

1//! Binary header prepended to every event-vision block on the Zenoh `evs` key.
2//!
3//! An event-vision camera — a LUCID Triton2 EVS, for one
4//! ([#138](https://github.com/VitalyVorobyev/viva-genicam/issues/138)) —
5//! streams encoded events, not pixels. Its blocks are published on
6//! [`keys::evs`](crate::keys::evs) rather than [`keys::image`](crate::keys::image),
7//! framed the way images are: a fixed little-endian header, then the payload
8//! exactly as the device sent it.
9//!
10//! ## Layout (24 bytes, all fields little-endian)
11//!
12//! | Offset | Size | Field       | Value / Notes                                   |
13//! |--------|------|-------------|-------------------------------------------------|
14//! | 0      | 2    | magic       | `0x5645` LE (`[0x45, 0x56]`, `"EV"`)            |
15//! | 2      | 1    | version     | `1`                                             |
16//! | 3      | 1    | format      | event encoding discriminant (see [`EvsFormat`]) |
17//! | 4      | 4    | seq         | per-acquisition block counter, u32              |
18//! | 8      | 8    | timestamp   | device timestamp; meaningful only if flagged    |
19//! | 16     | 4    | payload_len | length of the event bytes that follow, u32      |
20//! | 20     | 1    | flags       | bit 0: `timestamp` is present                   |
21//! | 21     | 3    | reserved    | zero                                            |
22
23use thiserror::Error;
24
25/// Magic bytes identifying an event-vision block header.
26/// Little-endian encoding of `0x5645` -> bytes `[0x45, 0x56]` (`"EV"`).
27pub const EVS_MAGIC: u16 = 0x5645;
28
29/// Fixed size of the binary event-vision block header in bytes.
30pub const EVS_HEADER_SIZE: usize = 24;
31
32/// The only supported header version. Bumped when the layout changes.
33pub const EVS_SUPPORTED_VERSION: u8 = 1;
34
35const FLAG_TIMESTAMP: u8 = 0x01;
36
37/// Encoding of the event bytes that follow an [`EvsHeader`].
38///
39/// Codes are only appended, never reordered; a code this build does not know
40/// decodes to [`EvsFormat::Unknown`] rather than failing, so a newer service
41/// does not break an older client.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub enum EvsFormat {
45    /// An encoding this build does not know. Wire code `0`.
46    Unknown,
47    /// Prophesee EVT 3.0: 16-bit words. Wire code `1`.
48    Evt30,
49    /// Prophesee EVT 2.1: 64-bit events. Wire code `2`.
50    Evt21,
51}
52
53impl EvsFormat {
54    /// The stable one-byte wire code.
55    pub fn code(self) -> u8 {
56        match self {
57            Self::Unknown => 0,
58            Self::Evt30 => 1,
59            Self::Evt21 => 2,
60        }
61    }
62
63    /// The format for a wire code; [`EvsFormat::Unknown`] for any code this
64    /// build does not know.
65    pub fn from_code(code: u8) -> Self {
66        match code {
67            1 => Self::Evt30,
68            2 => Self::Evt21,
69            _ => Self::Unknown,
70        }
71    }
72
73    /// A short human-readable name: `"EVT3.0"`, `"EVT2.1"` or `"Unknown"`.
74    pub fn as_str(self) -> &'static str {
75        match self {
76            Self::Unknown => "Unknown",
77            Self::Evt30 => "EVT3.0",
78            Self::Evt21 => "EVT2.1",
79        }
80    }
81}
82
83/// Errors returned by [`EvsHeader::decode`].
84#[derive(Debug, Error, PartialEq, Eq)]
85#[non_exhaustive]
86pub enum EvsHeaderError {
87    /// Buffer is shorter than [`EVS_HEADER_SIZE`] bytes.
88    #[error("buffer too short: need {EVS_HEADER_SIZE} bytes, got {0}")]
89    TooShort(usize),
90
91    /// First two bytes do not match [`EVS_MAGIC`].
92    #[error("bad magic: expected 0x{:04X}, got 0x{got:04X}", EVS_MAGIC)]
93    BadMagic {
94        /// The two bytes found, read little-endian.
95        got: u16,
96    },
97
98    /// Version byte is not [`EVS_SUPPORTED_VERSION`].
99    #[error("unsupported version {0}; only version {EVS_SUPPORTED_VERSION} is supported")]
100    UnsupportedVersion(u8),
101
102    /// The header's `payload_len` disagrees with the bytes that follow it.
103    #[error("header declares {declared} payload bytes, {actual} follow")]
104    LengthMismatch {
105        /// `payload_len` from the header.
106        declared: u32,
107        /// Bytes actually following the header.
108        actual: usize,
109    },
110}
111
112/// 24-byte header prepended to every event-vision block.
113///
114/// See the module-level documentation for the byte layout.
115///
116/// `#[non_exhaustive]`: build one with [`EvsHeader::new`], so that adding the
117/// next field is not a breaking change.
118#[derive(Debug, Clone, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct EvsHeader {
121    /// Encoding of the event bytes.
122    pub format: EvsFormat,
123    /// Block counter, starting at zero for each acquisition (wraps at
124    /// `u32::MAX`). Counts event blocks only; images have their own `seq`.
125    pub seq: u32,
126    /// Device timestamp from the GVSP leader, when the stream carried one.
127    pub timestamp: Option<u64>,
128    /// Length in bytes of the event data that follows the header.
129    pub payload_len: u32,
130}
131
132impl EvsHeader {
133    /// A header for `payload_len` bytes of `format` events.
134    pub fn new(format: EvsFormat, seq: u32, timestamp: Option<u64>, payload_len: u32) -> Self {
135        Self {
136            format,
137            seq,
138            timestamp,
139            payload_len,
140        }
141    }
142
143    /// Encode this header into a 24-byte `Vec<u8>`.
144    pub fn encode(&self) -> Vec<u8> {
145        let mut buf = Vec::with_capacity(EVS_HEADER_SIZE);
146        buf.extend_from_slice(&EVS_MAGIC.to_le_bytes());
147        buf.push(EVS_SUPPORTED_VERSION);
148        buf.push(self.format.code());
149        buf.extend_from_slice(&self.seq.to_le_bytes());
150        buf.extend_from_slice(&self.timestamp.unwrap_or(0).to_le_bytes());
151        buf.extend_from_slice(&self.payload_len.to_le_bytes());
152        buf.push(if self.timestamp.is_some() {
153            FLAG_TIMESTAMP
154        } else {
155            0
156        });
157        buf.extend_from_slice(&[0; 3]);
158        buf
159    }
160
161    /// Decode a header from the front of `buf`.
162    ///
163    /// On success returns `(header, event_bytes)`, where `event_bytes` is the
164    /// remainder after the header and is exactly `payload_len` long.
165    pub fn decode(buf: &[u8]) -> Result<(EvsHeader, &[u8]), EvsHeaderError> {
166        if buf.len() < EVS_HEADER_SIZE {
167            return Err(EvsHeaderError::TooShort(buf.len()));
168        }
169
170        let magic = u16::from_le_bytes([buf[0], buf[1]]);
171        if magic != EVS_MAGIC {
172            return Err(EvsHeaderError::BadMagic { got: magic });
173        }
174
175        let version = buf[2];
176        if version != EVS_SUPPORTED_VERSION {
177            return Err(EvsHeaderError::UnsupportedVersion(version));
178        }
179
180        let format = EvsFormat::from_code(buf[3]);
181        let seq = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]);
182        let mut ts = [0u8; 8];
183        ts.copy_from_slice(&buf[8..16]);
184        let payload_len = u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]);
185        let timestamp = (buf[20] & FLAG_TIMESTAMP != 0).then(|| u64::from_le_bytes(ts));
186
187        let events = &buf[EVS_HEADER_SIZE..];
188        if events.len() != payload_len as usize {
189            return Err(EvsHeaderError::LengthMismatch {
190                declared: payload_len,
191                actual: events.len(),
192            });
193        }
194
195        Ok((EvsHeader::new(format, seq, timestamp, payload_len), events))
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    fn framed(header: &EvsHeader, events: &[u8]) -> Vec<u8> {
204        let mut buf = header.encode();
205        buf.extend_from_slice(events);
206        buf
207    }
208
209    #[test]
210    fn roundtrip_with_and_without_timestamp() {
211        let events = [1u8, 2, 3, 4, 5, 6];
212        for timestamp in [Some(0), Some(0x0123_4567_89AB_CDEF), None] {
213            let header = EvsHeader::new(EvsFormat::Evt30, 9, timestamp, events.len() as u32);
214            let buf = framed(&header, &events);
215            assert_eq!(buf.len(), EVS_HEADER_SIZE + events.len());
216            let (decoded, rest) = EvsHeader::decode(&buf).expect("decode");
217            assert_eq!(decoded, header);
218            assert_eq!(rest, events);
219        }
220    }
221
222    #[test]
223    fn magic_is_distinct_from_the_image_header() {
224        assert_ne!(EVS_MAGIC, crate::FRAME_MAGIC);
225        let buf = EvsHeader::new(EvsFormat::Evt21, 0, None, 0).encode();
226        assert_eq!(&buf[..2], b"EV");
227        assert!(crate::FrameHeader::decode(&buf).is_err());
228    }
229
230    #[test]
231    fn format_codes_are_stable_and_unknown_codes_degrade() {
232        for format in [EvsFormat::Unknown, EvsFormat::Evt30, EvsFormat::Evt21] {
233            assert_eq!(EvsFormat::from_code(format.code()), format);
234        }
235        assert_eq!(EvsFormat::Evt30.code(), 1);
236        assert_eq!(EvsFormat::Evt21.code(), 2);
237        assert_eq!(EvsFormat::from_code(0xFF), EvsFormat::Unknown);
238    }
239
240    #[test]
241    fn decode_rejects_malformed_buffers() {
242        assert_eq!(
243            EvsHeader::decode(&[0; 23]).unwrap_err(),
244            EvsHeaderError::TooShort(23)
245        );
246
247        let good = framed(&EvsHeader::new(EvsFormat::Evt30, 0, None, 2), &[7, 7]);
248
249        let mut bad_magic = good.clone();
250        bad_magic[0] = 0;
251        assert!(matches!(
252            EvsHeader::decode(&bad_magic).unwrap_err(),
253            EvsHeaderError::BadMagic { .. }
254        ));
255
256        let mut bad_version = good.clone();
257        bad_version[2] = 2;
258        assert_eq!(
259            EvsHeader::decode(&bad_version).unwrap_err(),
260            EvsHeaderError::UnsupportedVersion(2)
261        );
262
263        assert_eq!(
264            EvsHeader::decode(&good[..good.len() - 1]).unwrap_err(),
265            EvsHeaderError::LengthMismatch {
266                declared: 2,
267                actual: 1
268            }
269        );
270    }
271}