Skip to main content

viva_genicam/stream/
u3v.rs

1//! USB3 Vision frame streams (ADR-0032).
2//!
3//! `viva-u3v`'s [`U3vStream`](crate::u3v::U3vStream) keeps several transfers
4//! queued on the stream endpoint and resynchronises after a failed transfer;
5//! here it runs on a thread of its own — a `std::thread`, not a Tokio
6//! runtime's blocking pool, so the blocking API (ADR-0027) streams from a
7//! USB3 Vision camera too — and hands frames on through the GVSP receive
8//! engine's drop-oldest queue, counted in the same [`StreamStats`].
9
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::thread::JoinHandle;
13use std::time::{Duration, Instant, SystemTime};
14
15use tracing::{debug, warn};
16use viva_pfnc::PixelFormat;
17
18use super::receiver::{DELIVERY_CAPACITY, DeliveryQueue, Popped};
19use super::stats::{StreamStats, StreamStatsAccumulator};
20use crate::frame::{Frame, FrameStatus};
21use crate::u3v::{RawFrame, U3vError, U3vStatus, U3vStream, U3vStreamOptions, UsbTransfer};
22use crate::{GenicamError, TimeSync, U3vRegisterIo};
23
24/// How long the reader waits for a transfer before checking whether it was
25/// told to stop: what dropping or closing a stream waits at most.
26const U3V_READ_POLL: Duration = Duration::from_millis(50);
27
28/// Clears a device's StreamEnable. Called with `true` it waits for the
29/// device lock; with `false` it gives up if someone holds the lock, and
30/// returns whether it ran.
31type DisableStream = Arc<dyn Fn(bool) -> bool + Send + Sync>;
32
33/// State shared between a [`U3vFrameStream`] and its reader thread.
34struct Shared {
35    queue: DeliveryQueue<Frame, U3vError>,
36    stop: AtomicBool,
37    deliver_incomplete: AtomicBool,
38}
39
40impl Shared {
41    fn new() -> Self {
42        Self {
43            queue: DeliveryQueue::new(DELIVERY_CAPACITY),
44            stop: AtomicBool::new(false),
45            deliver_incomplete: AtomicBool::new(false),
46        }
47    }
48
49    fn enqueue(&self, frame: Frame, stats: &StreamStatsAccumulator) {
50        if self.queue.push(frame).is_some() {
51            stats.record_backpressure_drop();
52        }
53    }
54}
55
56/// Frames from a USB3 Vision camera, read on a thread of its own.
57///
58/// [`next_frame`](Self::next_frame) waits asynchronously,
59/// [`next_frame_blocking`](Self::next_frame_blocking) on the calling thread;
60/// neither needs the other. A stream from [`U3vStreamBuilder`] or
61/// [`Camera::open_stream`](crate::Camera::open_stream) clears the device's
62/// StreamEnable when it is closed or dropped.
63///
64/// A transfer that fails is recovered from — the endpoint reset, the block
65/// in progress lost and counted — and the stream goes on; a camera that is
66/// unplugged ends it with [`U3vError::Disconnected`] as the source of the
67/// error, and marks the camera's transport lost
68/// ([`U3vRegisterIo::is_lost`]).
69///
70/// ```rust,ignore
71/// let mut frames = camera.open_stream(U3vStreamOptions::default())?;
72/// camera.acquisition_start()?;
73/// while let Some(frame) = frames.next_frame().await? {
74///     println!("{}x{} frame {}", frame.width, frame.height, frame.block_id);
75/// }
76/// ```
77pub struct U3vFrameStream {
78    shared: Arc<Shared>,
79    reader: Option<JoinHandle<()>>,
80    stats: StreamStatsAccumulator,
81    time_sync: Option<TimeSync>,
82    disable: Option<DisableStream>,
83}
84
85impl U3vFrameStream {
86    /// Read frames from `stream`, a stream already configured and enabled on
87    /// the device. Nothing clears the device's StreamEnable when it ends;
88    /// [`U3vStreamBuilder`] starts streams that do.
89    pub fn start(stream: U3vStream) -> Self {
90        Self::start_inner(stream, None, None)
91    }
92
93    fn start_inner(
94        stream: U3vStream,
95        disable: Option<DisableStream>,
96        lost: Option<Arc<AtomicBool>>,
97    ) -> Self {
98        let shared = Arc::new(Shared::new());
99        let stats = StreamStatsAccumulator::new();
100        let reader = {
101            let (shared, stats) = (Arc::clone(&shared), stats.clone());
102            std::thread::Builder::new()
103                .name("viva-u3v-stream".into())
104                .spawn(move || read_loop(stream, &shared, &stats, lost.as_deref()))
105        };
106        let reader = match reader {
107            Ok(handle) => Some(handle),
108            Err(error) => {
109                warn!(%error, "could not start the USB3 Vision reader thread");
110                shared.queue.finish();
111                None
112            }
113        };
114        Self {
115            shared,
116            reader,
117            stats,
118            time_sync: None,
119            disable,
120        }
121    }
122
123    /// Also deliver frames that did not complete — a block given up before
124    /// its trailer, or one whose trailer reports an error — with their
125    /// [`FrameStatus`] saying how (default: off). Every incomplete frame is
126    /// counted in [`StreamStats::frames_incomplete`] either way.
127    pub fn set_deliver_incomplete(&mut self, deliver: bool) {
128        self.shared
129            .deliver_incomplete
130            .store(deliver, Ordering::Relaxed);
131    }
132
133    /// Map device timestamps to host time with `time_sync`, fitted by
134    /// [`Camera::time_calibrate`](crate::Camera::time_calibrate).
135    pub fn set_time_sync(&mut self, time_sync: TimeSync) {
136        self.time_sync = Some(time_sync);
137    }
138
139    /// Snapshot the stream's counters.
140    pub fn stats(&self) -> StreamStats {
141        self.stats.snapshot()
142    }
143
144    /// A clone of the counters' handle, readable from any thread.
145    pub fn stats_handle(&self) -> StreamStatsAccumulator {
146        self.stats.clone()
147    }
148
149    /// Receive the next frame. `Ok(None)` means the stream has ended.
150    /// Cancel-safe.
151    pub async fn next_frame(&mut self) -> Result<Option<Frame>, GenicamError> {
152        let popped = self.shared.queue.pop().await;
153        self.take(popped)
154    }
155
156    /// Wait up to `timeout` for the next frame on the calling thread:
157    /// `Ok(None)` when the stream has ended, [`GenicamError::Timeout`] when
158    /// nothing arrived.
159    pub fn next_frame_blocking(
160        &mut self,
161        timeout: Duration,
162    ) -> Result<Option<Frame>, GenicamError> {
163        match self.shared.queue.pop_blocking(timeout) {
164            Popped::Empty => Err(GenicamError::Timeout(timeout)),
165            popped => self.take(popped),
166        }
167    }
168
169    /// Account for a frame leaving the queue and give it its host time.
170    fn take(&mut self, popped: Popped<Frame, U3vError>) -> Result<Option<Frame>, GenicamError> {
171        match popped {
172            Popped::Item(mut frame) => {
173                frame.ts_host = frame.ts_dev.and_then(|ticks| {
174                    self.time_sync
175                        .as_ref()
176                        .and_then(|sync| sync.to_host_time(ticks))
177                });
178                if frame.is_complete() {
179                    let latency = frame
180                        .ts_host
181                        .and_then(|ts| SystemTime::now().duration_since(ts).ok());
182                    self.stats
183                        .record_frame(frame.payload.len(), latency, Instant::now());
184                } else {
185                    self.stats.record_incomplete_frame();
186                }
187                Ok(Some(frame))
188            }
189            Popped::Failed(during, source) => Err(GenicamError::U3v { during, source }),
190            Popped::Finished | Popped::Empty => Ok(None),
191        }
192    }
193
194    /// Tell the reader to stop. It stops within a read poll; this does not
195    /// wait for it, [`close`](Self::close) does.
196    pub fn stop(&self) {
197        self.shared.stop.store(true, Ordering::Release);
198    }
199
200    /// Stop the reader, wait for it, and clear the device's StreamEnable:
201    /// the endpoint and the device are free once this returns.
202    pub fn close(mut self) {
203        self.close_inner();
204    }
205
206    /// [`close`](Self::close), for async callers: the wait runs on the
207    /// runtime's blocking pool.
208    pub async fn shutdown(self) {
209        let closing = tokio::task::spawn_blocking(move || self.close());
210        let _ = closing.await;
211    }
212
213    fn close_inner(&mut self) {
214        self.stop();
215        if let Some(reader) = self.reader.take() {
216            let _ = reader.join();
217        }
218        if let Some(disable) = self.disable.take() {
219            disable(true);
220        }
221    }
222}
223
224impl Drop for U3vFrameStream {
225    /// A stream dropped without [`close`](Self::close) still stops its
226    /// reader and the device's stream. If the device is busy, a thread of
227    /// its own waits for it: the dropping thread must not block on a lock it
228    /// may hold, and giving up left StreamEnable set (Codex review of #184).
229    fn drop(&mut self) {
230        self.stop();
231        if let Some(reader) = self.reader.take() {
232            let _ = reader.join();
233        }
234        if let Some(disable) = self.disable.take()
235            && !disable(false)
236        {
237            std::thread::spawn(move || {
238                disable(true);
239            });
240        }
241    }
242}
243
244/// The reader thread: blocks from the stream, counted, converted and queued
245/// until told to stop or the stream ends.
246fn read_loop(
247    mut stream: U3vStream,
248    shared: &Shared,
249    stats: &StreamStatsAccumulator,
250    lost: Option<&AtomicBool>,
251) {
252    let mut counted = stream.counters();
253    let mut last_block: Option<u64> = None;
254    let mut chunk_layout_warned = false;
255    loop {
256        if shared.stop.load(Ordering::Acquire) {
257            break;
258        }
259        let result = stream.next_frame_within(U3V_READ_POLL);
260        let counters = stream.counters();
261        stats.record_packets_received(counters.transfers - counted.transfers);
262        stats.record_malformed_packets(counters.transfers_skipped - counted.transfers_skipped);
263        stats.record_transfer_errors(counters.transfer_errors - counted.transfer_errors);
264        counted = counters;
265        match result {
266            Ok(None) => {}
267            Ok(Some(raw)) => {
268                // Block ids count up by one; a lower id is the camera
269                // starting again, not a gap.
270                let id = raw.leader.block_id;
271                if let Some(last) = last_block
272                    && id > last + 1
273                {
274                    stats.record_missed_frames(id - last - 1);
275                }
276                last_block = Some(id);
277                deliver(raw, shared, stats, &mut chunk_layout_warned);
278            }
279            Err(error) => {
280                if matches!(error, U3vError::Disconnected) {
281                    warn!("the USB3 Vision camera is gone; its stream ends");
282                    if let Some(lost) = lost {
283                        lost.store(true, Ordering::Release);
284                    }
285                }
286                shared.queue.fail("read a frame", error);
287                break;
288            }
289        }
290    }
291    shared.queue.finish();
292}
293
294/// Queue one block as a frame — or count it, when it is incomplete and the
295/// application did not ask for incomplete ones, or not an image or chunks.
296fn deliver(raw: RawFrame, shared: &Shared, stats: &StreamStatsAccumulator, warned: &mut bool) {
297    let payload_type = raw.leader.payload_type;
298    if payload_type & !CHUNK_FLAG != PAYLOAD_TYPE_IMAGE && payload_type != CHUNK_FLAG {
299        debug!(
300            payload_type,
301            "a USB3 Vision payload type that is not assembled"
302        );
303        stats.record_unsupported_block();
304        return;
305    }
306    let block_id = raw.leader.block_id;
307    let (frame, chunk_error) = to_frame(raw);
308    if let Some(error) = chunk_error {
309        if !*warned {
310            *warned = true;
311            warn!(
312                block_id,
313                %error,
314                "a frame's chunk data does not parse; it is delivered with its whole payload \
315                 and no chunks. Further failures are logged at debug"
316            );
317        } else {
318            debug!(block_id, %error, "chunk data does not parse");
319        }
320    }
321    if !frame.is_complete() && !shared.deliver_incomplete.load(Ordering::Relaxed) {
322        stats.record_incomplete_frame();
323        return;
324    }
325    shared.enqueue(frame, stats);
326}
327
328/// An image, with or without chunks (USB3 Vision `0x0001`, `0x4001`).
329const PAYLOAD_TYPE_IMAGE: u16 = 0x0001;
330/// The extended chunk flag; alone, chunk data (`0x4000`).
331const CHUNK_FLAG: u16 = 0x4000;
332
333/// The frame a block makes, and why its chunks did not parse, if they did
334/// not.
335fn to_frame(raw: RawFrame) -> (Frame, Option<U3vError>) {
336    let RawFrame {
337        leader,
338        payload,
339        trailer,
340        ..
341    } = raw;
342    let status = match &trailer {
343        None => FrameStatus::TrailerMissing,
344        Some(t) if t.status & 0x8000 != 0 => {
345            FrameStatus::U3vDeviceStatus(U3vStatus::from_raw(t.status))
346        }
347        Some(t) if (payload.len() as u64) < t.valid_payload_size => {
348            FrameStatus::Incomplete { missing_packets: 0 }
349        }
350        Some(_) => FrameStatus::Complete,
351    };
352    let raw_payload = payload.clone();
353    let (image, chunks) = if status.is_complete() {
354        crate::chunks::split_u3v(payload, leader.payload_type)
355    } else {
356        (payload, None)
357    };
358    let (chunks, chunk_error) = match chunks {
359        Some(Ok(chunks)) => (Some(chunks), None),
360        Some(Err(error)) => (None, Some(error)),
361        None => (None, None),
362    };
363    let mut frame = Frame::new(
364        image,
365        leader.width,
366        leader.height,
367        PixelFormat::from_code(leader.pixel_format),
368    );
369    frame.raw_payload = raw_payload;
370    frame.chunks = chunks;
371    frame.ts_dev = Some(leader.timestamp);
372    frame.padding_x = leader.x_padding;
373    frame.block_id = leader.block_id;
374    frame.payload_type = leader.payload_type;
375    frame.status = status;
376    frame.delivered_height = trailer
377        .as_ref()
378        .and_then(|t| t.size_y)
379        .filter(|_| leader.payload_type & !CHUNK_FLAG == PAYLOAD_TYPE_IMAGE);
380    frame.expected_size = trailer
381        .as_ref()
382        .and_then(|t| usize::try_from(t.valid_payload_size).ok());
383    (frame, chunk_error)
384}
385
386/// Builder for a USB3 Vision [`U3vFrameStream`] on a camera's transport —
387/// the device, as GigE Vision's `StreamBuilder` takes the device.
388///
389/// [`build`](Self::build) is synchronous where GigE Vision's is async:
390/// opening a USB3 Vision stream is a handful of blocking register writes,
391/// with nothing to wait on a socket for, and a program on the blocking API
392/// (ADR-0027) must be able to open one without a runtime (ADR-0032).
393pub struct U3vStreamBuilder<'a, T: UsbTransfer + 'static> {
394    device: &'a U3vRegisterIo<T>,
395    options: U3vStreamOptions,
396    time_sync: Option<TimeSync>,
397}
398
399impl<'a, T: UsbTransfer + 'static> U3vStreamBuilder<'a, T> {
400    /// A builder for the stream of the camera behind `device`, with the
401    /// default transfer settings.
402    pub fn new(device: &'a U3vRegisterIo<T>) -> Self {
403        Self {
404            device,
405            options: U3vStreamOptions::default(),
406            time_sync: None,
407        }
408    }
409
410    /// The transfer settings and payload size hint.
411    pub fn options(mut self, options: U3vStreamOptions) -> Self {
412        self.options = options;
413        self
414    }
415
416    /// Bytes in one frame, used only when the device's SIRM leaves its
417    /// Required Payload Size at 0.
418    pub fn payload_size(mut self, bytes: u64) -> Self {
419        self.options.payload_size_hint = bytes;
420        self
421    }
422
423    /// The largest payload transfer to ask for.
424    pub fn max_transfer_size(mut self, bytes: u32) -> Self {
425        self.options.max_transfer_size = bytes;
426        self
427    }
428
429    /// How many transfers to keep queued on the stream endpoint.
430    pub fn transfers_in_flight(mut self, transfers: usize) -> Self {
431        self.options.transfers_in_flight = transfers;
432        self
433    }
434
435    /// Map device timestamps to host time with `time_sync`.
436    pub fn time_sync(mut self, time_sync: TimeSync) -> Self {
437        self.time_sync = Some(time_sync);
438        self
439    }
440
441    /// Configure the SIRM, reset the stream endpoint, set StreamEnable, and
442    /// start reading. The stream clears StreamEnable again when it is closed
443    /// or dropped.
444    pub fn build(self) -> Result<U3vFrameStream, GenicamError> {
445        let device = self.device.shared_device();
446        let stream = device
447            .lock()
448            .map_err(|_| GenicamError::Panicked("a thread holding the camera's device lock"))?
449            .open_stream_with(&self.options)
450            .map_err(|source| {
451                if matches!(source, U3vError::Disconnected) {
452                    self.device.mark_lost();
453                }
454                GenicamError::U3v {
455                    during: "open the stream",
456                    source,
457                }
458            })?;
459        let disable: DisableStream = Arc::new(move |wait: bool| {
460            let guard = if wait {
461                device.lock().ok()
462            } else {
463                device.try_lock().ok()
464            };
465            let Some(mut device) = guard else {
466                return false;
467            };
468            if let Err(error) = device.stop_stream() {
469                debug!(%error, "clearing StreamEnable");
470            }
471            true
472        });
473        let mut frames =
474            U3vFrameStream::start_inner(stream, Some(disable), Some(self.device.lost_flag()));
475        if let Some(time_sync) = self.time_sync {
476            frames.set_time_sync(time_sync);
477        }
478        Ok(frames)
479    }
480}
481
482impl<T: UsbTransfer + 'static> crate::Camera<U3vRegisterIo<T>> {
483    /// Open the camera's stream, ready for `acquisition_start`: the recipe
484    /// [`Camera::open_stream`](crate::Camera::open_stream) is for GigE
485    /// Vision, with the camera's `PayloadSize` as the hint when the device's
486    /// SIRM gives none, and its time sync.
487    ///
488    /// Without `PayloadSize`, the hint is computed from Width, Height and
489    /// PixelFormat; a camera that has the feature and cannot answer it is
490    /// an error, since a computed size misses padding and chunk data.
491    pub fn open_stream(
492        &mut self,
493        options: U3vStreamOptions,
494    ) -> Result<U3vFrameStream, GenicamError> {
495        let mut options = options;
496        if options.payload_size_hint == 0 {
497            options.payload_size_hint = frame_size(self)?;
498        }
499        U3vStreamBuilder::new(self.transport())
500            .options(options)
501            .time_sync(self.time_sync().clone())
502            .build()
503    }
504}
505
506/// Bytes in one frame. The camera's `PayloadSize` is the authority: it knows
507/// its own packing and padding. Without it, the format's `image_bytes` for
508/// width × height, exact for a packed format such as `Mono12Packed`; guessing
509/// one byte a pixel made the reader take the rest of the image for the
510/// trailer and fail (Codex review of #179).
511fn frame_size<T: viva_genapi::RegisterIo>(camera: &crate::Camera<T>) -> Result<u64, GenicamError> {
512    match camera.get("PayloadSize") {
513        Ok(text) => {
514            if let Some(size) = text.parse::<u64>().ok().filter(|&size| size > 0) {
515                return Ok(size);
516            }
517        }
518        // Only a camera without the feature falls back. One that has it but
519        // cannot answer — I/O, access, availability — must not get a
520        // computed size that misses its padding or chunk data (Codex review
521        // of #180).
522        Err(error) if payload_size_is_absent(&error) => {}
523        Err(error) => return Err(error),
524    }
525    let dimension = |name: &str| -> Result<u32, GenicamError> {
526        let value = camera.get_integer(name)?;
527        u32::try_from(value).map_err(|_| {
528            viva_genapi::GenApiError::Range {
529                name: name.to_string(),
530                value: viva_genapi::swissknife::Value::Int(value),
531                violation: viva_genapi::RangeViolation::Unrepresentable,
532            }
533            .into()
534        })
535    };
536    let pixel_format = camera.get("PixelFormat")?;
537    computed_frame_size(&pixel_format, dimension("Width")?, dimension("Height")?)
538}
539
540/// The bytes a `width × height` frame in the `pixel_format` named occupies,
541/// for a camera without `PayloadSize`.
542fn computed_frame_size(pixel_format: &str, width: u32, height: u32) -> Result<u64, GenicamError> {
543    PixelFormat::from_name(pixel_format)
544        .image_bytes(width, height)
545        .map(|bytes| bytes as u64)
546        .ok_or_else(|| GenicamError::UnsizedFrame {
547            pixel_format: pixel_format.to_string(),
548        })
549}
550
551/// Whether reading `PayloadSize` failed because the camera has no such
552/// feature, the one failure a computed size may stand in for.
553fn payload_size_is_absent(error: &GenicamError) -> bool {
554    matches!(
555        error,
556        GenicamError::GenApi(viva_genapi::GenApiError::NodeNotFound(_))
557    )
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    fn idle_frame_receiver() -> U3vFrameStream {
565        U3vFrameStream {
566            shared: Arc::new(Shared::new()),
567            reader: None,
568            stats: StreamStatsAccumulator::new(),
569            time_sync: None,
570            disable: None,
571        }
572    }
573
574    fn enqueue_burst(frames: &U3vFrameStream, count: u64) {
575        for block_id in 1..=count {
576            let mut frame = Frame::new(
577                bytes::Bytes::from(vec![block_id as u8; 24 * 16]),
578                24,
579                16,
580                PixelFormat::Mono8,
581            );
582            frame.block_id = block_id;
583            frames.shared.enqueue(frame, &frames.stats);
584        }
585        frames.shared.queue.finish();
586    }
587
588    #[test]
589    fn default_u3v_delivery_keeps_startup_frames_until_first_read() {
590        let mut frames = idle_frame_receiver();
591        enqueue_burst(&frames, 12);
592        assert_eq!(frames.stats().frames_backpressure, 0);
593        assert_eq!(frames.stats().frames_complete, 0);
594        for block_id in 1..=12 {
595            let frame = frames.next_frame_blocking(Duration::ZERO).unwrap().unwrap();
596            assert_eq!(frame.block_id, block_id);
597            assert!(frame.is_complete());
598            assert!(frame.payload.iter().all(|&byte| byte == block_id as u8));
599        }
600        assert!(
601            frames
602                .next_frame_blocking(Duration::ZERO)
603                .unwrap()
604                .is_none()
605        );
606        let stats = frames.stats();
607        assert_eq!(stats.frames_complete, 12);
608        assert_eq!(stats.frames_lost(), 0);
609        assert_eq!(stats.bytes, 12 * 24 * 16);
610    }
611
612    #[test]
613    fn default_u3v_delivery_is_bounded_and_counts_overflow_once() {
614        let mut frames = idle_frame_receiver();
615        enqueue_burst(&frames, 20);
616        assert_eq!(frames.stats().frames_backpressure, 4);
617        assert_eq!(frames.stats().frames_complete, 0);
618        let mut delivered = Vec::new();
619        while let Some(frame) = frames.next_frame_blocking(Duration::ZERO).unwrap() {
620            delivered.push(frame.block_id);
621        }
622        assert_eq!(delivered, (5..=20).collect::<Vec<_>>());
623        let stats = frames.stats();
624        assert_eq!(stats.frames_complete, 16);
625        assert_eq!(stats.frames_backpressure, 4);
626        assert_eq!(stats.frames_complete + stats.frames_lost(), 20);
627        assert_eq!((stats.frames_incomplete, stats.frames_missed), (0, 0));
628    }
629
630    /// Only a missing `PayloadSize` may be replaced by a computed size (Codex
631    /// review of #180).
632    #[test]
633    fn only_a_missing_payload_size_falls_back() {
634        use viva_genapi::GenApiError;
635        let missing = GenicamError::GenApi(GenApiError::NodeNotFound("PayloadSize".into()));
636        let refused = GenicamError::GenApi(GenApiError::Access {
637            name: "PayloadSize".into(),
638            refused: viva_genapi::AccessDirection::Read,
639        });
640        let failed = GenicamError::U3v {
641            during: "read PayloadSize",
642            source: U3vError::Timeout,
643        };
644        assert!(payload_size_is_absent(&missing));
645        assert!(!payload_size_is_absent(&refused));
646        assert!(!payload_size_is_absent(&failed));
647    }
648
649    /// Without `PayloadSize`, a frame is sized from its PFNC code: a packed
650    /// format at its packed size (`Mono12Packed`: 64 × 48 × 1.5, as the fake
651    /// U3V camera's own `PayloadSize` says), not refused.
652    #[test]
653    fn a_camera_without_payload_size_is_sized_from_its_format() {
654        assert_eq!(computed_frame_size("Mono8", 64, 48).unwrap(), 3072);
655        assert_eq!(computed_frame_size("Mono16", 64, 48).unwrap(), 6144);
656        assert_eq!(computed_frame_size("Mono12Packed", 64, 48).unwrap(), 4608);
657        assert_eq!(computed_frame_size("Mono10p", 64, 48).unwrap(), 3840);
658        assert_eq!(computed_frame_size("YUV422Packed", 64, 48).unwrap(), 6144);
659        // A name nobody knows has no size to compute.
660        assert!(computed_frame_size("Fancy42", 64, 48).is_err());
661    }
662}