#![allow(dead_code)]
use std::os::fd::RawFd;
use usbdac_core::{
AltFormat, Capabilities, Dac, DacConfig, DeviceInfo, Error, RatePolicy, Result, StreamFormat,
StreamRequest,
};
pub trait UsbHost {
fn fd(&self) -> RawFd;
fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>>;
fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8>;
}
pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
if !config.disable_feedback {
let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
let got = host.claim_optional(&candidates);
info.configuration_id = Some(configuration);
info.unavailable_feedback_interfaces = candidates
.iter()
.copied()
.filter(|n| !got.contains(n))
.collect();
info.claimed_interfaces.extend(got);
}
Dac::open(host.fd(), info, config)
}
pub struct Choices {
pub allow_fixed_volume: bool,
pub capture_support_trace: bool,
}
pub fn config_for(choices: &Choices) -> DacConfig {
DacConfig {
require_hardware_volume: !choices.allow_fixed_volume,
capture_feedback_trace: choices.capture_support_trace,
..DacConfig::default()
}
}
#[derive(Clone, Copy, Debug)]
pub struct TrackFormat {
pub sample_rate: u32,
pub channels: u16,
pub bits: u8,
}
pub struct Negotiated {
pub format: StreamFormat,
pub resample_to: Option<u32>,
}
pub fn negotiate(dac: &Dac, track: TrackFormat, allow_nearest: bool) -> Result<Negotiated> {
let policy = if allow_nearest {
RatePolicy::NearestSupported
} else {
RatePolicy::Exact
};
let request =
StreamRequest::pcm(track.sample_rate, track.channels, track.bits).with_rate_policy(policy);
let format = dac.negotiate(&request)?;
let resample_to = format
.rate_differs_from_request()
.then_some(format.sample_rate);
Ok(Negotiated {
format,
resample_to,
})
}
pub fn offers(capabilities: &Capabilities, track: TrackFormat) -> bool {
capabilities.alt_settings.iter().any(|alt| {
alt.format == AltFormat::Pcm
&& alt.channels == track.channels
&& alt.valid_bits == track.bits
&& alt.sample_rates.contains(&track.sample_rate)
})
}
pub enum Next {
AskListener(&'static str),
OtherOutput(&'static str),
FixTheHost(&'static str),
Report(&'static str),
}
pub fn next_step(error: &Error) -> Next {
match error {
Error::VolumeUnavailable => {
Next::AskListener("the DAC has no volume control: allow a fixed level and open again")
}
Error::Claim(_) => Next::AskListener(
"the system keeps the DAC: replug it and check that nothing else holds it",
),
Error::Busy => Next::FixTheHost(
"this DAC already has an owner, or a reconfigure is running: close it or retry",
),
Error::Unsupported { .. } => {
Next::OtherOutput("the DAC has no alternate setting for this format")
}
Error::ImplicitFeedbackUnsupported => {
Next::OtherOutput("an asynchronous endpoint without feedback")
}
Error::ClockUnverified { .. } => Next::Report("the DAC did not confirm its sampling rate"),
Error::DeviceLost => Next::AskListener("the DAC was unplugged"),
Error::PlatformUnsupported => {
Next::Report("direct USB needs Linux usbfs: Android or Linux")
}
Error::InvalidState(_) | Error::InvalidArgument(_) => {
Next::FixTheHost("the call was not valid in this state")
}
Error::Transfer(_) | Error::Control(_) => {
Next::Report("a transfer or class request failed")
}
_ => Next::Report("an error this host does not know"),
}
}
pub struct AndroidHost {
fd: RawFd,
claimed: Vec<u8>,
claim_more: ClaimMore,
}
type ClaimMore = Box<dyn FnMut(&[u8]) -> Vec<u8> + Send>;
impl AndroidHost {
pub fn new(fd: RawFd, claimed: Vec<u8>, claim_more: ClaimMore) -> Self {
Self {
fd,
claimed,
claim_more,
}
}
}
impl UsbHost for AndroidHost {
fn fd(&self) -> RawFd {
self.fd
}
fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>> {
Ok(self.claimed.clone())
}
fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8> {
(self.claim_more)(candidates)
}
}
pub fn open_from_android(
host: &mut AndroidHost,
vendor_id: u16,
product_id: u16,
product_name: &str,
device_name: &str,
config: DacConfig,
) -> Result<Dac> {
let identity =
DeviceInfo::new(vendor_id, product_id, product_name).with_device_name(device_name);
open_dac(host, identity, config)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod usbfs {
use super::UsbHost;
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::os::fd::{AsRawFd, RawFd};
use std::path::Path;
use usbdac_core::{Error, Result};
#[repr(C)]
struct DisconnectClaim {
interface: libc::c_uint,
flags: libc::c_uint,
driver: [libc::c_char; 256],
}
#[repr(C)]
struct IoctlTransfer {
interface: libc::c_int,
code: libc::c_int,
data: *mut libc::c_void,
}
const CLAIM_INTERFACE: libc::Ioctl = libc::_IOR::<libc::c_uint>(b'U' as u32, 15);
const RELEASE_INTERFACE: libc::Ioctl = libc::_IOR::<libc::c_uint>(b'U' as u32, 16);
const IOCTL: libc::Ioctl = libc::_IOWR::<IoctlTransfer>(b'U' as u32, 18);
const DISCONNECT_CLAIM: libc::Ioctl = libc::_IOR::<DisconnectClaim>(b'U' as u32, 27);
const CONNECT: libc::c_int = libc::_IO(b'U' as u32, 23) as libc::c_int;
#[derive(Debug, Clone, Copy)]
struct Setting {
number: u8,
class: u8,
subclass: u8,
isochronous_out: bool,
}
pub struct UsbfsHost {
file: File,
settings: Vec<Setting>,
claimed: Vec<u8>,
}
impl UsbfsHost {
pub fn open(path: &Path) -> io::Result<Self> {
let mut file = OpenOptions::new().read(true).write(true).open(path)?;
let mut raw = Vec::new();
file.read_to_end(&mut raw)?;
let settings = parse_settings(raw.get(18..).unwrap_or(&[]));
Ok(Self {
file,
settings,
claimed: Vec::new(),
})
}
fn ioctl<T>(&self, request: libc::Ioctl, argument: *mut T) -> io::Result<()> {
if unsafe { libc::ioctl(self.file.as_raw_fd(), request, argument) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
fn claim(&mut self, interface: u8) -> io::Result<()> {
let mut claim = DisconnectClaim {
interface: interface.into(),
flags: 0,
driver: [0; 256],
};
self.ioctl(DISCONNECT_CLAIM, &mut claim)?;
self.claimed.push(interface);
Ok(())
}
}
impl UsbHost for UsbfsHost {
fn fd(&self) -> RawFd {
self.file.as_raw_fd()
}
fn claim_audio_interfaces(&mut self) -> Result<Vec<u8>> {
let mut wanted: Vec<u8> = self
.settings
.iter()
.filter(|s| {
s.class == 1 && (s.subclass == 1 || (s.subclass == 2 && s.isochronous_out))
})
.map(|s| s.number)
.collect();
wanted.sort_unstable();
wanted.dedup();
if wanted.is_empty() {
return Err(Error::Claim(
"no AudioControl and playback AudioStreaming interface".into(),
));
}
for interface in &wanted {
self.claim(*interface)
.map_err(|e| Error::Claim(format!("interface {interface}: {e}")))?;
}
Ok(wanted)
}
fn claim_optional(&mut self, candidates: &[u8]) -> Vec<u8> {
candidates
.iter()
.copied()
.filter(|n| self.claim(*n).is_ok())
.collect()
}
}
impl Drop for UsbfsHost {
fn drop(&mut self) {
for interface in std::mem::take(&mut self.claimed) {
let mut number: libc::c_uint = interface.into();
let _ = self.ioctl(RELEASE_INTERFACE, &mut number);
let mut connect = IoctlTransfer {
interface: interface.into(),
code: CONNECT,
data: std::ptr::null_mut(),
};
let _ = self.ioctl(IOCTL, &mut connect);
}
}
}
fn parse_settings(descriptors: &[u8]) -> Vec<Setting> {
let mut settings: Vec<Setting> = Vec::new();
let mut at = 0;
while at + 2 <= descriptors.len() {
let length = usize::from(descriptors[at]);
if length < 2 || at + length > descriptors.len() {
break;
}
let body = &descriptors[at..at + length];
match body[1] {
4 if length >= 9 => settings.push(Setting {
number: body[2],
class: body[5],
subclass: body[6],
isochronous_out: false,
}),
5 if length >= 7 => {
if let Some(last) = settings.last_mut() {
last.isochronous_out |= body[2] & 0x80 == 0 && body[3] & 0x03 == 1;
}
}
_ => {}
}
at += length;
}
let copy = settings.clone();
for setting in &mut settings {
setting.isochronous_out = copy
.iter()
.any(|s| s.number == setting.number && s.isochronous_out);
}
settings
}
}
fn main() {
println!(
"guide_open is a compile-checked example of docs/sdk/guide-rust.md; it needs a DAC to run."
);
}