Skip to main content

viva_genicam/
chunks.rs

1//! Chunk data in a GigE Vision or USB3 Vision payload.
2//!
3//! A camera in chunk mode sends each frame as a run of chunks — the image
4//! first, then one chunk per enabled value — each its data followed by a tag
5//! naming its chunk ID and length (TC-06, [`viva_gige::parse_chunks`]).
6//! What a chunk *means* is not decided here: the camera's own XML declares
7//! which registers sit on which chunk, at which offset and in which byte
8//! order, and [`Camera::with_chunks`](crate::Camera::with_chunks) reads them
9//! through GenApi like any other feature (ADR-0026).
10
11use bytes::Bytes;
12pub use viva_genapi::ChunkData;
13pub use viva_gige::ChunkError;
14use viva_gige::{PAYLOAD_TYPE_CHUNK_DATA, has_extended_chunks, is_image_payload};
15
16/// Split a GigE Vision chunk payload into a [`ChunkData`], by chunk ID.
17///
18/// `payload` must end where the camera's data ends. Each chunk is a slice of
19/// `payload`; nothing is copied.
20pub fn chunk_data(payload: &Bytes) -> Result<ChunkData, ChunkError> {
21    let chunks = viva_gige::parse_chunks(payload)?;
22    Ok(chunks
23        .into_iter()
24        .map(|chunk| {
25            let end = chunk.offset + chunk.data.len();
26            (u64::from(chunk.id), payload.slice(chunk.offset..end))
27        })
28        .collect())
29}
30
31/// Whether a block of `payload_type` is made of chunks: chunk data
32/// (`0x0004`), or any type with the extended chunk flag (`0x4000`).
33pub(crate) fn carries_chunks(payload_type: u16) -> bool {
34    has_extended_chunks(payload_type) || payload_type & 0x3FFF == PAYLOAD_TYPE_CHUNK_DATA
35}
36
37/// A block's image and chunks, from its whole payload.
38///
39/// For an image with chunks the image is the first chunk, at offset 0, and is
40/// returned on its own; the chunks come back by ID, the image among them. A
41/// chunk-data block has no image, so its payload comes back whole. A payload
42/// that does not tile into chunks keeps its bytes and has none — the error
43/// says where it went wrong.
44pub(crate) fn split(
45    payload: Bytes,
46    payload_type: u16,
47) -> (Bytes, Option<Result<ChunkData, ChunkError>>) {
48    if !carries_chunks(payload_type) {
49        return (payload, None);
50    }
51    match chunk_data(&payload) {
52        Ok(data) => {
53            let image = data
54                .iter()
55                .next()
56                .filter(|_| is_image_payload(payload_type))
57                .map(|(_, first)| first.clone());
58            (image.unwrap_or(payload), Some(Ok(data)))
59        }
60        Err(err) => (payload, Some(Err(err))),
61    }
62}
63
64/// A USB3 Vision block's image and chunks: GigE Vision's layout with
65/// little-endian tags ([`viva_u3v::parse_chunks`]). Any payload type with
66/// the chunk flag (`0x4000`) carries chunks; with an image (`0x4001`) the
67/// image is the first chunk, and comes back on its own.
68#[cfg(feature = "u3v")]
69pub(crate) fn split_u3v(
70    payload: Bytes,
71    payload_type: u16,
72) -> (Bytes, Option<Result<ChunkData, viva_u3v::U3vError>>) {
73    if payload_type & 0x4000 == 0 {
74        return (payload, None);
75    }
76    match viva_u3v::parse_chunks(&payload) {
77        Ok(chunks) => {
78            let data: ChunkData = chunks
79                .iter()
80                .map(|&(id, offset, len)| (u64::from(id), payload.slice(offset..offset + len)))
81                .collect();
82            let image = chunks
83                .first()
84                .filter(|_| payload_type & 0x3FFF == 0x0001)
85                .map(|&(_, offset, len)| payload.slice(offset..offset + len));
86            (image.unwrap_or(payload), Some(Ok(data)))
87        }
88        Err(err) => (payload, Some(Err(err))),
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    /// `[image 4][tag id 1, len 4][value 4][tag id 0x0508000E, len 4]`,
97    /// written out by hand.
98    #[rustfmt::skip]
99    const BLOCK: [u8; 24] = [
100        0xA0, 0xA1, 0xA2, 0xA3,
101        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04,
102        0x2A, 0x00, 0x00, 0x00,
103        0x05, 0x08, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x04,
104    ];
105
106    #[test]
107    fn an_image_with_chunks_splits_into_the_image_and_the_chunks() {
108        let (image, chunks) = split(Bytes::from_static(&BLOCK), 0x4001);
109        assert_eq!(&image[..], &[0xA0, 0xA1, 0xA2, 0xA3]);
110        let chunks = chunks.expect("chunk flag").expect("well-formed");
111        assert_eq!(chunks.ids().collect::<Vec<_>>(), vec![1, 0x0508_000E]);
112        assert_eq!(
113            &chunks.get(0x0508_000E).expect("value")[..],
114            &[0x2A, 0, 0, 0]
115        );
116    }
117
118    /// GigE Vision 1.x's extended chunk data (`0x0005`), as an Allied Vision
119    /// Manta G-125B sends it: the image is the first chunk, as with `0x4001`.
120    #[test]
121    fn a_gige_vision_1_extended_chunk_block_splits_like_0x4001() {
122        let (image, chunks) = split(Bytes::from_static(&BLOCK), 0x0005);
123        assert_eq!(&image[..], &[0xA0, 0xA1, 0xA2, 0xA3]);
124        assert_eq!(chunks.expect("chunks").expect("well-formed").len(), 2);
125    }
126
127    #[test]
128    fn a_chunk_data_block_keeps_its_payload_whole() {
129        let (payload, chunks) = split(Bytes::from_static(&BLOCK), 0x0004);
130        assert_eq!(payload.len(), BLOCK.len());
131        assert_eq!(chunks.expect("chunk data").expect("well-formed").len(), 2);
132    }
133
134    #[test]
135    fn a_plain_image_has_no_chunks() {
136        let (payload, chunks) = split(Bytes::from_static(&BLOCK), 0x0001);
137        assert_eq!(payload.len(), BLOCK.len());
138        assert!(chunks.is_none());
139    }
140
141    #[test]
142    fn a_malformed_layout_keeps_the_bytes_and_reports_the_error() {
143        let (payload, chunks) = split(Bytes::from_static(&BLOCK[1..]), 0x4001);
144        assert_eq!(payload.len(), BLOCK.len() - 1);
145        // The image chunk's tag now claims one byte more than precedes it.
146        assert!(matches!(
147            chunks,
148            Some(Err(ChunkError::LengthPastStart {
149                id: 1,
150                tag_offset: 3,
151                length: 4
152            }))
153        ));
154    }
155}