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