Skip to main content

two_dac_smoke/
two_dac_smoke.rs

1//! Bounded normal-path two-device probe for QEMU's two UAC1 usb-audio devices.
2#[cfg(target_os = "linux")]
3mod linux {
4    use std::{
5        fs::{File, OpenOptions},
6        os::fd::AsRawFd,
7        sync::Arc,
8        time::{Duration, Instant},
9    };
10    use usbdac_core::{Dac, DacConfig, DacStream, DeviceInfo, Error, StreamRequest};
11    #[repr(C)]
12    struct Control {
13        kind: u8,
14        request: u8,
15        value: u16,
16        index: u16,
17        length: u16,
18        timeout: u32,
19        data: *mut u8,
20    }
21    fn read(
22        fd: i32,
23        kind: u8,
24        request: u8,
25        value: u16,
26        index: u16,
27        bytes: &mut [u8],
28    ) -> std::io::Result<()> {
29        let mut control = Control {
30            kind,
31            request,
32            value,
33            index,
34            length: bytes.len() as u16,
35            timeout: 1000,
36            data: bytes.as_mut_ptr(),
37        };
38        let result = unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) };
39        if result != bytes.len() as i32 {
40            Err(std::io::Error::last_os_error())
41        } else {
42            Ok(())
43        }
44    }
45    fn volume(fd: i32) -> std::io::Result<[i16; 2]> {
46        let mut values = [0; 2];
47        for channel in 1..=2u16 {
48            let mut bytes = [0; 2];
49            read(fd, 0xa1, 0x81, 0x0200 | channel, 0x0200, &mut bytes)?;
50            values[(channel - 1) as usize] = i16::from_le_bytes(bytes);
51        }
52        Ok(values)
53    }
54    fn alternate(fd: i32) -> std::io::Result<u8> {
55        let mut value = [255];
56        read(fd, 0x81, 10, 0, 1, &mut value)?;
57        Ok(value[0])
58    }
59    type OpenedDac = (File, Dac, DacStream, [i16; 2]);
60
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    }
89    fn feed(streams: &[&DacStream], duration: Duration) -> Result<(), Error> {
90        let mut audio = Vec::new();
91        for sample in 0..4800i16 {
92            let value = (sample % 96 - 48) * 20;
93            audio.extend_from_slice(&value.to_le_bytes());
94            audio.extend_from_slice(&(-value).to_le_bytes());
95        }
96        for stream in streams {
97            for _ in 0..3 {
98                stream.write(&audio)?;
99            }
100        }
101        let start = Instant::now();
102        while start.elapsed() < duration {
103            for stream in streams {
104                let bytes = stream.writable_bytes().min(audio.len()) / 4 * 4;
105                if bytes > 0 {
106                    stream.write(&audio[..bytes])?;
107                }
108            }
109            std::thread::sleep(Duration::from_millis(2));
110        }
111        Ok(())
112    }
113    fn release(file: &File) -> std::io::Result<()> {
114        for interface in [1u32, 0] {
115            if unsafe { libc::ioctl(file.as_raw_fd(), 0x80045510u32 as _, &interface) } != 0 {
116                return Err(std::io::Error::last_os_error());
117            }
118        }
119        Ok(())
120    }
121    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
122        let (first_fd, first, first_stream, first_original) = open("/dev/bus/usb/001/002")?;
123        let (second_fd, second, second_stream, second_original) = open("/dev/bus/usb/001/003")?;
124        feed(&[&first_stream, &second_stream], Duration::from_secs(2))?;
125        let a = first_stream.stats();
126        let b = second_stream.stats();
127        assert!(
128            a.played_frames > 20_000
129                && b.played_frames > 20_000
130                && a.lost_frames == 0
131                && b.lost_frames == 0
132        );
133        let second_level = volume(second_fd.as_raw_fd())?;
134        let first_retirement = first.retirement();
135        first_stream.close()?;
136        first.close()?;
137        assert!(first_retirement.wait(Duration::from_secs(2)));
138        assert_eq!(alternate(first_fd.as_raw_fd())?, 0);
139        assert_eq!(volume(first_fd.as_raw_fd())?, first_original);
140        assert_eq!(alternate(second_fd.as_raw_fd())?, 1);
141        assert_eq!(
142            volume(second_fd.as_raw_fd())?,
143            second_level,
144            "first close changed second volume"
145        );
146        feed(&[&second_stream], Duration::from_secs(1))?;
147        let after = second_stream.stats();
148        assert!(after.played_frames > b.played_frames && after.lost_frames == 0);
149        let second_retirement = second.retirement();
150        second_stream.close()?;
151        second.close()?;
152        assert!(second_retirement.wait(Duration::from_secs(2)));
153        assert_eq!(alternate(second_fd.as_raw_fd())?, 0);
154        assert_eq!(volume(second_fd.as_raw_fd())?, second_original);
155        release(&first_fd)?;
156        release(&second_fd)?;
157        println!("TWO_DACS_PASS first_frames={} second_frames={} independent volume/alt-zero/retirement/duplicate protection",a.played_frames,after.played_frames);
158        Ok(())
159    }
160}
161#[cfg(target_os = "linux")]
162fn main() -> Result<(), Box<dyn std::error::Error>> {
163    linux::run()
164}
165#[cfg(not(target_os = "linux"))]
166fn main() {
167    eprintln!("two_dac_smoke requires a Linux guest with two QEMU UAC1 devices");
168}