Skip to main content

DeviceInfo

Struct DeviceInfo 

Source
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: String

Product 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.

§unavailable_feedback_interfaces: Vec<u8>

Plausible feedback sources the host could not claim.

Implementations§

Source§

impl DeviceInfo

Source

pub fn new( vendor_id: u16, product_id: u16, product_name: impl Into<String>, ) -> Self

Examples found in repository?
examples/guide_open.rs (line 218)
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
Hide additional examples
examples/sdk_host_boundary.rs (line 15)
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}
examples/two_dac_smoke.rs (line 77)
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    }
examples/qemu_smoke.rs (line 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}
examples/loopback_capture.rs (lines 50-54)
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}
examples/usbip_lifecycle.rs (line 931)
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    }
Source

pub fn with_claimed_interfaces(self, interfaces: impl Into<Vec<u8>>) -> Self

Examples found in repository?
examples/guide_open.rs (line 36)
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
Hide additional examples
examples/two_dac_smoke.rs (line 79)
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    }
examples/qemu_smoke.rs (line 89)
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}
examples/usbip_lifecycle.rs (line 932)
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    }
Source

pub fn with_device_name(self, name: impl Into<String>) -> Self

Examples found in repository?
examples/guide_open.rs (line 218)
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
Hide additional examples
examples/two_dac_smoke.rs (line 78)
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    }
examples/qemu_smoke.rs (line 90)
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}
examples/loopback_capture.rs (line 55)
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}
examples/usbip_lifecycle.rs (line 933)
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    }
Source

pub fn with_manufacturer_name(self, name: impl Into<String>) -> Self

Trait Implementations§

Source§

impl Clone for DeviceInfo

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DeviceInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for DeviceInfo

Source§

impl PartialEq for DeviceInfo

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for DeviceInfo

Auto Trait Implementations§

§

impl Forget for DeviceInfo

§

impl Freeze for DeviceInfo
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for DeviceInfo

§

impl RefUnwindSafe for DeviceInfo

§

impl Send for DeviceInfo
where RawVecInner: Send,

§

impl Sync for DeviceInfo
where RawVecInner: Sync,

§

impl Unpin for DeviceInfo
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for DeviceInfo

§

impl UnwindSafe for DeviceInfo
where RawVecInner: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.