Skip to main content

viva_u3v/
native.rs

1//! The `usb` feature's transport: [`nusb`], a pure-Rust USB library
2//! (ADR-0032).
3//!
4//! One camera has run it: on macOS over USB 2 (ADR-0032 §8), and on Windows
5//! once WinUSB was installed on its interface 0; Linux and SuperSpeed have
6//! not (backlog TC-27). What the code relies on
7//! is `nusb`'s documented behaviour: transfers on one endpoint
8//! complete in the order they were submitted, a cancelled transfer still
9//! comes back, an IN transfer ends at a short packet, and its length must
10//! be a multiple of the endpoint's maximum packet size.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16
17use nusb::transfer::{Buffer, Bulk, ControlOut, ControlType, In, Out, Recipient, TransferError};
18use nusb::{Endpoint, Interface, MaybeFuture};
19
20use crate::U3vError;
21use crate::bootstrap::UsbSpeed;
22use crate::descriptor::{U3vInterfaceInfo, parse_u3v_interfaces};
23use crate::discovery::U3vDeviceInfo;
24use crate::usb::{BulkIn, Completion, UsbTransfer};
25
26/// The standard `SET_FEATURE` request, and the `ENDPOINT_HALT` feature
27/// (USB 3.2 §9.4.9, Table 9-7).
28const SET_FEATURE: u8 = 0x03;
29const ENDPOINT_HALT: u16 = 0;
30
31/// How long the control transfers of an endpoint reset may take.
32const RESET_TIMEOUT: Duration = Duration::from_millis(1000);
33
34/// [`UsbTransfer`] over a USB3 Vision device opened with `nusb`: its
35/// control interface claimed, and its streaming and event interfaces when
36/// it has them.
37///
38/// A streaming or event interface that cannot be claimed does not stop the
39/// camera from opening — its features still work — but opening a stream or
40/// events on it returns the claim's error (backlog UV-03: it used to be
41/// discarded).
42pub struct NusbTransfer {
43    interfaces: U3vInterfaceInfo,
44    control_in: Mutex<Endpoint<Bulk, In>>,
45    control_out: Mutex<Endpoint<Bulk, Out>>,
46    stream: Option<Claimed>,
47    event: Option<Claimed>,
48    packet_sizes: HashMap<u8, usize>,
49    speed: Option<UsbSpeed>,
50    presence: Arc<Presence>,
51}
52
53/// Whether the opened device is still listed by the operating system: what
54/// tells an unplug apart on macOS, where the transfers of an unplugged
55/// mvBlueFOX3-2004G failed with `kIOReturnNotResponding`,
56/// `kIOReturnNotReady` and `kIOReturnNotAttached` — unknown errors to
57/// `nusb`, which maps only `kIOReturnNoDevice` to a disconnect (UV-03).
58struct Presence {
59    /// `nusb`'s id for the device: the IORegistry entry on macOS, the bus
60    /// and address on Linux, the device instance on Windows. A device
61    /// plugged in again gets a new one.
62    id: nusb::DeviceId,
63    /// Once unlisted, gone for good: this handle cannot reach it again.
64    gone: AtomicBool,
65}
66
67impl Presence {
68    /// One look at the device list; `None` when it cannot be read.
69    fn check(&self) -> Option<bool> {
70        if self.gone.load(Ordering::Relaxed) {
71            return Some(false);
72        }
73        let mut devices = nusb::list_devices().wait().ok()?;
74        let present = devices.any(|device| device.id() == self.id);
75        if !present {
76            self.gone.store(true, Ordering::Relaxed);
77        }
78        Some(present)
79    }
80}
81
82/// A data interface, claimed or not.
83struct Claimed {
84    number: u8,
85    interface: Result<Interface, nusb::Error>,
86}
87
88impl NusbTransfer {
89    /// Open the device enumeration reported as `info` and claim its
90    /// USB3 Vision interfaces: control, and streaming and events where it
91    /// has them. [`U3vDevice::open_device`](crate::U3vDevice::open_device)
92    /// opens one this way.
93    pub fn open(info: &U3vDeviceInfo) -> Result<Self, U3vError> {
94        let found = nusb::list_devices()
95            .wait()
96            .map_err(nusb_error)?
97            .find(|d| {
98                d.bus_id() == info.bus
99                    && d.device_address() == info.address
100                    && d.vendor_id() == info.vendor_id
101                    && d.product_id() == info.product_id
102            })
103            .ok_or_else(|| U3vError::NotFound {
104                bus: info.bus.clone(),
105                address: info.address,
106            })?;
107        let device = found.open().wait().map_err(nusb_error)?;
108        let (interfaces, packet_sizes) = {
109            let config = device.active_configuration().map_err(U3vError::usb)?;
110            parse_u3v_interfaces(&config)
111                .ok_or(U3vError::Device("has no USB3 Vision control interface"))?
112        };
113
114        let claim = |number: u8| device.claim_interface(number).wait();
115        let control = claim(interfaces.control_iface)
116            .map_err(|source| claim_error("control", interfaces.control_iface, source))?;
117        let control_in = control
118            .endpoint::<Bulk, In>(interfaces.control_ep_in)
119            .map_err(nusb_error)?;
120        let control_out = control
121            .endpoint::<Bulk, Out>(interfaces.control_ep_out)
122            .map_err(nusb_error)?;
123        let data_interface = |which: &'static str, number: Option<u8>| {
124            number.map(|number| {
125                let interface = claim(number);
126                if let Err(error) = &interface {
127                    let error = claim_error(which, number, error.clone());
128                    tracing::warn!(
129                        %error,
130                        "cannot claim the camera's {which} interface; its features work, \
131                         but opening its {which} will fail"
132                    );
133                }
134                Claimed { number, interface }
135            })
136        };
137        let stream = data_interface("stream", interfaces.stream_iface);
138        let event = data_interface("event", interfaces.event_iface);
139
140        Ok(Self {
141            interfaces,
142            control_in: Mutex::new(control_in),
143            control_out: Mutex::new(control_out),
144            stream,
145            event,
146            packet_sizes: packet_sizes.into_iter().collect(),
147            speed: found.speed().map(speed),
148            presence: Arc::new(Presence {
149                id: found.id(),
150                gone: AtomicBool::new(false),
151            }),
152        })
153    }
154
155    /// The device's USB3 Vision interfaces and endpoints.
156    pub fn interfaces(&self) -> &U3vInterfaceInfo {
157        &self.interfaces
158    }
159
160    /// The claimed interface `endpoint` belongs to.
161    fn data_interface(&self, endpoint: u8) -> Result<&Interface, U3vError> {
162        let (which, claimed) = if Some(endpoint) == self.interfaces.stream_ep_in {
163            ("stream", self.stream.as_ref())
164        } else if Some(endpoint) == self.interfaces.event_ep_in {
165            ("event", self.event.as_ref())
166        } else {
167            return Err(U3vError::Device("has no such bulk IN endpoint"));
168        };
169        let claimed = claimed.ok_or(U3vError::Device("has no such interface"))?;
170        claimed
171            .interface
172            .as_ref()
173            .map_err(|source| claim_error(which, claimed.number, source.clone()))
174    }
175
176    fn packet_size(&self, endpoint: u8) -> usize {
177        self.packet_sizes
178            .get(&endpoint)
179            .copied()
180            .unwrap_or(1)
181            .max(1)
182    }
183}
184
185impl UsbTransfer for NusbTransfer {
186    fn bulk_write(&self, endpoint: u8, data: &[u8], timeout: Duration) -> Result<usize, U3vError> {
187        if endpoint != self.interfaces.control_ep_out {
188            return Err(U3vError::Device("has no such bulk OUT endpoint"));
189        }
190        let mut out = self
191            .control_out
192            .lock()
193            .map_err(|_| U3vError::Device("control endpoint lock poisoned"))?;
194        let completion = out.transfer_blocking(Buffer::from(data), timeout);
195        completion
196            .status
197            .map_err(|error| blocking_error(endpoint, error))?;
198        Ok(completion.actual_len)
199    }
200
201    fn bulk_read(
202        &self,
203        endpoint: u8,
204        buf: &mut [u8],
205        timeout: Duration,
206    ) -> Result<usize, U3vError> {
207        let requested = buf.len().div_ceil(self.packet_size(endpoint)) * self.packet_size(endpoint);
208        let completion = if endpoint == self.interfaces.control_ep_in {
209            let mut control = self
210                .control_in
211                .lock()
212                .map_err(|_| U3vError::Device("control endpoint lock poisoned"))?;
213            control.transfer_blocking(Buffer::new(requested.max(1)), timeout)
214        } else {
215            let mut queue = self
216                .data_interface(endpoint)?
217                .endpoint::<Bulk, In>(endpoint)
218                .map_err(nusb_error)?;
219            queue.transfer_blocking(Buffer::new(requested.max(1)), timeout)
220        };
221        completion
222            .status
223            .map_err(|error| blocking_error(endpoint, error))?;
224        let data = completion.buffer.into_vec();
225        if data.len() > buf.len() {
226            return Err(U3vError::Length {
227                what: "bulk IN transfer",
228                expected: buf.len(),
229                got: data.len(),
230            });
231        }
232        buf[..data.len()].copy_from_slice(&data);
233        Ok(data.len())
234    }
235
236    fn bulk_in(self: &Arc<Self>, endpoint: u8) -> Result<Box<dyn BulkIn>, U3vError> {
237        let interface = self.data_interface(endpoint)?.clone();
238        let queue = interface
239            .endpoint::<Bulk, In>(endpoint)
240            .map_err(nusb_error)?;
241        Ok(Box::new(NusbBulkIn {
242            packet: queue.max_packet_size().max(1),
243            queue,
244            interface,
245            endpoint,
246            presence: Arc::clone(&self.presence),
247        }))
248    }
249
250    fn max_packet_size(&self, endpoint: u8) -> Option<usize> {
251        self.packet_sizes.get(&endpoint).copied()
252    }
253
254    fn link_speed(&self) -> Option<UsbSpeed> {
255        self.speed
256    }
257
258    fn is_present(&self) -> Option<bool> {
259        self.presence.check()
260    }
261}
262
263/// A bulk IN endpoint with `nusb`'s own transfer queue.
264struct NusbBulkIn {
265    queue: Endpoint<Bulk, In>,
266    /// For the control request that halts the endpoint.
267    interface: Interface,
268    endpoint: u8,
269    packet: usize,
270    presence: Arc<Presence>,
271}
272
273impl BulkIn for NusbBulkIn {
274    fn submit(&mut self, len: usize) {
275        // nusb refuses an IN transfer that is not a whole number of packets.
276        let len = len.max(1).div_ceil(self.packet) * self.packet;
277        self.queue.submit(Buffer::new(len));
278    }
279
280    fn pending(&self) -> usize {
281        self.queue.pending()
282    }
283
284    fn wait_next(&mut self, timeout: Duration) -> Option<Completion> {
285        if self.queue.pending() == 0 {
286            return None;
287        }
288        let completion = self.queue.wait_next_complete(timeout)?;
289        let status = completion
290            .status
291            .map_err(|error| transfer_error(self.endpoint, error));
292        Some(Completion::new(completion.buffer.into_vec(), status))
293    }
294
295    fn cancel_all(&mut self) {
296        self.queue.cancel_all();
297    }
298
299    fn reset(&mut self) -> Result<(), U3vError> {
300        self.interface
301            .control_out(
302                ControlOut {
303                    control_type: ControlType::Standard,
304                    recipient: Recipient::Endpoint,
305                    request: SET_FEATURE,
306                    value: ENDPOINT_HALT,
307                    index: u16::from(self.endpoint),
308                    data: &[],
309                },
310                RESET_TIMEOUT,
311            )
312            .wait()
313            .map_err(|error| transfer_error(self.endpoint, error))?;
314        self.queue.clear_halt().wait().map_err(nusb_error)
315    }
316
317    fn is_present(&self) -> Option<bool> {
318        self.presence.check()
319    }
320}
321
322/// A transfer's failure as the stream tells them apart: a disconnect ends
323/// it, a stall is recovered from, and the rest are recovered from as well
324/// (backlog UV-05 keeps which ones a camera really sends open).
325fn transfer_error(endpoint: u8, error: TransferError) -> U3vError {
326    match error {
327        TransferError::Disconnected => U3vError::Disconnected,
328        TransferError::Stall => U3vError::Stalled { endpoint },
329        TransferError::Cancelled => U3vError::Cancelled,
330        TransferError::Unknown(code) => U3vError::usb(OsError(code)),
331        other => U3vError::usb(other),
332    }
333}
334
335/// An operating-system code `nusb` passes on without a meaning: named when
336/// it is one of the IOKit codes an unplug on macOS produced, so a log says
337/// what happened. None of them is taken as a disconnect on its own —
338/// `kIOReturnNotResponding` can be transient — the device list decides
339/// ([`U3vError::may_mean_gone`]).
340#[derive(Debug)]
341struct OsError(u32);
342
343/// The IOKit codes an unplugged device's transfers fail with, as
344/// `IOReturn.h` names them.
345const IOKIT_CODES: [(u32, &str); 4] = [
346    (0xe000_02c0, "kIOReturnNoDevice"),
347    (0xe000_02d8, "kIOReturnNotReady"),
348    (0xe000_02d9, "kIOReturnNotAttached"),
349    (0xe000_02ed, "kIOReturnNotResponding"),
350];
351
352impl std::fmt::Display for OsError {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        match IOKIT_CODES.iter().find(|(code, _)| *code == self.0) {
355            Some((_, name)) => write!(f, "{name} (error {:#010x})", self.0),
356            None => write!(f, "unknown (error {:#010x})", self.0),
357        }
358    }
359}
360
361impl std::error::Error for OsError {}
362
363/// [`transfer_error`] for a blocking transfer, which `nusb` cancels when it
364/// times out.
365fn blocking_error(endpoint: u8, error: TransferError) -> U3vError {
366    match error {
367        TransferError::Cancelled => U3vError::Timeout,
368        other => transfer_error(endpoint, other),
369    }
370}
371
372/// A failure that is not a transfer's: opening, claiming, clearing a halt.
373fn nusb_error(error: nusb::Error) -> U3vError {
374    match error.kind() {
375        nusb::ErrorKind::Disconnected => U3vError::Disconnected,
376        _ => U3vError::usb(error),
377    }
378}
379
380/// An interface `nusb` could not claim, with what to do about it when that
381/// is known.
382fn claim_error(interface: &'static str, number: u8, source: nusb::Error) -> U3vError {
383    U3vError::Claim {
384        interface,
385        number,
386        hint: claim_hint(source.kind(), cfg!(windows)),
387        source: Box::new(source),
388    }
389}
390
391/// What the user can do about a failed claim. On Windows, `nusb` claims only
392/// through WinUSB, and Windows binds no driver to a USB3 Vision interface on
393/// its own: every driver problem — none, another one, WinUSB without its
394/// device interface GUID — comes back as `Unsupported`. An mvBlueFOX3 on
395/// Windows failed with "could not determine driver for interface" until
396/// WinUSB was installed on its interface 0 (backlog TC-27).
397fn claim_hint(kind: nusb::ErrorKind, windows: bool) -> Option<&'static str> {
398    (windows && kind == nusb::ErrorKind::Unsupported).then_some(
399        "on Windows the camera needs the WinUSB driver, which Zadig installs: \
400         see https://vitalyvorobyev.github.io/viva-genicam/usb.html#windows",
401    )
402}
403
404/// The speed `nusb` reports.
405pub(crate) fn speed(speed: nusb::Speed) -> UsbSpeed {
406    match speed {
407        nusb::Speed::Low => UsbSpeed::Low,
408        nusb::Speed::Full => UsbSpeed::Full,
409        nusb::Speed::High => UsbSpeed::High,
410        nusb::Speed::Super => UsbSpeed::Super,
411        // `nusb::Speed` is non-exhaustive; anything newer is faster.
412        _ => UsbSpeed::SuperPlus,
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    /// UV-02/UV-03: a disconnect is its own error, a stall names its
421    /// endpoint, a blocking transfer's cancellation is its timeout, and the
422    /// rest keep the library's error as their source.
423    #[test]
424    fn transfer_failures_map_to_what_the_stream_tells_apart() {
425        assert!(matches!(
426            transfer_error(0x82, TransferError::Disconnected),
427            U3vError::Disconnected
428        ));
429        assert!(matches!(
430            transfer_error(0x82, TransferError::Stall),
431            U3vError::Stalled { endpoint: 0x82 }
432        ));
433        assert!(matches!(
434            transfer_error(0x82, TransferError::Cancelled),
435            U3vError::Cancelled
436        ));
437        assert!(matches!(
438            blocking_error(0x81, TransferError::Cancelled),
439            U3vError::Timeout
440        ));
441        let fault = transfer_error(0x82, TransferError::Fault);
442        let U3vError::Usb(source) = &fault else {
443            panic!("{fault:?}");
444        };
445        assert!(source.downcast_ref::<TransferError>().is_some());
446        assert!(matches!(
447            blocking_error(0x81, TransferError::Disconnected),
448            U3vError::Disconnected
449        ));
450    }
451
452    /// The codes an unplug on macOS gave are named, and left to the device
453    /// list: on their own they are not a disconnect (UV-03).
454    #[test]
455    fn iokit_codes_are_named_and_not_conclusive() {
456        let error = transfer_error(0x83, TransferError::Unknown(0xe000_02ed));
457        assert_eq!(
458            error.to_string(),
459            "usb: kIOReturnNotResponding (error 0xe00002ed)"
460        );
461        assert!(error.may_mean_gone());
462        let other = transfer_error(0x83, TransferError::Unknown(0x47));
463        assert_eq!(other.to_string(), "usb: unknown (error 0x00000047)");
464    }
465
466    /// TC-27: a driver problem on Windows says to install WinUSB; anything
467    /// else, or the same kind elsewhere, has no hint.
468    #[test]
469    fn a_windows_driver_problem_points_at_winusb() {
470        let hint = claim_hint(nusb::ErrorKind::Unsupported, true).expect("a hint");
471        assert!(hint.contains("WinUSB"), "{hint}");
472        assert_eq!(claim_hint(nusb::ErrorKind::Busy, true), None);
473        assert_eq!(claim_hint(nusb::ErrorKind::Unsupported, false), None);
474
475        let error = U3vError::Claim {
476            interface: "control",
477            number: 0,
478            source: "could not determine driver for interface".into(),
479            hint: Some(hint),
480        };
481        assert_eq!(
482            error.to_string(),
483            format!(
484                "claim the control interface (0): could not determine driver for interface; {hint}"
485            )
486        );
487    }
488
489    #[test]
490    fn nusb_speeds_map_to_ours() {
491        assert_eq!(speed(nusb::Speed::High), UsbSpeed::High);
492        assert_eq!(speed(nusb::Speed::Super), UsbSpeed::Super);
493        assert!(speed(nusb::Speed::High).is_below_superspeed());
494        assert!(!speed(nusb::Speed::SuperPlus).is_below_superspeed());
495    }
496}