1#![allow(dead_code)]
2use std::os::fd::RawFd;
8use usbdac_core::{
9 AltFormat, Capabilities, Dac, DacConfig, DeviceInfo, Error, RatePolicy, Result, StreamFormat,
10 StreamRequest,
11};
12
13pub trait UsbHost {
18 fn fd(&self) -> RawFd;
20
21 fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>>;
24
25 fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8>;
28}
29pub 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 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 Dac::open(host.fd(), info, config)
51}
52pub struct Choices {
57 pub allow_fixed_volume: bool,
59 pub capture_support_trace: bool,
61}
62
63pub fn config_for(choices: &Choices) -> DacConfig {
64 DacConfig {
65 require_hardware_volume: !choices.allow_fixed_volume,
66 capture_feedback_trace: choices.capture_support_trace,
67 ..DacConfig::default()
68 }
69}
70#[derive(Clone, Copy, Debug)]
75pub struct TrackFormat {
76 pub sample_rate: u32,
77 pub channels: u16,
78 pub bits: u8,
80}
81
82pub struct Negotiated {
84 pub format: StreamFormat,
85 pub resample_to: Option<u32>,
87}
88
89pub fn negotiate(dac: &Dac, track: TrackFormat, allow_nearest: bool) -> Result<Negotiated> {
92 let policy = if allow_nearest {
93 RatePolicy::NearestSupported
94 } else {
95 RatePolicy::Exact
96 };
97 let request =
98 StreamRequest::pcm(track.sample_rate, track.channels, track.bits).with_rate_policy(policy);
99 let format = dac.negotiate(&request)?;
100 let resample_to = format
101 .rate_differs_from_request()
102 .then_some(format.sample_rate);
103 Ok(Negotiated {
104 format,
105 resample_to,
106 })
107}
108
109pub fn offers(capabilities: &Capabilities, track: TrackFormat) -> bool {
113 capabilities.alt_settings.iter().any(|alt| {
114 alt.format == AltFormat::Pcm
115 && alt.channels == track.channels
116 && alt.valid_bits >= track.bits
117 && alt.sample_rates.contains(&track.sample_rate)
118 })
119}
120pub enum Next {
125 AskListener(&'static str),
127 OtherOutput(&'static str),
129 FixTheHost(&'static str),
131 Report(&'static str),
133}
134
135pub fn next_step(error: &Error) -> Next {
136 match error {
137 Error::VolumeUnavailable => {
138 Next::AskListener("the DAC has no volume control: allow a fixed level and open again")
139 }
140 Error::Claim(_) => Next::AskListener(
141 "the system keeps the DAC: replug it and check that nothing else holds it",
142 ),
143 Error::Busy => Next::FixTheHost(
144 "this DAC already has an owner, or a reconfigure is running: close it or retry",
145 ),
146 Error::Unsupported { .. } => {
147 Next::OtherOutput("the DAC has no alternate setting for this format")
148 }
149 Error::ImplicitFeedbackUnsupported => {
150 Next::OtherOutput("an asynchronous endpoint without feedback")
151 }
152 Error::ClockUnverified { .. } => Next::Report("the DAC did not confirm its sampling rate"),
153 Error::DeviceLost => Next::AskListener("the DAC was unplugged"),
154 Error::PlatformUnsupported => {
155 Next::Report("direct USB needs Linux usbfs: Android or Linux")
156 }
157 Error::InvalidState(_) | Error::InvalidArgument(_) => {
158 Next::FixTheHost("the call was not valid in this state")
159 }
160 Error::Transfer(_) | Error::Control(_) => {
161 Next::Report("a transfer or class request failed")
162 }
163 _ => Next::Report("an error this host does not know"),
165 }
166}
167pub struct AndroidHost {
175 fd: RawFd,
176 claimed: Vec<u8>,
177 claim_more: ClaimMore,
179}
180
181type ClaimMore = Box<dyn FnMut(&[u8]) -> Vec<u8> + Send>;
182
183impl AndroidHost {
184 pub fn new(fd: RawFd, claimed: Vec<u8>, claim_more: ClaimMore) -> Self {
185 Self {
186 fd,
187 claimed,
188 claim_more,
189 }
190 }
191}
192
193impl UsbHost for AndroidHost {
194 fn fd(&self) -> RawFd {
195 self.fd
196 }
197
198 fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>> {
199 Ok(self.claimed.clone())
200 }
201
202 fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8> {
203 (self.claim_more)(candidates)
204 }
205}
206
207pub 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}
221#[cfg(any(target_os = "linux", target_os = "android"))]
227pub mod usbfs {
228 use super::UsbHost;
229 use std::fs::{File, OpenOptions};
230 use std::io::{self, Read};
231 use std::os::fd::{AsRawFd, RawFd};
232 use std::path::Path;
233 use usbdac_core::{Error, Result};
234
235 #[repr(C)]
236 struct DisconnectClaim {
237 interface: libc::c_uint,
238 flags: libc::c_uint,
239 driver: [libc::c_char; 256],
240 }
241
242 #[repr(C)]
243 struct IoctlTransfer {
244 interface: libc::c_int,
245 code: libc::c_int,
246 data: *mut libc::c_void,
247 }
248
249 const CLAIM_INTERFACE: libc::Ioctl = libc::_IOR::<libc::c_uint>(b'U' as u32, 15);
251 const RELEASE_INTERFACE: libc::Ioctl = libc::_IOR::<libc::c_uint>(b'U' as u32, 16);
252 const IOCTL: libc::Ioctl = libc::_IOWR::<IoctlTransfer>(b'U' as u32, 18);
253 const DISCONNECT_CLAIM: libc::Ioctl = libc::_IOR::<DisconnectClaim>(b'U' as u32, 27);
254 const CONNECT: libc::c_int = libc::_IO(b'U' as u32, 23) as libc::c_int;
256
257 #[derive(Debug, Clone, Copy)]
259 struct Setting {
260 number: u8,
261 class: u8,
262 subclass: u8,
263 isochronous_out: bool,
264 }
265
266 pub struct UsbfsHost {
267 file: File,
268 settings: Vec<Setting>,
269 claimed: Vec<u8>,
270 }
271
272 impl UsbfsHost {
273 pub fn open(path: &Path) -> io::Result<Self> {
278 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
279 let mut raw = Vec::new();
280 file.read_to_end(&mut raw)?;
281 let settings = parse_settings(raw.get(18..).unwrap_or(&[]));
282 Ok(Self {
283 file,
284 settings,
285 claimed: Vec::new(),
286 })
287 }
288
289 fn ioctl<T>(&self, request: libc::Ioctl, argument: *mut T) -> io::Result<()> {
290 if unsafe { libc::ioctl(self.file.as_raw_fd(), request, argument) } < 0 {
291 return Err(io::Error::last_os_error());
292 }
293 Ok(())
294 }
295
296 fn claim(&mut self, interface: u8) -> io::Result<()> {
297 let mut claim = DisconnectClaim {
299 interface: interface.into(),
300 flags: 0,
301 driver: [0; 256],
302 };
303 self.ioctl(DISCONNECT_CLAIM, &mut claim)?;
304 self.claimed.push(interface);
305 Ok(())
306 }
307 }
308
309 impl UsbHost for UsbfsHost {
310 fn fd(&self) -> RawFd {
311 self.file.as_raw_fd()
312 }
313
314 fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>> {
315 let mut wanted: Vec<u8> = self
318 .settings
319 .iter()
320 .filter(|s| {
321 s.class == 1 && (s.subclass == 1 || (s.subclass == 2 && s.isochronous_out))
322 })
323 .map(|s| s.number)
324 .collect();
325 wanted.sort_unstable();
326 wanted.dedup();
327 if wanted.is_empty() {
328 return Err(Error::Claim(
329 "no AudioControl and playback AudioStreaming interface".into(),
330 ));
331 }
332 for interface in &wanted {
333 self.claim(*interface)
334 .map_err(|e| Error::Claim(format!("interface {interface}: {e}")))?;
335 }
336 Ok(wanted)
337 }
338
339 fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8> {
340 candidates
341 .iter()
342 .copied()
343 .filter(|n| self.claim(*n).is_ok())
344 .collect()
345 }
346 }
347
348 impl Drop for UsbfsHost {
349 fn drop(&mut self) {
352 for interface in std::mem::take(&mut self.claimed) {
353 let mut number: libc::c_uint = interface.into();
354 let _ = self.ioctl(RELEASE_INTERFACE, &mut number);
355 let mut connect = IoctlTransfer {
356 interface: interface.into(),
357 code: CONNECT,
358 data: std::ptr::null_mut(),
359 };
360 let _ = self.ioctl(IOCTL, &mut connect);
361 }
362 }
363 }
364
365 fn parse_settings(descriptors: &[u8]) -> Vec<Setting> {
367 let mut settings: Vec<Setting> = Vec::new();
368 let mut at = 0;
369 while at + 2 <= descriptors.len() {
370 let length = usize::from(descriptors[at]);
371 if length < 2 || at + length > descriptors.len() {
372 break;
373 }
374 let body = &descriptors[at..at + length];
375 match body[1] {
376 4 if length >= 9 => settings.push(Setting {
378 number: body[2],
379 class: body[5],
380 subclass: body[6],
381 isochronous_out: false,
382 }),
383 5 if length >= 7 => {
385 if let Some(last) = settings.last_mut() {
386 last.isochronous_out |= body[2] & 0x80 == 0 && body[3] & 0x03 == 1;
387 }
388 }
389 _ => {}
390 }
391 at += length;
392 }
393 let copy = settings.clone();
395 for setting in &mut settings {
396 setting.isochronous_out = copy
397 .iter()
398 .any(|s| s.number == setting.number && s.isochronous_out);
399 }
400 settings
401 }
402}
403fn main() {
406 println!(
407 "guide_open is a compile-checked example of docs/sdk/guide-rust.md; it needs a DAC to run."
408 );
409}