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.
  • 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.
  • 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 and orders them as the DAC needs (big-endian or little-endian, optional bit reversal, per quirk or config).

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 101)
99    fn position_seconds(&self) -> f64 {
100        let base = lock(&self.state).base_seconds;
101        base + self.stream.played_frames() as f64 / f64::from(self.stream.format().counter_rate_hz())
102    }
103
104    /// The decoder is at the end of the track and the DAC has played it all.
105    fn finished(&self) -> bool {
106        lock(&self.state).ended && self.stream.is_drained()
107    }
108}
109
110impl Drop for PullAdapter {
111    fn drop(&mut self) {
112        self.stop.store(true, Ordering::Release);
113        if let Some(writer) = self.writer.take() {
114            let _ = writer.join();
115        }
116    }
117}
118
119fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
120    let frame = stream.format().bytes_per_frame();
121    // About 10 ms per render call.
122    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
123    let mut scratch = vec![0u8; chunk_frames * frame];
124    while !stop.load(Ordering::Acquire) {
125        let mut state = lock(state);
126        if state.ended {
127            drop(state);
128            thread::sleep(Duration::from_millis(10));
129            continue;
130        }
131        // Render only when the ring wants more, so the decoder is never ahead of
132        // the configured buffer depth (and a seek never has much to throw away).
133        if state.taken == state.chunk.len() {
134            if stream.writable_bytes() < scratch.len() {
135                drop(state);
136                thread::sleep(Duration::from_millis(2));
137                continue;
138            }
139            let rendered = state.source.render(&mut scratch);
140            if rendered == 0 {
141                // No more audio: let the ring play out, even a short tail.
142                if stream.drain().is_ok() {
143                    state.ended = true;
144                }
145                continue;
146            }
147            state.chunk.clear();
148            state.chunk.extend_from_slice(&scratch[..rendered]);
149            state.taken = 0;
150        }
151        match stream.write(&state.chunk[state.taken..]) {
152            Ok(0) => {
153                drop(state);
154                thread::sleep(Duration::from_millis(2));
155            }
156            Ok(taken) => state.taken += taken,
157            Err(error) => {
158                // The stream closed or failed; the listener has the details.
159                eprintln!("writer stopping: {error}");
160                return;
161            }
162        }
163    }
164}
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/pull_adapter.rs (line 151)
119fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
120    let frame = stream.format().bytes_per_frame();
121    // About 10 ms per render call.
122    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
123    let mut scratch = vec![0u8; chunk_frames * frame];
124    while !stop.load(Ordering::Acquire) {
125        let mut state = lock(state);
126        if state.ended {
127            drop(state);
128            thread::sleep(Duration::from_millis(10));
129            continue;
130        }
131        // Render only when the ring wants more, so the decoder is never ahead of
132        // the configured buffer depth (and a seek never has much to throw away).
133        if state.taken == state.chunk.len() {
134            if stream.writable_bytes() < scratch.len() {
135                drop(state);
136                thread::sleep(Duration::from_millis(2));
137                continue;
138            }
139            let rendered = state.source.render(&mut scratch);
140            if rendered == 0 {
141                // No more audio: let the ring play out, even a short tail.
142                if stream.drain().is_ok() {
143                    state.ended = true;
144                }
145                continue;
146            }
147            state.chunk.clear();
148            state.chunk.extend_from_slice(&scratch[..rendered]);
149            state.taken = 0;
150        }
151        match stream.write(&state.chunk[state.taken..]) {
152            Ok(0) => {
153                drop(state);
154                thread::sleep(Duration::from_millis(2));
155            }
156            Ok(taken) => state.taken += taken,
157            Err(error) => {
158                // The stream closed or failed; the listener has the details.
159                eprintln!("writer stopping: {error}");
160                return;
161            }
162        }
163    }
164}
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).

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

pub fn is_drained(&self) -> bool

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

Examples found in repository?
examples/pull_adapter.rs (line 106)
105    fn finished(&self) -> bool {
106        lock(&self.state).ended && self.stream.is_drained()
107    }
Source

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

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

Source

pub fn state(&self) -> StreamState

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/pull_adapter.rs (line 101)
99    fn position_seconds(&self) -> f64 {
100        let base = lock(&self.state).base_seconds;
101        base + self.stream.played_frames() as f64 / f64::from(self.stream.format().counter_rate_hz())
102    }
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.

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

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

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.