Skip to main content

viva_zenoh_api/
frame_header.rs

1//! Binary image envelope on the Zenoh image key.
2//!
3//! Version 3 keeps the version-2 geometry offsets, then carries a bounded
4//! JSON metadata object in the same packet as its pixels. The fixed prefix
5//! is 24 bytes, all integers little endian:
6//!
7//! | Offset | Size | Field |
8//! |--------|------|-------|
9//! | 0 | 2 | magic `0x4746` |
10//! | 2 | 1 | version `3` |
11//! | 3 | 1 | pixel format code |
12//! | 4 | 4 | width |
13//! | 8 | 4 | height |
14//! | 12 | 4 | sequence counter |
15//! | 16 | 4 | row stride, or 0 for continuous packing |
16//! | 20 | 4 | metadata JSON byte length, at most 64 KiB |
17//!
18//! Metadata bytes follow, then the image pixels. Length 0 means no metadata.
19
20use crate::{FrameMetadata, MAX_FRAME_METADATA_BYTES};
21use thiserror::Error;
22use viva_pfnc::PixelFormat;
23
24/// Little-endian image magic, bytes `[0x46, 0x47]`.
25pub const FRAME_MAGIC: u16 = 0x4746;
26/// Fixed prefix size, excluding the optional metadata object and pixels.
27pub const HEADER_SIZE: usize = 24;
28/// The only supported image envelope version.
29pub const SUPPORTED_VERSION: u8 = 3;
30
31/// A malformed or unrepresentable image envelope.
32#[derive(Debug, Error, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum FrameHeaderError {
35    /// The fixed prefix is incomplete.
36    #[error("buffer too short: need {HEADER_SIZE} bytes, got {0}")]
37    TooShort(usize),
38    /// The image magic is wrong.
39    #[error("bad magic: expected 0x{:04X}, got 0x{got:04X}", FRAME_MAGIC)]
40    BadMagic {
41        /// What the packet's magic field holds.
42        got: u16,
43    },
44    /// The sender uses a different envelope version.
45    #[error("unsupported version {0}; only version {SUPPORTED_VERSION} is supported")]
46    UnsupportedVersion(u8),
47    /// Metadata exceeds the packet's bounded allocation limit.
48    #[error("frame metadata length {0} exceeds {MAX_FRAME_METADATA_BYTES}")]
49    MetadataTooLarge(usize),
50    /// The declared metadata length exceeds the available bytes.
51    #[error("frame metadata is truncated")]
52    TruncatedMetadata,
53    /// Metadata JSON or its field bounds are invalid.
54    #[error("invalid frame metadata: {0}")]
55    InvalidMetadata(String),
56}
57
58/// Geometry and optional metadata for the pixels that follow it.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct FrameHeader {
61    /// PFNC format projected onto the wire's byte code.
62    pub pixel_format: PixelFormat,
63    /// Image width in pixels.
64    pub width: u32,
65    /// Image height in pixels.
66    pub height: u32,
67    /// Service image sequence, wrapping at `u32::MAX`.
68    pub seq: u32,
69    /// Bytes per padded row; `None` means continuous packing.
70    pub row_stride: Option<u32>,
71    /// Facts from this exact frame, inline rather than separately published.
72    pub metadata: Option<FrameMetadata>,
73}
74
75impl FrameHeader {
76    /// Encode the prefix and bounded metadata. Append the pixels afterward.
77    pub fn encode(&self) -> Result<Vec<u8>, FrameHeaderError> {
78        let metadata = self
79            .metadata
80            .as_ref()
81            .map(FrameMetadata::encode)
82            .transpose()
83            .map_err(|e| FrameHeaderError::InvalidMetadata(e.to_string()))?
84            .unwrap_or_default();
85        let mut buf = Vec::with_capacity(HEADER_SIZE + metadata.len());
86        buf.extend_from_slice(&FRAME_MAGIC.to_le_bytes());
87        buf.push(SUPPORTED_VERSION);
88        buf.push(pixel_format_to_u8(self.pixel_format));
89        buf.extend_from_slice(&self.width.to_le_bytes());
90        buf.extend_from_slice(&self.height.to_le_bytes());
91        buf.extend_from_slice(&self.seq.to_le_bytes());
92        buf.extend_from_slice(&self.row_stride.unwrap_or(0).to_le_bytes());
93        buf.extend_from_slice(&(metadata.len() as u32).to_le_bytes());
94        buf.extend_from_slice(&metadata);
95        Ok(buf)
96    }
97
98    /// Decode bounded metadata before exposing the remaining image bytes.
99    /// Older envelope versions are rejected, never read with guessed offsets.
100    pub fn decode(buf: &[u8]) -> Result<(FrameHeader, &[u8]), FrameHeaderError> {
101        if buf.len() < HEADER_SIZE {
102            return Err(FrameHeaderError::TooShort(buf.len()));
103        }
104        let magic = u16::from_le_bytes([buf[0], buf[1]]);
105        if magic != FRAME_MAGIC {
106            return Err(FrameHeaderError::BadMagic { got: magic });
107        }
108        let version = buf[2];
109        if version != SUPPORTED_VERSION {
110            return Err(FrameHeaderError::UnsupportedVersion(version));
111        }
112        let size = u32::from_le_bytes([buf[20], buf[21], buf[22], buf[23]]) as usize;
113        if size > MAX_FRAME_METADATA_BYTES {
114            return Err(FrameHeaderError::MetadataTooLarge(size));
115        }
116        let end = HEADER_SIZE
117            .checked_add(size)
118            .filter(|&end| end <= buf.len())
119            .ok_or(FrameHeaderError::TruncatedMetadata)?;
120        let metadata = if size == 0 {
121            None
122        } else {
123            Some(
124                FrameMetadata::decode(&buf[HEADER_SIZE..end])
125                    .map_err(FrameHeaderError::InvalidMetadata)?,
126            )
127        };
128        let stride = u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]);
129        Ok((
130            Self {
131                pixel_format: u8_to_pixel_format(buf[3]),
132                width: u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]),
133                height: u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
134                seq: u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]),
135                row_stride: (stride != 0).then_some(stride),
136                metadata,
137            },
138            &buf[end..],
139        ))
140    }
141}
142
143/// The frame header's one-byte format codes.
144///
145/// The Zenoh wire's own map, and nothing more: what a format *is* is
146/// `viva-pfnc`'s to say (ADR-0030); this table says which byte carries it.
147/// Codes are only appended, never reordered. A format without a code travels
148/// as 0 and decodes as `PixelFormat::Unknown(0)`; [`ImageMeta`](crate::ImageMeta)
149/// names it in full. Giving `Coord3D_*` codes (backlog DC-02) changes the wire.
150const WIRE_CODES: &[(u8, PixelFormat)] = &[
151    (1, PixelFormat::Mono8),
152    (2, PixelFormat::Mono10),
153    (3, PixelFormat::Mono12),
154    (4, PixelFormat::Mono16),
155    (5, PixelFormat::BayerRG8),
156    (6, PixelFormat::BayerGR8),
157    (7, PixelFormat::BayerBG8),
158    (8, PixelFormat::BayerGB8),
159    (9, PixelFormat::BayerRG10),
160    (10, PixelFormat::BayerGR10),
161    (11, PixelFormat::BayerBG10),
162    (12, PixelFormat::BayerGB10),
163    (13, PixelFormat::BayerRG12),
164    (14, PixelFormat::BayerGR12),
165    (15, PixelFormat::BayerBG12),
166    (16, PixelFormat::BayerGB12),
167    (17, PixelFormat::BayerRG16),
168    (18, PixelFormat::BayerGR16),
169    (19, PixelFormat::BayerBG16),
170    (20, PixelFormat::BayerGB16),
171    (21, PixelFormat::RGB8Packed),
172    (22, PixelFormat::BGR8Packed),
173    (23, PixelFormat::RGBa8),
174    (24, PixelFormat::YCbCr422_8),
175    (25, PixelFormat::YCbCr8),
176    (26, PixelFormat::Coord3DC16),
177    (27, PixelFormat::Mono14),
178    (28, PixelFormat::Mono10p),
179    (29, PixelFormat::Mono12p),
180    (30, PixelFormat::Mono10Packed),
181    (31, PixelFormat::Mono12Packed),
182    (32, PixelFormat::BayerRG10p),
183    (33, PixelFormat::BayerGR10p),
184    (34, PixelFormat::BayerBG10p),
185    (35, PixelFormat::BayerGB10p),
186    (36, PixelFormat::BayerRG12p),
187    (37, PixelFormat::BayerGR12p),
188    (38, PixelFormat::BayerBG12p),
189    (39, PixelFormat::BayerGB12p),
190    (40, PixelFormat::BayerRG10Packed),
191    (41, PixelFormat::BayerGR10Packed),
192    (42, PixelFormat::BayerBG10Packed),
193    (43, PixelFormat::BayerGB10Packed),
194    (44, PixelFormat::BayerRG12Packed),
195    (45, PixelFormat::BayerGR12Packed),
196    (46, PixelFormat::BayerBG12Packed),
197    (47, PixelFormat::BayerGB12Packed),
198    (48, PixelFormat::BGRa8),
199    (49, PixelFormat::YUV422_8),
200    (50, PixelFormat::YUV422_8_UYVY),
201    (51, PixelFormat::YCbCr422_8_CbYCrY),
202    (52, PixelFormat::YUV411_8_UYYVYY),
203    (53, PixelFormat::YUV8_UYV),
204    (54, PixelFormat::YCbCr8_CbYCr),
205];
206
207/// The one-byte code the frame header carries `format` as; 0 for a format
208/// without one.
209pub fn pixel_format_to_u8(format: PixelFormat) -> u8 {
210    WIRE_CODES
211        .iter()
212        .find(|&&(_, named)| named == format)
213        .map_or(0, |&(code, _)| code)
214}
215
216/// The format a frame header's one-byte code names; `PixelFormat::Unknown(0)`
217/// for 0 and for a code this table does not know.
218pub fn u8_to_pixel_format(code: u8) -> PixelFormat {
219    WIRE_CODES
220        .iter()
221        .find(|&&(known, _)| known == code)
222        .map_or(PixelFormat::Unknown(0), |&(_, format)| format)
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    fn make_header(pf: PixelFormat) -> FrameHeader {
230        FrameHeader {
231            pixel_format: pf,
232            width: 640,
233            height: 480,
234            seq: 7,
235            row_stride: None,
236            metadata: None,
237        }
238    }
239
240    #[test]
241    fn v3_wire_layout_has_literal_offsets_and_continuous_sentinel() {
242        let header = FrameHeader {
243            pixel_format: PixelFormat::Mono8,
244            width: 0x12345678,
245            height: 2,
246            seq: 0x44332211,
247            row_stride: Some(0x88776655),
248            metadata: None,
249        };
250        let expected = [
251            0x46, 0x47, 3, 1, 0x78, 0x56, 0x34, 0x12, 2, 0, 0, 0, 0x11, 0x22, 0x33, 0x44, 0x55,
252            0x66, 0x77, 0x88, 0, 0, 0, 0,
253        ];
254        assert_eq!(header.encode().unwrap(), expected);
255        let mut wire = expected.to_vec();
256        wire.extend_from_slice(&[9, 8]);
257        assert_eq!(FrameHeader::decode(&wire).unwrap(), (header, &[9, 8][..]));
258        wire[16..20].fill(0);
259        assert_eq!(FrameHeader::decode(&wire).unwrap().0.row_stride, None);
260        for version in [0, 1, 2, 255] {
261            wire[2] = version;
262            assert_eq!(
263                FrameHeader::decode(&wire),
264                Err(FrameHeaderError::UnsupportedVersion(version))
265            );
266        }
267        for length in 0..24 {
268            assert_eq!(
269                FrameHeader::decode(&wire[..length]),
270                Err(FrameHeaderError::TooShort(length))
271            );
272        }
273    }
274
275    #[test]
276    fn test_encode_decode_roundtrip_mono8() {
277        let hdr = make_header(PixelFormat::Mono8);
278        let encoded = hdr.encode().unwrap();
279        let (decoded, remaining) = FrameHeader::decode(&encoded).expect("decode should succeed");
280        assert_eq!(decoded, hdr);
281        assert!(remaining.is_empty());
282    }
283
284    #[test]
285    fn test_encode_produces_correct_magic() {
286        let hdr = make_header(PixelFormat::Mono8);
287        let encoded = hdr.encode().unwrap();
288        assert_eq!(encoded[0], 0x46);
289        assert_eq!(encoded[1], 0x47);
290    }
291
292    #[test]
293    fn test_encode_length() {
294        let hdr = make_header(PixelFormat::Mono8);
295        let encoded = hdr.encode().unwrap();
296        assert_eq!(encoded.len(), HEADER_SIZE);
297    }
298
299    #[test]
300    fn test_decode_buffer_too_short() {
301        let buf = [0u8; 19];
302        let err = FrameHeader::decode(&buf).unwrap_err();
303        assert_eq!(err, FrameHeaderError::TooShort(19));
304    }
305
306    #[test]
307    fn test_decode_bad_magic() {
308        let mut buf = make_header(PixelFormat::Mono8).encode().unwrap();
309        buf[0] = 0x00;
310        buf[1] = 0x00;
311        let err = FrameHeader::decode(&buf).unwrap_err();
312        assert!(matches!(err, FrameHeaderError::BadMagic { got: 0x0000 }));
313    }
314
315    #[test]
316    fn test_decode_unsupported_version() {
317        let mut buf = make_header(PixelFormat::Mono8).encode().unwrap();
318        buf[2] = 1;
319        let err = FrameHeader::decode(&buf).unwrap_err();
320        assert_eq!(err, FrameHeaderError::UnsupportedVersion(1));
321    }
322
323    /// The published codes keep their meaning, written out as literals
324    /// rather than from the table: a client built before the table moved
325    /// onto `viva-pfnc` reads the same bytes.
326    #[test]
327    fn the_published_codes_keep_their_meaning() {
328        let published: &[(u8, &str)] = &[
329            (1, "Mono8"),
330            (2, "Mono10"),
331            (3, "Mono12"),
332            (4, "Mono16"),
333            (5, "BayerRG8"),
334            (20, "BayerGB16"),
335            (21, "RGB8Packed"),
336            (22, "BGR8Packed"),
337            (23, "RGBa8"),
338            (24, "YCbCr422_8"),
339            (25, "YCbCr8"),
340            (26, "Coord3D_C16"),
341            (27, "Mono14"),
342            (28, "Mono10p"),
343            (31, "Mono12Packed"),
344            (48, "BGRa8"),
345            (50, "YUV422_8_UYVY"),
346            (54, "YCbCr8_CbYCr"),
347        ];
348        for &(code, name) in published {
349            let format = PixelFormat::from_name(name);
350            assert_eq!(pixel_format_to_u8(format), code, "{name}");
351            assert_eq!(u8_to_pixel_format(code), format, "{code}");
352        }
353    }
354
355    /// Every code names one format, and every coded format round-trips.
356    #[test]
357    fn every_code_is_its_own_format() {
358        let mut seen = std::collections::HashSet::new();
359        for &(code, format) in WIRE_CODES {
360            assert_ne!(code, 0, "{format}");
361            assert!(seen.insert(code), "{format} reuses code {code}");
362            assert!(
363                !matches!(format, PixelFormat::Unknown(_)),
364                "code {code} names no PFNC format"
365            );
366            assert_eq!(u8_to_pixel_format(pixel_format_to_u8(format)), format);
367        }
368    }
369
370    /// A format without a code travels as 0, and 0 and unknown codes decode
371    /// as unknown.
372    #[test]
373    fn a_format_without_a_code_is_unknown_on_the_wire() {
374        assert_eq!(pixel_format_to_u8(PixelFormat::Coord3DABC32f), 0);
375        assert_eq!(u8_to_pixel_format(0), PixelFormat::Unknown(0));
376        assert_eq!(u8_to_pixel_format(0xFF), PixelFormat::Unknown(0));
377    }
378}
379
380#[cfg(test)]
381mod metadata_tests {
382    use super::*;
383
384    #[test]
385    fn inline_metadata_stays_with_its_pixels() {
386        let header = FrameHeader {
387            pixel_format: PixelFormat::Mono8,
388            width: 2,
389            height: 1,
390            seq: 9,
391            row_stride: None,
392            metadata: Some(FrameMetadata {
393                block_id: u64::MAX.to_string(),
394                ts_dev: Some(u64::MAX.to_string()),
395                ts_host_ns: None,
396                complete: true,
397                chunks: Vec::new(),
398                features: Vec::new(),
399                chunk_error: None,
400                truncated: false,
401            }),
402        };
403        let mut packet = header.encode().unwrap();
404        packet.extend_from_slice(&[21, 22]);
405        let (decoded, pixels) = FrameHeader::decode(&packet).unwrap();
406        assert_eq!(decoded, header);
407        assert_eq!(pixels, &[21, 22]);
408    }
409
410    #[test]
411    fn malformed_and_oversized_metadata_never_becomes_pixels() {
412        let header = FrameHeader {
413            pixel_format: PixelFormat::Mono8,
414            width: 1,
415            height: 1,
416            seq: 0,
417            row_stride: None,
418            metadata: None,
419        };
420        let mut packet = header.encode().unwrap();
421        packet[20..24].copy_from_slice(&((MAX_FRAME_METADATA_BYTES + 1) as u32).to_le_bytes());
422        assert_eq!(
423            FrameHeader::decode(&packet),
424            Err(FrameHeaderError::MetadataTooLarge(
425                MAX_FRAME_METADATA_BYTES + 1
426            ))
427        );
428        packet[20..24].copy_from_slice(&8u32.to_le_bytes());
429        assert_eq!(
430            FrameHeader::decode(&packet),
431            Err(FrameHeaderError::TruncatedMetadata)
432        );
433        packet[20..24].copy_from_slice(&1u32.to_le_bytes());
434        packet.push(b'{');
435        assert!(matches!(
436            FrameHeader::decode(&packet),
437            Err(FrameHeaderError::InvalidMetadata(_))
438        ));
439    }
440}