pub struct DeviceInfo {
pub vendor_id: u16,
pub product_id: u16,
pub product_name: String,
pub manufacturer_name: Option<String>,
pub device_name: Option<String>,
pub claimed_interfaces: Vec<u8>,
pub configuration_id: Option<u8>,
pub unavailable_feedback_interfaces: Vec<u8>,
}Expand description
Identity of the USB device and the interfaces the host has claimed.
On Android the host gets the file descriptor from
UsbDeviceConnection.getFileDescriptor() after claiming the audio
interfaces with claimInterface; claimed_interfaces lists those interface
numbers. The library never claims or releases interfaces itself: it checks
that the host claimed all AudioControl and playback AudioStreaming interfaces
of the active configuration, plus only preflight-approved feedback sources.
Fields§
§vendor_id: u16§product_id: u16§product_name: StringProduct string (UsbDevice.getProductName()); used for quirk matching.
manufacturer_name: Option<String>§device_name: Option<String>Platform device name, for example /dev/bus/usb/001/004. Only used to
key the remembered original volume.
claimed_interfaces: Vec<u8>Interface numbers the host has claimed.
configuration_id: Option<u8>Active configuration identified by feedback claim preflight.
Plausible feedback sources the host could not claim.
Implementations§
Source§impl DeviceInfo
impl DeviceInfo
Sourcepub fn new(
vendor_id: u16,
product_id: u16,
product_name: impl Into<String>,
) -> Self
pub fn new( vendor_id: u16, product_id: u16, product_name: impl Into<String>, ) -> Self
Examples found in repository?
209pub fn open_from_android(
210 host: &mut AndroidHost,
211 vendor_id: u16,
212 product_id: u16,
213 product_name: &str,
214 device_name: &str,
215 config: DacConfig,
216) -> Result<Dac> {
217 let identity =
218 DeviceInfo::new(vendor_id, product_id, product_name).with_device_name(device_name);
219 open_dac(host, identity, config)
220}More examples
9fn discovery() {
10 use usbdac_core::{DeviceInfo, HotplugHub, UsbPermission};
11 let hub = HotplugHub::new();
12 let events = hub.subscribe();
13 let attachment = hub.attached(
14 "android-device-name",
15 DeviceInfo::new(1, 2, "DAC"),
16 UsbPermission::Required,
17 );
18 // Pass attachment.id through the host permission request/callback.
19 assert!(hub.permission_changed(attachment.id, UsbPermission::Granted));
20 hub.detached(attachment.id);
21 assert!(!hub.permission_changed(attachment.id, UsbPermission::Granted));
22 drop(events);
23}
24
25use usbdac_core::{Result, VolumeControl};
26async fn change(volume: VolumeControl) -> Result<()> {
27 let controls = volume.nonblocking()?;
28 let applied = controls.set_db(-45.0)?.await?;
29 assert!(applied.db <= 0.0);
30 Ok(())
31}
32
33fn fake() {
34 use std::sync::Arc;
35 use usbdac_core::{fake::FakeDac, DeviceInfo, PlaybackDevice, PlaybackStream, StreamRequest};
36 let request = StreamRequest::pcm(48_000, 2, 16);
37 let dac = FakeDac::new(DeviceInfo::new(1, 2, "test"), vec![request], 128).unwrap();
38 let format = dac.negotiate(&request).unwrap();
39 let stream = dac.open_stream(&format, Arc::new(|_| {})).unwrap();
40 assert_eq!(stream.write(&[0; 16]).unwrap(), 16);
41 assert_eq!(stream.advance(4).unwrap(), 4);
42 assert_eq!(stream.played_frames(), 4);
43 dac.detach();
44 assert!(stream.write(&[0; 4]).is_err());
45}61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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}4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn with_claimed_interfaces(self, interfaces: impl Into<Vec<u8>>) -> Self
pub fn with_claimed_interfaces(self, interfaces: impl Into<Vec<u8>>) -> Self
Examples found in repository?
35pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
36 let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
37 if !config.disable_feedback {
38 // Read-only: it names the active configuration and the IN interfaces a DAC may pace itself with.
39 let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
40 let got = host.claim_optional(&candidates);
41 info.configuration_id = Some(configuration);
42 info.unavailable_feedback_interfaces = candidates
43 .iter()
44 .copied()
45 .filter(|n| !got.contains(n))
46 .collect();
47 info.claimed_interfaces.extend(got);
48 }
49 // Lowers the DAC to at most -40 dB, verifies it, and touches neither the clock nor the audio.
50 Dac::open(host.fd(), info, config)
51}More examples
61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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}Sourcepub fn with_device_name(self, name: impl Into<String>) -> Self
pub fn with_device_name(self, name: impl Into<String>) -> Self
Examples found in repository?
209pub fn open_from_android(
210 host: &mut AndroidHost,
211 vendor_id: u16,
212 product_id: u16,
213 product_name: &str,
214 device_name: &str,
215 config: DacConfig,
216) -> Result<Dac> {
217 let identity =
218 DeviceInfo::new(vendor_id, product_id, product_name).with_device_name(device_name);
219 open_dac(host, identity, config)
220}More examples
61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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}4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}