usbdac_core/stream.rs
1//! The output stream.
2//!
3//! The model is *push*: the library owns the ring and the USB output thread,
4//! the host writes audio into the ring from its own thread. There is no render
5//! thread and no callback into the host on the audio path.
6
7use crate::dac::DacShared;
8use crate::error::{Error, Result};
9use crate::events::StreamState;
10use crate::format::StreamFormat;
11use crate::transport::session::{bit_perfect_now, current_bit_perfect_blocker, stream_verdicts};
12use crate::transport::shared::StreamShared;
13use crate::transport::StreamHandle;
14use parking_lot::Mutex;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::Arc;
17
18/// What stands in the way of [`DacStream::is_bit_perfect`], most significant
19/// first. `None` from [`DacStream::bit_perfect_blocker`] means nothing does.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum BitPerfectBlocker {
23 /// The stream is closed or not running.
24 NoStream,
25 /// At least one frame queued to the DAC was never taken (latched for the
26 /// life of the stream).
27 LostFrames,
28 /// The DAC runs another rate or format than the one requested
29 /// (`RatePolicy::NearestSupported`).
30 FormatChanged,
31 /// The DAC did not confirm its sampling frequency.
32 ClockUnverified,
33 /// Software gain other than 1.0 is applied.
34 SoftwareGain,
35 /// An asynchronous endpoint without a feedback endpoint, streamed at the
36 /// nominal rate because `DacConfig::allow_unsynchronized_async` is on.
37 UnsynchronizedAsync,
38 /// The wire payload audit has not seen real audio (yet), or lost it.
39 FeedbackUnlocked,
40 PayloadUnverified,
41}
42
43impl BitPerfectBlocker {
44 /// Stable identifier: `no_stream`, `lost_frames`, `format_changed`,
45 /// `clock_unverified`, `software_gain`, `unsynchronized_async`,
46 /// `payload_unverified`.
47 pub fn code(self) -> &'static str {
48 match self {
49 Self::NoStream => "no_stream",
50 Self::LostFrames => "lost_frames",
51 Self::FormatChanged => "format_changed",
52 Self::ClockUnverified => "clock_unverified",
53 Self::SoftwareGain => "software_gain",
54 Self::UnsynchronizedAsync => "unsynchronized_async",
55 Self::FeedbackUnlocked => "feedback_unlocked",
56 Self::PayloadUnverified => "payload_unverified",
57 }
58 }
59
60 pub(crate) fn description(self) -> &'static str {
61 match self {
62 Self::NoStream => "stream inactive",
63 Self::LostFrames => "audio lost on the USB transport",
64 Self::FormatChanged => "requested/effective format mismatch",
65 Self::ClockUnverified => "clock verification reset",
66 Self::SoftwareGain => "software gain active",
67 Self::UnsynchronizedAsync => {
68 "asynchronous endpoint without feedback, host-paced at the nominal rate"
69 }
70 Self::FeedbackUnlocked => "feedback pacing has not locked",
71 Self::PayloadUnverified => "wire payload audit failed",
72 }
73 }
74}
75
76/// Counters of a stream. Frames are in the unit
77/// [`StreamFormat::counter_rate_hz`] gives the rate of.
78#[derive(Debug, Clone, PartialEq)]
79#[non_exhaustive]
80pub struct StreamStats {
81 pub state: StreamState,
82 pub bit_perfect: bool,
83 /// Why `bit_perfect` is false, if it is.
84 pub bit_perfect_blocker: Option<BitPerfectBlocker>,
85 pub software_gain: f32,
86 /// Runs of padding because the ring ran dry (counted per transfer).
87 pub underruns: u64,
88 /// Frames not confirmed delivered. Failed packets are charged in full, so
89 /// this may exceed actual loss when a failed request reports partial bytes.
90 pub lost_frames: u64,
91 pub short_packets: u64,
92 pub zero_packets: u64,
93 /// Isochronous transfers libusb reported as timed out.
94 pub urb_timeouts: u64,
95 pub completed_transfers: u64,
96 /// Frames the host has written.
97 pub frames_written: u64,
98 /// Frames the DAC has taken, music and padding alike.
99 pub frames_completed: u64,
100 /// Music frames completed on the bus since the start or the last flush.
101 pub played_frames: u64,
102 /// Music frames between the host and the DAC: ring plus bus.
103 pub latency_frames: u64,
104 pub latency_ms: f64,
105 /// Frames in the ring.
106 pub queued_frames: u64,
107 pub buffer_ms: u32,
108 /// The deep ring depth (`DacConfig::buffer_target_ms`).
109 pub buffer_target_ms: u32,
110 /// The depth `writable_bytes()` asks for now: `buffer_target_ms`, or the
111 /// shallower processing depth while software gain or host processing is on.
112 pub active_target_ms: u32,
113 pub buffer_capacity_ms: u32,
114 /// Transfers currently submitted to the bus.
115 pub transfer_queue_depth: u32,
116 pub last_turnaround_us: u64,
117 pub max_turnaround_us: u64,
118 pub last_submit_gap_us: u64,
119 pub max_submit_gap_us: u64,
120 /// Checkpoint gaps excluding the most recent event-pump elapsed time.
121 pub worker_gap_over_10ms: u64,
122 pub worker_gap_over_50ms: u64,
123 pub max_worker_gap_us: u64,
124 /// Longest checkpoint-to-checkpoint interval, including the event pump.
125 pub max_worker_loop_gap_us: u64,
126 /// Longest time inside the event pump, including callbacks and scheduling.
127 pub max_event_pump_elapsed_us: u64,
128 /// Largest event-pump elapsed time beyond its requested timeout.
129 pub max_event_pump_timeout_overrun_us: u64,
130 pub adaptive_queue_changes: u64,
131 pub adaptive_queue_slots: u64,
132 pub adaptive_queue_us: u64,
133
134 /// Rate the DAC has actually consumed frames at since the start.
135 pub effective_rate_hz: f64,
136 /// Live feedback is locked. Equivalent to `feedback_locked` in 0.1.1.
137 pub feedback_active: bool,
138 pub feedback_reports: u64,
139 pub feedback_timeouts: u64,
140 pub feedback_errors: u64,
141 pub feedback_rejected: u64,
142 /// Time since the last valid feedback report.
143 pub feedback_age_ms: Option<u64>,
144 /// The sample rate the last feedback report implies.
145 pub feedback_rate_hz: Option<f64>,
146 pub feedback_stale: bool,
147 /// The selected explicit or implicit source has established usable timing.
148 pub feedback_locked: bool,
149 /// Empty explicit polls or empty implicit IN patterns.
150 pub feedback_empty: u64,
151 pub implicit_fifo_depth: u32,
152 pub implicit_fifo_high_water: u32,
153 pub implicit_waits: u64,
154 pub implicit_empty_bus: u64,
155 pub implicit_overruns: u64,
156 pub implicit_in_transfers: u64,
157 pub implicit_out_of_order: u64,
158 pub implicit_invalid_packets: u64,
159 pub implicit_measured_frames: u64,
160 pub implicit_scheduled_frames: u64,
161
162 /// The transfers have been lossless for long enough (about 256 ms) with no
163 /// underrun and no lost audio. A stream that lost audio is never stable
164 /// again.
165 pub stable: bool,
166 /// The DAC confirmed the sampling frequency (or the device quirk trusts
167 /// its `SET_CUR`). False before the clock is verified and after it is lost.
168 pub clock_verified: bool,
169 /// The wire payload audit passes (see `is_bit_perfect`).
170 pub payload_verified: bool,
171 /// How long, in milliseconds, the wire payload has been failing the audit,
172 /// while it does.
173 pub payload_constant_for_ms: Option<u64>,
174}
175
176pub(crate) struct StreamInner {
177 dac: Arc<DacShared>,
178 handle: Mutex<Option<StreamHandle>>,
179 pub(crate) shared: Arc<StreamShared>,
180 format: StreamFormat,
181 usb_handle_identity: usize,
182 closed: AtomicBool,
183 retirement_guard: Mutex<()>,
184}
185
186impl StreamInner {
187 pub(crate) fn new(
188 dac: Arc<DacShared>,
189 handle: StreamHandle,
190 format: StreamFormat,
191 ) -> Arc<Self> {
192 Arc::new(Self {
193 dac,
194 shared: Arc::clone(&handle.shared),
195 usb_handle_identity: handle.usb_handle_identity,
196 handle: Mutex::new(Some(handle)),
197 format,
198 closed: AtomicBool::new(false),
199 retirement_guard: Mutex::new(()),
200 })
201 }
202
203 pub(crate) fn is_closed(&self) -> bool {
204 self.closed.load(Ordering::Acquire)
205 }
206
207 /// Publishes the initial state once the listener is in place.
208 pub(crate) fn start_events(&self) {
209 let _scope = self.dac.context.enter();
210 self.shared.refresh_state();
211 }
212
213 pub(crate) fn close(&self) -> Result<()> {
214 let _guard = self.retirement_guard.lock();
215 self.close_locked()
216 }
217
218 fn close_locked(&self) -> Result<()> {
219 let _scope = self.dac.context.enter();
220 if self.closed.swap(true, Ordering::AcqRel) {
221 return Ok(());
222 }
223 let result = match self.handle.lock().take() {
224 Some(mut handle) => handle.stop().map_err(Error::Transfer),
225 None => Ok(()),
226 };
227 self.shared.mark_closed();
228 // The Closed event is queued with the listener it belongs to; the slot
229 // can be cleared now.
230 self.dac.events.set_stream_listener(None);
231 let mut slot = self.dac.stream.lock();
232 if slot
233 .as_ref()
234 .and_then(std::sync::Weak::upgrade)
235 .is_some_and(|current| std::ptr::eq(Arc::as_ptr(¤t), self))
236 {
237 *slot = None;
238 }
239 result
240 }
241}
242
243/// An open output stream. Dropping it closes it.
244///
245/// All methods take `&self`, so a stream can be shared between the host's
246/// writer thread and its control thread behind an `Arc`.
247///
248/// # Sample layout
249///
250/// [`write`](Self::write) takes **wire-layout bytes**: the bytes exactly as
251/// they go into the USB packets, in whole *wire frames*
252/// (`format.bytes_per_frame()` = `subslot_bytes * channels` bytes, channels
253/// interleaved in the DAC's channel order). Samples are little-endian.
254///
255/// * **PCM** — each sample is `subslot_bytes` bytes, a signed two's-complement
256/// integer, *left-justified*: the sign bit is the top bit of the subslot and
257/// unused low bits are zero. 16-bit audio in a 2-byte subslot is a plain
258/// `i16`; 24-bit audio in a 3-byte subslot is a packed `i24`; 24-bit audio
259/// in a 4-byte subslot is the `i24` shifted left by 8 (low byte zero);
260/// 32-bit audio is an `i32`. With the layout the DAC advertises, the bytes
261/// written are the bytes on the wire.
262/// * **Unsigned 8-bit PCM** — one unsigned byte per sample, silence 0x80. Bytes are retained exactly.
263/// * **IEEE float32 PCM** — one little-endian binary32 bit pattern per sample. NaN payloads,
264/// signed zero, infinity and subnormals are retained without a numeric conversion. Silence is +0.
265/// For these two explicit encodings, use `write`; `write_i32` and nonunity software gain refuse.
266/// * **DoP** — each sample is the DoP word in the same subslot layout, the 16
267/// DSD bits in the top two bytes below the marker: for a 3-byte subslot
268/// `[dsd_low, dsd_high, marker]`, for a 4-byte subslot `[0, dsd_low,
269/// dsd_high, marker]`. `dsd_high` holds the older 8 DSD bits (MSB first). The
270/// marker byte is **ignored and overwritten**: the library owns the
271/// `0x05`/`0xFA` alternation so the phase survives pause, flush and underrun.
272/// DoP uses PCM framing even on UAC3; carrier capability does not prove
273/// that the device decodes the markers.
274/// * **Native DSD** — raw DSD bytes, MSB first (the oldest bit in bit 7),
275/// interleaved one byte per channel: `[ch0, ch1, ch0, ch1, ...]` in
276/// stream order. A wire frame is `subslot_bytes * channels` such bytes (one
277/// wire word per channel); the library groups consecutive bytes of a channel
278/// into the wire word. Standard UAC3 DSD uses 8-byte words at `bit_rate / 64`,
279/// D63 oldest, emitted little-endian (LE64): each channel's eight chronological
280/// input bytes are reversed on the wire. Legacy 1-, 2- and 4-byte formats
281/// retain byte-order and bit-reversal quirks/config; those overrides do not
282/// change the standard UAC3 layout.
283///
284/// [`write_i32`](Self::write_i32) takes the ring's own sample unit instead:
285/// PCM as full-scale 32-bit left-justified `i32` (the encoder keeps the top
286/// `valid_bits` bits), DoP as `i32` words with the DSD bits in bits 23..8 (bits
287/// 31..24 are overwritten with the marker), native DSD as one DSD byte per
288/// `i32` in bits 7..0.
289pub struct DacStream {
290 inner: Arc<StreamInner>,
291}
292
293impl std::fmt::Debug for DacStream {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 f.debug_struct("DacStream")
296 .field("format", &self.inner.format)
297 .finish_non_exhaustive()
298 }
299}
300
301impl DacStream {
302 pub(crate) fn from_inner(inner: Arc<StreamInner>) -> Self {
303 Self { inner }
304 }
305
306 fn shared(&self) -> &StreamShared {
307 &self.inner.shared
308 }
309
310 fn ensure_open(&self) -> Result<()> {
311 if self.inner.is_closed() {
312 return Err(Error::InvalidState("the stream is closed".to_string()));
313 }
314 Ok(())
315 }
316
317 pub(crate) fn reconfigure_identity(&self, owner: &Arc<DacShared>) -> Result<usize> {
318 self.ensure_open()?;
319 if !Arc::ptr_eq(owner, &self.inner.dac) {
320 return Err(Error::InvalidArgument(
321 "stream belongs to another DAC session".into(),
322 ));
323 }
324 if self
325 .inner
326 .handle
327 .lock()
328 .as_ref()
329 .is_some_and(|handle| handle.capture.is_some())
330 {
331 return Err(Error::Unsupported { reason: "reconfigure the duplex pair explicitly; playback-only reconfiguration is refused".into(), offered: vec![] });
332 }
333 Ok(self.inner.usb_handle_identity)
334 }
335
336 pub(crate) fn is_current(&self, owner: &Arc<DacShared>) -> bool {
337 owner
338 .stream
339 .lock()
340 .as_ref()
341 .and_then(std::sync::Weak::upgrade)
342 .is_some_and(|stream| Arc::ptr_eq(&stream, &self.inner))
343 }
344
345 pub(crate) fn lock_retirement(&self) -> parking_lot::MutexGuard<'_, ()> {
346 self.inner.retirement_guard.lock()
347 }
348
349 pub(crate) fn retire_for_reconfigure_locked(&self) -> Result<()> {
350 self.inner.close_locked()
351 }
352
353 pub(crate) fn retire_for_reconfigure(&self) -> Result<()> {
354 self.inner.close()
355 }
356
357 /// The wire format this stream runs.
358 pub fn format(&self) -> &StreamFormat {
359 &self.inner.format
360 }
361
362 /// Appends wire-layout bytes (see the type-level documentation). Never
363 /// blocks. Returns the number of bytes taken: a whole number of wire frames,
364 /// as many as fit in the ring; a partial or zero count means the ring is
365 /// full, so retry with the remainder later. Input shorter than one wire
366 /// frame is not taken.
367 ///
368 /// [`Error::InvalidState`] after [`drain`](Self::drain) (until
369 /// [`flush`](Self::flush)), or once the stream has closed or failed.
370 pub fn write(&self, data: &[u8]) -> Result<usize> {
371 let _scope = self.inner.dac.enter()?;
372 self.ensure_open()?;
373 self.shared().write_bytes(data)
374 }
375
376 /// Like [`write`](Self::write) for the ring's native `i32` samples. Counts
377 /// and returns samples (a whole number of wire frames: multiples of
378 /// `channels`, or of `subslot_bytes * channels` for native DSD).
379 pub fn write_i32(&self, samples: &[i32]) -> Result<usize> {
380 let _scope = self.inner.dac.enter()?;
381 self.ensure_open()?;
382 self.shared().write_samples(samples)
383 }
384
385 /// How many bytes the host should write now to bring the ring to its
386 /// target depth ([`DacConfig::buffer_target_ms`], or the shallower
387 /// `processing_buffer_target_ms` while software gain is on). A whole number
388 /// of wire frames. `write` still accepts more, up to the ring's capacity.
389 ///
390 /// [`DacConfig::buffer_target_ms`]: crate::DacConfig::buffer_target_ms
391 pub fn writable_bytes(&self) -> usize {
392 if self.inner.is_closed() {
393 return 0;
394 }
395 self.shared().writable_bytes()
396 }
397
398 /// Resumes after [`pause`](Self::pause). A new stream plays by itself once
399 /// the ring holds the start threshold; this is only needed after a pause.
400 pub fn play(&self) -> Result<()> {
401 let _retirement = self.inner.retirement_guard.lock();
402 let _scope = self.inner.dac.enter()?;
403 self.ensure_open()?;
404 self.shared().set_paused(false);
405 Ok(())
406 }
407
408 /// Holds the stream: wire-correct silence goes out (zero for PCM, the
409 /// idle pattern for DSD, DoP markers keep alternating) so the DAC stays
410 /// locked, and the ring is not consumed. Audio already submitted to the bus
411 /// (about [`DacConfig::bus_queue_ms`](crate::DacConfig::bus_queue_ms), 16 ms
412 /// by default, at every service interval) still plays out first; the ring
413 /// resumes exactly where it was.
414 pub fn pause(&self) -> Result<()> {
415 let _retirement = self.inner.retirement_guard.lock();
416 let _scope = self.inner.dac.enter()?;
417 self.ensure_open()?;
418 self.shared().set_paused(true);
419 Ok(())
420 }
421
422 /// Drops everything queued in the ring and resets
423 /// [`played_frames`](Self::played_frames) to 0. The stream holds wire
424 /// silence until the ring holds the start threshold again. Also clears
425 /// [`drain`](Self::drain), so the stream can be reused.
426 ///
427 /// Returns at once. With
428 /// [`DacConfig::cancel_in_flight_on_flush`](crate::DacConfig::cancel_in_flight_on_flush)
429 /// (the default) the output thread then cancels the transfers already on
430 /// the bus, within about one transfer (2 ms), waits for every one to be
431 /// handed back and refills the slots with silence; those transfers are not
432 /// lost audio, not underruns and not counted as played. Off, or when only
433 /// silence is queued (a flush while paused), the queue plays out
434 /// ([`DacConfig::bus_queue_ms`](crate::DacConfig::bus_queue_ms), 16 ms by
435 /// default) and is not counted as played.
436 pub fn flush(&self) -> Result<()> {
437 let _retirement = self.inner.retirement_guard.lock();
438 let _scope = self.inner.dac.enter()?;
439 self.ensure_open()?;
440 self.shared().flush();
441 Ok(())
442 }
443
444 /// Declares that no more audio will be written: the ring plays out, even a
445 /// tail shorter than the start threshold, and the stream then reports
446 /// [`is_drained`](Self::is_drained) and the `Drained` state. The padded
447 /// tail is not an underrun. Further writes fail until
448 /// [`flush`](Self::flush).
449 pub fn drain(&self) -> Result<()> {
450 let _retirement = self.inner.retirement_guard.lock();
451 let _scope = self.inner.dac.enter()?;
452 self.ensure_open()?;
453 self.shared().drain();
454 Ok(())
455 }
456
457 /// `drain()` was called and everything written has been played.
458 pub fn is_drained(&self) -> bool {
459 self.shared().is_drained()
460 }
461
462 /// Closes the stream and waits for the output thread. The DAC stays open.
463 pub fn close(self) -> Result<()> {
464 self.inner.close()
465 }
466
467 pub fn state(&self) -> StreamState {
468 self.shared().current_state()
469 }
470
471 /// Music frames the DAC has completed on the bus since the stream started
472 /// or the last [`flush`](Self::flush). Padding, held silence and lost
473 /// frames are not counted. The unit is `format().counter_rate_hz()`.
474 pub fn played_frames(&self) -> u64 {
475 self.shared().stats.played_frames()
476 }
477
478 /// Music frames between the host and the DAC: in the ring plus on the bus.
479 /// What the audible position lags the written position by.
480 pub fn latency_frames(&self) -> u64 {
481 self.shared().stats.output_latency_frames()
482 }
483
484 /// Frames waiting in the ring, in the unit of
485 /// [`StreamFormat::counter_rate_hz`]. Cheaper than [`stats`](Self::stats)
486 /// (`StreamStats::queued_frames`), for a host that wants to know how full the
487 /// ring is on every cycle of its writer loop.
488 pub fn queued_frames(&self) -> u64 {
489 if self.inner.is_closed() {
490 return 0;
491 }
492 self.shared().stats.queued_frames()
493 }
494
495 /// Bit-perfect means: no software gain, a verified clock at the requested
496 /// rate, no frame lost on the bus, and the wire payload is real audio.
497 /// False as soon as any of that stops being true, and for good after a lost
498 /// frame.
499 pub fn is_bit_perfect(&self) -> bool {
500 let _scope = self.inner.dac.context.enter();
501 !self.inner.is_closed() && self.shared().note_bit_perfect()
502 }
503
504 /// Why [`is_bit_perfect`](Self::is_bit_perfect) is false: `None` when it is
505 /// true, otherwise the first condition that fails.
506 pub fn bit_perfect_blocker(&self) -> Option<BitPerfectBlocker> {
507 let _scope = self.inner.dac.context.enter();
508 if self.inner.is_closed() {
509 return Some(BitPerfectBlocker::NoStream);
510 }
511 current_bit_perfect_blocker()
512 }
513
514 /// Scales PCM samples by `gain` (0.0 to 16.0) as each transfer is prepared,
515 /// so it takes effect within the bus latency rather than the ring depth.
516 /// Rounds to nearest and saturates; no dither. Any value other than 1.0
517 /// ends bit-perfect output. Refused for DoP and native DSD (it would corrupt
518 /// the bitstream).
519 pub fn set_software_gain(&self, gain: f32) -> Result<()> {
520 let _scope = self.inner.dac.enter()?;
521 self.ensure_open()?;
522 self.shared().set_software_gain(gain)
523 }
524
525 pub fn software_gain(&self) -> f32 {
526 self.shared().stats.software_gain()
527 }
528
529 /// Tells the stream that the host processes the audio (EQ, DSP, crossfade,
530 /// pitch) before it writes it. A change the host makes is then heard after
531 /// the ring's fill, so [`writable_bytes`](Self::writable_bytes) asks for the
532 /// shallow `processing_buffer_target_ms` instead of the deep target, as it
533 /// does for software gain. Nothing is flushed when the depth changes (see
534 /// `writable_bytes`).
535 ///
536 /// It is only a hint about buffering. It does not change a sample, and the
537 /// library cannot see what the host did to the audio, so it does not touch
538 /// [`is_bit_perfect`](Self::is_bit_perfect): a host that processes audio is
539 /// responsible for not claiming bit-perfect output. It has no effect for DoP
540 /// and native DSD, which are never processed.
541 pub fn set_host_processing(&self, processing: bool) {
542 self.shared()
543 .stats
544 .host_processing
545 .store(processing, std::sync::atomic::Ordering::Relaxed);
546 }
547
548 /// Whether [`set_host_processing`](Self::set_host_processing) is on.
549 pub fn host_processing(&self) -> bool {
550 self.shared()
551 .stats
552 .host_processing
553 .load(std::sync::atomic::Ordering::Relaxed)
554 }
555
556 /// A bounded snapshot of the explicit USB feedback path for this stream.
557 ///
558 /// Available after the worker has selected the endpoint, including after
559 /// a feedback failure. Other pacing modes return `None`.
560 pub fn explicit_feedback_diagnostics(&self) -> Option<crate::ExplicitFeedbackDiagnostics> {
561 *self.shared().stats.explicit_feedback_diagnostics.lock()
562 }
563
564 pub fn stats(&self) -> StreamStats {
565 let _scope = self.inner.dac.context.enter();
566 use std::sync::atomic::Ordering::Relaxed;
567 let shared = self.shared();
568 let stats = &shared.stats;
569 let feedback_last = stats.feedback_last_report_ms.load(Relaxed);
570 let elapsed_ms = stats
571 .started_at
572 .elapsed()
573 .as_millis()
574 .min(u128::from(u64::MAX)) as u64;
575 let verdicts = if self.inner.is_closed() {
576 Default::default()
577 } else {
578 stream_verdicts()
579 };
580 StreamStats {
581 state: shared.current_state(),
582 bit_perfect: !self.inner.is_closed() && bit_perfect_now(),
583 bit_perfect_blocker: self.bit_perfect_blocker(),
584 software_gain: stats.software_gain(),
585 underruns: stats.underrun_count.load(Relaxed),
586 lost_frames: stats.lost_frames.load(Relaxed),
587 short_packets: stats.short_packets.load(Relaxed),
588 zero_packets: stats.zero_packets.load(Relaxed),
589 urb_timeouts: stats.data_urb_timeouts.load(Relaxed),
590 completed_transfers: stats.completed_transfers.load(Relaxed),
591 frames_written: stats.producer_frames.load(Relaxed),
592 frames_completed: stats.consumer_frames.load(Relaxed),
593 played_frames: stats.played_frames(),
594 latency_frames: stats.output_latency_frames(),
595 latency_ms: stats.output_latency_ms(),
596 queued_frames: stats.queued_frames(),
597 buffer_ms: stats.buffer_fill_ms(),
598 buffer_target_ms: stats.buffer_target_ms(),
599 active_target_ms: stats.active_target_ms(),
600 buffer_capacity_ms: stats.buffer_capacity_ms(),
601 transfer_queue_depth: stats.transfer_queue_depth.load(Relaxed) as u32,
602 last_turnaround_us: stats.last_transfer_turnaround_us.load(Relaxed),
603 max_turnaround_us: stats.max_transfer_turnaround_us.load(Relaxed),
604 last_submit_gap_us: stats.last_submit_gap_us.load(Relaxed),
605 max_submit_gap_us: stats.max_submit_gap_us.load(Relaxed),
606 worker_gap_over_10ms: stats.worker_gap_over_10ms.load(Relaxed),
607 worker_gap_over_50ms: stats.worker_gap_over_50ms.load(Relaxed),
608 max_worker_gap_us: stats.max_worker_gap_us.load(Relaxed),
609 max_worker_loop_gap_us: stats.max_worker_loop_gap_us.load(Relaxed),
610 max_event_pump_elapsed_us: stats.max_event_pump_elapsed_us.load(Relaxed),
611 max_event_pump_timeout_overrun_us: stats
612 .max_event_pump_timeout_overrun_us
613 .load(Relaxed),
614 adaptive_queue_changes: stats.adaptive_queue_changes.load(Relaxed),
615 adaptive_queue_slots: stats.adaptive_queue_slots.load(Relaxed),
616 adaptive_queue_us: stats.adaptive_queue_us.load(Relaxed),
617
618 effective_rate_hz: stats.effective_consumer_rate_milli_hz.load(Relaxed) as f64
619 / 1_000.0,
620 feedback_active: stats.feedback_locked.load(Relaxed),
621 feedback_reports: stats.feedback_reports.load(Relaxed),
622 feedback_timeouts: stats.feedback_timeouts.load(Relaxed),
623 feedback_errors: stats.feedback_errors.load(Relaxed),
624 feedback_rejected: stats.feedback_rejected.load(Relaxed),
625 feedback_age_ms: (feedback_last != u64::MAX)
626 .then(|| elapsed_ms.saturating_sub(feedback_last)),
627 feedback_rate_hz: (stats.feedback_reports.load(Relaxed) > 0)
628 .then(|| stats.feedback_rate_milli_hz.load(Relaxed) as f64 / 1_000.0),
629 feedback_stale: stats.feedback_stale.load(Relaxed),
630 feedback_locked: stats.feedback_locked.load(Relaxed),
631 feedback_empty: stats.feedback_empty.load(Relaxed),
632 implicit_fifo_depth: stats.implicit_fifo_depth.load(Relaxed) as u32,
633 implicit_fifo_high_water: stats.implicit_fifo_high_water.load(Relaxed) as u32,
634 implicit_waits: stats.implicit_waits.load(Relaxed),
635 implicit_empty_bus: stats.implicit_empty_bus.load(Relaxed),
636 implicit_overruns: stats.implicit_overruns.load(Relaxed),
637 implicit_in_transfers: stats.implicit_in_transfers.load(Relaxed),
638 implicit_out_of_order: stats.implicit_out_of_order.load(Relaxed),
639 implicit_invalid_packets: stats.implicit_invalid_packets.load(Relaxed),
640 implicit_measured_frames: stats.implicit_measured_frames.load(Relaxed),
641 implicit_scheduled_frames: stats.implicit_scheduled_frames.load(Relaxed),
642
643 stable: verdicts.stable,
644 clock_verified: verdicts.clock_verified,
645 payload_verified: verdicts.payload_verified,
646 payload_constant_for_ms: verdicts.payload_constant_for_ms,
647 }
648 }
649}
650
651impl Drop for DacStream {
652 fn drop(&mut self) {
653 let _ = self.inner.close();
654 }
655}