#[non_exhaustive]pub enum Error {
Show 15 variants
Busy,
PlatformUnsupported,
Claim(String),
HostUsb {
operation: String,
kind: HostUsbFailureKind,
detail: String,
},
Unsupported {
reason: String,
offered: Vec<AltSetting>,
},
ImplicitFeedbackUnsupported,
ClockUnverified {
requested_hz: u32,
reported_hz: Option<u32>,
},
DeviceLost,
Transfer(String),
Control(String),
InvalidState(String),
InvalidArgument(String),
VolumeUnavailable,
ReconfigureDrainTimeout,
ReconfigureUnusable(String),
}Expand description
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).
Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
Busy
Another Dac is already open in this process (v0.1
supports one DAC at a time), or a previous one is still shutting down.
PlatformUnsupported
Opening a DAC needs the Linux usbfs interface (Android or Linux).
Claim(String)
The file descriptor could not be used, or the interfaces the host claimed do not match what the library needs to drive the device.
HostUsb
A macOS libusb open, whole-device capture, or interface claim failed.
Unsupported
The DAC offers no alternate setting that can carry the request.
offered lists what it does offer.
ImplicitFeedbackUnsupported
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
to stream it at the nominal rate anyway (never bit-perfect).
ClockUnverified
The DAC would not confirm the sampling frequency, and the
configuration requires a verified rate
(DacConfig::require_verified_rate).
DeviceLost
The device was unplugged or stopped answering on the bus.
Transfer(String)
An isochronous transfer, or the stream machinery around it, failed.
Control(String)
A class control request (clock, volume, mute) failed.
InvalidState(String)
The call is not valid in the current state (closed handle, writing
after drain(), a second stream while one is open, …).
InvalidArgument(String)
An argument was out of range or malformed.
The DAC has no usable hardware volume control (none, or its start-up
attenuation could not be verified) and
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.
ReconfigureDrainTimeout
Reconfiguration did not drain before its deadline. The original stream remains open/draining.
ReconfigureUnusable(String)
Stream retirement, retained ownership, or rollback failed. Close the DAC before further use.
Implementations§
Source§impl Error
impl Error
Sourcepub fn code(&self) -> &'static str
pub fn code(&self) -> &'static str
Stable identifier: busy, platform_unsupported, claim,
unsupported, implicit_feedback_unsupported, clock_unverified, device_lost, transfer,
control, invalid_state, invalid_argument, volume_unavailable.
Examples found in repository?
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69 log::set_logger(&LOGGER).unwrap();
70 log::set_max_level(log::LevelFilter::Info);
71 println!(
72 "SOURCE {}; QEMU null audio backend",
73 option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74 );
75 let f = OpenOptions::new()
76 .read(true)
77 .write(true)
78 .open("/dev/bus/usb/001/002")?;
79 let fd = f.as_raw_fd();
80 for i in [0u32, 1] {
81 let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82 println!("CLAIM interface={i} result={r}");
83 if r != 0 {
84 return Err(std::io::Error::last_os_error().into());
85 }
86 }
87 assert_eq!(alt(fd), 0);
88 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89 .with_claimed_interfaces(vec![0u8, 1])
90 .with_device_name("/dev/bus/usb/001/002");
91 let before = volume(fd)?;
92 let dac = Dac::open(fd, info, DacConfig::default())?;
93 let capabilities = dac.capabilities()?;
94 assert_eq!(
95 capabilities.uac_version,
96 usbdac_core::UacVersion::V1,
97 "this probe proves UAC1 only"
98 );
99 println!("CAPABILITIES {capabilities:?}");
100 let exact = StreamRequest::pcm(44_100, 2, 16);
101 assert!(
102 matches!(
103 dac.negotiate(&exact),
104 Err(usbdac_core::Error::Unsupported { .. })
105 ),
106 "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107 );
108 let adaptive = StreamRequest {
109 rate_policy: usbdac_core::RatePolicy::NearestSupported,
110 ..exact
111 };
112 let fmt = dac.negotiate(&adaptive)?;
113 assert_eq!(
114 fmt.sample_rate, 48_000,
115 "adaptive QEMU setup must use the supported wire rate"
116 );
117 println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118 println!("FORMAT {fmt:?}");
119 let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120 let mut stream = dac.open_stream(&fmt, listener.clone())?;
121 let mut data = Vec::new();
122 for i in 0..4800i32 {
123 let v = (((i % 96) - 48) * 20) as i16;
124 data.extend_from_slice(&v.to_le_bytes());
125 data.extend_from_slice(&(-v).to_le_bytes());
126 }
127 for _ in 0..3 {
128 println!("PRIME {}", stream.write(&data)?);
129 }
130 stream.play()?;
131 let start = Instant::now();
132 while start.elapsed() < Duration::from_secs(2) {
133 let n = stream.writable_bytes().min(data.len());
134 if n >= 4 {
135 stream.write(&data[..n - n % 4])?;
136 }
137 thread::sleep(Duration::from_millis(2));
138 }
139 let st = stream.stats();
140 println!("PCM_STATS {st:?}");
141 let good = st.played_frames > 20_000
142 && st.completed_transfers > 0
143 && st.lost_frames == 0
144 && st.underruns == 0
145 && st.urb_timeouts == 0
146 && st.short_packets == 0
147 && st.zero_packets == 0;
148 stream.pause()?;
149 let held_volume = volume(fd)?;
150 let replacement = dac.reconfigure_stream(
151 &stream,
152 &StreamRequest::pcm(48_000, 2, 16),
153 listener.clone(),
154 Duration::from_secs(3),
155 )?;
156 assert!(replacement.rollback_cause.is_none());
157 assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158 assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159 assert_eq!(replacement.stream.played_frames(), 0);
160 assert_eq!(
161 volume(fd)?,
162 held_volume,
163 "reconfigure changed hardware volume"
164 );
165 stream = replacement.stream;
166 println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167 // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168 let rollback = dac.reconfigure_stream(
169 &stream,
170 &StreamRequest::pcm_float32(48_000, 2),
171 listener.clone(),
172 Duration::from_secs(3),
173 )?;
174 assert_eq!(
175 rollback.rollback_cause.as_ref().map(|e| e.code()),
176 Some("unsupported")
177 );
178 assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179 assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180 assert_eq!(
181 rollback.stream.format().request,
182 StreamRequest::pcm(48_000, 2, 16)
183 );
184 assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185 stream = rollback.stream;
186 for _ in 0..3 {
187 stream.write(&data)?;
188 }
189 stream.play()?;
190 thread::sleep(Duration::from_millis(100));
191 assert!(
192 stream.played_frames() > 0,
193 "rolled-back stream did not resume real completions"
194 );
195 assert_eq!(stream.stats().lost_frames, 0);
196 println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197 stream.pause()?;
198 stream.close()?;
199 dac.close()?;
200 assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201 println!("RETIRED true");
202 assert_eq!(alt(fd), 0);
203 let after = volume(fd)?;
204 assert_eq!(
205 after, before,
206 "original per-channel volume was not restored"
207 );
208 println!("VOLUME_RESTORED {after:?}");
209 for i in [1u32, 0] {
210 let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211 println!("RELEASE interface={i} result={r}");
212 assert_eq!(r, 0);
213 }
214 assert!(good, "no proven lossless media completions");
215 println!("QEMU_PCM_PASS");
216 Ok(())
217}Trait Implementations§
Source§impl Error for Error
impl Error for Error
1.30.0 · Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
use the Display impl or to_string()