#[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
The requested device or operation has a retained owner, or a previous owner is still shutting down.
PlatformUnsupported
The platform or requested USB backend is unavailable.
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, host_usb,
reconfigure_drain_timeout, reconfigure_unusable.
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}More examples
829 pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830 let args: Vec<_> = std::env::args().collect();
831 if args.len() != 3
832 || !matches!(
833 args[2].as_str(),
834 "normal"
835 | "bad-cur"
836 | "stale-cur"
837 | "badd"
838 | "full-uac3"
839 | "full-uac3-volatile"
840 | "full-uac3-clock"
841 | "full-uac3-clock-bad"
842 | "full-uac3-clock-stale"
843 | "duplex"
844 | "retire"
845 | "reconfigure"
846 | "selector"
847 | "refuse-set"
848 | "zero-res"
849 | "full-uac3-nearest"
850 | "dop-carrier32"
851 | "dop-stereo24"
852 | "dop-no-carrier"
853 )
854 {
855 return Err(
856 "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857 );
858 }
859 let path = &args[1];
860 if !path.starts_with("/dev/bus/usb/") {
861 return Err("expected a usbfs device path".into());
862 }
863 let file = OpenOptions::new().read(true).write(true).open(path)?;
864 let fd = file.as_raw_fd();
865 // Read and validate the actual descriptor before claiming or invoking the driver.
866 let mut descriptor = [0u8; 18];
867 assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868 assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869 assert_eq!(
870 (
871 u16::from_le_bytes([descriptor[8], descriptor[9]]),
872 u16::from_le_bytes([descriptor[10], descriptor[11]])
873 ),
874 (VID, PID),
875 "refusing a device other than the fixture"
876 );
877 // Select the explicitly advertised fixture configuration before interface claims.
878 let configuration = match args[2].as_str() {
879 "badd" => 2u32,
880 "full-uac3"
881 | "full-uac3-volatile"
882 | "full-uac3-clock"
883 | "full-uac3-clock-bad"
884 | "full-uac3-clock-stale"
885 | "full-uac3-nearest" => 3,
886 _ => 1,
887 };
888 if configuration != 1 {
889 let mut config_descriptor = [0u8; 9];
890 assert_eq!(
891 control(
892 fd,
893 0x80,
894 6,
895 0x0200 | (configuration as u16 - 1),
896 0,
897 &mut config_descriptor
898 )?,
899 9
900 );
901 assert_eq!(
902 (
903 config_descriptor[0],
904 config_descriptor[1],
905 config_descriptor[5]
906 ),
907 (9, 2, configuration as u8)
908 );
909 if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910 return Err(std::io::Error::last_os_error().into());
911 }
912 }
913 let claims = if args[2] == "duplex" {
914 vec![0u8, 1, 2, 3]
915 } else {
916 vec![0u8, 1]
917 };
918 for &interface in &claims {
919 claim(fd, u32::from(interface), true)?;
920 }
921 assert_eq!(alt(fd)?, 0);
922 if matches!(
923 args[2].as_str(),
924 "badd" | "full-uac3" | "full-uac3-volatile"
925 ) {
926 assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927 let mut state = [2u8];
928 assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929 assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930 }
931 let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932 .with_claimed_interfaces(claims)
933 .with_device_name(path);
934 info.configuration_id = Some(configuration as u8);
935 let config = DacConfig {
936 require_hardware_volume: false,
937 require_verified_rate: true,
938 ..DacConfig::default()
939 };
940 let dac = if args[2] == "duplex" {
941 Dac::open_duplex_device(fd, info, config)?
942 } else {
943 Dac::open(fd, info, config)?
944 };
945 if args[2] == "duplex" {
946 return duplex(dac, fd);
947 }
948 if args[2] == "retire" {
949 return retire(dac, fd);
950 }
951 if args[2] == "reconfigure" {
952 return reconfigure(dac, fd);
953 }
954 if args[2].starts_with("dop-") {
955 return dop_resolution(dac, fd, &args[2]);
956 }
957 let caps = dac.capabilities()?;
958 if args[2] == "refuse-set" {
959 out_of_band("reset")?;
960 let requests = [
961 StreamRequest::pcm(96_000, 2, 16),
962 StreamRequest::pcm(48_000, 2, 16),
963 ];
964 let failure = dac.negotiate_candidates(&requests);
965 assert!(
966 matches!(
967 failure,
968 Err(Error::ClockUnverified {
969 requested_hz: 96_000,
970 ..
971 })
972 ),
973 "refused SET must be terminal: {failure:?}"
974 );
975 let snapshot = out_of_band("snapshot")?;
976 let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977 assert!(rates.contains("96000"));
978 assert!(
979 !rates.contains("48000"),
980 "second candidate was tried after uncertain SET: {snapshot}"
981 );
982 let retirement = dac.retirement();
983 dac.close()?;
984 assert!(retirement.wait(Duration::from_secs(3)));
985 assert_eq!(alt(fd)?, 0);
986 for interface in [1, 0] {
987 claim(fd, interface, false)?;
988 }
989 println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990 return Ok(());
991 }
992 if matches!(args[2].as_str(), "selector" | "zero-res") {
993 let (requested, expected) = if args[2] == "selector" {
994 (192_000, 96_000)
995 } else {
996 (96_000, 44_100)
997 };
998 out_of_band("reset")?;
999 let request =
1000 StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001 let format = dac.negotiate(&request)?;
1002 assert_eq!(format.sample_rate, expected);
1003 let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004 let snapshot = out_of_band("snapshot")?;
1005 let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006 let rejected = requested.to_string();
1007 assert!(
1008 !rates
1009 .split(|c: char| !c.is_ascii_digit())
1010 .any(|v| v == rejected),
1011 "requested unsupported rate was sent: {snapshot}"
1012 );
1013 println!(
1014 "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015 args[2]
1016 );
1017 stream.close()?;
1018 let retirement = dac.retirement();
1019 dac.close()?;
1020 assert!(retirement.wait(Duration::from_secs(3)));
1021 assert_eq!(alt(fd)?, 0);
1022 for interface in [1, 0] {
1023 claim(fd, interface, false)?;
1024 }
1025 println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026 return Ok(());
1027 }
1028 if args[2] == "badd" {
1029 badd(&dac, fd, &caps)?;
1030 assert_eq!(alt(fd)?, 0);
1031 dac.close()?;
1032 assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033 assert_eq!(alt(fd)?, 0);
1034 assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035 let power_log = out_of_band("snapshot")?;
1036 let powers = power_log
1037 .split("power=[")
1038 .nth(1)
1039 .ok_or("missing power history")?
1040 .split(']')
1041 .next()
1042 .ok_or("missing power terminator")?;
1043 assert!(
1044 powers
1045 .split(", ")
1046 .collect::<Vec<_>>()
1047 .windows(2)
1048 .any(|pair| pair == ["0", "2"]),
1049 "expected D0 to D2 transition: {power_log}"
1050 );
1051 for interface in [1, 0] {
1052 claim(fd, interface, false)?;
1053 }
1054 println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055 return Ok(());
1056 }
1057 if args[2] == "full-uac3-nearest" {
1058 return full_uac3_nearest(dac, fd, &caps);
1059 }
1060 if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061 return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062 }
1063 assert_eq!(
1064 caps.uac_version,
1065 if args[2].starts_with("full-uac3-clock") {
1066 UacVersion::V3
1067 } else {
1068 UacVersion::V2
1069 }
1070 );
1071 assert_eq!(caps.link_speed, LinkSpeed::High);
1072 let mut rates = caps.pcm_sample_rates.clone();
1073 rates.sort_unstable();
1074 rates.dedup();
1075 assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076 assert!(
1077 matches!(
1078 dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079 Err(Error::Unsupported { .. })
1080 ),
1081 "exact 192 kHz must be refused"
1082 );
1083 let request =
1084 StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085 let format = dac.negotiate(&request)?;
1086 assert_eq!(
1087 (
1088 format.sample_rate,
1089 format.channels,
1090 format.valid_bits,
1091 format.subslot_bytes,
1092 format.interface_number,
1093 format.alt_setting
1094 ),
1095 (96_000, 2, 16, 2, 1, 1)
1096 );
1097 assert_eq!(format.sync_type, SyncKind::Synchronous);
1098 assert_eq!(format.endpoint_address, 0x01);
1099 assert_eq!(format.link_speed, LinkSpeed::High);
1100 assert_eq!(format.bytes_per_frame(), 4);
1101 if args[2].starts_with("full-uac3-clock") {
1102 assert_eq!(format.service_interval_us, 125);
1103 assert!(!format.explicit_feedback);
1104 }
1105 let clock = format
1106 .clock
1107 .as_ref()
1108 .ok_or("fixture clock missing")?
1109 .clone();
1110 assert_eq!(
1111 (clock.control_interface, clock.source_id),
1112 (
1113 0,
1114 if args[2].starts_with("full-uac3-clock") {
1115 9
1116 } else {
1117 0x10
1118 }
1119 )
1120 );
1121 println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122 let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123 match args[2].as_str() {
1124 "normal" | "full-uac3-clock" => {
1125 let stream = dac.open_stream(&format, listener)?;
1126 assert_eq!(alt(fd)?, 1);
1127 let mut current = [0u8; 4];
1128 assert_eq!(
1129 control(
1130 fd,
1131 0xa1,
1132 1,
1133 0x0100,
1134 (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135 &mut current
1136 )?,
1137 4
1138 );
1139 assert_eq!(
1140 u32::from_le_bytes(current),
1141 96_000,
1142 "post-alt clock readback"
1143 );
1144 let mut pcm = Vec::with_capacity(9600 * 4);
1145 for i in 0..9600i32 {
1146 let v = (((i % 96) - 48) * 20) as i16;
1147 pcm.extend_from_slice(&v.to_le_bytes());
1148 pcm.extend_from_slice(&(-v).to_le_bytes());
1149 }
1150 for _ in 0..3 {
1151 stream.write(&pcm)?;
1152 }
1153 stream.play()?;
1154 let start = Instant::now();
1155 while start.elapsed() < Duration::from_secs(3)
1156 && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157 {
1158 let n = stream.writable_bytes().min(pcm.len());
1159 if n >= 4 {
1160 stream.write(&pcm[..n - n % 4])?;
1161 }
1162 thread::sleep(Duration::from_millis(2));
1163 }
1164 let stats = stream.stats();
1165 println!("PCM_STATS {stats:?}");
1166 assert!(
1167 stats.played_frames > 0 && stats.completed_transfers > 0,
1168 "no actual PCM completions"
1169 );
1170 stream.close()?;
1171 }
1172 mode => match dac.open_stream(&format, listener) {
1173 Err(error @ Error::ClockUnverified { .. }) => {
1174 let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175 None
1176 } else {
1177 Some(48_000)
1178 };
1179 assert!(
1180 matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181 );
1182 println!(
1183 "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184 error.code()
1185 );
1186 }
1187 Err(error) => {
1188 return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189 }
1190 Ok(stream) => {
1191 stream.close()?;
1192 return Err(format!("{mode} incorrectly admitted the stream").into());
1193 }
1194 },
1195 }
1196 assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197 dac.close()?;
1198 assert!(
1199 Dac::await_usb_retirement(Duration::from_secs(3)),
1200 "USB retirement timed out"
1201 );
1202 assert_eq!(alt(fd)?, 0);
1203 for interface in [1, 0] {
1204 claim(fd, interface, false)?;
1205 }
1206 println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207 Ok(())
1208 }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()