Skip to main content

viva_gige/
gvsp.rs

1//! GVSP packet parsing and stream configuration.
2//!
3//! The GigE Vision Streaming Protocol delivers a block (one image) as a leader,
4//! data packets and a trailer over UDP. [`parse_packet_ref`] reads one datagram
5//! without copying it; the receive engine in `viva-genicam` assembles blocks
6//! from what it returns.
7
8use std::net::Ipv4Addr;
9use std::ops::RangeInclusive;
10
11use crate::nic::Iface;
12use bytes::Buf;
13use thiserror::Error;
14use tracing::debug;
15
16/// GVSP payload type for image data. Bits 13..0 of the 16-bit field carry the
17/// type; bit 14 ([`PAYLOAD_TYPE_EXTENDED_CHUNK`]) flags extended chunk data,
18/// so `0x4001` is an image with chunks (TC-05). aravis masks the same way
19/// (`payload_type & 0x3fff`, `& 0x4000` for chunks in `arvgvspprivate.h`).
20pub const PAYLOAD_TYPE_IMAGE: u16 = 0x0001;
21
22/// Bit 14 of the payload type: the block carries extended chunk data.
23pub const PAYLOAD_TYPE_EXTENDED_CHUNK: u16 = 0x4000;
24
25/// GVSP payload type for chunk data: a block made only of chunks, whose
26/// leader carries no image geometry (`reserved | payload type | timestamp`)
27/// and whose trailer reports the payload data length where an image's
28/// reports Size Y. Layout corroborated by Wireshark's
29/// `dissect_chunk_data_leader` / `_trailer`.
30pub const PAYLOAD_TYPE_CHUNK_DATA: u16 = 0x0004;
31
32/// GVSP payload type for GigE Vision 1.x's extended chunk data, deprecated
33/// by GigE Vision 2.0 for an image with the chunk flag (`0x4001`), whose
34/// layout it shares: an image leader, a payload of chunks with the image
35/// first, and a trailer of reserved | payload type | payload data length |
36/// Size Y | chunk layout ID. An Allied Vision Manta G-125B (GigE Vision 1.2)
37/// sends it with `ChunkModeActive` on. Layout corroborated by Wireshark's
38/// `dissect_extended_chunk_data_leader` / `_trailer`; aravis treats it as an
39/// image with chunks.
40pub const PAYLOAD_TYPE_EXTENDED_CHUNK_DATA: u16 = 0x0005;
41
42/// Bits of the payload type that name the type itself.
43const PAYLOAD_TYPE_MASK: u16 = 0x3FFF;
44
45/// Whether `payload_type` is an image, with or without extended chunk data:
46/// GigE Vision 1.x's [`PAYLOAD_TYPE_EXTENDED_CHUNK_DATA`] is one too.
47pub fn is_image_payload(payload_type: u16) -> bool {
48    matches!(
49        payload_type & PAYLOAD_TYPE_MASK,
50        PAYLOAD_TYPE_IMAGE | PAYLOAD_TYPE_EXTENDED_CHUNK_DATA
51    )
52}
53
54/// Whether `payload_type` is chunk data, with or without the chunk flag.
55pub fn is_chunk_data_payload(payload_type: u16) -> bool {
56    payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_CHUNK_DATA
57}
58
59/// Whether `payload_type` carries extended chunk data: it has the chunk flag
60/// (bit 14), or is GigE Vision 1.x's [`PAYLOAD_TYPE_EXTENDED_CHUNK_DATA`].
61pub fn has_extended_chunks(payload_type: u16) -> bool {
62    payload_type & PAYLOAD_TYPE_EXTENDED_CHUNK != 0
63        || payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_EXTENDED_CHUNK_DATA
64}
65
66/// Size of the standard GVSP header.
67pub const GVSP_HEADER_SIZE: usize = 8;
68
69/// Size of the extended-ID GVSP header (GigE Vision 2.0).
70pub const GVSP_EXTENDED_HEADER_SIZE: usize = 20;
71
72/// Extended ID flag: bit 7 of the packet-format byte.
73const EXTENDED_ID_FLAG: u8 = 0x80;
74
75/// Packet format: data leader.
76const FORMAT_LEADER: u8 = 0x01;
77/// Packet format: data trailer.
78const FORMAT_TRAILER: u8 = 0x02;
79/// Packet format: generic data payload.
80const FORMAT_PAYLOAD: u8 = 0x03;
81
82/// Destination for GVSP packets received by the stream.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum StreamDest {
85    /// Standard unicast delivery towards a single host.
86    Unicast {
87        /// Destination IPv4 address configured on the camera.
88        dst_ip: Ipv4Addr,
89        /// UDP port used for streaming.
90        dst_port: u16,
91    },
92    /// Multicast delivery towards one or more hosts joined to the group.
93    Multicast {
94        /// Multicast group IPv4 address.
95        group: Ipv4Addr,
96        /// UDP port used for streaming.
97        port: u16,
98        /// Whether loopback is enabled on the local socket.
99        loopback: bool,
100        /// Outbound multicast time-to-live.
101        ttl: u32,
102    },
103}
104
105impl StreamDest {
106    /// Retrieve the configured UDP port.
107    pub fn port(&self) -> u16 {
108        match self {
109            StreamDest::Unicast { dst_port, .. } => *dst_port,
110            StreamDest::Multicast { port, .. } => *port,
111        }
112    }
113
114    /// Retrieve the configured IPv4 destination address.
115    pub fn addr(&self) -> Ipv4Addr {
116        match self {
117            StreamDest::Unicast { dst_ip, .. } => *dst_ip,
118            StreamDest::Multicast { group, .. } => *group,
119        }
120    }
121
122    /// Whether the destination represents multicast delivery.
123    pub fn is_multicast(&self) -> bool {
124        matches!(self, StreamDest::Multicast { .. })
125    }
126}
127
128/// Stream configuration shared between the control plane and GVSP receiver.
129#[derive(Debug, Clone)]
130pub struct StreamConfig {
131    /// Destination configuration for the GVSP stream.
132    pub dest: StreamDest,
133    /// Interface used for receiving packets and multicast subscription.
134    pub iface: Iface,
135    /// GVSP packet size in force.
136    pub packet_size: Option<u32>,
137    /// `GevSCPD` written, in timestamp ticks; `None` when left alone.
138    pub packet_delay: Option<u32>,
139    /// The only address GVSP is accepted from: the camera's. Datagrams from
140    /// any other source are ignored and counted.
141    pub source_filter: Option<Ipv4Addr>,
142}
143
144/// Errors raised while handling GVSP packets.
145#[derive(Debug, Error)]
146#[non_exhaustive]
147pub enum GvspError {
148    #[error("unsupported packet type: {0}")]
149    /// A packet of a kind the parser does not handle.
150    Unsupported(&'static str),
151    #[error("invalid packet: {0}")]
152    /// A packet that does not have the shape GVSP gives it.
153    Invalid(&'static str),
154}
155
156/// Length of a chunk tag: chunk ID and data length, 32 bits each.
157const CHUNK_TAG_LEN: usize = 8;
158
159/// One chunk of a GVSP chunk payload, borrowing the payload.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct ChunkRaw<'a> {
162    /// Chunk ID: 32 bits, as a `<Port>`'s `<ChunkID>` names it.
163    pub id: u32,
164    /// Where the chunk's data starts in the payload.
165    pub offset: usize,
166    /// The chunk's data, without its tag.
167    pub data: &'a [u8],
168}
169
170/// A chunk payload that does not tile into tagged chunks.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
172#[non_exhaustive]
173pub enum ChunkError {
174    /// What remains at the front of the payload is too short for a tag.
175    #[error(
176        "{remaining} bytes remain at offset 0 of the chunk data, too few for an \
177         8-byte chunk tag"
178    )]
179    TruncatedTag {
180        /// Bytes left before the last chunk parsed.
181        remaining: usize,
182    },
183    /// A tag claims more data than precedes it.
184    #[error(
185        "chunk {id:#010x} tagged at offset {tag_offset} claims {length} bytes of data, \
186         more than the {tag_offset} before it"
187    )]
188    LengthPastStart {
189        /// The chunk ID in the tag.
190        id: u32,
191        /// Where the tag starts.
192        tag_offset: usize,
193        /// The data length it claims.
194        length: u32,
195    },
196}
197
198/// Split a GigE Vision chunk payload into its chunks, in payload order.
199///
200/// Each chunk is its data followed by an 8-byte tag — the chunk ID, then the
201/// data length, both 32-bit big-endian — so the payload can only be read from
202/// its end: the last 8 bytes are the last chunk's tag, its length says where
203/// that chunk's data begins, and the 8 bytes before that are the previous
204/// tag. With payload type `0x4001` the image is the first chunk, and the scan
205/// ends exactly at offset 0 after it.
206///
207/// The GigE Vision specification is not available to us; the layout is
208/// corroborated by aravis (`arv_buffer_get_chunk_data` walks
209/// `{u32 id; u32 size}` tags back from the received size, big-endian for
210/// GigE Vision) and by the vendor corpus's 32-bit `<ChunkID>`s such as
211/// FLIR's `0x0508000E` (ADR-0026). `payload` must end where the camera's data
212/// ends — the received length, not a buffer sized from `PayloadSize`.
213///
214/// Remote input: a tag that claims more than precedes it, or a front too
215/// short for a tag, is an error naming the offset. A zero-length chunk is a
216/// chunk; the scan still moves back by its tag, so it cannot loop.
217pub fn parse_chunks(payload: &[u8]) -> Result<Vec<ChunkRaw<'_>>, ChunkError> {
218    let mut chunks = Vec::new();
219    let mut end = payload.len();
220    while end > 0 {
221        let tag_offset = end
222            .checked_sub(CHUNK_TAG_LEN)
223            .ok_or(ChunkError::TruncatedTag { remaining: end })?;
224        let tag = &payload[tag_offset..end];
225        let id = u32::from_be_bytes([tag[0], tag[1], tag[2], tag[3]]);
226        let length = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
227        let start = tag_offset
228            .checked_sub(length as usize)
229            .ok_or(ChunkError::LengthPastStart {
230                id,
231                tag_offset,
232                length,
233            })?;
234        chunks.push(ChunkRaw {
235            id,
236            offset: start,
237            data: &payload[start..tag_offset],
238        });
239        end = start;
240    }
241    chunks.reverse();
242    Ok(chunks)
243}
244
245/// The header every GVSP packet starts with, in either layout.
246///
247/// | Bytes | Standard (8)        | Extended ids (20)           |
248/// |-------|---------------------|-----------------------------|
249/// | 0–1   | status              | status                      |
250/// | 2–3   | block id (16 bits)  | flags                       |
251/// | 4     | packet format       | `0x80` \| packet format     |
252/// | 5–7   | packet id (24 bits) | unused                      |
253/// | 8–15  |                     | block id (64 bits)          |
254/// | 16–19 |                     | packet id (32 bits)         |
255///
256/// The extended layout is corroborated by aravis's `ArvGvspExtendedHeader` and
257/// by a LUCID TRT009S-E capture, whose bytes 2–3 and 5–7 are zero (the
258/// `lucid_evt30_*` tests below).
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub struct GvspHeader {
261    /// Status word, raw: decode it with [`GigeStatus`](crate::GigeStatus).
262    /// Bit 15 marks an error (aravis `arv_gvsp_packet_status_is_error`);
263    /// `0x0100` flags a resent packet.
264    pub status: u16,
265    /// Block id: 16 bits widened, or the 64-bit extended id.
266    pub block_id: u64,
267    /// Packet id: 24 bits widened, or the 32-bit extended id.
268    pub packet_id: u32,
269    /// Whether the packet carries the 20-byte extended-ID header.
270    pub extended_ids: bool,
271    /// Bytes of header before the packet's own data: 8 or 20.
272    pub header_len: usize,
273}
274
275/// Image fields of a leader whose payload type is an image.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub struct ImageLeader {
278    /// PFNC pixel format code.
279    pub pixel_format: u32,
280    /// Size X in pixels.
281    pub width: u32,
282    /// Size Y in lines.
283    pub height: u32,
284    /// Offset X.
285    pub offset_x: u32,
286    /// Offset Y.
287    pub offset_y: u32,
288    /// Bytes of padding at the end of each line.
289    pub padding_x: u16,
290    /// Bytes of padding at the end of the image.
291    pub padding_y: u16,
292}
293
294/// The fields of a data leader.
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296pub struct GvspLeader {
297    /// The full 16-bit payload type, chunk flag included (TC-05).
298    pub payload_type: u16,
299    /// Device timestamp.
300    pub timestamp: u64,
301    /// Image fields; `None` for a payload type that is not an image, whose
302    /// leader has a different layout.
303    pub image: Option<ImageLeader>,
304}
305
306/// The fields of a data trailer.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct GvspTrailer {
309    /// Payload type the trailer closes, chunk flag included.
310    pub payload_type: u16,
311    /// Size Y for an image: the lines the block delivered. For a chunk-data
312    /// block (`0x0004`) the same field is the payload data length.
313    pub size_y: u32,
314    /// With the chunk flag (`0x4000`), the chunk data payload length the
315    /// trailer reports after its 8 bytes; `None` without one.
316    pub chunk_payload_length: Option<u32>,
317    /// With the chunk flag, the chunk layout ID: the device changes it when
318    /// the set or position of chunks changes, so a receiver may cache a
319    /// layout while it holds.
320    pub chunk_layout_id: Option<u32>,
321}
322
323/// What a GVSP packet carries after its header.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325#[non_exhaustive]
326pub enum GvspContent<'a> {
327    /// Data leader (packet id 0).
328    Leader(GvspLeader),
329    /// Generic data payload, borrowed from the datagram.
330    Payload(&'a [u8]),
331    /// Data trailer.
332    Trailer(GvspTrailer),
333    /// A packet format this crate does not assemble: all-in (`0x04`),
334    /// H.264 (`0x05`), multi-zone (`0x06`), multipart (`0x07`), GenDC (`0x08`)
335    /// or anything else. Kept as a value so a receiver can count it rather than
336    /// lose it as a parse error.
337    Unsupported {
338        /// The packet-format nibble.
339        packet_format: u8,
340    },
341}
342
343/// A GVSP packet borrowing the datagram it was parsed from.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct GvspPacketRef<'a> {
346    /// The header.
347    pub header: GvspHeader,
348    /// What follows it.
349    pub content: GvspContent<'a>,
350}
351
352/// Parse one GVSP datagram without copying it.
353///
354/// Fails only on a datagram too short for the header its own flag announces,
355/// or for the fixed fields of a leader or trailer.
356pub fn parse_packet_ref(datagram: &[u8]) -> Result<GvspPacketRef<'_>, GvspError> {
357    let header = parse_header(datagram)?;
358    let packet_format = datagram[4] & 0x0F;
359    let body = &datagram[header.header_len..];
360    let content = match packet_format {
361        FORMAT_LEADER => GvspContent::Leader(parse_leader(body)?),
362        FORMAT_PAYLOAD => GvspContent::Payload(body),
363        FORMAT_TRAILER => GvspContent::Trailer(parse_trailer(header.block_id, body)?),
364        other => GvspContent::Unsupported {
365            packet_format: other,
366        },
367    };
368    Ok(GvspPacketRef { header, content })
369}
370
371/// Parse only the header of a GVSP datagram.
372///
373/// What a packet that carries nothing else needs: a device answering a resend
374/// request it cannot serve sends a bare header with an error status, which
375/// [`parse_packet_ref`] would refuse as a truncated leader or trailer.
376pub fn parse_header(datagram: &[u8]) -> Result<GvspHeader, GvspError> {
377    if datagram.len() < GVSP_HEADER_SIZE {
378        return Err(GvspError::Invalid("GVSP header truncated"));
379    }
380    let status = u16::from_be_bytes([datagram[0], datagram[1]]);
381    let format_byte = datagram[4];
382    let extended_ids = format_byte & EXTENDED_ID_FLAG != 0;
383
384    let header = if extended_ids {
385        if datagram.len() < GVSP_EXTENDED_HEADER_SIZE {
386            return Err(GvspError::Invalid("extended GVSP header truncated"));
387        }
388        let mut block = [0u8; 8];
389        block.copy_from_slice(&datagram[8..16]);
390        GvspHeader {
391            status,
392            block_id: u64::from_be_bytes(block),
393            packet_id: u32::from_be_bytes([datagram[16], datagram[17], datagram[18], datagram[19]]),
394            extended_ids,
395            header_len: GVSP_EXTENDED_HEADER_SIZE,
396        }
397    } else {
398        GvspHeader {
399            status,
400            block_id: u64::from(u16::from_be_bytes([datagram[2], datagram[3]])),
401            packet_id: u32::from_be_bytes([0, datagram[5], datagram[6], datagram[7]]),
402            extended_ids,
403            header_len: GVSP_HEADER_SIZE,
404        }
405    };
406    Ok(header)
407}
408
409/// Parse a data leader's payload.
410///
411/// | Offset | Size | Field        |
412/// |--------|------|--------------|
413/// |      0 |    2 | Reserved     |
414/// |      2 |    2 | Payload type |
415/// |      4 |    8 | Timestamp    |
416/// |     12 |    4 | Pixel format |
417/// |     16 |    4 | Size X       |
418/// |     20 |    4 | Size Y       |
419/// |     24 |    4 | Offset X     |
420/// |     28 |    4 | Offset Y     |
421/// |     32 |    2 | Padding X    |
422/// |     34 |    2 | Padding Y    |
423///
424/// Offsets and padding are optional: a leader that stops after Size Y still
425/// describes its image, so it is read with zeros there rather than refused.
426fn parse_leader(body: &[u8]) -> Result<GvspLeader, GvspError> {
427    if body.len() < 12 {
428        return Err(GvspError::Invalid("leader payload truncated"));
429    }
430    let mut cursor = body;
431    let _reserved = cursor.get_u16();
432    let payload_type = cursor.get_u16();
433    let timestamp = cursor.get_u64();
434    let image = if is_image_payload(payload_type) {
435        if cursor.len() < 12 {
436            return Err(GvspError::Invalid("image leader truncated"));
437        }
438        let pixel_format = cursor.get_u32();
439        let width = cursor.get_u32();
440        let height = cursor.get_u32();
441        let (offset_x, offset_y) = if cursor.len() >= 8 {
442            (cursor.get_u32(), cursor.get_u32())
443        } else {
444            (0, 0)
445        };
446        let (padding_x, padding_y) = if cursor.len() >= 4 {
447            (cursor.get_u16(), cursor.get_u16())
448        } else {
449            (0, 0)
450        };
451        Some(ImageLeader {
452            pixel_format,
453            width,
454            height,
455            offset_x,
456            offset_y,
457            padding_x,
458            padding_y,
459        })
460    } else {
461        None
462    };
463    Ok(GvspLeader {
464        payload_type,
465        timestamp,
466        image,
467    })
468}
469
470/// Parse a data trailer's payload.
471///
472/// | Offset | Size | Field                                         |
473/// |--------|------|-----------------------------------------------|
474/// |      0 |    2 | Reserved                                      |
475/// |      2 |    2 | Payload type                                  |
476/// |      4 |    4 | Size Y (image), payload data length (`0x0004`)|
477/// |      8 |    4 | Chunk data payload length, with `0x4000`      |
478/// |     12 |    4 | Chunk layout ID, with `0x4000`                |
479///
480/// GigE Vision 1.x's extended chunk data (`0x0005`) puts the payload data
481/// length at 4, Size Y at 8 and the chunk layout ID at 12.
482///
483/// Chunk data travels in the data packets, not here: with the chunk flag set
484/// the trailer only adds the two fields at 8 and 12. Those 8 bytes used to be
485/// handed to the chunk parser as a "chunk region" (TC-06). The layout is
486/// corroborated by Wireshark's `dissect_packet_trailer` and
487/// `dissect_extra_chunk_info`; the specification is not available to us.
488///
489/// `status` comes from the packet header, not from here; the first two bytes
490/// of this payload are reserved and carry no status.
491fn parse_trailer(block_id: u64, body: &[u8]) -> Result<GvspTrailer, GvspError> {
492    if body.len() < 2 {
493        return Err(GvspError::Invalid("trailer truncated"));
494    }
495    // The specification fixes this payload at 8 bytes. A device that sends
496    // fewer still gets its frame delivered, with the fields it left out
497    // reported as zero.
498    if body.len() < 8 {
499        debug!(
500            block_id,
501            len = body.len(),
502            "trailer payload shorter than the specified 8 bytes"
503        );
504        return Ok(GvspTrailer {
505            payload_type: 0,
506            size_y: 0,
507            chunk_payload_length: None,
508            chunk_layout_id: None,
509        });
510    }
511    let mut cursor = &body[2..];
512    let payload_type = cursor.get_u16();
513    if payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_EXTENDED_CHUNK_DATA && cursor.len() >= 12 {
514        // GigE Vision 1.x: the payload data length comes first, then Size Y.
515        let length = cursor.get_u32();
516        let size_y = cursor.get_u32();
517        return Ok(GvspTrailer {
518            payload_type,
519            size_y,
520            chunk_payload_length: Some(length),
521            chunk_layout_id: Some(cursor.get_u32()),
522        });
523    }
524    let size_y = cursor.get_u32();
525    let (chunk_payload_length, chunk_layout_id) =
526        if has_extended_chunks(payload_type) && cursor.len() >= 8 {
527            (Some(cursor.get_u32()), Some(cursor.get_u32()))
528        } else {
529            (None, None)
530        };
531    Ok(GvspTrailer {
532        payload_type,
533        size_y,
534        chunk_payload_length,
535        chunk_layout_id,
536    })
537}
538
539/// Bitmap tracking received packets within a block.
540///
541/// Reusable: [`PacketBitmap::reset`] clears it for another block while keeping
542/// its allocation.
543#[derive(Debug, Clone, Default)]
544pub struct PacketBitmap {
545    words: Vec<u64>,
546    received: usize,
547    total: usize,
548}
549
550impl PacketBitmap {
551    /// Create a bitmap with the given packet capacity.
552    pub fn new(total: usize) -> Self {
553        let words = total.div_ceil(64);
554        Self {
555            words: vec![0; words],
556            received: 0,
557            total,
558        }
559    }
560
561    /// Clear every bit and track `total` packets, reusing the allocation.
562    pub fn reset(&mut self, total: usize) {
563        self.words.clear();
564        self.words.resize(total.div_ceil(64), 0);
565        self.received = 0;
566        self.total = total;
567    }
568
569    /// Grow to track at least `total` packets, keeping the bits already set.
570    pub fn grow(&mut self, total: usize) {
571        if total > self.total {
572            self.words.resize(total.div_ceil(64), 0);
573            self.total = total;
574        }
575    }
576
577    /// Packets this bitmap tracks.
578    pub fn len(&self) -> usize {
579        self.total
580    }
581
582    /// Whether the bitmap tracks no packets.
583    pub fn is_empty(&self) -> bool {
584        self.total == 0
585    }
586
587    /// Packets marked received.
588    pub fn received(&self) -> usize {
589        self.received
590    }
591
592    fn mask_for(&self, packet_id: usize) -> (usize, u64) {
593        let word = packet_id / 64;
594        let bit = packet_id % 64;
595        (word, 1u64 << bit)
596    }
597
598    /// Whether a packet index is marked received.
599    pub fn contains(&self, packet_id: usize) -> bool {
600        if packet_id >= self.total {
601            return false;
602        }
603        let (word, mask) = self.mask_for(packet_id);
604        self.words[word] & mask != 0
605    }
606
607    /// Mark a packet index as received. Returns `false` for an index already
608    /// marked or beyond the bitmap.
609    pub fn set(&mut self, packet_id: usize) -> bool {
610        if packet_id >= self.total {
611            return false;
612        }
613        let (word, mask) = self.mask_for(packet_id);
614        let entry = &mut self.words[word];
615        if *entry & mask == 0 {
616            *entry |= mask;
617            self.received += 1;
618            true
619        } else {
620            false
621        }
622    }
623
624    /// Unmark a packet index. Returns `false` for an index not marked.
625    pub fn clear(&mut self, packet_id: usize) -> bool {
626        if !self.contains(packet_id) {
627            return false;
628        }
629        let (word, mask) = self.mask_for(packet_id);
630        self.words[word] &= !mask;
631        self.received -= 1;
632        true
633    }
634
635    /// Whether the first `count` indices are all marked received.
636    pub fn first_n_complete(&self, count: usize) -> bool {
637        if count > self.total {
638            return false;
639        }
640        let full = count / 64;
641        if self.words[..full].iter().any(|w| *w != u64::MAX) {
642            return false;
643        }
644        let rest = count % 64;
645        rest == 0 || self.words[full] & ((1u64 << rest) - 1) == (1u64 << rest) - 1
646    }
647
648    /// Check whether the bitmap reports all packets received.
649    pub fn is_complete(&self) -> bool {
650        self.received == self.total
651    }
652
653    /// Return missing packet ranges as inclusive `[start, end]` indices.
654    pub fn missing_ranges(&self) -> Vec<RangeInclusive<u32>> {
655        let mut ranges = Vec::new();
656        let mut current: Option<(u32, u32)> = None;
657        for idx in 0..self.total {
658            let (word, mask) = self.mask_for(idx);
659            let present = (self.words[word] & mask) != 0;
660            match (present, current) {
661                (false, None) => current = Some((idx as u32, idx as u32)),
662                (false, Some((start, _))) => current = Some((start, idx as u32)),
663                (true, Some((start, end))) => {
664                    ranges.push(start..=end);
665                    current = None;
666                }
667                _ => {}
668            }
669        }
670        if let Some((start, end)) = current {
671            ranges.push(start..=end);
672        }
673        ranges
674    }
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680
681    /// Extended-ID leader captured from a LUCID TRT009S-E producing EVT 3.0.
682    /// Keeping this literal makes the event-stream path rest on hardware bytes,
683    /// not on a packet generated from our own interpretation.
684    #[test]
685    fn lucid_evt30_capture_uses_an_image_leader() {
686        #[rustfmt::skip]
687        const LEADER: [u8; 56] = [
688            0x00, 0x00,             // status
689            0x00, 0x00,             // 16-bit block-id compatibility field
690            0x81,                   // extended-ID leader
691            0x00, 0x00, 0x00,       // 24-bit packet-id compatibility field
692            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // block id
693            0x00, 0x00, 0x00, 0x00, // packet id
694            0x00, 0x00,             // reserved
695            0x00, 0x01,             // IMAGE payload type
696            0x00, 0x00, 0x42, 0x2d, 0x66, 0xd4, 0x39, 0xc8, // timestamp
697            0x81, 0x10, 0x0e, 0x30, // EVT 3.0 data format
698            0x00, 0x00, 0x00, 0x01, // size X
699            0x00, 0x00, 0xfa, 0x00, // size Y (64000)
700            0x00, 0x00, 0x00, 0x00, // offset X
701            0x00, 0x00, 0x00, 0x00, // offset Y
702            0x00, 0x00, 0x00, 0x00, // padding X/Y
703        ];
704
705        let packet = parse_packet_ref(&LEADER).expect("parse captured LUCID leader");
706        let GvspContent::Leader(leader) = packet.content else {
707            panic!("expected leader");
708        };
709        let image = leader.image.expect("an IMAGE leader has image fields");
710
711        assert_eq!(packet.header.block_id, 1);
712        assert_eq!(packet.header.packet_id, 0);
713        assert_eq!(packet.header.header_len, GVSP_EXTENDED_HEADER_SIZE);
714        assert_eq!(leader.payload_type, PAYLOAD_TYPE_IMAGE);
715        assert_eq!(leader.timestamp, 0x0000_422d_66d4_39c8);
716        assert_eq!(image.pixel_format, 0x8110_0e30);
717        assert_eq!((image.width, image.height), (1, 64_000));
718    }
719
720    /// Trailer paired with [`lucid_evt30_capture_uses_an_image_leader`].
721    #[test]
722    fn lucid_evt30_capture_trailer_reports_payload_bytes() {
723        #[rustfmt::skip]
724        const TRAILER: [u8; 28] = [
725            0x00, 0x00,             // status
726            0x00, 0x00,             // 16-bit block-id compatibility field
727            0x82,                   // extended-ID trailer
728            0x00, 0x00, 0x00,       // 24-bit packet-id compatibility field
729            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // block id
730            0x00, 0x00, 0x00, 0x02, // packet id
731            0x00, 0x00,             // reserved
732            0x00, 0x01,             // IMAGE payload type
733            0x00, 0x00, 0x03, 0x38, // captured payload length (824)
734        ];
735
736        let packet = parse_packet_ref(&TRAILER).expect("parse captured LUCID trailer");
737        let GvspContent::Trailer(trailer) = packet.content else {
738            panic!("expected trailer");
739        };
740
741        assert_eq!(packet.header.block_id, 1);
742        assert_eq!(packet.header.packet_id, 2);
743        assert_eq!(packet.header.status, 0);
744        assert_eq!(trailer.payload_type, PAYLOAD_TYPE_IMAGE);
745        assert_eq!(trailer.size_y, 824);
746        assert_eq!(trailer.chunk_payload_length, None);
747    }
748
749    /// The leader and trailer of one block from an Allied Vision Manta G-125B
750    /// (GigE Vision 1.2, firmware 00.01.44.28514) with `ChunkModeActive` on,
751    /// received on a socket of our own: payload type `0x0005`, GigE Vision
752    /// 1.x's extended chunk data. The leader is an image's; the trailer is
753    /// payload data length (1 245 544: the image, its tag, 40 bytes of the
754    /// camera's chunk and its tag), Size Y, chunk layout ID — the layout
755    /// Wireshark's `dissect_extended_chunk_data_trailer` reads.
756    #[test]
757    fn a_gige_vision_1_extended_chunk_block_is_an_image_with_chunks() {
758        #[rustfmt::skip]
759        const LEADER: [u8; 44] = [
760            0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00,
761            0x00, 0x01,             // reserved
762            0x00, 0x05,             // EXTENDED CHUNK DATA
763            0x00, 0x00, 0x00, 0x2e, 0xf1, 0xc1, 0x84, 0xe8, // timestamp
764            0x01, 0x08, 0x00, 0x01, // Mono8
765            0x00, 0x00, 0x05, 0x0c, // 1292
766            0x00, 0x00, 0x03, 0xc4, // 964
767            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
768            0x00, 0x00, 0x00, 0x00,
769        ];
770        #[rustfmt::skip]
771        const TRAILER: [u8; 24] = [
772            0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x03, 0x54,
773            0x00, 0x00,             // reserved
774            0x00, 0x05,             // EXTENDED CHUNK DATA
775            0x00, 0x13, 0x01, 0x68, // payload data length
776            0x00, 0x00, 0x03, 0xc4, // size Y
777            0x00, 0x00, 0x00, 0x01, // chunk layout ID
778        ];
779        let GvspContent::Leader(leader) = parse_packet_ref(&LEADER).expect("leader").content else {
780            panic!("expected a leader");
781        };
782        let image = leader.image.expect("an image leader");
783        assert_eq!(
784            (image.pixel_format, image.width, image.height),
785            (0x0108_0001, 1292, 964)
786        );
787        assert!(is_image_payload(leader.payload_type));
788        assert!(has_extended_chunks(leader.payload_type));
789
790        let GvspContent::Trailer(trailer) = parse_packet_ref(&TRAILER).expect("trailer").content
791        else {
792            panic!("expected a trailer");
793        };
794        assert_eq!(trailer.payload_type, PAYLOAD_TYPE_EXTENDED_CHUNK_DATA);
795        assert_eq!(trailer.size_y, 964);
796        assert_eq!(trailer.chunk_payload_length, Some(1_245_544));
797        assert_eq!(trailer.chunk_layout_id, Some(1));
798    }
799
800    /// A standard-header image leader with `payload_type`, written from the
801    /// field table (header 8, then reserved 2 | payload type 2 | timestamp 8 |
802    /// pixel format 4 | size x 4 | size y 4 | offsets 8 | padding 4).
803    fn golden_leader(payload_type: u16) -> Vec<u8> {
804        let mut pkt = vec![0x00, 0x00, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00];
805        pkt.extend_from_slice(&0u16.to_be_bytes());
806        pkt.extend_from_slice(&payload_type.to_be_bytes());
807        pkt.extend_from_slice(&0x0102_0304_0506_0708u64.to_be_bytes());
808        pkt.extend_from_slice(&0x0108_0001u32.to_be_bytes());
809        pkt.extend_from_slice(&640u32.to_be_bytes());
810        pkt.extend_from_slice(&480u32.to_be_bytes());
811        pkt.extend_from_slice(&[0u8; 12]);
812        pkt
813    }
814
815    /// TC-05: the payload type is 16 bits, and bit 14 flags extended chunk
816    /// data. Truncated to a byte, 0x4001 reads as 0x01 and the flag is gone.
817    #[test]
818    fn leader_keeps_the_extended_chunk_bit() {
819        let pkt = golden_leader(0x4001);
820        let GvspContent::Leader(leader) = parse_packet_ref(&pkt).expect("parse leader").content
821        else {
822            panic!("expected a leader");
823        };
824        assert_eq!(leader.payload_type, 0x4001);
825    }
826
827    /// A GVSP data trailer, assembled from the specification rather than from
828    /// what our own parser or fake camera happen to produce (ADR-0019).
829    ///
830    /// Standard header (8 bytes): `status(2) | block_id(2) | format(1) |
831    /// packet_id(3)`, then the trailer payload (8 bytes): `reserved(2) |
832    /// payload_type(2) | size_y(4)`, then whatever `extra` holds.
833    fn golden_trailer(status: u16, payload_type: u16, size_y: u32, extra: &[u8]) -> Vec<u8> {
834        let mut pkt = Vec::new();
835        pkt.extend_from_slice(&status.to_be_bytes());
836        pkt.extend_from_slice(&0x0007u16.to_be_bytes()); // block_id
837        pkt.push(0x02); // packet format: trailer
838        pkt.extend_from_slice(&[0x00, 0x00, 0x42]); // packet_id (24-bit)
839        pkt.extend_from_slice(&0u16.to_be_bytes()); // reserved
840        pkt.extend_from_slice(&payload_type.to_be_bytes());
841        pkt.extend_from_slice(&size_y.to_be_bytes());
842        pkt.extend_from_slice(extra);
843        pkt
844    }
845
846    /// The regression behind the per-frame `chunk header truncated
847    /// remaining=6` a JAI produced on issue #70: a trailer closing a plain
848    /// image block is 8 bytes — `payload_type` and `size_y` were what the old
849    /// parser reported as a truncated chunk header.
850    #[test]
851    fn a_plain_image_trailer_has_no_chunk_fields() {
852        let pkt = golden_trailer(0, PAYLOAD_TYPE_IMAGE, 1536, &[]);
853        assert_eq!(pkt.len(), 16, "8-byte header + 8-byte trailer payload");
854
855        let packet = parse_packet_ref(&pkt).expect("parse trailer");
856        let GvspContent::Trailer(trailer) = packet.content else {
857            panic!("expected a trailer");
858        };
859
860        assert_eq!(packet.header.block_id, 0x0007);
861        assert_eq!(packet.header.packet_id, 0x42);
862        assert_eq!(packet.header.status, 0);
863        assert_eq!(trailer.payload_type, 0x0001);
864        assert_eq!(trailer.size_y, 1536);
865        assert_eq!(trailer.chunk_payload_length, None);
866        assert_eq!(trailer.chunk_layout_id, None);
867    }
868
869    /// TC-06: with the chunk flag the trailer grows by two 32-bit fields —
870    /// the chunk data payload length, then the chunk layout ID (Wireshark's
871    /// `dissect_extra_chunk_info`, corroboration only). The chunks themselves
872    /// travel in the data packets; these eight bytes used to be parsed as a
873    /// chunk region.
874    #[test]
875    fn an_extended_chunk_trailer_reports_length_and_layout_id() {
876        let mut extra = Vec::new();
877        extra.extend_from_slice(&0x0004_B044u32.to_be_bytes()); // chunk payload length
878        extra.extend_from_slice(&0xC0DE_0001u32.to_be_bytes()); // chunk layout id
879        let pkt = golden_trailer(0, 0x4001, 480, &extra);
880        let GvspContent::Trailer(trailer) = parse_packet_ref(&pkt).expect("parse trailer").content
881        else {
882            panic!("expected a trailer");
883        };
884        assert_eq!(trailer.payload_type, 0x4001);
885        assert_eq!(trailer.size_y, 480);
886        assert_eq!(trailer.chunk_payload_length, Some(0x0004_B044));
887        assert_eq!(trailer.chunk_layout_id, Some(0xC0DE_0001));
888    }
889
890    /// The status word lives in the packet header, not in the trailer payload
891    /// whose first two bytes are reserved. Reading it from the payload meant
892    /// the receiver's `status != 0` frame check tested the wrong field.
893    #[test]
894    fn trailer_status_comes_from_the_packet_header() {
895        // A non-zero header status with an all-zero (reserved) payload prefix:
896        // the old code read the payload and saw success.
897        let pkt = golden_trailer(0x8004, PAYLOAD_TYPE_IMAGE, 0, &[]);
898        let packet = parse_packet_ref(&pkt).expect("parse trailer");
899        assert!(matches!(packet.content, GvspContent::Trailer(_)));
900        assert_eq!(packet.header.status, 0x8004);
901    }
902
903    #[test]
904    fn bitmap_missing_ranges_coalesce() {
905        let mut bitmap = PacketBitmap::new(10);
906        for &idx in &[0usize, 1, 5, 6, 9] {
907            bitmap.set(idx);
908        }
909        let ranges = bitmap.missing_ranges();
910        assert_eq!(ranges.len(), 2);
911        assert_eq!(ranges[0], 2..=4);
912        assert_eq!(ranges[1], 7..=8);
913    }
914
915    #[test]
916    fn bitmap_reset_and_grow_keep_their_promises() {
917        let mut bitmap = PacketBitmap::new(70);
918        assert!(bitmap.set(0) && bitmap.set(69));
919        bitmap.grow(130);
920        assert!(bitmap.contains(69), "growing keeps what was set");
921        assert_eq!(bitmap.len(), 130);
922        bitmap.reset(3);
923        assert_eq!((bitmap.len(), bitmap.received()), (3, 0));
924        assert!(!bitmap.contains(0));
925    }
926
927    #[test]
928    fn first_n_complete_checks_a_prefix() {
929        let mut bitmap = PacketBitmap::new(130);
930        for idx in 0..128 {
931            bitmap.set(idx);
932        }
933        assert!(bitmap.first_n_complete(64));
934        assert!(bitmap.first_n_complete(128));
935        assert!(!bitmap.first_n_complete(129));
936        assert!(
937            !bitmap.first_n_complete(131),
938            "beyond the bitmap is never complete"
939        );
940        assert!(bitmap.first_n_complete(0));
941    }
942
943    /// An extended-ID data packet: its data starts at byte 20, not byte 8,
944    /// and its ids come from the 64- and 32-bit fields.
945    #[test]
946    fn extended_payload_data_starts_after_the_20_byte_header() {
947        #[rustfmt::skip]
948        let pkt = [
949            0x00, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00,
950            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, // block id
951            0x00, 0x01, 0x00, 0x00,                         // packet id
952            0xAA, 0xBB, 0xCC,
953        ];
954        let packet = parse_packet_ref(&pkt).expect("parse");
955        assert_eq!(packet.header.block_id, 0x0000_0001_0000_0002);
956        assert_eq!(packet.header.packet_id, 0x0001_0000);
957        assert_eq!(packet.header.header_len, 20);
958        assert!(packet.header.extended_ids);
959        assert_eq!(packet.content, GvspContent::Payload(&[0xAA, 0xBB, 0xCC]));
960    }
961
962    /// TC-05: a leader of another payload type is a value, not an error; only
963    /// image types carry the image fields.
964    #[test]
965    fn a_non_image_leader_is_typed_not_refused() {
966        let file = golden_leader(0x0003);
967        let packet = parse_packet_ref(&file).expect("a file leader parses");
968        let GvspContent::Leader(leader) = packet.content else {
969            panic!("expected a leader");
970        };
971        assert_eq!(leader.payload_type, 0x0003);
972        assert_eq!(leader.image, None);
973
974        let chunked = golden_leader(0x4001);
975        let packet = parse_packet_ref(&chunked).expect("parse");
976        let GvspContent::Leader(leader) = packet.content else {
977            panic!("expected a leader");
978        };
979        assert!(is_image_payload(leader.payload_type));
980        assert!(has_extended_chunks(leader.payload_type));
981        let image = leader.image.expect("an image leader has image fields");
982        assert_eq!((image.width, image.height), (640, 480));
983        assert_eq!(leader.timestamp, 0x0102_0304_0506_0708);
984    }
985
986    /// Packet formats beyond leader, payload and trailer (H.264, multipart,
987    /// GenDC, ...) come back as `Unsupported` for the receiver to count.
988    #[test]
989    fn other_packet_formats_are_unsupported_values() {
990        let pkt = [0x00, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x05, 0x00];
991        let packet = parse_packet_ref(&pkt).expect("parse");
992        assert_eq!(
993            packet.content,
994            GvspContent::Unsupported {
995                packet_format: 0x07
996            }
997        );
998        assert_eq!(packet.header.packet_id, 5);
999    }
1000
1001    #[test]
1002    fn a_truncated_extended_header_is_invalid() {
1003        let pkt = [0x00, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00];
1004        assert!(matches!(parse_packet_ref(&pkt), Err(GvspError::Invalid(_))));
1005    }
1006
1007    /// A device that cannot resend a packet answers with a bare header: an
1008    /// error status, the block and the packet id. Only the header parser can
1009    /// read it; as a trailer it is truncated.
1010    #[test]
1011    fn a_bare_header_parses_on_its_own() {
1012        let bare = [0x80, 0x0C, 0x00, 0x09, 0x02, 0x00, 0x00, 0x05];
1013        let header = parse_header(&bare).expect("header");
1014        assert_eq!(
1015            crate::GigeStatus::from_raw(header.status),
1016            crate::GigeStatus::PacketUnavailable
1017        );
1018        assert_eq!((header.block_id, header.packet_id), (9, 5));
1019        assert!(parse_packet_ref(&bare).is_err());
1020    }
1021}