Skip to main content

usbdac_core/
error.rs

1//! The error type of the public API.
2
3use crate::capabilities::AltSetting;
4use std::fmt;
5
6/// Host-side USB admission failure; it does not by itself identify a DAC fault.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
8pub enum HostUsbFailureKind {
9    AccessDenied,
10    InUse,
11    DeviceLost,
12    NotSupported,
13    Other,
14}
15
16/// Everything the public API can fail with.
17///
18/// [`Error::code`] returns a stable machine-readable identifier for each
19/// variant (the JNI layer puts it in the exception message).
20#[derive(Debug, Clone, PartialEq)]
21#[non_exhaustive]
22pub enum Error {
23    /// The requested device or operation has a retained owner, or a previous owner is still shutting down.
24    Busy,
25    /// The platform or requested USB backend is unavailable.
26    PlatformUnsupported,
27    /// The file descriptor could not be used, or the interfaces the host
28    /// claimed do not match what the library needs to drive the device.
29    Claim(String),
30    /// A macOS libusb open, whole-device capture, or interface claim failed.
31    HostUsb {
32        operation: String,
33        kind: HostUsbFailureKind,
34        detail: String,
35    },
36    /// The DAC offers no alternate setting that can carry the request.
37    /// `offered` lists what it does offer.
38    Unsupported {
39        reason: String,
40        offered: Vec<AltSetting>,
41    },
42    /// The only way to stream the request is an asynchronous endpoint that has
43    /// no explicit feedback endpoint, which would need implicit feedback (an
44    /// associated IN data endpoint). That is not supported: without feedback the
45    /// DAC's clock and the host's packet timing drift apart. Set
46    /// [`DacConfig::allow_unsynchronized_async`](crate::DacConfig::allow_unsynchronized_async)
47    /// to stream it at the nominal rate anyway (never bit-perfect).
48    ImplicitFeedbackUnsupported,
49    /// The DAC would not confirm the sampling frequency, and the
50    /// configuration requires a verified rate
51    /// ([`DacConfig::require_verified_rate`](crate::DacConfig::require_verified_rate)).
52    ClockUnverified {
53        requested_hz: u32,
54        reported_hz: Option<u32>,
55    },
56    /// The device was unplugged or stopped answering on the bus.
57    DeviceLost,
58    /// An isochronous transfer, or the stream machinery around it, failed.
59    Transfer(String),
60    /// A class control request (clock, volume, mute) failed.
61    Control(String),
62    /// The call is not valid in the current state (closed handle, writing
63    /// after `drain()`, a second stream while one is open, ...).
64    InvalidState(String),
65    /// An argument was out of range or malformed.
66    InvalidArgument(String),
67    /// The DAC has no usable hardware volume control (none, or its start-up
68    /// attenuation could not be verified) and
69    /// [`DacConfig::require_hardware_volume`](crate::DacConfig::require_hardware_volume)
70    /// is on: a stream would play at the DAC's own level with no way for the
71    /// host to bring it down. Ask the user to allow fixed-level output and open
72    /// the DAC again with `require_hardware_volume` off. `negotiate` and
73    /// `capabilities` still work, so the host can show what the DAC offers.
74    VolumeUnavailable,
75    /// Reconfiguration did not drain before its deadline. The original stream remains open/draining.
76    ReconfigureDrainTimeout,
77    /// Stream retirement, retained ownership, or rollback failed. Close the DAC before further use.
78    ReconfigureUnusable(String),
79}
80
81impl Error {
82    /// Stable identifier: `busy`, `platform_unsupported`, `claim`,
83    /// `unsupported`, `implicit_feedback_unsupported`, `clock_unverified`, `device_lost`, `transfer`,
84    /// `control`, `invalid_state`, `invalid_argument`, `volume_unavailable`, `host_usb`,
85    /// `reconfigure_drain_timeout`, `reconfigure_unusable`.
86    pub fn code(&self) -> &'static str {
87        match self {
88            Self::Busy => "busy",
89            Self::PlatformUnsupported => "platform_unsupported",
90            Self::Claim(_) => "claim",
91            Self::HostUsb { .. } => "host_usb",
92            Self::Unsupported { .. } => "unsupported",
93            Self::ImplicitFeedbackUnsupported => "implicit_feedback_unsupported",
94            Self::ClockUnverified { .. } => "clock_unverified",
95            Self::DeviceLost => "device_lost",
96            Self::Transfer(_) => "transfer",
97            Self::Control(_) => "control",
98            Self::InvalidState(_) => "invalid_state",
99            Self::InvalidArgument(_) => "invalid_argument",
100            Self::VolumeUnavailable => "volume_unavailable",
101            Self::ReconfigureDrainTimeout => "reconfigure_drain_timeout",
102            Self::ReconfigureUnusable(_) => "reconfigure_unusable",
103        }
104    }
105
106    /// Human-readable description without the code prefix.
107    pub fn message(&self) -> String {
108        match self {
109            Self::Busy => "the device or operation is busy, or a prior owner is shutting down".to_string(),
110            Self::PlatformUnsupported => {
111                "the requested USB backend is unavailable on this platform".to_string()
112            }
113            Self::HostUsb { operation, kind, detail } => format!("{operation}: {kind:?}: {detail}"),
114            Self::Claim(m)
115            | Self::Transfer(m)
116            | Self::Control(m)
117            | Self::InvalidState(m)
118            | Self::InvalidArgument(m)
119            | Self::ReconfigureUnusable(m) => m.clone(),
120            Self::Unsupported { reason, offered } => {
121                format!("{reason} ({} alternate setting(s) offered)", offered.len())
122            }
123            Self::ImplicitFeedbackUnsupported => "the DAC's asynchronous endpoint has no explicit feedback endpoint and no compatible input stream to take implicit feedback from (DacConfig::allow_unsynchronized_async streams it at the nominal rate, never bit-perfect)".to_string(),
124            Self::ClockUnverified {
125                requested_hz,
126                reported_hz,
127            } => match reported_hz {
128                Some(reported) => format!(
129                    "DAC clock not verified at {requested_hz} Hz (the DAC reports {reported} Hz)"
130                ),
131                None => format!("DAC clock not verified at {requested_hz} Hz (no readback)"),
132            },
133            Self::DeviceLost => "the USB device was disconnected".to_string(),
134            Self::ReconfigureDrainTimeout => "drain deadline expired; original stream remains open/draining and no alternate or clock was changed".into(),
135            Self::VolumeUnavailable => "the DAC has no usable hardware volume control, so a stream would play at the DAC's own level; allow fixed-level output (DacConfig::require_hardware_volume = false) to stream anyway".to_string(),
136        }
137    }
138}
139
140impl fmt::Display for Error {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write!(f, "{}: {}", self.code(), self.message())
143    }
144}
145
146impl std::error::Error for Error {}
147
148/// `Result` with the crate [`Error`].
149pub type Result<T> = std::result::Result<T, Error>;
150
151/// Maps a transport-internal `String` failure to [`Error::Control`], or to
152/// [`Error::DeviceLost`] when the message says the device went away.
153pub(crate) trait OrControl<T> {
154    fn or_control(self) -> Result<T>;
155}
156
157impl<T> OrControl<T> for std::result::Result<T, String> {
158    fn or_control(self) -> Result<T> {
159        self.map_err(|message| {
160            if is_device_gone(&message) {
161                Error::DeviceLost
162            } else {
163                Error::Control(message)
164            }
165        })
166    }
167}
168
169/// Whether a transport error message reports a vanished device (ENODEV or
170/// libusb's NO_DEVICE).
171pub(crate) fn is_device_gone(message: &str) -> bool {
172    let lower = message.to_ascii_lowercase();
173    lower.contains("no such device")
174        || lower.contains("os error 19")
175        || lower.contains("disconnected")
176        || lower.contains("no device")
177}