1use crate::{FrameMetadata, MAX_FRAME_METADATA_BYTES};
21use thiserror::Error;
22use viva_pfnc::PixelFormat;
23
24pub const FRAME_MAGIC: u16 = 0x4746;
26pub const HEADER_SIZE: usize = 24;
28pub const SUPPORTED_VERSION: u8 = 3;
30
31#[derive(Debug, Error, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum FrameHeaderError {
35 #[error("buffer too short: need {HEADER_SIZE} bytes, got {0}")]
37 TooShort(usize),
38 #[error("bad magic: expected 0x{:04X}, got 0x{got:04X}", FRAME_MAGIC)]
40 BadMagic {
41 got: u16,
43 },
44 #[error("unsupported version {0}; only version {SUPPORTED_VERSION} is supported")]
46 UnsupportedVersion(u8),
47 #[error("frame metadata length {0} exceeds {MAX_FRAME_METADATA_BYTES}")]
49 MetadataTooLarge(usize),
50 #[error("frame metadata is truncated")]
52 TruncatedMetadata,
53 #[error("invalid frame metadata: {0}")]
55 InvalidMetadata(String),
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct FrameHeader {
61 pub pixel_format: PixelFormat,
63 pub width: u32,
65 pub height: u32,
67 pub seq: u32,
69 pub row_stride: Option<u32>,
71 pub metadata: Option<FrameMetadata>,
73}
74
75impl FrameHeader {
76 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 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
143const 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
207pub 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
216pub 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 #[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 #[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 #[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}