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.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
46}
47
48impl PullAdapter {
49    fn start(stream: Arc<DacStream>, source: Box<dyn Render>) -> Self {
50        let state = Arc::new(Mutex::new(State {
51            source,
52            chunk: Vec::new(),
53            taken: 0,
54            ended: false,
55            base_seconds: 0.0,
56        }));
57        let stop = Arc::new(AtomicBool::new(false));
58        let writer = {
59            let (stream, state, stop) = (Arc::clone(&stream), Arc::clone(&state), Arc::clone(&stop));
60            thread::Builder::new()
61                .name("host-writer".into())
62                .spawn(move || write_loop(&stream, &state, &stop))
63                .expect("spawn the writer thread")
64        };
65        Self {
66            stream,
67            state,
68            stop,
69            writer: Some(writer),
70        }
71    }
72
73    /// Pause keeps the writer running: it fills the ring to its target and then
74    /// idles on `writable_bytes() == 0`, so resume is instant.
75    fn pause(&self) -> Result<()> {
76        self.stream.pause()
77    }
78
79    fn resume(&self) -> Result<()> {
80        self.stream.play()
81    }
82
83    /// Seek: reposition the decoder, drop what was rendered for the old
84    /// position, then flush the ring. After `flush()` the stream holds silence
85    /// until the start threshold of new audio has arrived, and `played_frames()`
86    /// counts from zero again.
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    }
96
97    /// The position that is audible right now: where the last flush started,
98    /// plus the music the DAC has completed since.
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}
165
166fn main() {
167    // Needs a DAC; see the README for how a host obtains the file descriptor.
168    println!("pull_adapter is a compile-checked example, see the source.");
169}