Skip to main content

DacStream

Struct DacStream 

Source
pub struct DacStream { /* private fields */ }
Expand description

An open output stream. Dropping it closes it.

All methods take &self, so a stream can be shared between the host’s writer thread and its control thread behind an Arc.

§Sample layout

write takes wire-layout bytes: the bytes exactly as they go into the USB packets, in whole wire frames (format.bytes_per_frame() = subslot_bytes * channels bytes, channels interleaved in the DAC’s channel order). Samples are little-endian.

  • PCM — each sample is subslot_bytes bytes, a signed two’s-complement integer, left-justified: the sign bit is the top bit of the subslot and unused low bits are zero. 16-bit audio in a 2-byte subslot is a plain i16; 24-bit audio in a 3-byte subslot is a packed i24; 24-bit audio in a 4-byte subslot is the i24 shifted left by 8 (low byte zero); 32-bit audio is an i32. With the layout the DAC advertises, the bytes written are the bytes on the wire.
  • Unsigned 8-bit PCM — one unsigned byte per sample, silence 0x80. Bytes are retained exactly.
  • IEEE float32 PCM — one little-endian binary32 bit pattern per sample. NaN payloads, signed zero, infinity and subnormals are retained without a numeric conversion. Silence is +0. For these two explicit encodings, use write; write_i32 and nonunity software gain refuse.
  • DoP — each sample is the DoP word in the same subslot layout, the 16 DSD bits in the top two bytes below the marker: for a 3-byte subslot [dsd_low, dsd_high, marker], for a 4-byte subslot [0, dsd_low, dsd_high, marker]. dsd_high holds the older 8 DSD bits (MSB first). The marker byte is ignored and overwritten: the library owns the 0x05/0xFA alternation so the phase survives pause, flush and underrun. DoP uses PCM framing even on UAC3; carrier capability does not prove that the device decodes the markers.
  • Native DSD — raw DSD bytes, MSB first (the oldest bit in bit 7), interleaved one byte per channel: [ch0, ch1, ch0, ch1, ...] in stream order. A wire frame is subslot_bytes * channels such bytes (one wire word per channel); the library groups consecutive bytes of a channel into the wire word. Standard UAC3 DSD uses 8-byte words at bit_rate / 64, D63 oldest, emitted little-endian (LE64): each channel’s eight chronological input bytes are reversed on the wire. Legacy 1-, 2- and 4-byte formats retain byte-order and bit-reversal quirks/config; those overrides do not change the standard UAC3 layout.

write_i32 takes the ring’s own sample unit instead: PCM as full-scale 32-bit left-justified i32 (the encoder keeps the top valid_bits bits), DoP as i32 words with the DSD bits in bits 23..8 (bits 31..24 are overwritten with the marker), native DSD as one DSD byte per i32 in bits 7..0.

Implementations§

Source§

impl DacStream

Source

pub fn format(&self) -> &StreamFormat

The wire format this stream runs.

Examples found in repository?
examples/pull_adapter.rs (line 105)
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
107
108    /// The decoder is at the end of the track and the DAC has played it all.
109    fn finished(&self) -> bool {
110        lock(&self.state).ended && self.stream.is_drained()
111    }
112}
113
114impl Drop for PullAdapter {
115    fn drop(&mut self) {
116        self.stop.store(true, Ordering::Release);
117        if let Some(writer) = self.writer.take() {
118            let _ = writer.join();
119        }
120    }
121}
122
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
More examples
Hide additional examples
examples/guide_player.rs (line 407)
404pub fn play_one(dac: Dac, format: &StreamFormat, source: Box<dyn Source>) -> Result<()> {
405    let (listener, events) = event_channel();
406    let stream = dac.open_stream(format, listener)?;
407    let shape = Shape::from(stream.format());
408    let player = Player::start(Arc::new(stream), shape, source);
409    let mut device_lost = false;
410    while !player.finished() {
411        match events.recv_timeout(Duration::from_millis(100)).map(react) {
412            Ok(Reaction::Pause(reason)) => {
413                log::warn!("{reason}");
414                device_lost = true;
415                break;
416            }
417            Ok(Reaction::Failed(error)) => {
418                device_lost = error == Error::DeviceLost;
419                log::warn!("the stream failed: {error}");
420                break;
421            }
422            _ => {}
423        }
424    }
425    log::info!("{}", status_line(player.ring(), true, false));
426    shutdown(player, dac, device_lost)
427}
examples/qemu_smoke.rs (line 181)
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}
Source

pub fn write(&self, data: &[u8]) -> Result<usize>

Appends wire-layout bytes (see the type-level documentation). Never blocks. Returns the number of bytes taken: a whole number of wire frames, as many as fit in the ring; a partial or zero count means the ring is full, so retry with the remainder later. Input shorter than one wire frame is not taken.

Error::InvalidState after drain (until flush), or once the stream has closed or failed.

Examples found in repository?
examples/two_dac_smoke.rs (line 98)
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    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 155)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
examples/qemu_smoke.rs (line 128)
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}
Source

pub fn write_i32(&self, samples: &[i32]) -> Result<usize>

Like write for the ring’s native i32 samples. Counts and returns samples (a whole number of wire frames: multiples of channels, or of subslot_bytes * channels for native DSD).

Examples found in repository?
examples/guide_player.rs (line 83)
82    fn write_i32(&self, samples: &[i32]) -> Result<usize> {
83        DacStream::write_i32(self, samples)
84    }
Source

pub fn writable_bytes(&self) -> usize

How many bytes the host should write now to bring the ring to its target depth (DacConfig::buffer_target_ms, or the shallower processing_buffer_target_ms while software gain is on). A whole number of wire frames. write still accepts more, up to the ring’s capacity.

Examples found in repository?
examples/guide_player.rs (line 80)
79    fn writable_bytes(&self) -> usize {
80        DacStream::writable_bytes(self)
81    }
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 104)
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    }
examples/pull_adapter.rs (line 138)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
examples/qemu_smoke.rs (line 133)
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}
Source

pub fn play(&self) -> Result<()>

Resumes after pause. A new stream plays by itself once the ring holds the start threshold; this is only needed after a pause.

Examples found in repository?
examples/pull_adapter.rs (line 83)
82    fn resume(&self) -> Result<()> {
83        self.stream.play()
84    }
More examples
Hide additional examples
examples/guide_player.rs (line 86)
85    fn play(&self) -> Result<()> {
86        DacStream::play(self)
87    }
examples/qemu_smoke.rs (line 130)
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}
Source

pub fn pause(&self) -> Result<()>

Holds the stream: wire-correct silence goes out (zero for PCM, the idle pattern for DSD, DoP markers keep alternating) so the DAC stays locked, and the ring is not consumed. Audio already submitted to the bus (about DacConfig::bus_queue_ms, 16 ms by default, at every service interval) still plays out first; the ring resumes exactly where it was.

Examples found in repository?
examples/pull_adapter.rs (line 79)
78    fn pause(&self) -> Result<()> {
79        self.stream.pause()
80    }
More examples
Hide additional examples
examples/guide_player.rs (line 89)
88    fn pause(&self) -> Result<()> {
89        DacStream::pause(self)
90    }
examples/qemu_smoke.rs (line 148)
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}
Source

pub fn flush(&self) -> Result<()>

Drops everything queued in the ring and resets played_frames to 0. The stream holds wire silence until the ring holds the start threshold again. Also clears drain, so the stream can be reused.

Returns at once. With DacConfig::cancel_in_flight_on_flush (the default) the output thread then cancels the transfers already on the bus, within about one transfer (2 ms), waits for every one to be handed back and refills the slots with silence; those transfers are not lost audio, not underruns and not counted as played. Off, or when only silence is queued (a flush while paused), the queue plays out (DacConfig::bus_queue_ms, 16 ms by default) and is not counted as played.

Examples found in repository?
examples/guide_player.rs (line 92)
91    fn flush(&self) -> Result<()> {
92        DacStream::flush(self)
93    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 97)
90    fn seek(&self, seconds: f64) -> Result<()> {
91        let mut state = lock(&self.state);
92        state.source.seek(seconds);
93        state.chunk.clear();
94        state.taken = 0;
95        state.ended = false;
96        state.base_seconds = seconds;
97        self.stream.flush()
98    }
Source

pub fn drain(&self) -> Result<()>

Declares that no more audio will be written: the ring plays out, even a tail shorter than the start threshold, and the stream then reports is_drained and the Drained state. The padded tail is not an underrun. Further writes fail until flush.

Examples found in repository?
examples/guide_player.rs (line 95)
94    fn drain(&self) -> Result<()> {
95        DacStream::drain(self)
96    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 146)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
Source

pub fn is_drained(&self) -> bool

drain() was called and everything written has been played.

Examples found in repository?
examples/guide_player.rs (line 98)
97    fn is_drained(&self) -> bool {
98        DacStream::is_drained(self)
99    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 110)
109    fn finished(&self) -> bool {
110        lock(&self.state).ended && self.stream.is_drained()
111    }
Source

pub fn close(self) -> Result<()>

Closes the stream and waits for the output thread. The DAC stays open.

Examples found in repository?
examples/guide_player.rs (line 384)
381pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382    let stream = player.stop(); // joins the writer thread
383    let stream_result = match Arc::try_unwrap(stream) {
384        Ok(stream) => stream.close(),
385        Err(_) => Err(Error::InvalidState(
386            "the stream is still shared".to_string(),
387        )),
388    };
389    let dac_result = if device_lost {
390        dac.close_with(CloseVolume::Forget)
391    } else {
392        dac.close()
393    };
394    if matches!(dac_result, Err(Error::Transfer(_))) {
395        // The output thread did not stop in time. Keep every claim and the descriptor until it has.
396        while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397    }
398    stream_result.and(dac_result)
399}
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 135)
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    }
examples/qemu_smoke.rs (line 198)
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}
Source

pub fn state(&self) -> StreamState

Examples found in repository?
examples/qemu_smoke.rs (line 157)
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}
Source

pub fn played_frames(&self) -> u64

Music frames the DAC has completed on the bus since the stream started or the last flush. Padding, held silence and lost frames are not counted. The unit is format().counter_rate_hz().

Examples found in repository?
examples/guide_player.rs (line 101)
100    fn played_frames(&self) -> u64 {
101        DacStream::played_frames(self)
102    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 104)
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
examples/qemu_smoke.rs (line 159)
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}
Source

pub fn latency_frames(&self) -> u64

Music frames between the host and the DAC: in the ring plus on the bus. What the audible position lags the written position by.

Source

pub fn queued_frames(&self) -> u64

Frames waiting in the ring, in the unit of StreamFormat::counter_rate_hz. Cheaper than stats (StreamStats::queued_frames), for a host that wants to know how full the ring is on every cycle of its writer loop.

Source

pub fn is_bit_perfect(&self) -> bool

Bit-perfect means: no software gain, a verified clock at the requested rate, no frame lost on the bus, and the wire payload is real audio. False as soon as any of that stops being true, and for good after a lost frame.

Source

pub fn bit_perfect_blocker(&self) -> Option<BitPerfectBlocker>

Why is_bit_perfect is false: None when it is true, otherwise the first condition that fails.

Examples found in repository?
examples/guide_player.rs (line 350)
346pub fn status_line(stream: &DacStream, engine_untouched: bool, lossy_source: bool) -> String {
347    if !engine_untouched {
348        return "Not bit-perfect: the player is processing the audio".to_string();
349    }
350    match stream.bit_perfect_blocker() {
351        None if lossy_source => "Direct USB, decoded from a lossy file".to_string(),
352        None => "Bit-perfect".to_string(),
353        Some(blocker) => format!("Not bit-perfect: {}", blocker_text(blocker)),
354    }
355}
Source

pub fn set_software_gain(&self, gain: f32) -> Result<()>

Scales PCM samples by gain (0.0 to 16.0) as each transfer is prepared, so it takes effect within the bus latency rather than the ring depth. Rounds to nearest and saturates; no dither. Any value other than 1.0 ends bit-perfect output. Refused for DoP and native DSD (it would corrupt the bitstream).

Source

pub fn software_gain(&self) -> f32

Source

pub fn set_host_processing(&self, processing: bool)

Tells the stream that the host processes the audio (EQ, DSP, crossfade, pitch) before it writes it. A change the host makes is then heard after the ring’s fill, so writable_bytes asks for the shallow processing_buffer_target_ms instead of the deep target, as it does for software gain. Nothing is flushed when the depth changes (see writable_bytes).

It is only a hint about buffering. It does not change a sample, and the library cannot see what the host did to the audio, so it does not touch is_bit_perfect: a host that processes audio is responsible for not claiming bit-perfect output. It has no effect for DoP and native DSD, which are never processed.

Source

pub fn host_processing(&self) -> bool

Whether set_host_processing is on.

Source

pub fn explicit_feedback_diagnostics( &self, ) -> Option<ExplicitFeedbackDiagnostics>

A bounded snapshot of the explicit USB feedback path for this stream.

Available after the worker has selected the endpoint, including after a feedback failure. Other pacing modes return None.

Source

pub fn stats(&self) -> StreamStats

Examples found in repository?
examples/two_dac_smoke.rs (line 125)
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    }
More examples
Hide additional examples
examples/qemu_smoke.rs (line 139)
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}

Trait Implementations§

Source§

impl Debug for DacStream

Source§

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

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

impl Drop for DacStream

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl PlaybackStream for DacStream

Source§

fn write(&self, data: &[u8]) -> Result<usize>

Source§

fn writable_bytes(&self) -> usize

Source§

fn played_frames(&self) -> u64

Source§

fn latency_frames(&self) -> u64

Source§

fn play(&self) -> Result<()>

Source§

fn pause(&self) -> Result<()>

Source§

fn flush(&self) -> Result<()>

Source§

fn drain(&self) -> Result<()>

Auto Trait Implementations§

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