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_bytesbytes, 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 plaini16; 24-bit audio in a 3-byte subslot is a packedi24; 24-bit audio in a 4-byte subslot is thei24shifted left by 8 (low byte zero); 32-bit audio is ani32. 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_highholds the older 8 DSD bits (MSB first). The marker byte is ignored and overwritten: the library owns the0x05/0xFAalternation 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 issubslot_bytes * channelssuch 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
impl DacStream
Sourcepub fn format(&self) -> &StreamFormat
pub fn format(&self) -> &StreamFormat
The wire format this stream runs.
Examples found in repository?
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}Sourcepub fn write(&self, data: &[u8]) -> Result<usize>
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?
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}Sourcepub fn write_i32(&self, samples: &[i32]) -> Result<usize>
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).
Sourcepub fn writable_bytes(&self) -> usize
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?
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}Sourcepub fn play(&self) -> Result<()>
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.
Sourcepub fn pause(&self) -> Result<()>
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.
Sourcepub fn flush(&self) -> Result<()>
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.
Sourcepub fn drain(&self) -> Result<()>
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?
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}Sourcepub fn is_drained(&self) -> bool
pub fn is_drained(&self) -> bool
drain() was called and everything written has been played.
Sourcepub fn close(self) -> Result<()>
pub fn close(self) -> Result<()>
Closes the stream and waits for the output thread. The DAC stays open.
pub fn state(&self) -> StreamState
Sourcepub fn played_frames(&self) -> u64
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().
Sourcepub fn latency_frames(&self) -> u64
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.
Sourcepub fn queued_frames(&self) -> u64
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.
Sourcepub fn is_bit_perfect(&self) -> bool
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.
Sourcepub fn bit_perfect_blocker(&self) -> Option<BitPerfectBlocker>
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.
Sourcepub fn set_software_gain(&self, gain: f32) -> Result<()>
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).
pub fn software_gain(&self) -> f32
Sourcepub fn set_host_processing(&self, processing: bool)
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.
Sourcepub fn host_processing(&self) -> bool
pub fn host_processing(&self) -> bool
Whether set_host_processing is on.
Sourcepub fn explicit_feedback_diagnostics(
&self,
) -> Option<ExplicitFeedbackDiagnostics>
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.