Skip to main content

qemu_smoke/
qemu_smoke.rs

1#![cfg_attr(not(target_os = "linux"), allow(unused))]
2use std::{
3    fs::OpenOptions,
4    os::fd::AsRawFd,
5    sync::Arc,
6    thread,
7    time::{Duration, Instant},
8};
9use usbdac_core::{Dac, DacConfig, DacEvent, DeviceInfo, StreamRequest};
10struct Logger;
11impl log::Log for Logger {
12    fn enabled(&self, _: &log::Metadata) -> bool {
13        true
14    }
15    fn log(&self, r: &log::Record) {
16        eprintln!("{} {}", r.level(), r.args())
17    }
18    fn flush(&self) {}
19}
20static LOGGER: Logger = Logger;
21#[repr(C)]
22struct Control {
23    kind: u8,
24    request: u8,
25    value: u16,
26    index: u16,
27    length: u16,
28    timeout: u32,
29    data: *mut u8,
30}
31fn alt(fd: i32) -> i32 {
32    let mut b = 255u8;
33    let mut c = Control {
34        kind: 0x81,
35        request: 10,
36        value: 0,
37        index: 1,
38        length: 1,
39        timeout: 1000,
40        data: &mut b,
41    };
42    let r = unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut c) };
43    println!("GET_INTERFACE result={r} alt={b}");
44    i32::from(b)
45}
46fn volume(fd: i32) -> std::io::Result<[i16; 2]> {
47    let mut values = [0; 2];
48    for channel in 1..=2u16 {
49        let mut bytes = [0u8; 2];
50        let mut c = Control {
51            kind: 0xa1,
52            request: 0x81,
53            value: 0x0200 | channel,
54            index: 0x0200,
55            length: 2,
56            timeout: 1000,
57            data: bytes.as_mut_ptr(),
58        };
59        let result = unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut c) };
60        if result != 2 {
61            return Err(std::io::Error::last_os_error());
62        }
63        values[(channel - 1) as usize] = i16::from_le_bytes(bytes);
64    }
65    Ok(values)
66}
67#[cfg(target_os = "linux")]
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}
218
219#[cfg(not(target_os = "linux"))]
220fn main() {
221    eprintln!("qemu_smoke needs a Linux guest with the QEMU UAC1 virtual device");
222}