Skip to main content

guide_player/
guide_player.rs

1#![allow(dead_code)]
2//! Playing through an open DAC: the writer thread, the transport, events, volume, the bit-perfect line
3//! and a clean close.
4//!
5//! This is the code of the second half of `docs/sdk/guide-rust.md`. It compiles on every host and needs a
6//! DAC on Linux or Android to run. `cargo check --workspace --examples` keeps it compiling.
7
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::mpsc::{channel, Receiver};
10use std::sync::{Arc, Mutex, MutexGuard};
11use std::thread::{self, JoinHandle};
12use std::time::Duration;
13use usbdac_core::{
14    BitPerfectBlocker, CloseVolume, Dac, DacEvent, DacListener, DacStream, Error, Result,
15    StreamFormat, VolumeControl,
16};
17
18// region rust-source
19/// The host's decoder, as the writer thread sees it.
20pub trait Source: Send {
21    /// Fills `out` with whole frames of PCM as full-scale 32-bit samples, left-justified: a 16-bit sample
22    /// is `sample << 16`, a 24-bit one `sample << 8`. Returns how many samples it wrote, a multiple of the
23    /// channel count, or 0 at the end of the track. The stream keeps the top `valid_bits` bits.
24    fn render(&mut self, out: &mut [i32]) -> usize;
25
26    /// Moves the decoder to `seconds`.
27    fn seek(&mut self, seconds: f64);
28}
29
30/// A 440 Hz tone at 24-bit precision, for trying the code without a decoder.
31pub struct Tone {
32    rate: f64,
33    channels: usize,
34    phase: f64,
35}
36
37impl Tone {
38    pub fn new(rate: u32, channels: u16) -> Self {
39        Self {
40            rate: f64::from(rate),
41            channels: usize::from(channels),
42            phase: 0.0,
43        }
44    }
45}
46
47impl Source for Tone {
48    fn render(&mut self, out: &mut [i32]) -> usize {
49        for frame in out.chunks_exact_mut(self.channels) {
50            let sample = ((self.phase * std::f64::consts::TAU).sin() * 0.25 * 8_388_607.0) as i32;
51            frame.fill(sample << 8); // 24 bits, left-justified in 32
52            self.phase = (self.phase + 440.0 / self.rate).fract();
53        }
54        out.len()
55    }
56
57    fn seek(&mut self, _seconds: f64) {
58        self.phase = 0.0;
59    }
60}
61// endregion
62
63// region rust-ring
64/// The part of `DacStream` that the writer and the transport use. A host that wants to test its writer
65/// on a laptop writes a second implementation that records what it is given: `DacStream` cannot be
66/// built without a DAC.
67pub trait Ring: Send + Sync {
68    fn writable_bytes(&self) -> usize;
69    fn write_i32(&self, samples: &[i32]) -> Result<usize>;
70    fn play(&self) -> Result<()>;
71    fn pause(&self) -> Result<()>;
72    fn flush(&self) -> Result<()>;
73    fn drain(&self) -> Result<()>;
74    fn is_drained(&self) -> bool;
75    fn played_frames(&self) -> u64;
76}
77
78impl Ring for DacStream {
79    fn writable_bytes(&self) -> usize {
80        DacStream::writable_bytes(self)
81    }
82    fn write_i32(&self, samples: &[i32]) -> Result<usize> {
83        DacStream::write_i32(self, samples)
84    }
85    fn play(&self) -> Result<()> {
86        DacStream::play(self)
87    }
88    fn pause(&self) -> Result<()> {
89        DacStream::pause(self)
90    }
91    fn flush(&self) -> Result<()> {
92        DacStream::flush(self)
93    }
94    fn drain(&self) -> Result<()> {
95        DacStream::drain(self)
96    }
97    fn is_drained(&self) -> bool {
98        DacStream::is_drained(self)
99    }
100    fn played_frames(&self) -> u64 {
101        DacStream::played_frames(self)
102    }
103}
104
105/// What the writer needs to know about the wire format.
106#[derive(Clone, Copy, Debug)]
107pub struct Shape {
108    pub channels: usize,
109    /// Bytes of one sample on the wire (`subslot_bytes`): the unit `writable_bytes` counts in.
110    pub bytes_per_sample: usize,
111    pub sample_rate: u32,
112    /// The rate of `played_frames`.
113    pub counter_rate_hz: u32,
114}
115
116impl From<&StreamFormat> for Shape {
117    fn from(format: &StreamFormat) -> Self {
118        Self {
119            channels: usize::from(format.channels),
120            bytes_per_sample: usize::from(format.subslot_bytes),
121            sample_rate: format.sample_rate,
122            counter_rate_hz: format.counter_rate_hz(),
123        }
124    }
125}
126// endregion
127
128// region rust-player
129/// What the writer thread and the control calls share, under one lock so that a seek can never
130/// interleave with a half-written chunk.
131struct Shared {
132    source: Box<dyn Source>,
133    /// A rendered chunk that the ring has not fully taken yet.
134    chunk: Vec<i32>,
135    taken: usize,
136    ended: bool,
137    /// The source time of the first frame written since the last flush.
138    start_seconds: f64,
139}
140
141fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
142    shared
143        .lock()
144        .unwrap_or_else(|poisoned| poisoned.into_inner())
145}
146
147pub struct Player<R: Ring + 'static> {
148    ring: Arc<R>,
149    shape: Shape,
150    shared: Arc<Mutex<Shared>>,
151    stop: Arc<AtomicBool>,
152    writer: Option<JoinHandle<()>>,
153}
154
155impl<R: Ring + 'static> Player<R> {
156    /// Starts the writer thread. The stream starts by itself once the ring holds `start_threshold_ms`
157    /// of audio (100 ms by default); `play` is only for after a pause.
158    pub fn start(ring: Arc<R>, shape: Shape, source: Box<dyn Source>) -> Self {
159        let shared = Arc::new(Mutex::new(Shared {
160            source,
161            chunk: Vec::new(),
162            taken: 0,
163            ended: false,
164            start_seconds: 0.0,
165        }));
166        let stop = Arc::new(AtomicBool::new(false));
167        let writer = {
168            let (ring, shared, stop) = (Arc::clone(&ring), Arc::clone(&shared), Arc::clone(&stop));
169            thread::Builder::new()
170                .name("host-writer".into())
171                .spawn(move || write_loop(&*ring, shape, &shared, &stop))
172                .expect("spawn the writer thread")
173        };
174        Self {
175            ring,
176            shape,
177            shared,
178            stop,
179            writer: Some(writer),
180        }
181    }
182
183    /// Keep the writer running while paused: it fills the ring to its target and idles, so a resume
184    /// loses nothing.
185    pub fn pause(&self) -> Result<()> {
186        self.ring.pause()
187    }
188
189    pub fn resume(&self) -> Result<()> {
190        self.ring.play()
191    }
192
193    /// Reposition the decoder, drop what was rendered for the old position, then flush. The old audio
194    /// stops within a transfer or two, and `played_frames` starts again from zero.
195    pub fn seek(&self, seconds: f64) -> Result<()> {
196        let mut state = lock(&self.shared);
197        state.source.seek(seconds);
198        state.chunk.clear();
199        state.taken = 0;
200        state.ended = false;
201        state.start_seconds = seconds;
202        self.ring.flush()
203    }
204
205    /// The audible position: where the last flush started plus what the DAC has completed since.
206    pub fn position_seconds(&self) -> f64 {
207        let start = lock(&self.shared).start_seconds;
208        start + self.ring.played_frames() as f64 / f64::from(self.shape.counter_rate_hz)
209    }
210
211    /// The decoder reached the end and the DAC has played everything.
212    pub fn finished(&self) -> bool {
213        lock(&self.shared).ended && self.ring.is_drained()
214    }
215
216    pub fn ring(&self) -> &R {
217        &self.ring
218    }
219
220    /// Stops the writer and returns the ring, so that the caller can close it.
221    pub fn stop(mut self) -> Arc<R> {
222        self.stop.store(true, Ordering::Release);
223        if let Some(writer) = self.writer.take() {
224            let _ = writer.join();
225        }
226        Arc::clone(&self.ring)
227    }
228}
229
230impl<R: Ring + 'static> Drop for Player<R> {
231    fn drop(&mut self) {
232        self.stop.store(true, Ordering::Release);
233        if let Some(writer) = self.writer.take() {
234            let _ = writer.join();
235        }
236    }
237}
238
239fn write_loop(ring: &dyn Ring, shape: Shape, shared: &Mutex<Shared>, stop: &AtomicBool) {
240    // About 10 ms of audio per render call, in whole frames.
241    let mut scratch = vec![0i32; (shape.sample_rate as usize / 100).max(1) * shape.channels];
242    while !stop.load(Ordering::Acquire) {
243        let mut state = lock(shared);
244        if state.ended {
245            drop(state);
246            thread::sleep(Duration::from_millis(10));
247            continue;
248        }
249        if state.taken == state.chunk.len() {
250            // Render only when the ring wants this much, so the decoder is never ahead of the ring's
251            // target depth and a seek has little to throw away.
252            if ring.writable_bytes() < scratch.len() * shape.bytes_per_sample {
253                drop(state);
254                thread::sleep(Duration::from_millis(2));
255                continue;
256            }
257            let rendered = state.source.render(&mut scratch);
258            if rendered == 0 {
259                // The end of the track: let the ring play out, even a tail shorter than the start threshold.
260                if ring.drain().is_ok() {
261                    state.ended = true;
262                }
263                continue;
264            }
265            state.chunk.clear();
266            state.chunk.extend_from_slice(&scratch[..rendered]);
267            state.taken = 0;
268        }
269        // Never blocks. A count short of what was offered, or zero, means the ring is full.
270        match ring.write_i32(&state.chunk[state.taken..]) {
271            Ok(0) => {
272                drop(state);
273                thread::sleep(Duration::from_millis(2));
274            }
275            Ok(taken) => state.taken += taken,
276            Err(error) => {
277                // The stream closed or failed. The event listener has the reason.
278                log::warn!("the writer stops: {error}");
279                return;
280            }
281        }
282    }
283}
284// endregion
285
286// region rust-events
287/// A listener that hands events to a thread of the host's choice. It runs on the library's event
288/// thread, must not block, and must not call `Dac::close`. An unbounded channel's `send` does neither.
289pub fn event_channel() -> (Arc<dyn DacListener>, Receiver<DacEvent>) {
290    let (tx, rx) = channel();
291    let listener: Arc<dyn DacListener> = Arc::new(move |event: DacEvent| {
292        let _ = tx.send(event);
293    });
294    (listener, rx)
295}
296
297/// What the host does about each event.
298pub enum Reaction {
299    Nothing,
300    /// Count it; look at the decoder's read-ahead. Playback goes on with silence in the gap.
301    Underrun,
302    /// A sliver of audio never reached the DAC. The stream is not bit-perfect from here on.
303    NotBitPerfect,
304    /// Pause, say why, and do not carry on through another output unless the listener asks.
305    Pause(&'static str),
306    /// The stream failed. Stop the writer, close the stream and decide what to do next.
307    Failed(Error),
308}
309
310pub fn react(event: DacEvent) -> Reaction {
311    match event {
312        DacEvent::Underrun => Reaction::Underrun,
313        DacEvent::LostFrames { .. } => Reaction::NotBitPerfect,
314        DacEvent::FeedbackStale => Reaction::Nothing, // the stream recovers, or fails with its own event
315        DacEvent::DeviceLost => Reaction::Pause("the DAC was unplugged"),
316        DacEvent::Error(error) => Reaction::Failed(error),
317        // The state, the bit-perfect flag and the volume are read when the display needs them.
318        _ => Reaction::Nothing,
319    }
320}
321// endregion
322
323// region rust-volume
324/// When a DAC connects: the library has already lowered it to at most -40 dB. Restore the level the
325/// listener had for this DAC, but never above what the DAC itself had.
326pub fn restore_level(volume: &VolumeControl, remembered_db: Option<f64>) -> Result<f64> {
327    let ceiling = volume.startup().limit_db;
328    match remembered_db {
329        Some(db) => volume.set_db(db.min(ceiling)).map(|state| state.db),
330        None => volume.get().map(|state| state.db),
331    }
332}
333
334/// A volume key or a slider. Each call is a USB control transfer (milliseconds, up to a second):
335/// call it from a control thread and not from the writer or a UI thread.
336pub fn nudge(volume: &VolumeControl, up: bool) -> Result<f64> {
337    volume
338        .step(if up { 1 } else { -1 }, 0)
339        .map(|state| state.db)
340}
341// endregion
342
343// region rust-bit-perfect
344/// One line for a status display. The library's flag covers the transport; the host adds what it did
345/// to the samples and what the source was.
346pub fn status_line(stream: &DacStream, engine_untouched: bool, lossy_source: bool) -> String {
347    if !engine_untouched {
348        return "Not bit-perfect: the player is processing the audio".to_string();
349    }
350    match stream.bit_perfect_blocker() {
351        None if lossy_source => "Direct USB, decoded from a lossy file".to_string(),
352        None => "Bit-perfect".to_string(),
353        Some(blocker) => format!("Not bit-perfect: {}", blocker_text(blocker)),
354    }
355}
356
357fn blocker_text(blocker: BitPerfectBlocker) -> &'static str {
358    match blocker {
359        BitPerfectBlocker::LostFrames => "audio was lost on the USB bus",
360        BitPerfectBlocker::FormatChanged => "the DAC runs another rate than the track has",
361        BitPerfectBlocker::ClockUnverified => "the DAC did not confirm its sampling rate",
362        BitPerfectBlocker::SoftwareGain => "software gain is on",
363        BitPerfectBlocker::UnsynchronizedAsync => {
364            "the DAC has no feedback, so it plays at the nominal rate"
365        }
366        BitPerfectBlocker::FeedbackUnlocked => "the DAC's timing has not locked yet",
367        BitPerfectBlocker::PayloadUnverified => "waiting for real audio",
368        BitPerfectBlocker::NoStream => "no stream is running",
369        // `BitPerfectBlocker` is non-exhaustive.
370        _ => "the stream is not verified",
371    }
372}
373// endregion
374
375// region rust-close
376/// Stops the writer, closes the stream, then the DAC. The host releases its interfaces and its
377/// descriptor after this returns, never before.
378///
379/// `device_lost` is true when the DAC was unplugged: nothing can be written to it, and its recorded
380/// level must not outlive the attachment.
381pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382    let stream = player.stop(); // joins the writer thread
383    let stream_result = match Arc::try_unwrap(stream) {
384        Ok(stream) => stream.close(),
385        Err(_) => Err(Error::InvalidState(
386            "the stream is still shared".to_string(),
387        )),
388    };
389    let dac_result = if device_lost {
390        dac.close_with(CloseVolume::Forget)
391    } else {
392        dac.close()
393    };
394    if matches!(dac_result, Err(Error::Transfer(_))) {
395        // The output thread did not stop in time. Keep every claim and the descriptor until it has.
396        while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397    }
398    stream_result.and(dac_result)
399}
400// endregion
401
402// region rust-play-one
403/// How a host that plays one track fits the pieces together. `format` comes from `negotiate`.
404pub fn play_one(dac: Dac, format: &StreamFormat, source: Box<dyn Source>) -> Result<()> {
405    let (listener, events) = event_channel();
406    let stream = dac.open_stream(format, listener)?;
407    let shape = Shape::from(stream.format());
408    let player = Player::start(Arc::new(stream), shape, source);
409    let mut device_lost = false;
410    while !player.finished() {
411        match events.recv_timeout(Duration::from_millis(100)).map(react) {
412            Ok(Reaction::Pause(reason)) => {
413                log::warn!("{reason}");
414                device_lost = true;
415                break;
416            }
417            Ok(Reaction::Failed(error)) => {
418                device_lost = error == Error::DeviceLost;
419                log::warn!("the stream failed: {error}");
420                break;
421            }
422            _ => {}
423        }
424    }
425    log::info!("{}", status_line(player.ring(), true, false));
426    shutdown(player, dac, device_lost)
427}
428// endregion
429
430fn main() {
431    println!("guide_player is a compile-checked example of docs/sdk/guide-rust.md; it needs a DAC to run.");
432}