Skip to main content

guide_open/
guide_open.rs

1#![allow(dead_code)]
2//! The host's half of opening a DAC, from a USB file descriptor to a negotiated format.
3//!
4//! This is the code of the first half of `docs/sdk/guide-rust.md`. It compiles on every host; it only
5//! runs on Linux or Android with a DAC. `cargo check --workspace --examples` keeps it compiling.
6
7use std::os::fd::RawFd;
8use usbdac_core::{
9    AltFormat, Capabilities, Dac, DacConfig, DeviceInfo, Error, RatePolicy, Result, StreamFormat,
10    StreamRequest,
11};
12
13// region rust-host
14/// What the host does with USB itself, before and after the library. The library never claims an
15/// interface and never closes the descriptor: on Android the Kotlin side owns the connection, on Linux
16/// your own code owns the usbfs file.
17pub trait UsbHost {
18    /// The usbfs file descriptor of the open device. The library duplicates it.
19    fn fd(&self) -> RawFd;
20
21    /// Claims the AudioControl interfaces and the playback AudioStreaming interfaces, taking them from
22    /// the system's audio driver, and returns their numbers. Fails with `Error::Claim`.
23    fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>>;
24
25    /// Tries to claim `candidates`, the optional interfaces a DAC may use for implicit feedback, and
26    /// returns the ones it got. A claim that fails is not an error: the library plays without it.
27    fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8>;
28}
29// endregion
30
31// region rust-open
32/// Claims the interfaces, asks the library which optional ones it can use, claims those, and opens.
33///
34/// Blocks (descriptor and clock reads): call it from a thread of your own, never from a UI thread.
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}
52// endregion
53
54// region rust-config
55/// The listener's choices, as a Rust app keeps them.
56pub struct Choices {
57    /// Play on a DAC whose volume cannot be lowered, at its own level.
58    pub allow_fixed_volume: bool,
59    /// Keep a USB feedback trace of the next attempt, for a support report.
60    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// endregion
71
72// region rust-negotiate
73/// What a decoder says about the track it is about to play.
74#[derive(Clone, Copy, Debug)]
75pub struct TrackFormat {
76    pub sample_rate: u32,
77    pub channels: u16,
78    /// Significant bits of the source: 16, 24 or 32.
79    pub bits: u8,
80}
81
82/// The wire format for a track, and whether the host must resample first.
83pub struct Negotiated {
84    pub format: StreamFormat,
85    /// `Some(rate)` when the DAC runs another rate than the track has. The stream is then not bit-perfect.
86    pub resample_to: Option<u32>,
87}
88
89/// Asks for the track's own format. With `allow_nearest` the DAC may run the nearest rate it has, and
90/// the result says so. Takes 100 ms or more: it programs the DAC's clock and reads it back.
91pub 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
109/// Whether the DAC lists the format among its PCM alternate settings, without touching its clock. A
110/// DAC that takes a continuous range of rates lists none here, so a `false` is a hint and `negotiate`
111/// has the last word.
112pub 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}
120// endregion
121
122// region rust-errors
123/// What a host does about each failure of the open path.
124pub enum Next {
125    /// Tell the listener and let them decide: allow a fixed volume, grant permission, replug.
126    AskListener(&'static str),
127    /// Use another output, or convert if the listener allowed it.
128    OtherOutput(&'static str),
129    /// A bug in the host's own sequence: close what is open first.
130    FixTheHost(&'static str),
131    /// Log it with the DAC's ids and the descriptors, and give up on this DAC.
132    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        // `Error` is non-exhaustive: a newer library may add variants.
164        _ => Next::Report("an error this host does not know"),
165    }
166}
167// endregion
168
169// region rust-android
170/// The Android side of [`UsbHost`]. Kotlin owns the `UsbDeviceConnection`: it asked for permission,
171/// opened the device, claimed the interfaces and holds them until the `Dac` is closed. It hands over the
172/// connection's file descriptor and the interface numbers it claimed. How it crosses (JNI, UniFFI, Dart
173/// FFI) is your bridge's business.
174pub struct AndroidHost {
175    fd: RawFd,
176    claimed: Vec<u8>,
177    /// Calls back into Kotlin: `UsbDeviceConnection.claimInterface(iface, true)` for each candidate.
178    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
207/// The values Kotlin passes: `UsbDevice.vendorId`, `productId`, `productName`, `manufacturerName` and
208/// `deviceName`, with the interfaces it claimed.
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}
221// endregion
222
223// region rust-usbfs
224/// The Linux side of [`UsbHost`]: a usbfs file, interfaces claimed with its ioctls. Compile-checked for
225/// Linux and Android targets. It has not been run on a Linux desktop by this project.
226#[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    // The usbfs ioctls of <linux/usbdevice_fs.h>, with the architecture's own number layout.
250    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    /// A code for `IOCTL`: bind the kernel's driver to the interface again.
255    const CONNECT: libc::c_int = libc::_IO(b'U' as u32, 23) as libc::c_int;
256
257    /// One interface setting of the device's configuration descriptor.
258    #[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        /// Opens `/dev/bus/usb/BBB/DDD`. The process needs read and write access to the node, usually
274        /// through a udev rule. Reading the node returns the device descriptor and then the
275        /// configuration descriptors. This reads the first configuration only: a DAC with several
276        /// needs the active one (a GET_CONFIGURATION request) before it is claimed.
277        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            // Takes the interface from the kernel's audio driver if it holds it.
298            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            // AudioControl (class 1, subclass 1) and every AudioStreaming interface (subclass 2) with an
316            // isochronous OUT endpoint in some alternate setting. Capture-only interfaces stay with the kernel.
317            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        /// Gives every interface back and asks the kernel to bind its audio driver again. Close the `Dac`
350        /// first: the interfaces are in use until it has closed.
351        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    /// Walks a configuration descriptor and lists its interface settings.
366    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                // Interface: number, alternate setting, endpoints, class, subclass.
377                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                // Endpoint: address (bit 7 is the direction), attributes (bits 0-1 are the transfer type).
384                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        // The settings of one interface share its number: keep the flag if any alternate setting has the endpoint.
394        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}
403// endregion
404
405fn 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}