1#![allow(dead_code)]
2use 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
18pub trait Source: Send {
21 fn render(&mut self, out: &mut [i32]) -> usize;
25
26 fn seek(&mut self, seconds: f64);
28}
29
30pub 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); 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}
61pub 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#[derive(Clone, Copy, Debug)]
107pub struct Shape {
108 pub channels: usize,
109 pub bytes_per_sample: usize,
111 pub sample_rate: u32,
112 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}
126struct Shared {
132 source: Box<dyn Source>,
133 chunk: Vec<i32>,
135 taken: usize,
136 ended: bool,
137 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 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 pub fn pause(&self) -> Result<()> {
186 self.ring.pause()
187 }
188
189 pub fn resume(&self) -> Result<()> {
190 self.ring.play()
191 }
192
193 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 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 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 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 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 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 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 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 log::warn!("the writer stops: {error}");
279 return;
280 }
281 }
282 }
283}
284pub 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
297pub enum Reaction {
299 Nothing,
300 Underrun,
302 NotBitPerfect,
304 Pause(&'static str),
306 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, DacEvent::DeviceLost => Reaction::Pause("the DAC was unplugged"),
316 DacEvent::Error(error) => Reaction::Failed(error),
317 _ => Reaction::Nothing,
319 }
320}
321pub 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
334pub fn nudge(volume: &VolumeControl, up: bool) -> Result<f64> {
337 volume
338 .step(if up { 1 } else { -1 }, 0)
339 .map(|state| state.db)
340}
341pub 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 _ => "the stream is not verified",
371 }
372}
373pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382 let stream = player.stop(); 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 while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397 }
398 stream_result.and(dac_result)
399}
400pub 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}
428fn main() {
431 println!("guide_player is a compile-checked example of docs/sdk/guide-rust.md; it needs a DAC to run.");
432}