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
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 fn pause(&self) -> Result<()> {
79 self.stream.pause()
80 }
81
82 fn resume(&self) -> Result<()> {
83 self.stream.play()
84 }
85
86 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 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 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 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 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 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 eprintln!("writer stopping: {error}");
164 return;
165 }
166 }
167 }
168}
169
170fn main() {
171 println!("pull_adapter is a compile-checked example, see the source.");
173}