Skip to main content

viva_fake_gige/
gvsp.rs

1//! GVSP datagrams as a camera transmits them, and a deterministic script for
2//! damaging them.
3//!
4//! The byte layouts are written out from the GigE Vision field tables with this
5//! crate's **own** constants, never the client's (ADR-0019): a fake that
6//! borrowed `viva-gige`'s header length would agree with any mistake in it.
7//! The two layouts:
8//!
9//! | Bytes | Standard header (8)        | Extended-ID header (20)          |
10//! |-------|----------------------------|----------------------------------|
11//! | 0–1   | status                     | status                           |
12//! | 2–3   | block id (16 bits)         | flags (0)                        |
13//! | 4     | packet format              | `0x80` \| packet format          |
14//! | 5–7   | packet id (24 bits)        | 0 (unused in extended mode)      |
15//! | 8–15  | —                          | block id (64 bits)               |
16//! | 16–19 | —                          | packet id (32 bits)              |
17//!
18//! The extended layout's zero bytes 2–3 and 5–7 are what a LUCID TRT009S-E put
19//! on the wire (the capture pinned in `viva-gige`'s parser tests); aravis's
20//! `ArvGvspExtendedHeader` reads the same fields.
21//!
22//! `GevSCPSPacketSize` counts the IP datagram, so a data packet carries
23//! `packet_size − 20 (IPv4) − 8 (UDP) − header` bytes of image: 1 464 at 1 500
24//! with standard ids, 1 452 with extended ids.
25//!
26//! [`PacketScript`] reorders, repeats or drops datagrams by block and packet
27//! id, never by time, so a test that uses it behaves the same on every runner.
28
29// GVSP vocabulary, imported (ADR-0030): header sizes and payload types.
30// The packets themselves are laid out below from the specification.
31use viva_gige::{
32    GVSP_EXTENDED_HEADER_SIZE as EXTENDED_HEADER_LEN, GVSP_HEADER_SIZE as STANDARD_HEADER_LEN,
33};
34pub use viva_gige::{PAYLOAD_TYPE_CHUNK_DATA, PAYLOAD_TYPE_IMAGE};
35/// IPv4 header counted by `GevSCPSPacketSize`.
36const IPV4_HEADER_LEN: usize = 20;
37/// UDP header counted by `GevSCPSPacketSize`.
38const UDP_HEADER_LEN: usize = 8;
39
40/// Packet format: data leader.
41const FORMAT_LEADER: u8 = 0x01;
42/// Packet format: data trailer.
43const FORMAT_TRAILER: u8 = 0x02;
44/// Packet format: data payload (generic).
45const FORMAT_PAYLOAD: u8 = 0x03;
46/// Bit 7 of the packet-format byte: extended ids.
47const EXTENDED_ID_FLAG: u8 = 0x80;
48
49/// Bit 14 of the payload type: extended chunk data.
50const EXTENDED_CHUNK_FLAG: u16 = viva_gige::PAYLOAD_TYPE_EXTENDED_CHUNK;
51/// Payload type: image with extended chunk data (bit 14 set on image).
52pub const PAYLOAD_TYPE_IMAGE_EXTENDED_CHUNK: u16 = PAYLOAD_TYPE_IMAGE | EXTENDED_CHUNK_FLAG;
53/// Bits of the payload type that name the type.
54const PAYLOAD_TYPE_MASK: u16 = 0x3FFF;
55/// Payload type: GigE Vision 1.x's extended chunk data, what an Allied Vision
56/// Manta G-125B sends with chunk mode on. Its leader is an image's; its
57/// trailer is reserved | payload type | payload data length | Size Y | chunk
58/// layout ID.
59pub const PAYLOAD_TYPE_EXTENDED_CHUNK_DATA: u16 = 0x0005;
60/// A chunk's tag: its ID, then its data length, both 32-bit big-endian.
61pub(crate) const CHUNK_TAG_LEN: usize = 8;
62
63/// Lay `chunks` out as a GigE Vision chunk payload, in order: each chunk's
64/// data, then its tag — chunk ID and data length, 32-bit big-endian each.
65///
66/// Written from the layout itself, with this crate's own constants; it never
67/// calls the client's parser (ADR-0019). A receiver reads it from the end.
68/// For an image with chunks (`0x4001`) the image is the first chunk.
69pub fn chunk_payload(chunks: &[(u32, &[u8])]) -> Vec<u8> {
70    let total = chunks
71        .iter()
72        .map(|(_, data)| data.len() + CHUNK_TAG_LEN)
73        .sum();
74    let mut buf = Vec::with_capacity(total);
75    for (id, data) in chunks {
76        buf.extend_from_slice(data);
77        buf.extend_from_slice(&id.to_be_bytes());
78        buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
79    }
80    buf
81}
82
83/// Bytes an image of this format occupies on the wire, by the fake's own rule.
84///
85/// Bits 23–16 of a standard PFNC code are the pixel's bit depth, so a packed
86/// format such as `Mono12Packed` (12 bits) sends `ceil(w × h × 12 / 8)` bytes
87/// — not `w × h × bytes-per-pixel`, which no whole number satisfies. Vendor
88/// codes (bit 31 set) keep the fake's historical one byte per pixel; the EVS
89/// test streams were written around that.
90pub fn image_size(pixel_format: u32, width: u32, height: u32) -> usize {
91    let pixels = width as usize * height as usize;
92    if pixel_format & 0x8000_0000 != 0 {
93        return pixels;
94    }
95    let bits = ((pixel_format >> 16) & 0xFF) as usize;
96    if bits == 0 {
97        return pixels;
98    }
99    (pixels * bits).div_ceil(8)
100}
101
102/// What one block looks like on the wire.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct BlockSpec {
105    /// Block id; truncated to 16 bits unless `extended_ids`.
106    pub block_id: u64,
107    /// `GevSCPSPacketSize` in force.
108    pub packet_size: u32,
109    /// Send 20-byte extended-ID headers.
110    pub extended_ids: bool,
111    /// Payload type in the leader and trailer.
112    pub payload_type: u16,
113    /// PFNC code in the leader.
114    pub pixel_format: u32,
115    /// Size X in the leader.
116    pub width: u32,
117    /// Size Y in the leader.
118    pub height: u32,
119    /// Device timestamp in the leader.
120    pub timestamp: u64,
121    /// Status word of the trailer's header; 0 is success.
122    pub trailer_status: u16,
123    /// Size Y in the trailer: the lines the block actually delivered.
124    pub size_y: u32,
125    /// Chunk layout ID the trailer reports when the payload type carries the
126    /// extended chunk flag.
127    pub chunk_layout_id: u32,
128    /// Padding X in the leader: bytes after every line of the image.
129    pub padding_x: u16,
130}
131
132impl BlockSpec {
133    /// An image block with standard ids and a successful trailer.
134    pub fn image(
135        block_id: u64,
136        width: u32,
137        height: u32,
138        pixel_format: u32,
139        packet_size: u32,
140    ) -> Self {
141        Self {
142            block_id,
143            packet_size,
144            extended_ids: false,
145            payload_type: PAYLOAD_TYPE_IMAGE,
146            pixel_format,
147            width,
148            height,
149            timestamp: 0,
150            trailer_status: 0,
151            size_y: height,
152            chunk_layout_id: 0,
153            padding_x: 0,
154        }
155    }
156
157    /// A chunk-data block (`0x0004`): no image, so no geometry.
158    pub fn chunk_data(block_id: u64, packet_size: u32) -> Self {
159        Self {
160            payload_type: PAYLOAD_TYPE_CHUNK_DATA,
161            pixel_format: 0,
162            width: 0,
163            height: 0,
164            size_y: 0,
165            ..Self::image(block_id, 0, 0, 0, packet_size)
166        }
167    }
168
169    /// Whether the leader carries image geometry.
170    fn is_image(&self) -> bool {
171        matches!(
172            self.payload_type & PAYLOAD_TYPE_MASK,
173            PAYLOAD_TYPE_IMAGE | PAYLOAD_TYPE_EXTENDED_CHUNK_DATA
174        )
175    }
176
177    /// Header length this block's packets carry.
178    pub fn header_len(&self) -> usize {
179        if self.extended_ids {
180            EXTENDED_HEADER_LEN
181        } else {
182            STANDARD_HEADER_LEN
183        }
184    }
185
186    /// Image bytes one data packet carries.
187    pub fn payload_stride(&self) -> usize {
188        (self.packet_size as usize)
189            .saturating_sub(IPV4_HEADER_LEN + UDP_HEADER_LEN + self.header_len())
190    }
191}
192
193/// Which part of a block a datagram is.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum PacketKind {
196    /// Data leader (packet id 0).
197    Leader,
198    /// Data payload (packet ids 1..=n).
199    Payload,
200    /// Data trailer (packet id n + 1).
201    Trailer,
202}
203
204/// One GVSP datagram, labelled for scripting.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Datagram {
207    /// Block the datagram belongs to.
208    pub block_id: u64,
209    /// Its packet id.
210    pub packet_id: u32,
211    /// Leader, payload or trailer.
212    pub kind: PacketKind,
213    /// The UDP payload exactly as sent.
214    pub bytes: Vec<u8>,
215}
216
217fn put_header(buf: &mut Vec<u8>, spec: &BlockSpec, status: u16, format: u8, packet_id: u32) {
218    buf.extend_from_slice(&status.to_be_bytes());
219    if spec.extended_ids {
220        buf.extend_from_slice(&0u16.to_be_bytes()); // flags
221        buf.push(EXTENDED_ID_FLAG | format);
222        buf.extend_from_slice(&[0, 0, 0]); // unused 24-bit packet id
223        buf.extend_from_slice(&spec.block_id.to_be_bytes());
224        buf.extend_from_slice(&packet_id.to_be_bytes());
225    } else {
226        buf.extend_from_slice(&(spec.block_id as u16).to_be_bytes());
227        buf.push(format);
228        let id = packet_id.to_be_bytes();
229        buf.extend_from_slice(&id[1..4]);
230    }
231}
232
233/// The leader: header, then reserved(2) | payload type(2) | timestamp(8),
234/// then for an image pixel format(4) | size x(4) | size y(4) | offset x(4) |
235/// offset y(4) | padding x(2) | padding y(2). A chunk-data leader stops after
236/// the timestamp: it has no geometry to report.
237pub fn leader(spec: &BlockSpec) -> Vec<u8> {
238    let mut buf = Vec::with_capacity(spec.header_len() + 36);
239    put_header(&mut buf, spec, 0, FORMAT_LEADER, 0);
240    buf.extend_from_slice(&0u16.to_be_bytes());
241    buf.extend_from_slice(&spec.payload_type.to_be_bytes());
242    buf.extend_from_slice(&spec.timestamp.to_be_bytes());
243    if !spec.is_image() {
244        return buf;
245    }
246    buf.extend_from_slice(&spec.pixel_format.to_be_bytes());
247    buf.extend_from_slice(&spec.width.to_be_bytes());
248    buf.extend_from_slice(&spec.height.to_be_bytes());
249    buf.extend_from_slice(&0u32.to_be_bytes()); // offset x
250    buf.extend_from_slice(&0u32.to_be_bytes()); // offset y
251    buf.extend_from_slice(&spec.padding_x.to_be_bytes()); // padding x
252    buf.extend_from_slice(&0u16.to_be_bytes()); // padding y
253    buf
254}
255
256/// A data packet: header, then image bytes.
257pub fn payload(spec: &BlockSpec, packet_id: u32, data: &[u8]) -> Vec<u8> {
258    let mut buf = Vec::with_capacity(spec.header_len() + data.len());
259    put_header(&mut buf, spec, 0, FORMAT_PAYLOAD, packet_id);
260    buf.extend_from_slice(data);
261    buf
262}
263
264/// The trailer: header (carrying `trailer_status`), then reserved(2) |
265/// payload type(2) | size y(4) — for chunk data, the payload length in that
266/// field — and, with the extended chunk flag, chunk payload length(4) | chunk
267/// layout id(4). The chunks themselves travel in the data packets.
268pub fn trailer(spec: &BlockSpec, packet_id: u32, payload_len: usize) -> Vec<u8> {
269    let mut buf = Vec::with_capacity(spec.header_len() + 16);
270    put_header(
271        &mut buf,
272        spec,
273        spec.trailer_status,
274        FORMAT_TRAILER,
275        packet_id,
276    );
277    buf.extend_from_slice(&0u16.to_be_bytes());
278    buf.extend_from_slice(&spec.payload_type.to_be_bytes());
279    if spec.payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_EXTENDED_CHUNK_DATA {
280        buf.extend_from_slice(&(payload_len as u32).to_be_bytes());
281        buf.extend_from_slice(&spec.size_y.to_be_bytes());
282        buf.extend_from_slice(&spec.chunk_layout_id.to_be_bytes());
283        return buf;
284    }
285    let size_field = if spec.payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_CHUNK_DATA {
286        payload_len as u32
287    } else {
288        spec.size_y
289    };
290    buf.extend_from_slice(&size_field.to_be_bytes());
291    if spec.payload_type & EXTENDED_CHUNK_FLAG != 0 {
292        buf.extend_from_slice(&(payload_len as u32).to_be_bytes());
293        buf.extend_from_slice(&spec.chunk_layout_id.to_be_bytes());
294    }
295    buf
296}
297
298/// A GVSP packet that is a header and nothing else, carrying `status`: how
299/// the fake answers a resend request it cannot serve. The packet format is
300/// generic payload, the block and packet ids those of the first packet asked
301/// for.
302pub fn header_only(block_id: u64, extended_ids: bool, packet_id: u32, status: u16) -> Vec<u8> {
303    let mut spec = BlockSpec::image(block_id, 0, 0, 0, 0);
304    spec.extended_ids = extended_ids;
305    let mut buf = Vec::with_capacity(spec.header_len());
306    put_header(&mut buf, &spec, status, FORMAT_PAYLOAD, packet_id);
307    buf
308}
309
310/// Every datagram of one block in transmission order: the leader, `payload`
311/// split at the block's stride — an image, or a [`chunk_payload`] — and the
312/// trailer.
313pub fn block_datagrams(spec: &BlockSpec, data: &[u8]) -> Vec<Datagram> {
314    let stride = spec.payload_stride().max(1);
315    let mut out = Vec::with_capacity(data.len() / stride + 3);
316    out.push(Datagram {
317        block_id: spec.block_id,
318        packet_id: 0,
319        kind: PacketKind::Leader,
320        bytes: leader(spec),
321    });
322    let mut packet_id = 1u32;
323    for piece in data.chunks(stride) {
324        out.push(Datagram {
325            block_id: spec.block_id,
326            packet_id,
327            kind: PacketKind::Payload,
328            bytes: payload(spec, packet_id, piece),
329        });
330        packet_id += 1;
331    }
332    out.push(Datagram {
333        block_id: spec.block_id,
334        packet_id,
335        kind: PacketKind::Trailer,
336        bytes: trailer(spec, packet_id, data.len()),
337    });
338    out
339}
340
341/// One deterministic change to the datagrams of a block.
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343#[non_exhaustive]
344pub enum ScriptStep {
345    /// Never send packet `packet` of `block`.
346    Drop {
347        /// Block id.
348        block: u64,
349        /// Packet id.
350        packet: u32,
351    },
352    /// Send nothing of `block`.
353    DropBlock {
354        /// Block id.
355        block: u64,
356    },
357    /// Send packet `packet` of `block` twice in a row.
358    Duplicate {
359        /// Block id.
360        block: u64,
361        /// Packet id.
362        packet: u32,
363    },
364    /// Send packet `packet` of `block` after `by` more of the block's datagrams.
365    Delay {
366        /// Block id.
367        block: u64,
368        /// Packet id.
369        packet: u32,
370        /// How many datagrams overtake it.
371        by: usize,
372    },
373    /// Send the trailer of `block` just before its last payload packet.
374    TrailerBeforeLastPayload {
375        /// Block id.
376        block: u64,
377    },
378    /// Send the leader of `block` again after its payload packet `after`.
379    RepeatLeader {
380        /// Block id.
381        block: u64,
382        /// Payload packet id the repeat follows.
383        after: u32,
384    },
385    /// Alternate the datagrams of `block` with those of the next block.
386    ///
387    /// Only the live sender acts on this; [`PacketScript::apply`] sees one
388    /// block at a time. Tests driving datagrams themselves call [`interleave`].
389    Interleave {
390        /// Block id of the first of the two blocks.
391        block: u64,
392    },
393}
394
395/// A deterministic list of [`ScriptStep`]s, keyed by block and packet id.
396#[derive(Debug, Clone, Default, PartialEq, Eq)]
397pub struct PacketScript {
398    steps: Vec<ScriptStep>,
399}
400
401impl PacketScript {
402    /// An empty script: every datagram is sent once, in order.
403    pub fn new() -> Self {
404        Self::default()
405    }
406
407    /// Add a step.
408    pub fn step(mut self, step: ScriptStep) -> Self {
409        self.steps.push(step);
410        self
411    }
412
413    /// The steps, in the order they were added.
414    pub fn steps(&self) -> &[ScriptStep] {
415        &self.steps
416    }
417
418    /// Whether the script interleaves `block` with the block after it.
419    pub fn interleaves(&self, block: u64) -> bool {
420        self.steps
421            .iter()
422            .any(|s| matches!(s, ScriptStep::Interleave { block: b } if *b == block))
423    }
424
425    /// Apply every step that names the block of `datagrams`.
426    ///
427    /// Steps run in a fixed order whatever order they were added in: drops,
428    /// then the repeated leader, then the early trailer, then delays, then
429    /// duplicates.
430    pub fn apply(&self, mut datagrams: Vec<Datagram>) -> Vec<Datagram> {
431        let Some(block) = datagrams.first().map(|d| d.block_id) else {
432            return datagrams;
433        };
434        let mine = || self.steps.iter().filter(move |s| step_block(s) == block);
435
436        if mine().any(|s| matches!(s, ScriptStep::DropBlock { .. })) {
437            return Vec::new();
438        }
439        for step in mine() {
440            if let ScriptStep::Drop { packet, .. } = *step {
441                datagrams.retain(|d| d.packet_id != packet);
442            }
443        }
444        for step in mine() {
445            if let ScriptStep::RepeatLeader { after, .. } = *step
446                && let Some(leader) = datagrams
447                    .iter()
448                    .find(|d| d.kind == PacketKind::Leader)
449                    .cloned()
450                && let Some(pos) = datagrams
451                    .iter()
452                    .position(|d| d.kind == PacketKind::Payload && d.packet_id == after)
453            {
454                datagrams.insert(pos + 1, leader);
455            }
456        }
457        for step in mine() {
458            if let ScriptStep::TrailerBeforeLastPayload { .. } = *step
459                && let Some(t) = datagrams.iter().position(|d| d.kind == PacketKind::Trailer)
460            {
461                let trailer = datagrams.remove(t);
462                let last = datagrams
463                    .iter()
464                    .rposition(|d| d.kind == PacketKind::Payload)
465                    .unwrap_or(datagrams.len());
466                datagrams.insert(last, trailer);
467            }
468        }
469        for step in mine() {
470            if let ScriptStep::Delay { packet, by, .. } = *step
471                && let Some(pos) = datagrams.iter().position(|d| d.packet_id == packet)
472            {
473                let moved = datagrams.remove(pos);
474                let to = (pos + by).min(datagrams.len());
475                datagrams.insert(to, moved);
476            }
477        }
478        for step in mine() {
479            if let ScriptStep::Duplicate { packet, .. } = *step
480                && let Some(pos) = datagrams.iter().position(|d| d.packet_id == packet)
481            {
482                let copy = datagrams[pos].clone();
483                datagrams.insert(pos + 1, copy);
484            }
485        }
486        datagrams
487    }
488}
489
490fn step_block(step: &ScriptStep) -> u64 {
491    match *step {
492        ScriptStep::Drop { block, .. }
493        | ScriptStep::DropBlock { block }
494        | ScriptStep::Duplicate { block, .. }
495        | ScriptStep::Delay { block, .. }
496        | ScriptStep::TrailerBeforeLastPayload { block }
497        | ScriptStep::RepeatLeader { block, .. }
498        | ScriptStep::Interleave { block } => block,
499    }
500}
501
502/// Alternate two blocks' datagrams, `a` first; the longer one's tail follows.
503pub fn interleave(a: Vec<Datagram>, b: Vec<Datagram>) -> Vec<Datagram> {
504    let mut out = Vec::with_capacity(a.len() + b.len());
505    let mut a = a.into_iter();
506    let mut b = b.into_iter();
507    loop {
508        match (a.next(), b.next()) {
509            (None, None) => break,
510            (x, y) => {
511                out.extend(x);
512                out.extend(y);
513            }
514        }
515    }
516    out
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    /// Extended-ID leader bytes written out field by field, independently of
524    /// [`leader`] (ADR-0019 item 2).
525    #[test]
526    fn extended_leader_matches_the_field_table() {
527        let mut spec = BlockSpec::image(0x0102_0304_0506_0708, 2, 3, 0x0108_0001, 1500);
528        spec.extended_ids = true;
529        spec.timestamp = 0x1122_3344_5566_7788;
530        #[rustfmt::skip]
531        let expected: Vec<u8> = vec![
532            0x00, 0x00,                                     // status
533            0x00, 0x00,                                     // flags
534            0x81,                                           // EI | leader
535            0x00, 0x00, 0x00,                               // unused packet id
536            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // block id
537            0x00, 0x00, 0x00, 0x00,                         // packet id 0
538            0x00, 0x00,                                     // reserved
539            0x00, 0x01,                                     // payload type
540            0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, // timestamp
541            0x01, 0x08, 0x00, 0x01,                         // Mono8
542            0x00, 0x00, 0x00, 0x02,                         // size x
543            0x00, 0x00, 0x00, 0x03,                         // size y
544            0x00, 0x00, 0x00, 0x00,                         // offset x
545            0x00, 0x00, 0x00, 0x00,                         // offset y
546            0x00, 0x00, 0x00, 0x00,                         // padding x, y
547        ];
548        assert_eq!(leader(&spec), expected);
549    }
550
551    #[test]
552    fn extended_payload_carries_a_32_bit_packet_id_at_offset_16() {
553        let mut spec = BlockSpec::image(9, 2, 3, 0x0108_0001, 1500);
554        spec.extended_ids = true;
555        let pkt = payload(&spec, 0x0001_0203, &[0xAA, 0xBB]);
556        assert_eq!(pkt.len(), 22);
557        assert_eq!(pkt[4], 0x83);
558        assert_eq!(&pkt[8..16], &9u64.to_be_bytes());
559        assert_eq!(&pkt[16..20], &[0x00, 0x01, 0x02, 0x03]);
560        assert_eq!(&pkt[20..], &[0xAA, 0xBB]);
561    }
562
563    #[test]
564    fn a_header_only_packet_carries_its_status() {
565        assert_eq!(
566            header_only(0x1234, false, 0x0001_0203, 0x800C),
567            vec![0x80, 0x0C, 0x12, 0x34, 0x03, 0x01, 0x02, 0x03]
568        );
569        let ext = header_only(7, true, 9, 0x800C);
570        assert_eq!(ext.len(), 20);
571        assert_eq!(&ext[..5], &[0x80, 0x0C, 0x00, 0x00, 0x83]);
572        assert_eq!(&ext[8..16], &7u64.to_be_bytes());
573        assert_eq!(&ext[16..20], &9u32.to_be_bytes());
574    }
575
576    #[test]
577    fn the_stride_follows_the_header_length() {
578        let mut spec = BlockSpec::image(1, 8, 8, 0x0108_0001, 1500);
579        assert_eq!(spec.payload_stride(), 1464);
580        spec.extended_ids = true;
581        assert_eq!(spec.payload_stride(), 1452);
582    }
583
584    #[test]
585    fn packed_formats_are_sized_by_bit_depth() {
586        // Mono12Packed: 12 bits, so four pixels are six bytes.
587        assert_eq!(image_size(0x010C_0006, 4, 1), 6);
588        assert_eq!(image_size(0x010C_0006, 640, 480), 640 * 480 * 3 / 2);
589        assert_eq!(image_size(0x0108_0001, 640, 480), 640 * 480);
590        assert_eq!(image_size(0x0110_0007, 2, 2), 8); // Mono16
591        assert_eq!(image_size(0x0218_0014, 2, 2), 12); // RGB8
592        assert_eq!(image_size(0x8110_0E30, 16, 4), 64); // vendor: unchanged
593    }
594
595    fn ids(datagrams: &[Datagram]) -> Vec<u32> {
596        datagrams.iter().map(|d| d.packet_id).collect()
597    }
598
599    fn sample() -> Vec<Datagram> {
600        let spec = BlockSpec::image(5, 10, 1, 0x0108_0001, 28 + 8 + 4);
601        block_datagrams(&spec, &[0u8; 10])
602    }
603
604    #[test]
605    fn a_block_is_leader_payloads_trailer() {
606        // 10 bytes at a 4-byte stride: three payload packets.
607        assert_eq!(ids(&sample()), vec![0, 1, 2, 3, 4]);
608    }
609
610    #[test]
611    fn script_steps_act_by_packet_id() {
612        let d = || sample();
613        let s = |step| PacketScript::new().step(step);
614        assert_eq!(
615            ids(&s(ScriptStep::Drop {
616                block: 5,
617                packet: 2
618            })
619            .apply(d())),
620            vec![0, 1, 3, 4]
621        );
622        assert!(s(ScriptStep::DropBlock { block: 5 }).apply(d()).is_empty());
623        assert_eq!(
624            ids(&s(ScriptStep::Duplicate {
625                block: 5,
626                packet: 1
627            })
628            .apply(d())),
629            vec![0, 1, 1, 2, 3, 4]
630        );
631        assert_eq!(
632            ids(&s(ScriptStep::Delay {
633                block: 5,
634                packet: 1,
635                by: 2
636            })
637            .apply(d())),
638            vec![0, 2, 3, 1, 4]
639        );
640        assert_eq!(
641            ids(&s(ScriptStep::TrailerBeforeLastPayload { block: 5 }).apply(d())),
642            vec![0, 1, 2, 4, 3]
643        );
644        assert_eq!(
645            ids(&s(ScriptStep::RepeatLeader { block: 5, after: 2 }).apply(d())),
646            vec![0, 1, 2, 0, 3, 4]
647        );
648        // Another block's steps leave this one alone.
649        assert_eq!(
650            ids(&s(ScriptStep::Drop {
651                block: 6,
652                packet: 2
653            })
654            .apply(d())),
655            vec![0, 1, 2, 3, 4]
656        );
657    }
658
659    #[test]
660    fn interleave_alternates_two_blocks() {
661        let a = sample();
662        let mut b = sample();
663        for d in &mut b {
664            d.block_id = 6;
665        }
666        let merged = interleave(a, b);
667        let order: Vec<(u64, u32)> = merged.iter().map(|d| (d.block_id, d.packet_id)).collect();
668        assert_eq!(&order[..4], &[(5, 0), (6, 0), (5, 1), (6, 1)]);
669        assert_eq!(merged.len(), 10);
670    }
671
672    /// The chunk layout, byte for byte from the field description: each
673    /// chunk's data, then its 32-bit big-endian ID and length.
674    #[test]
675    fn chunk_payload_matches_the_layout() {
676        let payload = chunk_payload(&[(1, &[0xAA, 0xBB]), (0xA5A5_0100, &[1, 2, 3, 4])]);
677        #[rustfmt::skip]
678        let expected = [
679            0xAA, 0xBB,
680            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02,
681            0x01, 0x02, 0x03, 0x04,
682            0xA5, 0xA5, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04,
683        ];
684        assert_eq!(payload, expected);
685    }
686
687    /// With the chunk flag, the trailer adds the chunk payload length and the
688    /// layout ID after its 8 bytes; a chunk-data leader stops at the
689    /// timestamp, with no geometry.
690    #[test]
691    fn chunk_flavoured_leader_and_trailer_match_the_field_table() {
692        let mut spec = BlockSpec::image(9, 4, 2, 0x0108_0001, 576);
693        spec.payload_type = PAYLOAD_TYPE_IMAGE_EXTENDED_CHUNK;
694        spec.chunk_layout_id = 0x1234_5678;
695        let t = trailer(&spec, 3, 44);
696        assert_eq!(
697            &t[8..],
698            &[
699                0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2C, 0x12, 0x34,
700                0x56, 0x78
701            ]
702        );
703
704        let spec = BlockSpec::chunk_data(9, 576);
705        assert_eq!(
706            leader(&spec).len(),
707            8 + 12,
708            "reserved, payload type, timestamp"
709        );
710        let t = trailer(&spec, 3, 44);
711        assert_eq!(
712            &t[8..],
713            &[0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x2C],
714            "a chunk-data trailer reports the payload length where an image has Size Y"
715        );
716    }
717}