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