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