Skip to main content

Error

Enum Error 

Source
#[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
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

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.

Fields

§operation: String
§detail: String
§

Unsupported

The DAC offers no alternate setting that can carry the request. offered lists what it does offer.

Fields

§reason: String
§offered: Vec<AltSetting>
§

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).

Fields

§requested_hz: u32
§reported_hz: Option<u32>
§

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.

§

VolumeUnavailable

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

Source

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?
examples/qemu_smoke.rs (line 175)
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}
Source

pub fn message(&self) -> String

Human-readable description without the code prefix.

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Replaced by Error::source.
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl PartialEq for Error

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Error

Auto Trait Implementations§

§

impl Forget for Error

§

impl Freeze for Error

§

impl Move for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.