Skip to main content

viva_genicam/stream/
mod.rs

1//! GVSP streaming: control-plane setup and the receive engine.
2//!
3//! [`StreamBuilder`] negotiates the stream with the camera (destination,
4//! packet size, delay) and binds the socket. [`FrameStream`] runs the receive
5//! engine on it (ADR-0025): one thread per stream reads the socket, assembles
6//! blocks — reordered, interleaved, with extended ids — and hands complete
7//! frames to the application through a small drop-oldest queue, counting
8//! everything it sees in [`StreamStats`].
9//!
10//! ```rust,ignore
11//! let mut frames = FrameStream::new(stream, None);
12//! while let Some(frame) = frames.next_frame().await? {
13//!     println!("{}x{} frame {}", frame.width, frame.height, frame.block_id);
14//! }
15//! ```
16
17mod assembly;
18#[cfg(fuzzing)]
19mod fuzzing;
20mod receiver;
21mod resend;
22mod stats;
23#[cfg(feature = "u3v")]
24mod u3v;
25
26#[cfg(fuzzing)]
27#[doc(hidden)]
28pub use fuzzing::fuzz_assemble;
29
30pub use stats::{StreamStats, StreamStatsAccumulator};
31#[cfg(feature = "u3v")]
32pub use u3v::{U3vFrameStream, U3vStreamBuilder};
33
34/// The queue a USB3 Vision event reader hands events through.
35#[cfg(feature = "u3v")]
36pub(crate) type EventQueue = receiver::DeliveryQueue<crate::events::Event, viva_u3v::U3vError>;
37/// What a pop from an [`EventQueue`] found.
38#[cfg(feature = "u3v")]
39pub(crate) type EventPopped = receiver::Popped<crate::events::Event, viva_u3v::U3vError>;
40
41use std::net::{IpAddr, Ipv4Addr, SocketAddr};
42use std::sync::Arc;
43use std::thread::JoinHandle;
44use std::time::{Duration, SystemTime};
45
46use bytes::Bytes;
47use tokio::net::UdpSocket;
48// Used by the packet-size probe, which runs on the tokio socket before the
49// receive thread takes it over.
50use tokio::time::timeout;
51use tracing::{debug, info, warn};
52use viva_pfnc::PixelFormat;
53
54use crate::GenicamError;
55use crate::chunks::ChunkError;
56use crate::error::{gige, network};
57use crate::evs::EvsBlock;
58use crate::frame::{Frame, FrameStatus};
59use assembly::AssembledBlock;
60use receiver::{Popped, Shared};
61use viva_gige::GigeError;
62use viva_gige::StreamConfig;
63use viva_gige::TimeSync;
64use viva_gige::{DEFAULT_RCVBUF_BYTES, Iface, McOptions};
65use viva_gige::{GigeDevice, StreamParams};
66
67pub use viva_gige::StreamDest;
68
69/// The semantic payload carried by one complete GVSP block.
70#[derive(Debug, Clone)]
71#[non_exhaustive]
72pub enum StreamBlock {
73    /// A conventional image payload.
74    Image(Frame),
75    /// A LUCID event-vision payload encoded as EVT 2.1 or EVT 3.0.
76    Evs(EvsBlock),
77}
78
79/// An opaque complete GVSP block with common metadata accessors.
80///
81/// Convert this value into [`StreamBlock`] to inspect the image- or EVS-specific
82/// representation. Keeping the inner field private leaves room for adding
83/// common behavior without exposing storage details here.
84#[derive(Debug, Clone)]
85pub struct GenericStreamBlock {
86    inner: StreamBlock,
87    /// When the block's last packet arrived, for the frame rate.
88    completed: Option<std::time::Instant>,
89}
90
91impl From<GenericStreamBlock> for StreamBlock {
92    fn from(value: GenericStreamBlock) -> Self {
93        value.inner
94    }
95}
96
97impl GenericStreamBlock {
98    /// Borrow the complete application payload.
99    pub fn payload(&self) -> &Bytes {
100        match &self.inner {
101            StreamBlock::Image(frame) => &frame.payload,
102            StreamBlock::Evs(block) => &block.payload,
103        }
104    }
105
106    /// Host-correlated timestamp, when time synchronization is available.
107    pub fn host_time(&self) -> Option<SystemTime> {
108        match &self.inner {
109            StreamBlock::Image(frame) => frame.ts_host,
110            StreamBlock::Evs(block) => block.ts_host,
111        }
112    }
113
114    /// Image width, or `None` for a payload without image geometry.
115    pub fn width(&self) -> Option<u32> {
116        match &self.inner {
117            StreamBlock::Image(frame) => Some(frame.width),
118            StreamBlock::Evs(_) => None,
119        }
120    }
121
122    /// Image height, or `None` for a payload without image geometry.
123    pub fn height(&self) -> Option<u32> {
124        match &self.inner {
125            StreamBlock::Image(frame) => Some(frame.height),
126            StreamBlock::Evs(_) => None,
127        }
128    }
129
130    /// Block id from the transport.
131    pub fn block_id(&self) -> u64 {
132        match &self.inner {
133            StreamBlock::Image(frame) => frame.block_id,
134            StreamBlock::Evs(block) => block.block_id,
135        }
136    }
137
138    /// How the block ended. Only [`FrameStatus::Complete`] blocks are
139    /// delivered unless the stream was asked for incomplete ones.
140    pub fn status(&self) -> FrameStatus {
141        match &self.inner {
142            StreamBlock::Image(frame) => frame.status,
143            StreamBlock::Evs(block) => block.status,
144        }
145    }
146
147    fn device_timestamp(&self) -> Option<u64> {
148        match &self.inner {
149            StreamBlock::Image(frame) => frame.ts_dev,
150            StreamBlock::Evs(block) => block.ts_dev,
151        }
152    }
153
154    fn set_host_time(&mut self, timestamp: Option<SystemTime>) {
155        match &mut self.inner {
156            StreamBlock::Image(frame) => frame.ts_host = timestamp,
157            StreamBlock::Evs(block) => block.ts_host = timestamp,
158        }
159    }
160
161    fn into_legacy_frame(self) -> Frame {
162        match self.inner {
163            StreamBlock::Image(frame) => frame,
164            StreamBlock::Evs(block) => {
165                let mut frame = Frame::new(
166                    block.payload,
167                    block.leader_size_x,
168                    block.leader_size_y,
169                    block.format.pixel_format(),
170                );
171                frame.chunks = block.chunks;
172                frame.ts_dev = block.ts_dev;
173                frame.ts_host = block.ts_host;
174                frame.block_id = block.block_id;
175                frame.status = block.status;
176                frame
177            }
178        }
179    }
180}
181
182/// Turn an assembled block into the application's view of it: event data for
183/// the LUCID EVT formats, an image frame otherwise.
184///
185/// A complete block whose payload type carries chunks is split into its image
186/// and its chunks (TC-06); a chunk layout that does not parse is returned
187/// alongside, so the receive thread can say so, and the block keeps its bytes.
188/// An incomplete block is not split: its missing packets are zeros, and zeros
189/// read as tags would invent chunks.
190fn classify_completed_block(block: AssembledBlock) -> (GenericStreamBlock, Option<ChunkError>) {
191    let raw_payload = block.payload.clone();
192    let (payload, chunks) = if block.status.is_complete() {
193        crate::chunks::split(block.payload, block.payload_type)
194    } else {
195        (block.payload, None)
196    };
197    let (chunks, chunk_error) = match chunks {
198        Some(Ok(chunks)) => (Some(chunks), None),
199        Some(Err(err)) => (None, Some(err)),
200        None => (None, None),
201    };
202    let (width, height, pixel_format, ts_dev, padding_x) = match block.leader {
203        Some(leader) => (
204            leader.width,
205            leader.height,
206            PixelFormat::from_code(leader.pixel_format),
207            Some(leader.timestamp),
208            leader.padding_x,
209        ),
210        None => (0, 0, PixelFormat::Unknown(0), None, 0),
211    };
212    let evs = match pixel_format {
213        PixelFormat::VendorLucidEvsEvt30 => Some(crate::evs::EvsFormat::Evt30),
214        PixelFormat::VendorLucidEvsEvt21 => Some(crate::evs::EvsFormat::Evt21),
215        _ => None,
216    };
217    let inner = match evs {
218        Some(format) => StreamBlock::Evs(EvsBlock {
219            payload,
220            format,
221            ts_dev,
222            leader_size_x: width,
223            leader_size_y: height,
224            trailer_size_y: block.trailer_size_y.unwrap_or(0),
225            chunks,
226            ts_host: None,
227            block_id: block.block_id,
228            status: block.status,
229        }),
230        None => {
231            let mut frame = Frame::new(payload, width, height, pixel_format);
232            frame.raw_payload = raw_payload;
233            frame.padding_x = padding_x;
234            frame.chunks = chunks;
235            frame.ts_dev = ts_dev;
236            frame.block_id = block.block_id;
237            frame.payload_type = block.payload_type;
238            frame.status = block.status;
239            // A chunk-data trailer's Size Y is the payload length, not lines.
240            frame.delivered_height = block
241                .trailer_size_y
242                .filter(|_| viva_gige::is_image_payload(block.payload_type));
243            frame.expected_size = block.expected_size;
244            StreamBlock::Image(frame)
245        }
246    };
247    let completed = Some(block.last_packet);
248    (GenericStreamBlock { inner, completed }, chunk_error)
249}
250
251/// Smallest GVSP packet size we will configure: the IPv4 minimum reassembly
252/// buffer.
253const MIN_PACKET_SIZE: u32 = 576;
254
255/// Largest GVSP packet size we will configure.
256///
257/// Both bounds bite at once: an IPv4 datagram cannot exceed 65 535 bytes, and
258/// `GevSCPSPacketSize` holds the size in 16 bits.
259const MAX_PACKET_SIZE: u32 = viva_gige::consts::STREAM_PACKET_SIZE_MASK;
260
261/// Write `GevSCPSPacketSize`, then read it back and return what the device
262/// actually holds.
263///
264/// A camera may clamp the requested size to what it supports, and the write
265/// succeeds when it does — nothing on the wire distinguishes "accepted" from
266/// "accepted and reduced". The receive path derives every reassembly offset
267/// from [`StreamParams::packet_size`] (the payload stride), so believing the
268/// request produces a stream that carries packets and completes no frame:
269/// [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112), where a
270/// Vieworks FS3200T on a 16 114-byte link delivered zero frames on every Start
271/// and streamed correctly when forced to 1 500. Backlog SR-02.
272///
273/// The read comes first as well as last. Viva Studio rebuilds the stream on
274/// every Acquisition Start, so an unconditional write discards a working
275/// configuration once per Start; when the device already holds the size we
276/// want, the write is skipped entirely.
277///
278/// A device that will not answer the read-back is not failed — that would break
279/// streaming which works today on a camera whose only fault is refusing a
280/// READREG. It warns and keeps the requested value, which is exactly the old
281/// behaviour, now visible in the log rather than assumed.
282async fn configure_packet_size(
283    device: &mut GigeDevice,
284    channel: u32,
285    requested: u32,
286) -> Result<u32, GenicamError> {
287    if let Ok(current) = device.get_stream_packet_size(channel).await
288        && current == requested
289    {
290        debug!(
291            channel,
292            packet_size = requested,
293            "camera already holds the requested GVSP packet size; leaving it alone"
294        );
295        return Ok(requested);
296    }
297
298    device
299        .set_stream_packet_size(channel, requested)
300        .await
301        .map_err(gige("write GevSCPSPacketSize"))?;
302
303    let effective = match device.get_stream_packet_size(channel).await {
304        Ok(effective) => effective,
305        Err(err) => {
306            warn!(
307                channel,
308                packet_size = requested,
309                error = %err,
310                "could not read GevSCPSPacketSize back; assuming the requested size took effect. \
311                 If no frame completes, the camera may have clamped it — pass an explicit packet \
312                 size of 1500 to find out"
313            );
314            return Ok(requested);
315        }
316    };
317
318    if effective == requested {
319        return Ok(effective);
320    }
321
322    if effective < MIN_PACKET_SIZE {
323        warn!(
324            requested,
325            effective, "the camera reduced the GVSP packet size below the minimum"
326        );
327        return Err(GenicamError::PacketTooSmall {
328            size: effective,
329            min: MIN_PACKET_SIZE,
330        });
331    }
332
333    warn!(
334        channel,
335        requested,
336        effective,
337        "camera clamped the GVSP packet size; the receive path will follow the camera. \
338         The requested size is what the host interface MTU allows, so the camera is the \
339         narrower end of this link"
340    );
341    Ok(effective)
342}
343
344/// Packet size at or below which probing has nothing to discover, and the
345/// control size the probe uses to decide whether the device answers at all.
346///
347/// 1500 is the Ethernet default: a path that cannot carry it is broken in a way
348/// no negotiation can rescue.
349const PROBE_FLOOR: u32 = 1500;
350
351/// How long to wait for a test packet before calling the size unusable.
352const PROBE_TIMEOUT: Duration = Duration::from_millis(250);
353
354/// Find the largest packet size the network path will actually deliver.
355///
356/// `GevSCPSPacketSize` reports what the *device* stored, which is not what the
357/// *link* will carry. On the Vieworks FS3200T in
358/// [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112) the camera
359/// declares `Max=16366`, accepts and holds 16114, and streams nothing: the path
360/// tops out at a 9216-byte frame, so 9198 is the largest usable size. The
361/// reporter found that by bisecting by hand. The specification provides the
362/// mechanism to find it automatically — bit 31 asks the device for one test
363/// packet, bit 30 forbids fragmenting it — and we used neither.
364///
365/// **A device that does not implement test packets must not be punished for
366/// it.** Walking such a device down to 1500 would be a severe regression for
367/// every working jumbo link. So the probe first asks for a test packet at
368/// [`PROBE_FLOOR`], a size any functioning path carries: if *that* produces
369/// nothing, the device does not answer probes and the requested size is kept
370/// unchanged. Only a device that has demonstrably answered is allowed to talk
371/// us downwards.
372///
373/// The probe never increases the size, so an explicitly configured
374/// `--packet-size` is still a ceiling.
375///
376/// **Probing is destructive, so the answer has to be written back.** Asking for
377/// a test packet *is* a write to `GevSCPSPacketSize` — there is no separate
378/// register — so when the probe returns, the device holds the last size it was
379/// *asked about*, which is rarely the size that was chosen. Every path that
380/// probed therefore ends by configuring the negotiated value.
381///
382/// That rewrite also clears the do-not-fragment bit the probe set — except where
383/// the device already holds the negotiated size, since `configure_packet_size`
384/// skips a redundant write. The exception is the safe one: it is reachable only
385/// when a *DF-set* test packet of that size traversed the path a moment earlier,
386/// which is the evidence that leaving DF on cannot hurt.
387async fn probe_packet_size(
388    device: &mut GigeDevice,
389    channel: u32,
390    socket: &UdpSocket,
391    requested: u32,
392) -> Result<u32, GenicamError> {
393    if requested <= PROBE_FLOOR {
394        // Nothing was probed, so nothing was written and there is nothing to
395        // put back.
396        return Ok(requested);
397    }
398
399    // The test packets set do-not-fragment; whatever the register held is
400    // put back below (an Allied Vision Manta G-125B stores the flag).
401    let do_not_fragment = device.stream_do_not_fragment(channel).await.ok();
402    let negotiated = probe_path_ceiling(device, channel, socket, requested).await?;
403
404    // The register now holds the last size the probe *tested*, not `negotiated`.
405    // Both mismatches are real and neither is visible from here: a device that
406    // never answered was left at `PROBE_FLOOR`, and a bisection whose final
407    // probe failed was left one byte above its own answer -- 9199 against a
408    // negotiated 9198 on the numbers in #112, which is exactly the size that
409    // reporter measured as the first failing one. Left uncorrected, the host
410    // strides at `negotiated` while the camera sends something else, which is
411    // the SR-02 failure mode this probe was built on top of.
412    let negotiated = configure_packet_size(device, channel, negotiated).await?;
413    if let Some(on) = do_not_fragment
414        && let Err(err) = device.set_stream_do_not_fragment(channel, on).await
415    {
416        warn!(
417            channel,
418            error = %err,
419            "could not put GevSCPSPacketSize's do-not-fragment flag back after the probe"
420        );
421    }
422    Ok(negotiated)
423}
424
425/// The bisection itself: the largest size that arrives, or `requested` when the
426/// device does not answer probes at all.
427///
428/// Split out from [`probe_packet_size`] so that every early return still passes
429/// through the write-back, rather than each one having to remember it.
430async fn probe_path_ceiling(
431    device: &mut GigeDevice,
432    channel: u32,
433    socket: &UdpSocket,
434    requested: u32,
435) -> Result<u32, GenicamError> {
436    // Control probe. Establishes that this device answers at all before any
437    // negative result is allowed to mean anything.
438    if !test_packet_arrives(device, channel, socket, PROBE_FLOOR).await? {
439        debug!(
440            channel,
441            packet_size = requested,
442            "device did not answer a {PROBE_FLOOR}-byte test packet; it likely does not \
443             implement them, so the requested size stands"
444        );
445        return Ok(requested);
446    }
447
448    if test_packet_arrives(device, channel, socket, requested).await? {
449        debug!(
450            channel,
451            packet_size = requested,
452            "path carries the requested GVSP packet size"
453        );
454        return Ok(requested);
455    }
456
457    // Known good at `lo`, known bad at `hi`. Bisect to the byte: the boundary
458    // is a frame ceiling, not a round number, and landing one byte below it is
459    // the difference between a working jumbo link and 1500.
460    let (mut lo, mut hi) = (PROBE_FLOOR, requested);
461    while hi - lo > 1 {
462        let mid = lo + (hi - lo) / 2;
463        if test_packet_arrives(device, channel, socket, mid).await? {
464            lo = mid;
465        } else {
466            hi = mid;
467        }
468    }
469
470    warn!(
471        channel,
472        requested,
473        negotiated = lo,
474        "the network path did not carry a {requested}-byte GVSP test packet; negotiated down. \
475         Both the host interface and the camera accept the larger size, so the limit is the \
476         link between them"
477    );
478    Ok(lo)
479}
480
481/// Ask for one test packet of `size` and report whether it arrived.
482async fn test_packet_arrives(
483    device: &mut GigeDevice,
484    channel: u32,
485    socket: &UdpSocket,
486    size: u32,
487) -> Result<bool, GenicamError> {
488    // Discard anything already queued, so a previous probe's late arrival
489    // cannot be counted as this one's answer.
490    let mut scratch = [0u8; 2048];
491    while socket.try_recv_from(&mut scratch).is_ok() {}
492
493    device
494        .request_test_packet(channel, size)
495        .await
496        .map_err(gige("request a test packet"))?;
497
498    let mut buf = vec![0u8; size as usize + 64];
499    match timeout(PROBE_TIMEOUT, socket.recv_from(&mut buf)).await {
500        Ok(Ok(_)) => Ok(true),
501        // A receive error here is the socket's problem, not the path's; treat
502        // it as "no answer" rather than failing the whole stream.
503        Ok(Err(_)) | Err(_) => Ok(false),
504    }
505}
506
507/// How [`StreamBuilder`] chooses `GevSCPSPacketSize` (ADR-0021 / SR-14).
508///
509/// The variants differ only in where the *starting* size comes from. All three
510/// then hand it to the SR-13 path probe, which can lower it and never raise it,
511/// so no variant can end up above the size it began with.
512#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
513enum PacketSizeMode {
514    /// Start from the camera's current value; never write a larger one.
515    #[default]
516    Preserve,
517    /// Start from `best_packet_size(nic_mtu)`.
518    Auto,
519    /// Start from this size — a ceiling, never raised above.
520    Explicit(u32),
521}
522
523/// Whether a stream asks the camera to send lost packets again (SR-04).
524#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
525#[non_exhaustive]
526pub enum ResendPolicy {
527    /// Ask, if the camera's GVCP Capability register (`0x0934`) says it
528    /// supports `PACKETRESEND_CMD`. A multicast stream never asks.
529    #[default]
530    Auto,
531    /// Never ask.
532    Off,
533}
534
535/// Builder for configuring a GVSP stream.
536pub struct StreamBuilder<'a> {
537    device: &'a mut GigeDevice,
538    iface: Option<Iface>,
539    dest: Option<StreamDest>,
540    rcvbuf_bytes: Option<usize>,
541    target_mtu: Option<u32>,
542    packet_size_mode: PacketSizeMode,
543    packet_delay: Option<Duration>,
544    resend: ResendPolicy,
545    channel: u32,
546    dst_port: u16,
547    probe: bool,
548}
549
550impl<'a> StreamBuilder<'a> {
551    /// Create a new builder bound to an opened [`GigeDevice`].
552    ///
553    /// Default packet-size policy is **preserve**: the camera's current
554    /// `GevSCPSPacketSize` is used as-is. Call [`StreamBuilder::auto_packet_size`]
555    /// to set from the NIC MTU and path-probe, or [`StreamBuilder::packet_size`]
556    /// for an explicit ceiling (ADR-0021).
557    pub fn new(device: &'a mut GigeDevice) -> Self {
558        Self {
559            device,
560            iface: None,
561            dest: None,
562            rcvbuf_bytes: None,
563            target_mtu: None,
564            packet_size_mode: PacketSizeMode::Preserve,
565            packet_delay: None,
566            resend: ResendPolicy::Auto,
567            channel: 0,
568            dst_port: 0,
569            // On for every policy, Preserve included: the probe only lowers.
570            probe: true,
571        }
572    }
573
574    /// Whether to path-probe with a GVSP test packet before streaming
575    /// (default: on, under every packet-size policy).
576    ///
577    /// It applies under the default preserve policy too, which is not a
578    /// contradiction: the probe never *raises* a size, so it cannot override the
579    /// value an operator set. It can only decline to stream at a size the path
580    /// demonstrably drops — something no register read can discover, because
581    /// both endpoints accept it. Turning it off is what makes preserve literal.
582    ///
583    /// Turning it off restores the pre-0.4.2 behaviour: whatever
584    /// `GevSCPSPacketSize` holds is assumed to reach the host.
585    /// That is wrong on any path narrower than both endpoints
586    /// ([#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112)), so
587    /// the only good reason to disable it is a device that misbehaves when
588    /// asked for a test packet — in which case please open an issue, because
589    /// the probe is written to tolerate a device that simply ignores it.
590    pub fn probe(mut self, enable: bool) -> Self {
591        self.probe = enable;
592        self
593    }
594
595    /// Select the interface used for receiving GVSP packets.
596    pub fn iface(mut self, iface: Iface) -> Self {
597        self.iface = Some(iface);
598        self
599    }
600
601    /// Configure the stream destination.
602    pub fn dest(mut self, dest: StreamDest) -> Self {
603        self.dest = Some(dest);
604        self
605    }
606
607    /// Cap the MTU used when computing the GVSP packet size in
608    /// [`StreamBuilder::auto_packet_size`] mode.
609    ///
610    /// The interface's own MTU is still read; this only lowers the request.
611    pub fn target_mtu(mut self, mtu: u32) -> Self {
612        self.target_mtu = Some(mtu);
613        self
614    }
615
616    /// Set `GevSCPSPacketSize` from the host NIC MTU, then path-probe (SR-13).
617    ///
618    /// This is the explicit opt-in that replaces the old always-write-MTU
619    /// default (ADR-0021). It is **not** the pre-0.4 `--auto false ⇒ 1500`
620    /// behaviour.
621    pub fn auto_packet_size(mut self) -> Self {
622        self.packet_size_mode = PacketSizeMode::Auto;
623        self
624    }
625
626    /// Write this GVSP packet size (a ceiling for the path probe).
627    pub fn packet_size(mut self, size: u32) -> Self {
628        self.packet_size_mode = PacketSizeMode::Explicit(size);
629        self
630    }
631
632    /// Have the camera wait `delay` between stream packets: `GevSCPD`,
633    /// written in timestamp ticks at the frequency the camera reports
634    /// (`0x093C`/`0x0940`), rounded to the nearest tick.
635    ///
636    /// Without it `GevSCPD` is left as it is. A camera that reports no tick
637    /// frequency cannot be given a delay in time, and the build fails rather
638    /// than guess a unit.
639    pub fn packet_delay(mut self, delay: Duration) -> Self {
640        self.packet_delay = Some(delay);
641        self
642    }
643
644    /// Whether to ask the camera for lost packets (default
645    /// [`ResendPolicy::Auto`]).
646    pub fn resend(mut self, policy: ResendPolicy) -> Self {
647        self.resend = policy;
648        self
649    }
650
651    /// Receive on this UDP port, for a firewall that admits only it.
652    ///
653    /// By default the operating system picks a free port; either way the
654    /// port is written to the camera's `GevSCPHostPort`. The port is the
655    /// stream's alone: it is bound without `SO_REUSEPORT`, so a second
656    /// stream asking for the same one fails to open.
657    pub fn destination_port(mut self, port: u16) -> Self {
658        self.dst_port = port;
659        if let Some(dest) = &mut self.dest {
660            *dest = match *dest {
661                StreamDest::Unicast { dst_ip, .. } => StreamDest::Unicast {
662                    dst_ip,
663                    dst_port: port,
664                },
665                StreamDest::Multicast {
666                    group,
667                    loopback,
668                    ttl,
669                    ..
670                } => StreamDest::Multicast {
671                    group,
672                    port,
673                    loopback,
674                    ttl,
675                },
676            };
677        }
678        self
679    }
680
681    /// Configure multicast reception when the device is set to multicast mode.
682    pub fn multicast(mut self, group: Option<Ipv4Addr>) -> Self {
683        if let Some(group) = group {
684            self.dest = Some(StreamDest::Multicast {
685                group,
686                port: self.dst_port,
687                loopback: false,
688                ttl: 1,
689            });
690        } else {
691            self.dest = None;
692        }
693        self
694    }
695
696    /// Custom receive buffer size for the UDP socket.
697    pub fn rcvbuf_bytes(mut self, size: usize) -> Self {
698        self.rcvbuf_bytes = Some(size);
699        self
700    }
701
702    /// Select the GigE Vision stream channel to configure (defaults to 0).
703    ///
704    /// The build fails for a channel at or beyond the camera's
705    /// `GevNumberOfStreamChannels` (`0x0904`), before anything is written.
706    pub fn channel(mut self, channel: u32) -> Self {
707        self.channel = channel;
708        self
709    }
710
711    /// Finalise the builder and return a configured [`Stream`].
712    ///
713    /// In order: check the channel exists and that a requested packet delay
714    /// can be converted, bind the socket (port 0 unless one was asked for),
715    /// point the stream channel at it, negotiate the packet size, write
716    /// `GevSCPD` if asked, and read whether the camera supports resend.
717    pub async fn build(self) -> Result<Stream, GenicamError> {
718        let iface = self.iface.ok_or(GenicamError::NoInterface)?;
719        let host_ip = iface
720            .ipv4()
721            .ok_or_else(|| GenicamError::InterfaceWithoutIpv4(iface.name().to_string()))?;
722        let camera = self.device.remote_addr();
723        let IpAddr::V4(camera_ip) = camera.ip() else {
724            return Err(GigeError::NotIpv4("camera").into());
725        };
726
727        // Refusals first, so a refused stream has written nothing.
728        check_stream_channel(self.device, self.channel).await?;
729        let packet_delay = match self.packet_delay {
730            Some(delay) => Some(packet_delay_ticks(self.device, delay).await?),
731            None => None,
732        };
733
734        let mut dest = self.dest.unwrap_or(StreamDest::Unicast {
735            dst_ip: host_ip,
736            dst_port: self.dst_port,
737        });
738
739        let iface_mtu = viva_gige::mtu(&iface).bytes();
740        let mtu = self
741            .target_mtu
742            .map_or(iface_mtu, |limit| limit.min(iface_mtu));
743
744        // ADR-0021: default preserves the camera register. Auto writes the NIC
745        // MTU then SR-13-bisects; Explicit writes a caller ceiling. Preserve is
746        // never "fall back to 1500" (that was the pre-0.4 auto=false trap).
747        let (requested, write_camera) = match self.packet_size_mode {
748            PacketSizeMode::Preserve => {
749                let current = self
750                    .device
751                    .get_stream_packet_size(self.channel)
752                    .await
753                    .map_err(gige("read GevSCPSPacketSize"))?;
754                debug!(
755                    channel = self.channel,
756                    packet_size = current,
757                    "preserving camera GevSCPSPacketSize; pass auto_packet_size() \
758                     or packet_size(n) to negotiate"
759                );
760                (current, false)
761            }
762            PacketSizeMode::Auto => (viva_gige::best_packet_size(mtu), true),
763            PacketSizeMode::Explicit(size) => (size, true),
764        };
765
766        if requested < MIN_PACKET_SIZE {
767            return Err(GenicamError::PacketTooSmall {
768                size: requested,
769                min: MIN_PACKET_SIZE,
770            });
771        }
772        if requested > MAX_PACKET_SIZE {
773            return Err(GenicamError::PacketTooLarge {
774                size: requested,
775                max: MAX_PACKET_SIZE,
776            });
777        }
778
779        // Bind before configuring, so the socket is already listening when the
780        // probe below asks the camera to send to it — and so the port the
781        // operating system chose is known (SR-03).
782        let socket = Self::bind_socket(&dest, &iface, self.rcvbuf_bytes).await?;
783        let port = socket
784            .local_addr()
785            .map_err(network("read the stream socket's address"))?
786            .port();
787        match &mut dest {
788            StreamDest::Unicast { dst_port, .. } => *dst_port = port,
789            StreamDest::Multicast { port: p, .. } => *p = port,
790        }
791        info!(
792            addr = %dest.addr(),
793            port,
794            channel = self.channel,
795            multicast = dest.is_multicast(),
796            "configuring the stream channel"
797        );
798        self.device
799            .set_stream_destination(self.channel, dest.addr(), port)
800            .await
801            .map_err(gige("write GevSCDA/GevSCPHostPort"))?;
802
803        let packet_size = if write_camera {
804            configure_packet_size(self.device, self.channel, requested).await?
805        } else {
806            requested
807        };
808        // Preserve probes too. The probe only ever *lowers* a size, so it cannot
809        // override the value an operator chose -- it can only decline to send at
810        // a size the path demonstrably drops, which no register read can reveal
811        // (#112). Skipping it under Preserve would leave the reporter's own
812        // camera at the 16114 an earlier run wrote, streaming nothing, with the
813        // one mechanism that could rescue it turned off. `probe(false)` is the
814        // escape for a literal preserve.
815        let packet_size = if self.probe {
816            probe_packet_size(self.device, self.channel, &socket, packet_size).await?
817        } else {
818            packet_size
819        };
820
821        // SR-19: `GevSCPD` is the operator's unless the caller asked.
822        if let Some(ticks) = packet_delay {
823            self.device
824                .set_stream_packet_delay(self.channel, ticks)
825                .await
826                .map_err(gige("write GevSCPD"))?;
827        }
828
829        let resend = match self.resend {
830            ResendPolicy::Off => false,
831            ResendPolicy::Auto if dest.is_multicast() => false,
832            ResendPolicy::Auto => camera_supports_resend(self.device).await,
833        };
834        info!(
835            channel = self.channel,
836            resend,
837            "packet resend {}",
838            if resend { "on" } else { "off" }
839        );
840
841        let params = StreamParams {
842            packet_size,
843            packet_delay,
844            mtu,
845            host: dest.addr(),
846            port,
847            channel: self.channel,
848            camera: Some(camera),
849        };
850
851        let config = StreamConfig {
852            dest,
853            iface: iface.clone(),
854            packet_size: Some(packet_size),
855            packet_delay,
856            source_filter: Some(camera_ip),
857        };
858
859        Ok(Stream {
860            socket,
861            stats: StreamStatsAccumulator::new(),
862            params,
863            config,
864            rcvbuf_bytes: self.rcvbuf_bytes,
865            resend,
866        })
867    }
868
869    /// Bind a UDP socket for the given stream destination.
870    async fn bind_socket(
871        dest: &StreamDest,
872        iface: &Iface,
873        rcvbuf_bytes: Option<usize>,
874    ) -> Result<UdpSocket, GenicamError> {
875        match dest {
876            StreamDest::Unicast { dst_port, .. } => {
877                let bind_ip =
878                    IpAddr::V4(iface.ipv4().ok_or_else(|| {
879                        GenicamError::InterfaceWithoutIpv4(iface.name().to_string())
880                    })?);
881                viva_gige::bind_udp(bind_ip, *dst_port, Some(iface.clone()), rcvbuf_bytes)
882                    .await
883                    .map_err(network("bind the stream socket"))
884            }
885            StreamDest::Multicast {
886                group,
887                port,
888                loopback,
889                ttl,
890            } => {
891                let opts = McOptions {
892                    loopback: *loopback,
893                    ttl: *ttl,
894                    rcvbuf_bytes: rcvbuf_bytes.unwrap_or(DEFAULT_RCVBUF_BYTES),
895                    ..McOptions::default()
896                };
897                viva_gige::bind_multicast(iface, *group, *port, &opts)
898                    .await
899                    .map_err(network("join the multicast group"))
900            }
901        }
902    }
903}
904
905/// SR-21: refuse a stream channel the camera does not have.
906///
907/// A count of 0, or one that cannot be read, says nothing usable: channel 0,
908/// which every streaming device has, goes ahead with a warning, and any other
909/// is refused.
910async fn check_stream_channel(device: &mut GigeDevice, channel: u32) -> Result<(), GenicamError> {
911    let count = match device.stream_channel_count().await {
912        Ok(0) => {
913            warn!("the camera reports 0 stream channels (GevNumberOfStreamChannels)");
914            None
915        }
916        Ok(count) => Some(count),
917        Err(err) => {
918            warn!(error = %err, "could not read GevNumberOfStreamChannels");
919            None
920        }
921    };
922    match count {
923        Some(count) if channel >= count => Err(GenicamError::StreamChannel {
924            channel,
925            count: Some(count),
926        }),
927        None if channel > 0 => Err(GenicamError::StreamChannel {
928            channel,
929            count: None,
930        }),
931        _ => Ok(()),
932    }
933}
934
935/// SR-19: `delay` in the camera's timestamp ticks, the unit of `GevSCPD`.
936async fn packet_delay_ticks(device: &mut GigeDevice, delay: Duration) -> Result<u32, GenicamError> {
937    if delay.is_zero() {
938        return Ok(0);
939    }
940    let hz = device
941        .timestamp_tick_frequency()
942        .await
943        .map_err(gige("read the timestamp tick frequency, GevSCPD's unit"))?;
944    delay_in_ticks(delay, hz)
945}
946
947/// `delay` at `hz` ticks a second, rounded to the nearest tick and never 0
948/// for a delay that is not.
949fn delay_in_ticks(delay: Duration, hz: u64) -> Result<u32, GenicamError> {
950    if hz == 0 {
951        return Err(GenicamError::PacketDelay {
952            delay,
953            problem: "the camera reports a timestamp tick frequency of 0, so GevSCPD has no unit",
954        });
955    }
956    let ticks = (delay.as_nanos() * u128::from(hz) + 500_000_000) / 1_000_000_000;
957    let ticks = if ticks == 0 && !delay.is_zero() {
958        1
959    } else {
960        ticks
961    };
962    u32::try_from(ticks).map_err(|_| GenicamError::PacketDelay {
963        delay,
964        problem: "it is more ticks of the camera's clock than GevSCPD holds",
965    })
966}
967
968/// Whether the GVCP Capability register says the camera answers
969/// `PACKETRESEND_CMD`. Unreadable counts as no.
970async fn camera_supports_resend(device: &mut GigeDevice) -> bool {
971    match device.gvcp_capability().await {
972        Ok(caps) => caps.packet_resend(),
973        Err(err) => {
974            debug!(error = %err, "could not read GVCP Capability; packet resend stays off");
975            false
976        }
977    }
978}
979
980/// How [`Camera::open_stream`](crate::Camera::open_stream) sets up a GigE
981/// stream. The defaults: the interface the operating system routes to the
982/// camera, unicast to a port the operating system picks, the camera's own
983/// packet size (path-probed, ADR-0021) and packet delay, packet resend when
984/// the camera supports it, and a receive buffer the engine sizes from the
985/// frame.
986#[derive(Debug, Clone, Default)]
987pub struct StreamOptions {
988    iface: Option<Iface>,
989    packet_size: PacketSizeMode,
990    multicast: Option<Ipv4Addr>,
991    destination_port: Option<u16>,
992    rcvbuf_bytes: Option<usize>,
993    packet_delay: Option<Duration>,
994    resend: ResendPolicy,
995    monitor: bool,
996    payload_size: Option<usize>,
997}
998
999impl StreamOptions {
1000    /// Watch a multicast stream another application configured: claim
1001    /// nothing, write nothing, read the group, port and packet size from the
1002    /// camera's stream channel registers, join the group and receive. Never
1003    /// asks for lost packets.
1004    ///
1005    /// The camera must already stream to a multicast group; one streaming
1006    /// unicast to another host cannot be watched. Works on a camera opened
1007    /// with [`Access::Monitor`](crate::Access::Monitor) and on one this
1008    /// application controls.
1009    pub fn monitor() -> Self {
1010        Self {
1011            monitor: true,
1012            ..Self::default()
1013        }
1014    }
1015
1016    /// The defaults.
1017    pub fn new() -> Self {
1018        Self::default()
1019    }
1020
1021    /// Receive on this interface instead of the one routed to the camera.
1022    pub fn iface(mut self, iface: Iface) -> Self {
1023        self.iface = Some(iface);
1024        self
1025    }
1026
1027    /// Write this `GevSCPSPacketSize`, a ceiling for the path probe
1028    /// ([`StreamBuilder::packet_size`]).
1029    pub fn packet_size(mut self, size: u32) -> Self {
1030        self.packet_size = PacketSizeMode::Explicit(size);
1031        self
1032    }
1033
1034    /// Set the packet size from the interface MTU, then probe
1035    /// ([`StreamBuilder::auto_packet_size`]).
1036    pub fn auto_packet_size(mut self) -> Self {
1037        self.packet_size = PacketSizeMode::Auto;
1038        self
1039    }
1040
1041    /// Have the camera stream to a multicast group, and join it.
1042    pub fn multicast(mut self, group: Ipv4Addr) -> Self {
1043        self.multicast = Some(group);
1044        self
1045    }
1046
1047    /// Receive on this UDP port, for a firewall that admits only it
1048    /// ([`StreamBuilder::destination_port`]). By default the operating system
1049    /// picks a free one.
1050    pub fn destination_port(mut self, port: u16) -> Self {
1051        self.destination_port = Some(port);
1052        self
1053    }
1054
1055    /// Have the camera wait `delay` between packets
1056    /// ([`StreamBuilder::packet_delay`]). By default `GevSCPD` is left alone.
1057    pub fn packet_delay(mut self, delay: Duration) -> Self {
1058        self.packet_delay = Some(delay);
1059        self
1060    }
1061
1062    /// Whether to ask the camera for lost packets (default
1063    /// [`ResendPolicy::Auto`]).
1064    pub fn resend(mut self, policy: ResendPolicy) -> Self {
1065        self.resend = policy;
1066        self
1067    }
1068
1069    /// Ask for this `SO_RCVBUF` instead of letting the engine size it from
1070    /// the frame (`max(4 MiB, 2 × PayloadSize)`).
1071    pub fn rcvbuf_bytes(mut self, bytes: usize) -> Self {
1072        self.rcvbuf_bytes = Some(bytes);
1073        self
1074    }
1075
1076    /// The camera's `PayloadSize`: the exact size of every frame buffer
1077    /// ([`FrameStream::set_payload_size`]), in place before the first frame.
1078    /// [`Camera::open_stream`](crate::Camera::open_stream) reads it from the
1079    /// camera itself; [`GigeRegisterIo::open_stream`](crate::GigeRegisterIo::open_stream),
1080    /// which has no node map to read it with, sizes each frame from its
1081    /// leader without it.
1082    pub fn payload_size(mut self, bytes: usize) -> Self {
1083        self.payload_size = Some(bytes).filter(|&b| b > 0);
1084        self
1085    }
1086}
1087
1088impl crate::Camera<crate::GigeRegisterIo> {
1089    /// Open a GVSP stream from this camera, ready for `acquisition_start`.
1090    ///
1091    /// The one recipe every consumer uses (API-17), as
1092    /// [`GigeRegisterIo::open_stream`](crate::GigeRegisterIo::open_stream)
1093    /// describes it, with the camera's `PayloadSize` and time sync. A camera
1094    /// without a readable `PayloadSize` still streams: buffers are then sized
1095    /// from each leader.
1096    ///
1097    /// [`StreamOptions::monitor`] instead watches a multicast stream another
1098    /// application configured, claiming and writing nothing; it is the only
1099    /// stream a camera opened with [`Access::Monitor`](crate::Access::Monitor)
1100    /// can open.
1101    pub fn open_stream(&mut self, options: StreamOptions) -> Result<FrameStream, GenicamError> {
1102        if options.monitor {
1103            return self.watch_stream(options);
1104        }
1105        let mut options = options;
1106        if options.payload_size.is_none() {
1107            options.payload_size = read_payload_size(self);
1108        }
1109        let mut frames = self.transport().open_stream(options)?;
1110        frames.set_time_sync(self.time_sync().clone());
1111        Ok(frames)
1112    }
1113
1114    /// [`StreamOptions::monitor`]: join the multicast group the camera
1115    /// already streams to, reading where from its registers. Nothing is
1116    /// written.
1117    fn watch_stream(&mut self, options: StreamOptions) -> Result<FrameStream, GenicamError> {
1118        const CHANNEL: u32 = 0;
1119        let payload_size = read_payload_size(self);
1120        let time_sync = self.time_sync().clone();
1121        let transport = self.transport();
1122        let mut guard = transport.lock_device()?;
1123        let device: &mut GigeDevice = &mut guard;
1124        let (socket, packet_size, group, iface_ip, camera_ip) =
1125            transport.block_on(async move {
1126                let IpAddr::V4(camera_ip) = device.remote_addr().ip() else {
1127                    return Err(GigeError::NotIpv4("camera").into());
1128                };
1129                let (group, port) = device
1130                    .stream_destination(CHANNEL)
1131                    .await
1132                    .map_err(gige("read GevSCDA/GevSCPHostPort"))?;
1133                if !group.is_multicast() || port == 0 {
1134                    // A monitor can only watch a stream the controlling
1135                    // application sent to a multicast group.
1136                    return Err(GenicamError::NotMulticast(std::net::SocketAddrV4::new(
1137                        group, port,
1138                    )));
1139                }
1140                let packet_size = device
1141                    .get_stream_packet_size(CHANNEL)
1142                    .await
1143                    .map_err(gige("read GevSCPSPacketSize"))?;
1144                let iface = match options.iface {
1145                    Some(iface) => iface,
1146                    None => Iface::from_remote_ipv4(camera_ip).map_err(|source| {
1147                        GenicamError::NoRoute {
1148                            camera: camera_ip,
1149                            source,
1150                        }
1151                    })?,
1152                };
1153                let iface_ip = iface
1154                    .ipv4()
1155                    .ok_or_else(|| GenicamError::InterfaceWithoutIpv4(iface.name().to_string()))?;
1156                let mc = McOptions {
1157                    rcvbuf_bytes: options.rcvbuf_bytes.unwrap_or(DEFAULT_RCVBUF_BYTES),
1158                    ..McOptions::default()
1159                };
1160                let socket = viva_gige::bind_multicast(&iface, group, port, &mc)
1161                    .await
1162                    .map_err(network("join the camera's multicast group"))?;
1163                info!(%group, port, packet_size, "watching the camera's multicast stream");
1164                Ok((socket, packet_size, group, iface_ip, camera_ip))
1165            })??;
1166        drop(guard);
1167        let socket = socket
1168            .into_std()
1169            .map_err(network("hand the stream socket to the receive thread"))?;
1170        let mut frames = FrameStream::watch_multicast(socket, packet_size, group, iface_ip)?;
1171        frames.set_source_filter(Some(camera_ip));
1172        frames.set_payload_size(payload_size);
1173        frames.set_time_sync(time_sync);
1174        Ok(frames)
1175    }
1176}
1177
1178impl crate::GigeRegisterIo {
1179    /// Open a GVSP stream from this transport's camera, ready for
1180    /// acquisition: the recipe [`Camera::open_stream`](crate::Camera::open_stream)
1181    /// runs, for a caller without a node map — a GenTL producer, which the
1182    /// GenTL standard (§2.1.2) asks not to run GenApi itself.
1183    ///
1184    /// Claims control (again, if it was released) before anything is
1185    /// written, binds the socket, points the stream channel at it — or at a
1186    /// multicast group — negotiates the packet size, reads whether the camera
1187    /// supports resend, and starts the receive engine. Without
1188    /// [`StreamOptions::payload_size`] each frame is sized from its leader.
1189    /// [`StreamOptions::monitor`] needs the camera's node map; here it is
1190    /// refused.
1191    // The device lock is held for the whole setup, outside the future that
1192    // borrows the device: nothing else may use the control channel while the
1193    // stream channel is being configured.
1194    pub fn open_stream(&self, options: StreamOptions) -> Result<FrameStream, GenicamError> {
1195        if options.monitor || self.control_state() == crate::ControlState::Monitor {
1196            return Err(GenicamError::NotInControl(crate::ControlState::Monitor));
1197        }
1198        let payload_size = options.payload_size;
1199        let mut guard = self.lock_device()?;
1200        let device: &mut GigeDevice = &mut guard;
1201        let stream = self.block_on(async move {
1202            device
1203                .claim_control()
1204                .await
1205                .map_err(gige("claim control"))?;
1206            // A session that had lost or released control holds it again,
1207            // whatever happens to the setup below: the camera says so.
1208            self.note_claimed();
1209            let iface = match options.iface {
1210                Some(iface) => iface,
1211                None => {
1212                    let camera_ip = match device.remote_addr().ip() {
1213                        IpAddr::V4(ip) => ip,
1214                        IpAddr::V6(_) => {
1215                            return Err(GigeError::NotIpv4("camera").into());
1216                        }
1217                    };
1218                    Iface::from_remote_ipv4(camera_ip).map_err(|source| GenicamError::NoRoute {
1219                        camera: camera_ip,
1220                        source,
1221                    })?
1222                }
1223            };
1224            // The stream channel is configured through the bootstrap registers,
1225            // multicast included, and only now that control is held: a device
1226            // refuses those writes from an application without privilege.
1227            let mut builder = StreamBuilder::new(device)
1228                .iface(iface)
1229                .resend(options.resend);
1230            builder.packet_size_mode = options.packet_size;
1231            builder.packet_delay = options.packet_delay;
1232            if let Some(bytes) = options.rcvbuf_bytes {
1233                builder = builder.rcvbuf_bytes(bytes);
1234            }
1235            if let Some(group) = options.multicast {
1236                builder = builder.multicast(Some(group));
1237            }
1238            if let Some(port) = options.destination_port {
1239                builder = builder.destination_port(port);
1240            }
1241            builder.build().await
1242        })??;
1243        drop(guard);
1244        Ok(FrameStream::start_with(stream, None, payload_size))
1245    }
1246}
1247
1248/// The camera's `PayloadSize`, or `None` — with a warning unless the camera
1249/// simply has no such feature — when it cannot be read.
1250fn read_payload_size<T: viva_genapi::RegisterIo>(camera: &crate::Camera<T>) -> Option<usize> {
1251    match camera.get("PayloadSize") {
1252        Ok(text) => {
1253            let size = text.trim().parse::<u64>().ok().filter(|&size| size > 0);
1254            if size.is_none() {
1255                warn!(value = %text, "PayloadSize is not a positive integer; sizing frames from each leader");
1256            }
1257            size.and_then(|size| usize::try_from(size).ok())
1258        }
1259        Err(GenicamError::GenApi(viva_genapi::GenApiError::NodeNotFound(_))) => None,
1260        Err(err) => {
1261            warn!(error = %err, "could not read PayloadSize; sizing frames from each leader");
1262            None
1263        }
1264    }
1265}
1266
1267/// Handle returned by [`StreamBuilder`]: the bound socket and the negotiated
1268/// parameters, ready for [`FrameStream::new`].
1269pub struct Stream {
1270    socket: UdpSocket,
1271    stats: StreamStatsAccumulator,
1272    params: StreamParams,
1273    config: StreamConfig,
1274    /// `SO_RCVBUF` the caller chose, which the engine leaves alone.
1275    rcvbuf_bytes: Option<usize>,
1276    /// Whether the stream asks the camera for lost packets.
1277    resend: bool,
1278}
1279
1280impl Stream {
1281    /// Access the negotiated stream parameters.
1282    pub fn params(&self) -> StreamParams {
1283        self.params
1284    }
1285
1286    /// Obtain a clone of the statistics accumulator handle.
1287    pub fn stats_handle(&self) -> StreamStatsAccumulator {
1288        self.stats.clone()
1289    }
1290
1291    /// Snapshot the collected statistics.
1292    pub fn stats(&self) -> StreamStats {
1293        self.stats.snapshot()
1294    }
1295
1296    /// Immutable view of the stream configuration.
1297    pub fn config(&self) -> &StreamConfig {
1298        &self.config
1299    }
1300
1301    /// Whether the stream will ask the camera for lost packets.
1302    pub fn resend_enabled(&self) -> bool {
1303        self.resend
1304    }
1305}
1306
1307impl<'a> From<&'a mut GigeDevice> for StreamBuilder<'a> {
1308    fn from(device: &'a mut GigeDevice) -> Self {
1309        StreamBuilder::new(device)
1310    }
1311}
1312
1313// ============================================================================
1314// High-Level FrameStream API
1315// ============================================================================
1316
1317/// Frames from one GVSP stream, assembled by a receive thread of its own.
1318///
1319/// The thread starts when the stream is created and stops, joined within a
1320/// few milliseconds, when it is dropped. It reads every datagram as it
1321/// arrives, whether or not anything is waiting for a frame, and keeps up to
1322/// sixteen finished frames for [`next_block`](Self::next_block) or
1323/// [`next_block_blocking`](Self::next_block_blocking); when the application
1324/// falls behind, the oldest is dropped and counted in
1325/// [`StreamStats::frames_backpressure`].
1326///
1327/// Only complete frames are delivered unless
1328/// [`set_deliver_incomplete`](Self::set_deliver_incomplete) asks otherwise;
1329/// every block is counted either way.
1330///
1331/// # Example
1332///
1333/// ```rust,ignore
1334/// let raw_stream = StreamBuilder::new(&mut device)
1335///     .iface(iface)
1336///     .build()
1337///     .await?;
1338/// let mut frame_stream = FrameStream::new(raw_stream, None);
1339/// while let Some(frame) = frame_stream.next_frame().await? {
1340///     println!("Frame {}: {}x{}", frame.block_id, frame.width, frame.height);
1341/// }
1342/// ```
1343pub struct FrameStream {
1344    shared: Arc<Shared>,
1345    receiver: Option<JoinHandle<()>>,
1346    stats: StreamStatsAccumulator,
1347    params: StreamParams,
1348    config: Option<StreamConfig>,
1349    time_sync: Option<TimeSync>,
1350    /// The multicast group the socket joined, left when the stream drops.
1351    membership: Option<Membership>,
1352}
1353
1354/// A multicast group a stream's socket joined.
1355///
1356/// Holds a duplicate of the socket, so the group is left explicitly when the
1357/// stream drops — an IGMP leave the switch sees at once (SR-08) — rather than
1358/// whenever the last descriptor of the socket happens to close.
1359struct Membership {
1360    socket: std::net::UdpSocket,
1361    group: Ipv4Addr,
1362    iface: Ipv4Addr,
1363}
1364
1365impl Membership {
1366    fn of(socket: &std::net::UdpSocket, group: Ipv4Addr, iface: Ipv4Addr) -> Option<Self> {
1367        match socket.try_clone() {
1368            Ok(socket) => Some(Self {
1369                socket,
1370                group,
1371                iface,
1372            }),
1373            Err(err) => {
1374                debug!(%group, error = %err, "cannot keep the stream socket to leave its group");
1375                None
1376            }
1377        }
1378    }
1379}
1380
1381impl Drop for Membership {
1382    fn drop(&mut self) {
1383        match self.socket.leave_multicast_v4(&self.group, &self.iface) {
1384            Ok(()) => debug!(group = %self.group, "left the multicast group"),
1385            Err(err) => {
1386                debug!(group = %self.group, error = %err, "leaving the multicast group failed")
1387            }
1388        }
1389    }
1390}
1391
1392impl FrameStream {
1393    /// Start receiving on a configured [`Stream`].
1394    ///
1395    /// Optionally accepts a [`TimeSync`] for mapping device timestamps to host time.
1396    pub fn new(stream: Stream, time_sync: Option<TimeSync>) -> Self {
1397        Self::start_with(stream, time_sync, None)
1398    }
1399
1400    /// As [`new`](Self::new), with `PayloadSize` in place before the receive
1401    /// thread starts.
1402    fn start_with(
1403        stream: Stream,
1404        time_sync: Option<TimeSync>,
1405        payload_size: Option<usize>,
1406    ) -> Self {
1407        let Stream {
1408            socket,
1409            stats,
1410            params,
1411            config,
1412            rcvbuf_bytes,
1413            resend,
1414        } = stream;
1415        let source_filter = config.source_filter;
1416        let group = match (&config.dest, config.iface.ipv4()) {
1417            (StreamDest::Multicast { group, .. }, Some(iface)) => Some((*group, iface)),
1418            _ => None,
1419        };
1420        let mut frames = Self::idle(stats, params, Some(config), time_sync);
1421        frames.shared.set_payload_size(payload_size);
1422        frames.shared.set_source_filter(source_filter);
1423        if resend
1424            && let Some(SocketAddr::V4(camera)) = params.camera
1425            && let Ok(channel) = u16::try_from(params.channel)
1426        {
1427            frames.shared.set_resend_target(Some((camera, channel)));
1428        }
1429        match socket.into_std() {
1430            Ok(socket) => {
1431                frames.membership =
1432                    group.and_then(|(group, iface)| Membership::of(&socket, group, iface));
1433                frames.start(socket, rcvbuf_bytes);
1434            }
1435            Err(err) => frames
1436                .shared
1437                .queue
1438                .fail("hand the stream socket to the receive thread", err),
1439        }
1440        frames
1441    }
1442
1443    /// Receive GVSP on a socket the caller bound, from a camera configured
1444    /// some other way: another application holds control, or the stream was
1445    /// set up by hand.
1446    ///
1447    /// `packet_size` is the camera's `GevSCPSPacketSize`, which fixes where
1448    /// each packet's bytes belong. [`config`](Self::config) is `None` for such
1449    /// a stream.
1450    ///
1451    /// Such a stream accepts datagrams from any address until
1452    /// [`set_source_filter`](Self::set_source_filter) names the camera, and
1453    /// never asks for lost packets unless
1454    /// [`enable_resend`](Self::enable_resend) is called. A host that only
1455    /// monitors a stream must not ask: it does not control the camera, and its
1456    /// requests would add traffic to a stream another application configured.
1457    pub fn from_socket(
1458        socket: std::net::UdpSocket,
1459        packet_size: u32,
1460    ) -> Result<Self, GenicamError> {
1461        if assembly::payload_stride(packet_size, viva_gige::GVSP_EXTENDED_HEADER_SIZE) == 0 {
1462            return Err(GenicamError::PacketTooSmall {
1463                size: packet_size,
1464                min: MIN_PACKET_SIZE,
1465            });
1466        }
1467        let local = socket
1468            .local_addr()
1469            .map_err(network("read the stream socket's address"))?;
1470        let host = match local.ip() {
1471            IpAddr::V4(ip) => ip,
1472            IpAddr::V6(_) => Ipv4Addr::UNSPECIFIED,
1473        };
1474        let params = StreamParams {
1475            packet_size,
1476            packet_delay: None,
1477            mtu: packet_size,
1478            host,
1479            port: local.port(),
1480            channel: 0,
1481            camera: None,
1482        };
1483        let mut frames = Self::idle(StreamStatsAccumulator::new(), params, None, None);
1484        frames.start(socket, None);
1485        Ok(frames)
1486    }
1487
1488    /// Receive on `socket`, already joined to `group` on the interface at
1489    /// `iface`, and leave the group when the stream drops (SR-08).
1490    pub(crate) fn watch_multicast(
1491        socket: std::net::UdpSocket,
1492        packet_size: u32,
1493        group: Ipv4Addr,
1494        iface: Ipv4Addr,
1495    ) -> Result<Self, GenicamError> {
1496        let membership = Membership::of(&socket, group, iface);
1497        let mut frames = Self::from_socket(socket, packet_size)?;
1498        frames.membership = membership;
1499        Ok(frames)
1500    }
1501
1502    fn idle(
1503        stats: StreamStatsAccumulator,
1504        params: StreamParams,
1505        config: Option<StreamConfig>,
1506        time_sync: Option<TimeSync>,
1507    ) -> Self {
1508        Self {
1509            shared: Arc::new(Shared::new()),
1510            receiver: None,
1511            stats,
1512            params,
1513            config,
1514            time_sync,
1515            membership: None,
1516        }
1517    }
1518
1519    fn start(&mut self, socket: std::net::UdpSocket, rcvbuf_bytes: Option<usize>) {
1520        match receiver::spawn(
1521            socket,
1522            self.params.packet_size,
1523            self.stats.clone(),
1524            self.shared.clone(),
1525            rcvbuf_bytes,
1526        ) {
1527            Ok(handle) => self.receiver = Some(handle),
1528            Err(err) => self.shared.queue.fail("start the GVSP receive thread", err),
1529        }
1530    }
1531
1532    /// How long a block may go without a packet before it is closed as
1533    /// incomplete (default 100 ms).
1534    ///
1535    /// Counted from the block's **last** packet, not its first: a large frame
1536    /// on a slow or paced link takes as long as it takes, and only silence
1537    /// ends it.
1538    pub fn set_block_timeout(&mut self, timeout: Duration) {
1539        self.shared.set_block_timeout(timeout);
1540    }
1541
1542    /// The camera's `PayloadSize`: the exact size of every frame buffer.
1543    ///
1544    /// Without it each buffer is sized from the leader's geometry, which
1545    /// cannot know about chunk data or vendor padding. Set it before
1546    /// acquisition starts; blocks already in flight keep their buffers.
1547    pub fn set_payload_size(&mut self, payload_size: Option<usize>) {
1548        self.shared
1549            .set_payload_size(payload_size.filter(|&s| s > 0));
1550    }
1551
1552    /// Also deliver frames that did not complete, with their
1553    /// [`FrameStatus`] saying how (default: off).
1554    ///
1555    /// Lost packets' bytes are zero in the payload. Every incomplete frame is
1556    /// counted in [`StreamStats::frames_incomplete`] either way.
1557    pub fn set_deliver_incomplete(&mut self, deliver: bool) {
1558        self.shared.set_deliver_incomplete(deliver);
1559    }
1560
1561    /// Accept GVSP only from `camera`; `None` accepts any source.
1562    ///
1563    /// A stream from [`StreamBuilder`] or
1564    /// [`Camera::open_stream`](crate::Camera::open_stream) accepts only the
1565    /// camera's own address. Datagrams from anywhere else are ignored and
1566    /// counted in [`StreamStats::packets_ignored_foreign`]; a camera that
1567    /// sends its stream from another address than the one it answers GVCP on
1568    /// needs `None`.
1569    pub fn set_source_filter(&mut self, camera: Option<Ipv4Addr>) {
1570        self.shared.set_source_filter(camera);
1571    }
1572
1573    /// The only address GVSP is accepted from, if any.
1574    pub fn source_filter(&self) -> Option<Ipv4Addr> {
1575        self.shared.source_filter()
1576    }
1577
1578    /// Ask the camera at `camera` (its GVCP address, normally port 3956) to
1579    /// send lost packets of stream channel `channel` again.
1580    ///
1581    /// [`Camera::open_stream`](crate::Camera::open_stream) does this when the
1582    /// camera's capability register says it supports packet resend. Call it
1583    /// yourself only for a stream this application controls, on a camera
1584    /// that supports resend.
1585    pub fn enable_resend(&mut self, camera: std::net::SocketAddrV4, channel: u16) {
1586        self.shared.set_resend_target(Some((camera, channel)));
1587    }
1588
1589    /// Stop asking for lost packets.
1590    pub fn disable_resend(&mut self) {
1591        self.shared.set_resend_target(None);
1592    }
1593
1594    /// Whether the stream asks the camera for lost packets.
1595    pub fn resend_enabled(&self) -> bool {
1596        self.shared.resend_target().is_some()
1597    }
1598
1599    /// How old a gap in a block's packets must be before it is asked for
1600    /// (default 2 ms), so a packet that was only overtaken is not.
1601    pub fn set_resend_delay(&mut self, delay: Duration) {
1602        self.shared.set_resend_delay(delay);
1603    }
1604
1605    /// How long to wait for a resent packet before asking again (default
1606    /// 20 ms).
1607    pub fn set_resend_retry_interval(&mut self, interval: Duration) {
1608        self.shared.set_resend_retry_interval(interval);
1609    }
1610
1611    /// How many times one range of packets is asked for, the first request
1612    /// included (default 3).
1613    pub fn set_resend_max_requests(&mut self, requests: u32) {
1614        self.shared.set_resend_max_requests(requests);
1615    }
1616
1617    /// The share of a block's packets its requests may ask for, retries
1618    /// included (default 0.25, rounded up). A block that lost more is not
1619    /// worth flooding the camera for; it closes incomplete.
1620    pub fn set_resend_budget(&mut self, share: f64) {
1621        let share = if share.is_nan() { 0.0 } else { share };
1622        self.shared.set_resend_budget(share.clamp(0.0, 1.0));
1623    }
1624
1625    /// Update or set the time synchronization model for timestamp mapping.
1626    pub fn set_time_sync(&mut self, time_sync: TimeSync) {
1627        self.time_sync = Some(time_sync);
1628    }
1629
1630    /// Obtain a clone of the statistics accumulator handle.
1631    pub fn stats_handle(&self) -> StreamStatsAccumulator {
1632        self.stats.clone()
1633    }
1634
1635    /// Snapshot the collected statistics.
1636    pub fn stats(&self) -> StreamStats {
1637        self.stats.snapshot()
1638    }
1639
1640    /// Access the negotiated stream parameters.
1641    pub fn params(&self) -> StreamParams {
1642        self.params
1643    }
1644
1645    /// The stream configuration, or `None` for a stream made with
1646    /// [`from_socket`](Self::from_socket).
1647    pub fn config(&self) -> Option<&StreamConfig> {
1648        self.config.as_ref()
1649    }
1650
1651    /// Receive the next image frame.
1652    ///
1653    /// This backwards-compatible image API also returns an EVS block as a
1654    /// [`Frame`] carrying the raw bytes and its EVT PFNC code. New callers that
1655    /// need to distinguish event data should use [`next_block`](Self::next_block).
1656    pub async fn next_frame(&mut self) -> Result<Option<Frame>, GenicamError> {
1657        Ok(self
1658            .next_block()
1659            .await?
1660            .map(GenericStreamBlock::into_legacy_frame))
1661    }
1662
1663    /// Receive and classify the next GVSP block.
1664    ///
1665    /// `Ok(None)` means the stream has ended. Cancel-safe: dropping the
1666    /// future, as `tokio::select!` does, loses no block.
1667    pub async fn next_block(&mut self) -> Result<Option<GenericStreamBlock>, GenicamError> {
1668        let popped = self.shared.queue.pop().await;
1669        self.take(popped)
1670    }
1671
1672    /// Wait up to `timeout` for the next block on the calling thread.
1673    ///
1674    /// For callers without an async runtime. `Ok(None)` means the stream has
1675    /// ended; nothing within `timeout` is [`GenicamError::Timeout`].
1676    pub fn next_block_blocking(
1677        &mut self,
1678        timeout: Duration,
1679    ) -> Result<Option<GenericStreamBlock>, GenicamError> {
1680        match self.shared.queue.pop_blocking(timeout) {
1681            Popped::Empty => Err(GenicamError::Timeout(timeout)),
1682            popped => self.take(popped),
1683        }
1684    }
1685
1686    /// [`next_frame`](Self::next_frame) on the calling thread, waiting up to
1687    /// `timeout`: `Ok(None)` when the stream has ended,
1688    /// [`GenicamError::Timeout`] when nothing arrived.
1689    pub fn next_frame_blocking(
1690        &mut self,
1691        timeout: Duration,
1692    ) -> Result<Option<Frame>, GenicamError> {
1693        Ok(self
1694            .next_block_blocking(timeout)?
1695            .map(GenericStreamBlock::into_legacy_frame))
1696    }
1697
1698    /// Account for a block leaving the queue and give it its host time.
1699    fn take(
1700        &mut self,
1701        popped: Popped<GenericStreamBlock>,
1702    ) -> Result<Option<GenericStreamBlock>, GenicamError> {
1703        match popped {
1704            Popped::Item(mut block) => {
1705                let ts_host = block.device_timestamp().and_then(|timestamp| {
1706                    self.time_sync
1707                        .as_ref()
1708                        .and_then(|time_sync| time_sync.to_host_time(timestamp))
1709                });
1710                block.set_host_time(ts_host);
1711                if block.status().is_complete() {
1712                    let latency = ts_host.and_then(|ts| SystemTime::now().duration_since(ts).ok());
1713                    self.stats.record_frame(
1714                        block.payload().len(),
1715                        latency,
1716                        block.completed.unwrap_or_else(std::time::Instant::now),
1717                    );
1718                } else {
1719                    self.stats.record_incomplete_frame();
1720                }
1721                Ok(Some(block))
1722            }
1723            Popped::Failed(during, source) => Err(GenicamError::Network { during, source }),
1724            Popped::Finished | Popped::Empty => Ok(None),
1725        }
1726    }
1727}
1728
1729impl Drop for FrameStream {
1730    fn drop(&mut self) {
1731        self.shared
1732            .stop
1733            .store(true, std::sync::atomic::Ordering::Release);
1734        if let Some(receiver) = self.receiver.take() {
1735            let _ = receiver.join();
1736        }
1737    }
1738}
1739
1740#[cfg(test)]
1741mod tests {
1742    use super::*;
1743    use assembly::LeaderInfo;
1744
1745    /// SR-08: a stream that joined a multicast group leaves it when it drops,
1746    /// rather than leaving the membership to the socket's close — which
1747    /// never comes while anything else holds the socket. A duplicate of the
1748    /// socket shows it: leaving through it fails once the stream has left.
1749    #[test]
1750    fn a_multicast_stream_leaves_its_group_when_dropped() {
1751        let group = Ipv4Addr::new(239, 192, 1, 31);
1752        let iface = Ipv4Addr::LOCALHOST;
1753        let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).expect("bind");
1754        if let Err(err) = socket.join_multicast_v4(&group, &iface) {
1755            eprintln!("skipped: cannot join a group on loopback here: {err}");
1756            return;
1757        }
1758        let duplicate = socket.try_clone().expect("duplicate");
1759        let stream = FrameStream::watch_multicast(socket, 1500, group, iface).expect("stream");
1760        drop(stream);
1761        assert!(
1762            duplicate.leave_multicast_v4(&group, &iface).is_err(),
1763            "the group was still joined after the stream dropped"
1764        );
1765    }
1766
1767    /// A complete assembled block with a leader, as the engine hands it over.
1768    fn assembled(
1769        payload: Bytes,
1770        width: u32,
1771        height: u32,
1772        pixel_format: u32,
1773        timestamp: u64,
1774        trailer_size_y: u32,
1775    ) -> AssembledBlock {
1776        AssembledBlock {
1777            block_id: 1,
1778            status: FrameStatus::Complete,
1779            leader: Some(LeaderInfo {
1780                padding_x: 0,
1781                timestamp,
1782                pixel_format,
1783                width,
1784                height,
1785            }),
1786            payload_type: 0x0001,
1787            expected_size: Some(payload.len()),
1788            last_packet: std::time::Instant::now(),
1789            payload,
1790            trailer_size_y: Some(trailer_size_y),
1791        }
1792    }
1793
1794    /// SR-19: a delay in time becomes `GevSCPD` ticks at the camera's
1795    /// frequency, rounded to the nearest tick; no frequency, no conversion.
1796    #[test]
1797    fn a_packet_delay_is_converted_to_ticks() {
1798        let us = Duration::from_micros;
1799        assert_eq!(delay_in_ticks(us(10), 125_000_000).unwrap(), 1250);
1800        assert_eq!(delay_in_ticks(us(10), 1_000_000_000).unwrap(), 10_000);
1801        // 12 ns at 125 MHz is 1.5 ticks; 3 ns is 0.375, which is still not 0.
1802        assert_eq!(
1803            delay_in_ticks(Duration::from_nanos(12), 125_000_000).unwrap(),
1804            2
1805        );
1806        assert_eq!(
1807            delay_in_ticks(Duration::from_nanos(3), 125_000_000).unwrap(),
1808            1
1809        );
1810        assert!(delay_in_ticks(us(10), 0).is_err());
1811        assert!(delay_in_ticks(Duration::from_secs(10), 1_000_000_000).is_err());
1812    }
1813
1814    #[test]
1815    fn captured_lucid_evt30_metadata_is_classified_as_evs() {
1816        let payload = Bytes::from_static(&[0x8e, 0x8a, 0xff, 0xe0]);
1817        let block = classify_completed_block(assembled(
1818            payload.clone(),
1819            1,
1820            64_000,
1821            0x8110_0e30,
1822            0x0000_422d_66d4_39c8,
1823            824,
1824        ))
1825        .0;
1826
1827        assert_eq!(block.payload(), &payload);
1828        assert_eq!(block.width(), None);
1829        assert_eq!(block.height(), None);
1830        let StreamBlock::Evs(evs) = StreamBlock::from(block) else {
1831            panic!("EVT 3.0 must not be exposed as an image frame");
1832        };
1833        assert_eq!(evs.format, crate::evs::EvsFormat::Evt30);
1834        assert_eq!(evs.ts_dev, Some(0x0000_422d_66d4_39c8));
1835        assert_eq!(evs.leader_size_x, 1);
1836        assert_eq!(evs.leader_size_y, 64_000);
1837        assert_eq!(evs.trailer_size_y, 824);
1838        assert!(evs.chunks.is_none());
1839        assert_eq!(evs.payload, payload);
1840    }
1841
1842    #[test]
1843    fn evt21_is_classified_as_evs() {
1844        let block = classify_completed_block(assembled(
1845            Bytes::from_static(&[0; 8]),
1846            1,
1847            64_000,
1848            0x8140_0e21,
1849            7,
1850            8,
1851        ))
1852        .0;
1853
1854        let StreamBlock::Evs(evs) = StreamBlock::from(block) else {
1855            panic!("EVT 2.1 must not be exposed as an image frame");
1856        };
1857        assert_eq!(evs.format, crate::evs::EvsFormat::Evt21);
1858        assert_eq!(evs.payload.len(), 8);
1859    }
1860
1861    #[test]
1862    fn unknown_pfnc_code_remains_an_image() {
1863        let pixel_format = PixelFormat::from_code(0x0220_ffff);
1864        let block = classify_completed_block(assembled(
1865            Bytes::from_static(&[1, 2, 3, 4]),
1866            2,
1867            2,
1868            pixel_format.code(),
1869            9,
1870            2,
1871        ))
1872        .0;
1873
1874        let StreamBlock::Image(frame) = StreamBlock::from(block) else {
1875            panic!("an unknown PFNC code in an IMAGE leader is still an image");
1876        };
1877        assert_eq!(frame.pixel_format, pixel_format);
1878        assert_eq!((frame.width, frame.height), (2, 2));
1879        assert_eq!(frame.payload.as_ref(), &[1, 2, 3, 4]);
1880    }
1881
1882    #[test]
1883    fn legacy_frame_api_preserves_evt_wire_metadata() {
1884        let payload = Bytes::from_static(&[1, 2, 3]);
1885        let block = classify_completed_block(assembled(
1886            payload.clone(),
1887            1,
1888            64_000,
1889            PixelFormat::VendorLucidEvsEvt30.code(),
1890            11,
1891            3,
1892        ))
1893        .0;
1894
1895        let frame = block.into_legacy_frame();
1896        assert_eq!(frame.payload, payload);
1897        assert_eq!((frame.width, frame.height), (1, 64_000));
1898        assert_eq!(frame.pixel_format, PixelFormat::VendorLucidEvsEvt30);
1899        assert_eq!(frame.ts_dev, Some(11));
1900    }
1901
1902    /// An image with chunks: the frame's payload is the image chunk alone,
1903    /// and the chunks are kept by ID. Bytes written out by hand: an 8-byte
1904    /// Mono8 image tagged as chunk 1, then a 4-byte chunk 0x0504_0008.
1905    #[test]
1906    fn an_image_with_chunks_is_split_into_image_and_chunks() {
1907        #[rustfmt::skip]
1908        let payload = Bytes::from_static(&[
1909            1, 2, 3, 4, 5, 6, 7, 8,
1910            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08,
1911            0x88, 0x13, 0x00, 0x00,
1912            0x05, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04,
1913        ]);
1914        let mut block = assembled(payload, 4, 2, 0x0108_0001, 5, 2);
1915        block.payload_type = 0x4001;
1916        let (block, error) = classify_completed_block(block);
1917        assert!(error.is_none());
1918        let StreamBlock::Image(frame) = StreamBlock::from(block) else {
1919            panic!("an image");
1920        };
1921        assert_eq!(frame.payload.as_ref(), &[1, 2, 3, 4, 5, 6, 7, 8]);
1922        let chunks = frame.chunks.expect("chunks");
1923        assert_eq!(
1924            chunks.get(0x0504_0008).map(|c| c.to_vec()),
1925            Some(vec![0x88, 0x13, 0x00, 0x00])
1926        );
1927    }
1928
1929    /// The raw payload is the whole block, chunks and tags included, for an
1930    /// image with chunks as for a plain image.
1931    #[test]
1932    fn the_raw_payload_is_the_whole_block() {
1933        #[rustfmt::skip]
1934        let payload = Bytes::from_static(&[
1935            1, 2, 3, 4, 5, 6, 7, 8,
1936            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08,
1937            0x88, 0x13, 0x00, 0x00,
1938            0x05, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04,
1939        ]);
1940        for payload_type in [0x4001, 0x0001] {
1941            let mut block = assembled(payload.clone(), 4, 2, 0x0108_0001, 5, 2);
1942            block.payload_type = payload_type;
1943            let (block, _) = classify_completed_block(block);
1944            let StreamBlock::Image(frame) = StreamBlock::from(block) else {
1945                panic!("an image");
1946            };
1947            assert_eq!(
1948                frame.raw_payload, payload,
1949                "payload type {payload_type:#06x}"
1950            );
1951            assert!(frame.raw_payload.starts_with(&frame.payload));
1952        }
1953    }
1954
1955    /// A layout that does not parse keeps the whole payload, carries no
1956    /// chunks, and hands the error back for the receive thread to report.
1957    #[test]
1958    fn a_malformed_chunk_layout_is_reported_not_guessed() {
1959        let mut block = assembled(Bytes::from_static(&[0xFF; 12]), 2, 2, 0x0108_0001, 5, 2);
1960        block.payload_type = 0x4001;
1961        let (block, error) = classify_completed_block(block);
1962        assert!(
1963            matches!(error, Some(ChunkError::LengthPastStart { .. })),
1964            "{error:?}"
1965        );
1966        let StreamBlock::Image(frame) = StreamBlock::from(block) else {
1967            panic!("an image");
1968        };
1969        assert_eq!(frame.payload.len(), 12);
1970        assert!(frame.chunks.is_none());
1971    }
1972
1973    /// An incomplete block's zeros are not read as chunk tags.
1974    #[test]
1975    fn an_incomplete_block_is_not_split() {
1976        let mut block = assembled(Bytes::from_static(&[0; 16]), 2, 2, 0x0108_0001, 5, 2);
1977        block.payload_type = 0x4001;
1978        block.status = FrameStatus::Incomplete { missing_packets: 1 };
1979        let (block, error) = classify_completed_block(block);
1980        assert!(error.is_none());
1981        let StreamBlock::Image(frame) = StreamBlock::from(block) else {
1982            panic!("an image");
1983        };
1984        assert!(frame.chunks.is_none());
1985        assert_eq!(frame.payload.len(), 16);
1986    }
1987}