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    /// Another [`Dac`](crate::Dac) is already open in this process (v0.1
24    /// supports one DAC at a time), or a previous one is still shutting down.
25    Busy,
26    /// Opening a DAC needs the Linux usbfs interface (Android or Linux).
27    PlatformUnsupported,
28    /// The file descriptor could not be used, or the interfaces the host
29    /// claimed do not match what the library needs to drive the device.
30    Claim(String),
31    /// A macOS libusb open, whole-device capture, or interface claim failed.
32    HostUsb {
33        operation: String,
34        kind: HostUsbFailureKind,
35        detail: String,
36    },
37    /// The DAC offers no alternate setting that can carry the request.
38    /// `offered` lists what it does offer.
39    Unsupported {
40        reason: String,
41        offered: Vec<AltSetting>,
42    },
43    /// The only way to stream the request is an asynchronous endpoint that has
44    /// no explicit feedback endpoint, which would need implicit feedback (an
45    /// associated IN data endpoint). That is not supported: without feedback the
46    /// DAC's clock and the host's packet timing drift apart. Set
47    /// [`DacConfig::allow_unsynchronized_async`](crate::DacConfig::allow_unsynchronized_async)
48    /// to stream it at the nominal rate anyway (never bit-perfect).
49    ImplicitFeedbackUnsupported,
50    /// The DAC would not confirm the sampling frequency, and the
51    /// configuration requires a verified rate
52    /// ([`DacConfig::require_verified_rate`](crate::DacConfig::require_verified_rate)).
53    ClockUnverified {
54        requested_hz: u32,
55        reported_hz: Option<u32>,
56    },
57    /// The device was unplugged or stopped answering on the bus.
58    DeviceLost,
59    /// An isochronous transfer, or the stream machinery around it, failed.
60    Transfer(String),
61    /// A class control request (clock, volume, mute) failed.
62    Control(String),
63    /// The call is not valid in the current state (closed handle, writing
64    /// after `drain()`, a second stream while one is open, ...).
65    InvalidState(String),
66    /// An argument was out of range or malformed.
67    InvalidArgument(String),
68    /// The DAC has no usable hardware volume control (none, or its start-up
69    /// attenuation could not be verified) and
70    /// [`DacConfig::require_hardware_volume`](crate::DacConfig::require_hardware_volume)
71    /// is on: a stream would play at the DAC's own level with no way for the
72    /// host to bring it down. Ask the user to allow fixed-level output and open
73    /// the DAC again with `require_hardware_volume` off. `negotiate` and
74    /// `capabilities` still work, so the host can show what the DAC offers.
75    VolumeUnavailable,
76    /// Reconfiguration did not drain before its deadline. The original stream remains open/draining.
77    ReconfigureDrainTimeout,
78    /// Stream retirement, retained ownership, or rollback failed. Close the DAC before further use.
79    ReconfigureUnusable(String),
80}
81
82impl Error {
83    /// Stable identifier: `busy`, `platform_unsupported`, `claim`,
84    /// `unsupported`, `implicit_feedback_unsupported`, `clock_unverified`, `device_lost`, `transfer`,
85    /// `control`, `invalid_state`, `invalid_argument`, `volume_unavailable`.
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 => "another DAC session is open in this process".to_string(),
110            Self::PlatformUnsupported => {
111                "direct USB output needs Linux usbfs (Android or Linux)".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}