1use 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};
35const IPV4_HEADER_LEN: usize = 20;
37const UDP_HEADER_LEN: usize = 8;
39
40const FORMAT_LEADER: u8 = 0x01;
42const FORMAT_TRAILER: u8 = 0x02;
44const FORMAT_PAYLOAD: u8 = 0x03;
46const EXTENDED_ID_FLAG: u8 = 0x80;
48
49const EXTENDED_CHUNK_FLAG: u16 = viva_gige::PAYLOAD_TYPE_EXTENDED_CHUNK;
51pub const PAYLOAD_TYPE_IMAGE_EXTENDED_CHUNK: u16 = PAYLOAD_TYPE_IMAGE | EXTENDED_CHUNK_FLAG;
53const PAYLOAD_TYPE_MASK: u16 = 0x3FFF;
55pub const PAYLOAD_TYPE_EXTENDED_CHUNK_DATA: u16 = 0x0005;
60pub(crate) const CHUNK_TAG_LEN: usize = 8;
62
63pub 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
83pub 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#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct BlockSpec {
105 pub block_id: u64,
107 pub packet_size: u32,
109 pub extended_ids: bool,
111 pub payload_type: u16,
113 pub pixel_format: u32,
115 pub width: u32,
117 pub height: u32,
119 pub timestamp: u64,
121 pub trailer_status: u16,
123 pub size_y: u32,
125 pub chunk_layout_id: u32,
128 pub padding_x: u16,
130}
131
132impl BlockSpec {
133 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum PacketKind {
196 Leader,
198 Payload,
200 Trailer,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Datagram {
207 pub block_id: u64,
209 pub packet_id: u32,
211 pub kind: PacketKind,
213 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()); buf.push(EXTENDED_ID_FLAG | format);
222 buf.extend_from_slice(&[0, 0, 0]); 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
233pub 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()); buf.extend_from_slice(&0u32.to_be_bytes()); buf.extend_from_slice(&spec.padding_x.to_be_bytes()); buf.extend_from_slice(&0u16.to_be_bytes()); buf
254}
255
256pub 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
264pub 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
298pub 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
310pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343#[non_exhaustive]
344pub enum ScriptStep {
345 Drop {
347 block: u64,
349 packet: u32,
351 },
352 DropBlock {
354 block: u64,
356 },
357 Duplicate {
359 block: u64,
361 packet: u32,
363 },
364 Delay {
366 block: u64,
368 packet: u32,
370 by: usize,
372 },
373 TrailerBeforeLastPayload {
375 block: u64,
377 },
378 RepeatLeader {
380 block: u64,
382 after: u32,
384 },
385 Interleave {
390 block: u64,
392 },
393}
394
395#[derive(Debug, Clone, Default, PartialEq, Eq)]
397pub struct PacketScript {
398 steps: Vec<ScriptStep>,
399}
400
401impl PacketScript {
402 pub fn new() -> Self {
404 Self::default()
405 }
406
407 pub fn step(mut self, step: ScriptStep) -> Self {
409 self.steps.push(step);
410 self
411 }
412
413 pub fn steps(&self) -> &[ScriptStep] {
415 &self.steps
416 }
417
418 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 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
502pub 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 #[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, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x01, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
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 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); assert_eq!(image_size(0x0218_0014, 2, 2), 12); assert_eq!(image_size(0x8110_0E30, 16, 4), 64); }
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 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 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 #[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 #[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}