viva_genicam/frame.rs
1//! Frame representation combining pixel data with optional chunk data.
2
3use std::time::SystemTime;
4
5use bytes::Bytes;
6use viva_pfnc::PixelFormat;
7
8use crate::chunks::ChunkData;
9
10/// How a frame's block ended.
11///
12/// A stream hands out only [`FrameStatus::Complete`] frames unless it was asked
13/// to deliver incomplete ones too (`FrameStream::set_deliver_incomplete`).
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum FrameStatus {
17 /// Every packet arrived and the device reported success.
18 Complete,
19 /// The trailer arrived; `missing_packets` packets (the leader among them,
20 /// if it was lost) did not. Their bytes in the payload are zero.
21 Incomplete {
22 /// Packets that never arrived.
23 missing_packets: u32,
24 },
25 /// The trailer reported this error status (bit 15 set).
26 DeviceStatus(viva_gige::GigeStatus),
27 /// A USB3 Vision trailer reported this error status (bit 15 set), such
28 /// as `DATA_OVERRUN`: the device dropped data.
29 #[cfg(feature = "u3v")]
30 #[cfg_attr(docsrs, doc(cfg(feature = "u3v")))]
31 U3vDeviceStatus(viva_u3v::U3vStatus),
32 /// No trailer arrived before the block timed out or was displaced, so how
33 /// many packets the block had is unknown.
34 TrailerMissing,
35}
36
37impl FrameStatus {
38 /// Whether this is [`FrameStatus::Complete`].
39 pub fn is_complete(self) -> bool {
40 matches!(self, FrameStatus::Complete)
41 }
42}
43
44/// Image frame produced by the GigE Vision stream reassembler.
45///
46/// Construct one with [`Frame::new`]; the struct is `#[non_exhaustive]` so the
47/// stream can report more about a block without breaking callers.
48#[derive(Debug, Clone)]
49#[non_exhaustive]
50pub struct Frame {
51 /// The image: its lines one after another, each followed by
52 /// [`padding_x`](Self::padding_x) bytes.
53 ///
54 /// For an image with chunks (`0x4001`) this is the image chunk alone,
55 /// without the chunks that follow it. A chunk-data block (`0x0004`) has
56 /// no image: `payload` is its chunk data, and `width` and `height` are 0.
57 pub payload: Bytes,
58 /// Width of the image in pixels.
59 pub width: u32,
60 /// Height of the image in pixels.
61 pub height: u32,
62 /// Pixel format describing how to interpret the payload bytes.
63 pub pixel_format: PixelFormat,
64 /// The block's chunks by chunk ID, when its payload type carries chunks
65 /// (`0x0004`, or the `0x4000` flag), the block is complete, and its chunk
66 /// layout parsed.
67 ///
68 /// What each chunk holds is the camera's XML's to say: read the values
69 /// through GenApi with [`Camera::with_chunks`](crate::Camera::with_chunks)
70 /// or [`Camera::chunk_features`](crate::Camera::chunk_features).
71 pub chunks: Option<ChunkData>,
72 /// Device timestamp reported by the camera when available.
73 pub ts_dev: Option<u64>,
74 /// Host timestamp obtained by mapping the device ticks.
75 pub ts_host: Option<SystemTime>,
76 /// Block id from the transport: 16 bits widened, or the 64-bit extended id.
77 pub block_id: u64,
78 /// Payload type from the leader, all 16 bits: `0x0001` is an image and
79 /// `0x4001` an image with extended chunk data (TC-05).
80 pub payload_type: u16,
81 /// How the block ended.
82 pub status: FrameStatus,
83 /// Bytes the camera sends after every line of the image: the GVSP image
84 /// leader's `padding_x`, 0 for none. See [`row_stride`](Self::row_stride).
85 pub padding_x: u16,
86 /// The block's whole payload as the camera sent it: for an image with
87 /// chunks (`0x4001`), the image chunk first, then every other chunk and
88 /// the tags between them; otherwise the same bytes as
89 /// [`payload`](Self::payload). [`payload`](Self::payload) is a slice of
90 /// it, so keeping both costs no copy.
91 ///
92 /// What a consumer that parses the chunk layout itself needs — a GenTL
93 /// consumer, which locates chunks in the buffer the producer fills.
94 pub raw_payload: Bytes,
95 /// Lines the block delivered, from its trailer's Size Y: fewer than
96 /// [`height`](Self::height) when a variable-height frame (a line scan)
97 /// ended early. `None` when no trailer said — it was lost, or the
98 /// payload is not an image.
99 pub delivered_height: Option<u32>,
100 /// Bytes the block was meant to carry, lost ones included: for a complete
101 /// block, the length of [`raw_payload`](Self::raw_payload); for an
102 /// incomplete one, what its trailer's packet count, `PayloadSize` or the
103 /// leader's geometry say. `None` when none of them does.
104 pub expected_size: Option<usize>,
105}
106
107/// Payload type of an image block.
108const PAYLOAD_TYPE_IMAGE: u16 = 0x0001;
109
110impl Frame {
111 /// A complete image frame with no chunks, timestamps or block id; its
112 /// [`raw_payload`](Self::raw_payload) is `payload`.
113 pub fn new(payload: Bytes, width: u32, height: u32, pixel_format: PixelFormat) -> Self {
114 Self {
115 raw_payload: payload.clone(),
116 payload,
117 width,
118 height,
119 pixel_format,
120 chunks: None,
121 ts_dev: None,
122 ts_host: None,
123 block_id: 0,
124 payload_type: PAYLOAD_TYPE_IMAGE,
125 status: FrameStatus::Complete,
126 padding_x: 0,
127 delivered_height: None,
128 expected_size: None,
129 }
130 }
131
132 /// Bytes from the start of one line to the start of the next, when the
133 /// camera pads its lines: the line's own bytes, a packing group it ends
134 /// inside completed (PFNC 2.4 §6.7), plus [`padding_x`](Self::padding_x).
135 /// `None` without padding: the lines then follow one another, and the
136 /// pixels run on from one line to the next.
137 pub fn row_stride(&self) -> Option<usize> {
138 if self.padding_x == 0 {
139 return None;
140 }
141 self.pixel_format
142 .line_bytes(self.width)
143 .map(|line| line + usize::from(self.padding_x))
144 }
145
146 /// Whether every packet of the frame arrived.
147 pub fn is_complete(&self) -> bool {
148 self.status.is_complete()
149 }
150
151 /// Host-reconstructed timestamp if the camera reports a device timestamp.
152 pub fn host_time(&self) -> Option<SystemTime> {
153 self.ts_host
154 }
155
156 /// Return a borrowed slice of RGB pixels when the payload is already RGB8.
157 pub fn as_rgb8(&self) -> Option<&[u8]> {
158 match self.pixel_format {
159 PixelFormat::RGB8Packed => Some(self.payload.as_ref()),
160 _ => None,
161 }
162 }
163
164 /// Convert the frame payload into an owned RGB8 buffer.
165 ///
166 /// Every format [`viva_pfnc::convert`] handles: monochrome and Bayer at 8
167 /// to 16 bits, packed or not, RGB/BGR with or without alpha, and 8-bit
168 /// Y'CbCr. Samples deeper than 8 bits keep their top eight bits, and a
169 /// Bayer mosaic is demosaiced bilinearly — the same pixels Viva Studio's
170 /// viewer shows. Bytes past the image are ignored.
171 pub fn to_rgb8(&self) -> Result<Vec<u8>, crate::GenicamError> {
172 viva_pfnc::convert::to_rgb8(
173 self.pixel_format,
174 self.width,
175 self.height,
176 self.row_stride(),
177 &self.payload,
178 )
179 .map_err(crate::GenicamError::from)
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use bytes::Bytes;
187
188 fn frame_with_payload(
189 payload: &[u8],
190 width: u32,
191 height: u32,
192 pixel_format: PixelFormat,
193 ) -> Frame {
194 Frame::new(Bytes::copy_from_slice(payload), width, height, pixel_format)
195 }
196
197 #[test]
198 fn mono8_converts_to_rgb8() {
199 let payload = [0u8, 64, 128, 255];
200 let frame = frame_with_payload(&payload, 2, 2, PixelFormat::Mono8);
201 let rgb = frame.to_rgb8().expect("mono conversion");
202 assert_eq!(rgb.len(), 12);
203 assert_eq!(&rgb[0..3], &[0, 0, 0]);
204 assert_eq!(&rgb[3..6], &[64, 64, 64]);
205 assert_eq!(&rgb[9..12], &[255, 255, 255]);
206 }
207
208 #[test]
209 fn rgb8_fast_path_borrows_payload() {
210 let payload = vec![1u8, 2, 3, 4, 5, 6];
211 let frame = frame_with_payload(&payload, 1, 2, PixelFormat::RGB8Packed);
212 assert_eq!(frame.as_rgb8().unwrap(), payload.as_slice());
213 let owned = frame.to_rgb8().expect("rgb copy");
214 assert_eq!(owned, payload);
215 }
216
217 #[test]
218 fn bayer_rg8_demosaic_basic_pattern() {
219 // Simple 4x4 Bayer pattern with distinguishable colour quadrants.
220 let payload = [
221 255, 32, 255, 32, // R G R G row
222 32, 16, 32, 240, // G B G B row
223 255, 32, 255, 32, 32, 16, 32, 240,
224 ];
225 let frame = frame_with_payload(&payload, 4, 4, PixelFormat::BayerRG8);
226 let rgb = frame.to_rgb8().expect("bayer conversion");
227 assert_eq!(rgb.len(), 4 * 4 * 3);
228 // Top-left pixel should be red dominant.
229 assert!(rgb[0] > rgb[1] && rgb[0] > rgb[2]);
230 // Bottom-right pixel should carry the blue sample.
231 let last = &rgb[rgb.len() - 3..];
232 assert_eq!(last[2], 240);
233 }
234
235 /// `to_rgb8` is `viva_pfnc::convert::to_rgb8` — the conversion Viva
236 /// Studio's viewer draws with — for every family of format it handles.
237 #[test]
238 fn to_rgb8_is_the_shared_conversion() {
239 use viva_pfnc::convert;
240 let mosaic: Vec<u8> = (0..36u8).map(|v| v.wrapping_mul(37)).collect();
241 let cases: [(PixelFormat, u32, u32, Vec<u8>); 9] = [
242 (PixelFormat::BayerRG8, 6, 6, mosaic.clone()),
243 (PixelFormat::BayerGB8, 6, 6, mosaic.clone()),
244 (PixelFormat::Mono8, 6, 6, mosaic),
245 (PixelFormat::Mono16, 2, 1, vec![0x34, 0x12, 0xFF, 0xFF]),
246 (PixelFormat::Mono12Packed, 2, 1, vec![0xAB, 0x3C, 0x12]),
247 (
248 PixelFormat::BayerRG12p,
249 2,
250 2,
251 vec![0xBC, 0x3A, 0x12, 0x45, 0x06, 0x78],
252 ),
253 (PixelFormat::YUV422_8, 2, 1, vec![100, 150, 200, 90]),
254 (PixelFormat::BGR8Packed, 1, 1, vec![1, 2, 3]),
255 (PixelFormat::RGBa8, 1, 1, vec![1, 2, 3, 4]),
256 ];
257 for (format, width, height, payload) in cases {
258 let frame = frame_with_payload(&payload, width, height, format);
259 assert_eq!(
260 frame.to_rgb8().ok(),
261 convert::to_rgb8(format, width, height, None, &payload).ok(),
262 "{format}"
263 );
264 }
265 }
266
267 #[test]
268 fn to_rgb8_reports_a_short_payload_and_an_unconvertible_format() {
269 let short = frame_with_payload(&[1, 2, 3], 2, 2, PixelFormat::Mono8);
270 assert!(matches!(
271 short.to_rgb8(),
272 Err(crate::GenicamError::Convert(_))
273 ));
274 let depth = frame_with_payload(&[0; 4], 1, 1, PixelFormat::Coord3DC32f);
275 assert!(matches!(
276 depth.to_rgb8(),
277 Err(crate::GenicamError::UnsupportedPixelFormat(
278 PixelFormat::Coord3DC32f
279 ))
280 ));
281 }
282}