1use 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
24const U3V_READ_POLL: Duration = Duration::from_millis(50);
27
28type DisableStream = Arc<dyn Fn(bool) -> bool + Send + Sync>;
32
33struct 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
56pub 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 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 pub fn set_deliver_incomplete(&mut self, deliver: bool) {
128 self.shared
129 .deliver_incomplete
130 .store(deliver, Ordering::Relaxed);
131 }
132
133 pub fn set_time_sync(&mut self, time_sync: TimeSync) {
136 self.time_sync = Some(time_sync);
137 }
138
139 pub fn stats(&self) -> StreamStats {
141 self.stats.snapshot()
142 }
143
144 pub fn stats_handle(&self) -> StreamStatsAccumulator {
146 self.stats.clone()
147 }
148
149 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 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 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 pub fn stop(&self) {
197 self.shared.stop.store(true, Ordering::Release);
198 }
199
200 pub fn close(mut self) {
203 self.close_inner();
204 }
205
206 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 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
244fn 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 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
294fn 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
328const PAYLOAD_TYPE_IMAGE: u16 = 0x0001;
330const CHUNK_FLAG: u16 = 0x4000;
332
333fn 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
386pub 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 pub fn new(device: &'a U3vRegisterIo<T>) -> Self {
403 Self {
404 device,
405 options: U3vStreamOptions::default(),
406 time_sync: None,
407 }
408 }
409
410 pub fn options(mut self, options: U3vStreamOptions) -> Self {
412 self.options = options;
413 self
414 }
415
416 pub fn payload_size(mut self, bytes: u64) -> Self {
419 self.options.payload_size_hint = bytes;
420 self
421 }
422
423 pub fn max_transfer_size(mut self, bytes: u32) -> Self {
425 self.options.max_transfer_size = bytes;
426 self
427 }
428
429 pub fn transfers_in_flight(mut self, transfers: usize) -> Self {
431 self.options.transfers_in_flight = transfers;
432 self
433 }
434
435 pub fn time_sync(mut self, time_sync: TimeSync) -> Self {
437 self.time_sync = Some(time_sync);
438 self
439 }
440
441 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 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
506fn 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 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
540fn 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
551fn 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 #[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 #[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 assert!(computed_frame_size("Fancy42", 64, 48).is_err());
661 }
662}