Skip to main content

pull_adapter/
pull_adapter.rs

1#![allow(dead_code)]
2//! A host with a decoder that renders audio on request ("pull") driving the
3//! push API from a thread of its own, with seek, pause and position.
4//!
5//! The library never calls back into the host on the audio path. The adapter
6//! keeps the ring near its target depth by asking `writable_bytes()` and writing
7//! only then. It cannot run without a DAC; `cargo check --examples` keeps it
8//! compiling.
9
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex, MutexGuard};
12use std::thread::{self, JoinHandle};
13use std::time::Duration;
14use usbdac_core::{DacStream, Result};
15
16/// The host's decoder, as the adapter sees it.
17trait Render: Send {
18    /// Fills `out` with wire-layout bytes (see the `DacStream` documentation for
19    /// the layout of each encoding) in whole frames and returns how many bytes
20    /// it wrote; 0 at the end of the track.
21    fn render(&mut self, out: &mut [u8]) -> usize;
22    fn seek(&mut self, seconds: f64);
23}
24
25/// Everything the writer thread and the control calls share, under one lock so a
26/// seek can never interleave with a half-written chunk.
27struct State {
28    source: Box<dyn Render>,
29    /// A rendered chunk the ring has not fully taken yet.
30    chunk: Vec<u8>,
31    taken: usize,
32    ended: bool,
33    /// Source time of the first frame written since the last flush.
34    base_seconds: f64,
35}
36
37struct PullAdapter {
38    stream: Arc<DacStream>,
39    state: Arc<Mutex<State>>,
40    stop: Arc<AtomicBool>,
41    writer: Option<JoinHandle<()>>,
42}
43
44fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
45    state
46        .lock()
47        .unwrap_or_else(|poisoned| poisoned.into_inner())
48}
49
50impl PullAdapter {
51    fn start(stream: Arc<DacStream>, source: Box<dyn Render>) -> Self {
52        let state = Arc::new(Mutex::new(State {
53            source,
54            chunk: Vec::new(),
55            taken: 0,
56            ended: false,
57            base_seconds: 0.0,
58        }));
59        let stop = Arc::new(AtomicBool::new(false));
60        let writer = {
61            let (stream, state, stop) =
62                (Arc::clone(&stream), Arc::clone(&state), Arc::clone(&stop));
63            thread::Builder::new()
64                .name("host-writer".into())
65                .spawn(move || write_loop(&stream, &state, &stop))
66                .expect("spawn the writer thread")
67        };
68        Self {
69            stream,
70            state,
71            stop,
72            writer: Some(writer),
73        }
74    }
75
76    /// Pause keeps the writer running: it fills the ring to its target and then
77    /// idles on `writable_bytes() == 0`, so resume is instant.
78    fn pause(&self) -> Result<()> {
79        self.stream.pause()
80    }
81
82    fn resume(&self) -> Result<()> {
83        self.stream.play()
84    }
85
86    /// Seek: reposition the decoder, drop what was rendered for the old
87    /// position, then flush the ring. After `flush()` the stream holds silence
88    /// until the start threshold of new audio has arrived, and `played_frames()`
89    /// counts from zero again.
90    fn seek(&self, seconds: f64) -> Result<()> {
91        let mut state = lock(&self.state);
92        state.source.seek(seconds);
93        state.chunk.clear();
94        state.taken = 0;
95        state.ended = false;
96        state.base_seconds = seconds;
97        self.stream.flush()
98    }
99
100    /// The position that is audible right now: where the last flush started,
101    /// plus the music the DAC has completed since.
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
107
108    /// The decoder is at the end of the track and the DAC has played it all.
109    fn finished(&self) -> bool {
110        lock(&self.state).ended && self.stream.is_drained()
111    }
112}
113
114impl Drop for PullAdapter {
115    fn drop(&mut self) {
116        self.stop.store(true, Ordering::Release);
117        if let Some(writer) = self.writer.take() {
118            let _ = writer.join();
119        }
120    }
121}
122
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
169
170fn main() {
171    // Needs a DAC; see the README for how a host obtains the file descriptor.
172    println!("pull_adapter is a compile-checked example, see the source.");
173}