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 queued to the DAC that it never took.
89 pub lost_frames: u64,
90 pub short_packets: u64,
91 pub zero_packets: u64,
92 /// Isochronous transfers libusb reported as timed out.
93 pub urb_timeouts: u64,
94 pub completed_transfers: u64,
95 /// Frames the host has written.
96 pub frames_written: u64,
97 /// Frames the DAC has taken, music and padding alike.
98 pub frames_completed: u64,
99 /// Music frames completed on the bus since the start or the last flush.
100 pub played_frames: u64,
101 /// Music frames between the host and the DAC: ring plus bus.
102 pub latency_frames: u64,
103 pub latency_ms: f64,
104 /// Frames in the ring.
105 pub queued_frames: u64,
106 pub buffer_ms: u32,
107 /// The deep ring depth (`DacConfig::buffer_target_ms`).
108 pub buffer_target_ms: u32,
109 /// The depth `writable_bytes()` asks for now: `buffer_target_ms`, or the
110 /// shallower processing depth while software gain or host processing is on.
111 pub active_target_ms: u32,
112 pub buffer_capacity_ms: u32,
113 /// Transfers currently submitted to the bus.
114 pub transfer_queue_depth: u32,
115 pub last_turnaround_us: u64,
116 pub max_turnaround_us: u64,
117 pub last_submit_gap_us: u64,
118 pub max_submit_gap_us: u64,
119 /// Rate the DAC has actually consumed frames at since the start.
120 pub effective_rate_hz: f64,
121 /// Live feedback is locked. Equivalent to `feedback_locked` in 0.1.1.
122 pub feedback_active: bool,
123 pub feedback_reports: u64,
124 pub feedback_timeouts: u64,
125 pub feedback_errors: u64,
126 pub feedback_rejected: u64,
127 /// Time since the last valid feedback report.
128 pub feedback_age_ms: Option<u64>,
129 /// The sample rate the last feedback report implies.
130 pub feedback_rate_hz: Option<f64>,
131 pub feedback_stale: bool,
132 /// The selected explicit or implicit source has established usable timing.
133 pub feedback_locked: bool,
134 /// Empty explicit polls or empty implicit IN patterns.
135 pub feedback_empty: u64,
136 pub implicit_fifo_depth: u32,
137 pub implicit_fifo_high_water: u32,
138 pub implicit_waits: u64,
139 pub implicit_empty_bus: u64,
140 pub implicit_overruns: u64,
141 pub implicit_in_transfers: u64,
142 pub implicit_out_of_order: u64,
143 pub implicit_invalid_packets: u64,
144 pub implicit_measured_frames: u64,
145 pub implicit_scheduled_frames: u64,
146
147 /// The transfers have been lossless for long enough (about 256 ms) with no
148 /// underrun and no lost audio. A stream that lost audio is never stable
149 /// again.
150 pub stable: bool,
151 /// The DAC confirmed the sampling frequency (or the device quirk trusts
152 /// its `SET_CUR`). False before the clock is verified and after it is lost.
153 pub clock_verified: bool,
154 /// The wire payload audit passes (see `is_bit_perfect`).
155 pub payload_verified: bool,
156 /// How long, in milliseconds, the wire payload has been failing the audit,
157 /// while it does.
158 pub payload_constant_for_ms: Option<u64>,
159}
160
161pub(crate) struct StreamInner {
162 dac: Arc<DacShared>,
163 handle: Mutex<Option<StreamHandle>>,
164 pub(crate) shared: Arc<StreamShared>,
165 format: StreamFormat,
166 closed: AtomicBool,
167}
168
169impl StreamInner {
170 pub(crate) fn new(dac: Arc<DacShared>, handle: StreamHandle, format: StreamFormat) -> Arc<Self> {
171 Arc::new(Self {
172 dac,
173 shared: Arc::clone(&handle.shared),
174 handle: Mutex::new(Some(handle)),
175 format,
176 closed: AtomicBool::new(false),
177 })
178 }
179
180 pub(crate) fn is_closed(&self) -> bool {
181 self.closed.load(Ordering::Acquire)
182 }
183
184 /// Publishes the initial state once the listener is in place.
185 pub(crate) fn start_events(&self) {
186 self.shared.refresh_state();
187 }
188
189 pub(crate) fn close(&self) -> Result<()> {
190 if self.closed.swap(true, Ordering::AcqRel) {
191 return Ok(());
192 }
193 let result = match self.handle.lock().take() {
194 Some(mut handle) => handle.stop().map_err(Error::Transfer),
195 None => Ok(()),
196 };
197 self.shared.mark_closed();
198 // The Closed event is queued with the listener it belongs to; the slot
199 // can be cleared now.
200 self.dac.events.set_stream_listener(None);
201 let mut slot = self.dac.stream.lock();
202 if slot
203 .as_ref()
204 .and_then(std::sync::Weak::upgrade)
205 .is_some_and(|current| std::ptr::eq(Arc::as_ptr(¤t), self))
206 {
207 *slot = None;
208 }
209 result
210 }
211}
212
213/// An open output stream. Dropping it closes it.
214///
215/// All methods take `&self`, so a stream can be shared between the host's
216/// writer thread and its control thread behind an `Arc`.
217///
218/// # Sample layout
219///
220/// [`write`](Self::write) takes **wire-layout bytes**: the bytes exactly as
221/// they go into the USB packets, in whole *wire frames*
222/// (`format.bytes_per_frame()` = `subslot_bytes * channels` bytes, channels
223/// interleaved in the DAC's channel order). Samples are little-endian.
224///
225/// * **PCM** — each sample is `subslot_bytes` bytes, a signed two's-complement
226/// integer, *left-justified*: the sign bit is the top bit of the subslot and
227/// unused low bits are zero. 16-bit audio in a 2-byte subslot is a plain
228/// `i16`; 24-bit audio in a 3-byte subslot is a packed `i24`; 24-bit audio
229/// in a 4-byte subslot is the `i24` shifted left by 8 (low byte zero);
230/// 32-bit audio is an `i32`. With the layout the DAC advertises, the bytes
231/// written are the bytes on the wire.
232/// * **DoP** — each sample is the DoP word in the same subslot layout, the 16
233/// DSD bits in the top two bytes below the marker: for a 3-byte subslot
234/// `[dsd_low, dsd_high, marker]`, for a 4-byte subslot `[0, dsd_low,
235/// dsd_high, marker]`. `dsd_high` holds the older 8 DSD bits (MSB first). The
236/// marker byte is **ignored and overwritten**: the library owns the
237/// `0x05`/`0xFA` alternation so the phase survives pause, flush and underrun.
238/// * **Native DSD** — raw DSD bytes, MSB first (the oldest bit in bit 7),
239/// interleaved one byte per channel: `[ch0, ch1, ch0, ch1, ...]` in
240/// stream order. A wire frame is `subslot_bytes * channels` such bytes (one
241/// wire word per channel); the library groups consecutive bytes of a channel
242/// into the wire word and orders them as the DAC needs (big-endian or
243/// little-endian, optional bit reversal, per quirk or config).
244///
245/// [`write_i32`](Self::write_i32) takes the ring's own sample unit instead:
246/// PCM as full-scale 32-bit left-justified `i32` (the encoder keeps the top
247/// `valid_bits` bits), DoP as `i32` words with the DSD bits in bits 23..8 (bits
248/// 31..24 are overwritten with the marker), native DSD as one DSD byte per
249/// `i32` in bits 7..0.
250pub struct DacStream {
251 inner: Arc<StreamInner>,
252}
253
254impl std::fmt::Debug for DacStream {
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256 f.debug_struct("DacStream")
257 .field("format", &self.inner.format)
258 .finish_non_exhaustive()
259 }
260}
261
262impl DacStream {
263 pub(crate) fn from_inner(inner: Arc<StreamInner>) -> Self {
264 Self { inner }
265 }
266
267 fn shared(&self) -> &StreamShared {
268 &self.inner.shared
269 }
270
271 fn ensure_open(&self) -> Result<()> {
272 if self.inner.is_closed() {
273 return Err(Error::InvalidState("the stream is closed".to_string()));
274 }
275 Ok(())
276 }
277
278 /// The wire format this stream runs.
279 pub fn format(&self) -> &StreamFormat {
280 &self.inner.format
281 }
282
283 /// Appends wire-layout bytes (see the type-level documentation). Never
284 /// blocks. Returns the number of bytes taken: a whole number of wire frames,
285 /// as many as fit in the ring; a partial or zero count means the ring is
286 /// full, so retry with the remainder later. Input shorter than one wire
287 /// frame is not taken.
288 ///
289 /// [`Error::InvalidState`] after [`drain`](Self::drain) (until
290 /// [`flush`](Self::flush)), or once the stream has closed or failed.
291 pub fn write(&self, data: &[u8]) -> Result<usize> {
292 self.ensure_open()?;
293 self.shared().write_bytes(data)
294 }
295
296 /// Like [`write`](Self::write) for the ring's native `i32` samples. Counts
297 /// and returns samples (a whole number of wire frames: multiples of
298 /// `channels`, or of `subslot_bytes * channels` for native DSD).
299 pub fn write_i32(&self, samples: &[i32]) -> Result<usize> {
300 self.ensure_open()?;
301 self.shared().write_samples(samples)
302 }
303
304 /// How many bytes the host should write now to bring the ring to its
305 /// target depth ([`DacConfig::buffer_target_ms`], or the shallower
306 /// `processing_buffer_target_ms` while software gain is on). A whole number
307 /// of wire frames. `write` still accepts more, up to the ring's capacity.
308 ///
309 /// [`DacConfig::buffer_target_ms`]: crate::DacConfig::buffer_target_ms
310 pub fn writable_bytes(&self) -> usize {
311 if self.inner.is_closed() {
312 return 0;
313 }
314 self.shared().writable_bytes()
315 }
316
317 /// Resumes after [`pause`](Self::pause). A new stream plays by itself once
318 /// the ring holds the start threshold; this is only needed after a pause.
319 pub fn play(&self) -> Result<()> {
320 self.ensure_open()?;
321 self.shared().set_paused(false);
322 Ok(())
323 }
324
325 /// Holds the stream: wire-correct silence goes out (zero for PCM, the
326 /// idle pattern for DSD, DoP markers keep alternating) so the DAC stays
327 /// locked, and the ring is not consumed. Audio already submitted to the bus
328 /// (about [`DacConfig::bus_queue_ms`](crate::DacConfig::bus_queue_ms), 16 ms
329 /// by default, at every service interval) still plays out first; the ring
330 /// resumes exactly where it was.
331 pub fn pause(&self) -> Result<()> {
332 self.ensure_open()?;
333 self.shared().set_paused(true);
334 Ok(())
335 }
336
337 /// Drops everything queued in the ring and resets
338 /// [`played_frames`](Self::played_frames) to 0. The stream holds wire
339 /// silence until the ring holds the start threshold again. Also clears
340 /// [`drain`](Self::drain), so the stream can be reused.
341 ///
342 /// Returns at once. With
343 /// [`DacConfig::cancel_in_flight_on_flush`](crate::DacConfig::cancel_in_flight_on_flush)
344 /// (the default) the output thread then cancels the transfers already on
345 /// the bus, within about one transfer (2 ms), waits for every one to be
346 /// handed back and refills the slots with silence; those transfers are not
347 /// lost audio, not underruns and not counted as played. Off, or when only
348 /// silence is queued (a flush while paused), the queue plays out
349 /// ([`DacConfig::bus_queue_ms`](crate::DacConfig::bus_queue_ms), 16 ms by
350 /// default) and is not counted as played.
351 pub fn flush(&self) -> Result<()> {
352 self.ensure_open()?;
353 self.shared().flush();
354 Ok(())
355 }
356
357 /// Declares that no more audio will be written: the ring plays out, even a
358 /// tail shorter than the start threshold, and the stream then reports
359 /// [`is_drained`](Self::is_drained) and the `Drained` state. The padded
360 /// tail is not an underrun. Further writes fail until
361 /// [`flush`](Self::flush).
362 pub fn drain(&self) -> Result<()> {
363 self.ensure_open()?;
364 self.shared().drain();
365 Ok(())
366 }
367
368 /// `drain()` was called and everything written has been played.
369 pub fn is_drained(&self) -> bool {
370 self.shared().is_drained()
371 }
372
373 /// Closes the stream and waits for the output thread. The DAC stays open.
374 pub fn close(self) -> Result<()> {
375 self.inner.close()
376 }
377
378 pub fn state(&self) -> StreamState {
379 self.shared().current_state()
380 }
381
382 /// Music frames the DAC has completed on the bus since the stream started
383 /// or the last [`flush`](Self::flush). Padding, held silence and lost
384 /// frames are not counted. The unit is `format().counter_rate_hz()`.
385 pub fn played_frames(&self) -> u64 {
386 self.shared().stats.played_frames()
387 }
388
389 /// Music frames between the host and the DAC: in the ring plus on the bus.
390 /// What the audible position lags the written position by.
391 pub fn latency_frames(&self) -> u64 {
392 self.shared().stats.output_latency_frames()
393 }
394
395 /// Frames waiting in the ring, in the unit of
396 /// [`StreamFormat::counter_rate_hz`]. Cheaper than [`stats`](Self::stats)
397 /// (`StreamStats::queued_frames`), for a host that wants to know how full the
398 /// ring is on every cycle of its writer loop.
399 pub fn queued_frames(&self) -> u64 {
400 if self.inner.is_closed() {
401 return 0;
402 }
403 self.shared().stats.queued_frames()
404 }
405
406 /// Bit-perfect means: no software gain, a verified clock at the requested
407 /// rate, no frame lost on the bus, and the wire payload is real audio.
408 /// False as soon as any of that stops being true, and for good after a lost
409 /// frame.
410 pub fn is_bit_perfect(&self) -> bool {
411 !self.inner.is_closed() && self.shared().note_bit_perfect()
412 }
413
414 /// Why [`is_bit_perfect`](Self::is_bit_perfect) is false: `None` when it is
415 /// true, otherwise the first condition that fails.
416 pub fn bit_perfect_blocker(&self) -> Option<BitPerfectBlocker> {
417 if self.inner.is_closed() {
418 return Some(BitPerfectBlocker::NoStream);
419 }
420 current_bit_perfect_blocker()
421 }
422
423 /// Scales PCM samples by `gain` (0.0 to 16.0) as each transfer is prepared,
424 /// so it takes effect within the bus latency rather than the ring depth.
425 /// Rounds to nearest and saturates; no dither. Any value other than 1.0
426 /// ends bit-perfect output. Refused for DoP and native DSD (it would corrupt
427 /// the bitstream).
428 pub fn set_software_gain(&self, gain: f32) -> Result<()> {
429 self.ensure_open()?;
430 self.shared().set_software_gain(gain)
431 }
432
433 pub fn software_gain(&self) -> f32 {
434 self.shared().stats.software_gain()
435 }
436
437 /// Tells the stream that the host processes the audio (EQ, DSP, crossfade,
438 /// pitch) before it writes it. A change the host makes is then heard after
439 /// the ring's fill, so [`writable_bytes`](Self::writable_bytes) asks for the
440 /// shallow `processing_buffer_target_ms` instead of the deep target, as it
441 /// does for software gain. Nothing is flushed when the depth changes (see
442 /// `writable_bytes`).
443 ///
444 /// It is only a hint about buffering. It does not change a sample, and the
445 /// library cannot see what the host did to the audio, so it does not touch
446 /// [`is_bit_perfect`](Self::is_bit_perfect): a host that processes audio is
447 /// responsible for not claiming bit-perfect output. It has no effect for DoP
448 /// and native DSD, which are never processed.
449 pub fn set_host_processing(&self, processing: bool) {
450 self.shared()
451 .stats
452 .host_processing
453 .store(processing, std::sync::atomic::Ordering::Relaxed);
454 }
455
456 /// Whether [`set_host_processing`](Self::set_host_processing) is on.
457 pub fn host_processing(&self) -> bool {
458 self.shared()
459 .stats
460 .host_processing
461 .load(std::sync::atomic::Ordering::Relaxed)
462 }
463
464 /// A bounded snapshot of the explicit USB feedback path for this stream.
465 ///
466 /// Available after the worker has selected the endpoint, including after
467 /// a feedback failure. Other pacing modes return `None`.
468 pub fn explicit_feedback_diagnostics(&self) -> Option<crate::ExplicitFeedbackDiagnostics> {
469 *self.shared().stats.explicit_feedback_diagnostics.lock()
470 }
471
472 pub fn stats(&self) -> StreamStats {
473 use std::sync::atomic::Ordering::Relaxed;
474 let shared = self.shared();
475 let stats = &shared.stats;
476 let feedback_last = stats.feedback_last_report_ms.load(Relaxed);
477 let elapsed_ms = stats.started_at.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;
478 let verdicts = if self.inner.is_closed() {
479 Default::default()
480 } else {
481 stream_verdicts()
482 };
483 StreamStats {
484 state: shared.current_state(),
485 bit_perfect: !self.inner.is_closed() && bit_perfect_now(),
486 bit_perfect_blocker: self.bit_perfect_blocker(),
487 software_gain: stats.software_gain(),
488 underruns: stats.underrun_count.load(Relaxed),
489 lost_frames: stats.lost_frames.load(Relaxed),
490 short_packets: stats.short_packets.load(Relaxed),
491 zero_packets: stats.zero_packets.load(Relaxed),
492 urb_timeouts: stats.data_urb_timeouts.load(Relaxed),
493 completed_transfers: stats.completed_transfers.load(Relaxed),
494 frames_written: stats.producer_frames.load(Relaxed),
495 frames_completed: stats.consumer_frames.load(Relaxed),
496 played_frames: stats.played_frames(),
497 latency_frames: stats.output_latency_frames(),
498 latency_ms: stats.output_latency_ms(),
499 queued_frames: stats.queued_frames(),
500 buffer_ms: stats.buffer_fill_ms(),
501 buffer_target_ms: stats.buffer_target_ms(),
502 active_target_ms: stats.active_target_ms(),
503 buffer_capacity_ms: stats.buffer_capacity_ms(),
504 transfer_queue_depth: stats.transfer_queue_depth.load(Relaxed) as u32,
505 last_turnaround_us: stats.last_transfer_turnaround_us.load(Relaxed),
506 max_turnaround_us: stats.max_transfer_turnaround_us.load(Relaxed),
507 last_submit_gap_us: stats.last_submit_gap_us.load(Relaxed),
508 max_submit_gap_us: stats.max_submit_gap_us.load(Relaxed),
509 effective_rate_hz: stats.effective_consumer_rate_milli_hz.load(Relaxed) as f64 / 1_000.0,
510 feedback_active: stats.feedback_locked.load(Relaxed),
511 feedback_reports: stats.feedback_reports.load(Relaxed),
512 feedback_timeouts: stats.feedback_timeouts.load(Relaxed),
513 feedback_errors: stats.feedback_errors.load(Relaxed),
514 feedback_rejected: stats.feedback_rejected.load(Relaxed),
515 feedback_age_ms: (feedback_last != u64::MAX)
516 .then(|| elapsed_ms.saturating_sub(feedback_last)),
517 feedback_rate_hz: (stats.feedback_reports.load(Relaxed) > 0)
518 .then(|| stats.feedback_rate_milli_hz.load(Relaxed) as f64 / 1_000.0),
519 feedback_stale: stats.feedback_stale.load(Relaxed),
520 feedback_locked: stats.feedback_locked.load(Relaxed),
521 feedback_empty: stats.feedback_empty.load(Relaxed),
522 implicit_fifo_depth: stats.implicit_fifo_depth.load(Relaxed) as u32,
523 implicit_fifo_high_water: stats.implicit_fifo_high_water.load(Relaxed) as u32,
524 implicit_waits: stats.implicit_waits.load(Relaxed),
525 implicit_empty_bus: stats.implicit_empty_bus.load(Relaxed),
526 implicit_overruns: stats.implicit_overruns.load(Relaxed),
527 implicit_in_transfers: stats.implicit_in_transfers.load(Relaxed),
528 implicit_out_of_order: stats.implicit_out_of_order.load(Relaxed),
529 implicit_invalid_packets: stats.implicit_invalid_packets.load(Relaxed),
530 implicit_measured_frames: stats.implicit_measured_frames.load(Relaxed),
531 implicit_scheduled_frames: stats.implicit_scheduled_frames.load(Relaxed),
532
533 stable: verdicts.stable,
534 clock_verified: verdicts.clock_verified,
535 payload_verified: verdicts.payload_verified,
536 payload_constant_for_ms: verdicts.payload_constant_for_ms,
537 }
538 }
539}
540
541impl Drop for DacStream {
542 fn drop(&mut self) {
543 let _ = self.inner.close();
544 }
545}