pull_adapter/
pull_adapter.rs1#![allow(dead_code)]
2use 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
16trait Render: Send {
18 fn render(&mut self, out: &mut [u8]) -> usize;
22 fn seek(&mut self, seconds: f64);
23}
24
25struct State {
28 source: Box<dyn Render>,
29 chunk: Vec<u8>,
31 taken: usize,
32 ended: bool,
33 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 fn pause(&self) -> Result<()> {
76 self.stream.pause()
77 }
78
79 fn resume(&self) -> Result<()> {
80 self.stream.play()
81 }
82
83 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 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 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 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 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 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 eprintln!("writer stopping: {error}");
160 return;
161 }
162 }
163 }
164}
165
166fn main() {
167 println!("pull_adapter is a compile-checked example, see the source.");
169}