#![allow(dead_code)]
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use usbdac_core::{
BitPerfectBlocker, CloseVolume, Dac, DacEvent, DacListener, DacStream, Error, Result, StreamFormat,
VolumeControl,
};
pub trait Source: Send {
fn render(&mut self, out: &mut [i32]) -> usize;
fn seek(&mut self, seconds: f64);
}
pub struct Tone {
rate: f64,
channels: usize,
phase: f64,
}
impl Tone {
pub fn new(rate: u32, channels: u16) -> Self {
Self { rate: f64::from(rate), channels: usize::from(channels), phase: 0.0 }
}
}
impl Source for Tone {
fn render(&mut self, out: &mut [i32]) -> usize {
for frame in out.chunks_exact_mut(self.channels) {
let sample = ((self.phase * std::f64::consts::TAU).sin() * 0.25 * 8_388_607.0) as i32;
frame.fill(sample << 8); self.phase = (self.phase + 440.0 / self.rate).fract();
}
out.len()
}
fn seek(&mut self, _seconds: f64) {
self.phase = 0.0;
}
}
pub trait Ring: Send + Sync {
fn writable_bytes(&self) -> usize;
fn write_i32(&self, samples: &[i32]) -> Result<usize>;
fn play(&self) -> Result<()>;
fn pause(&self) -> Result<()>;
fn flush(&self) -> Result<()>;
fn drain(&self) -> Result<()>;
fn is_drained(&self) -> bool;
fn played_frames(&self) -> u64;
}
impl Ring for DacStream {
fn writable_bytes(&self) -> usize {
DacStream::writable_bytes(self)
}
fn write_i32(&self, samples: &[i32]) -> Result<usize> {
DacStream::write_i32(self, samples)
}
fn play(&self) -> Result<()> {
DacStream::play(self)
}
fn pause(&self) -> Result<()> {
DacStream::pause(self)
}
fn flush(&self) -> Result<()> {
DacStream::flush(self)
}
fn drain(&self) -> Result<()> {
DacStream::drain(self)
}
fn is_drained(&self) -> bool {
DacStream::is_drained(self)
}
fn played_frames(&self) -> u64 {
DacStream::played_frames(self)
}
}
#[derive(Clone, Copy, Debug)]
pub struct Shape {
pub channels: usize,
pub bytes_per_sample: usize,
pub sample_rate: u32,
pub counter_rate_hz: u32,
}
impl From<&StreamFormat> for Shape {
fn from(format: &StreamFormat) -> Self {
Self {
channels: usize::from(format.channels),
bytes_per_sample: usize::from(format.subslot_bytes),
sample_rate: format.sample_rate,
counter_rate_hz: format.counter_rate_hz(),
}
}
}
struct Shared {
source: Box<dyn Source>,
chunk: Vec<i32>,
taken: usize,
ended: bool,
start_seconds: f64,
}
fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
shared.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub struct Player<R: Ring + 'static> {
ring: Arc<R>,
shape: Shape,
shared: Arc<Mutex<Shared>>,
stop: Arc<AtomicBool>,
writer: Option<JoinHandle<()>>,
}
impl<R: Ring + 'static> Player<R> {
pub fn start(ring: Arc<R>, shape: Shape, source: Box<dyn Source>) -> Self {
let shared = Arc::new(Mutex::new(Shared { source, chunk: Vec::new(), taken: 0, ended: false, start_seconds: 0.0 }));
let stop = Arc::new(AtomicBool::new(false));
let writer = {
let (ring, shared, stop) = (Arc::clone(&ring), Arc::clone(&shared), Arc::clone(&stop));
thread::Builder::new()
.name("host-writer".into())
.spawn(move || write_loop(&*ring, shape, &shared, &stop))
.expect("spawn the writer thread")
};
Self { ring, shape, shared, stop, writer: Some(writer) }
}
pub fn pause(&self) -> Result<()> {
self.ring.pause()
}
pub fn resume(&self) -> Result<()> {
self.ring.play()
}
pub fn seek(&self, seconds: f64) -> Result<()> {
let mut state = lock(&self.shared);
state.source.seek(seconds);
state.chunk.clear();
state.taken = 0;
state.ended = false;
state.start_seconds = seconds;
self.ring.flush()
}
pub fn position_seconds(&self) -> f64 {
let start = lock(&self.shared).start_seconds;
start + self.ring.played_frames() as f64 / f64::from(self.shape.counter_rate_hz)
}
pub fn finished(&self) -> bool {
lock(&self.shared).ended && self.ring.is_drained()
}
pub fn ring(&self) -> &R {
&self.ring
}
pub fn stop(mut self) -> Arc<R> {
self.stop.store(true, Ordering::Release);
if let Some(writer) = self.writer.take() {
let _ = writer.join();
}
Arc::clone(&self.ring)
}
}
impl<R: Ring + 'static> Drop for Player<R> {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
if let Some(writer) = self.writer.take() {
let _ = writer.join();
}
}
}
fn write_loop(ring: &dyn Ring, shape: Shape, shared: &Mutex<Shared>, stop: &AtomicBool) {
let mut scratch = vec![0i32; (shape.sample_rate as usize / 100).max(1) * shape.channels];
while !stop.load(Ordering::Acquire) {
let mut state = lock(shared);
if state.ended {
drop(state);
thread::sleep(Duration::from_millis(10));
continue;
}
if state.taken == state.chunk.len() {
if ring.writable_bytes() < scratch.len() * shape.bytes_per_sample {
drop(state);
thread::sleep(Duration::from_millis(2));
continue;
}
let rendered = state.source.render(&mut scratch);
if rendered == 0 {
if ring.drain().is_ok() {
state.ended = true;
}
continue;
}
state.chunk.clear();
state.chunk.extend_from_slice(&scratch[..rendered]);
state.taken = 0;
}
match ring.write_i32(&state.chunk[state.taken..]) {
Ok(0) => {
drop(state);
thread::sleep(Duration::from_millis(2));
}
Ok(taken) => state.taken += taken,
Err(error) => {
log::warn!("the writer stops: {error}");
return;
}
}
}
}
pub fn event_channel() -> (Arc<dyn DacListener>, Receiver<DacEvent>) {
let (tx, rx) = channel();
let listener: Arc<dyn DacListener> = Arc::new(move |event: DacEvent| {
let _ = tx.send(event);
});
(listener, rx)
}
pub enum Reaction {
Nothing,
Underrun,
NotBitPerfect,
Pause(&'static str),
Failed(Error),
}
pub fn react(event: DacEvent) -> Reaction {
match event {
DacEvent::Underrun => Reaction::Underrun,
DacEvent::LostFrames { .. } => Reaction::NotBitPerfect,
DacEvent::FeedbackStale => Reaction::Nothing, DacEvent::DeviceLost => Reaction::Pause("the DAC was unplugged"),
DacEvent::Error(error) => Reaction::Failed(error),
_ => Reaction::Nothing,
}
}
pub fn restore_level(volume: &VolumeControl, remembered_db: Option<f64>) -> Result<f64> {
let ceiling = volume.startup().limit_db;
match remembered_db {
Some(db) => volume.set_db(db.min(ceiling)).map(|state| state.db),
None => volume.get().map(|state| state.db),
}
}
pub fn nudge(volume: &VolumeControl, up: bool) -> Result<f64> {
volume.step(if up { 1 } else { -1 }, 0).map(|state| state.db)
}
pub fn status_line(stream: &DacStream, engine_untouched: bool, lossy_source: bool) -> String {
if !engine_untouched {
return "Not bit-perfect: the player is processing the audio".to_string();
}
match stream.bit_perfect_blocker() {
None if lossy_source => "Direct USB, decoded from a lossy file".to_string(),
None => "Bit-perfect".to_string(),
Some(blocker) => format!("Not bit-perfect: {}", blocker_text(blocker)),
}
}
fn blocker_text(blocker: BitPerfectBlocker) -> &'static str {
match blocker {
BitPerfectBlocker::LostFrames => "audio was lost on the USB bus",
BitPerfectBlocker::FormatChanged => "the DAC runs another rate than the track has",
BitPerfectBlocker::ClockUnverified => "the DAC did not confirm its sampling rate",
BitPerfectBlocker::SoftwareGain => "software gain is on",
BitPerfectBlocker::UnsynchronizedAsync => "the DAC has no feedback, so it plays at the nominal rate",
BitPerfectBlocker::FeedbackUnlocked => "the DAC's timing has not locked yet",
BitPerfectBlocker::PayloadUnverified => "waiting for real audio",
BitPerfectBlocker::NoStream => "no stream is running",
_ => "the stream is not verified",
}
}
pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
let stream = player.stop(); let stream_result = match Arc::try_unwrap(stream) {
Ok(stream) => stream.close(),
Err(_) => Err(Error::InvalidState("the stream is still shared".to_string())),
};
let dac_result = if device_lost { dac.close_with(CloseVolume::Forget) } else { dac.close() };
if matches!(dac_result, Err(Error::Transfer(_))) {
while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
}
stream_result.and(dac_result)
}
pub fn play_one(dac: Dac, format: &StreamFormat, source: Box<dyn Source>) -> Result<()> {
let (listener, events) = event_channel();
let stream = dac.open_stream(format, listener)?;
let shape = Shape::from(stream.format());
let player = Player::start(Arc::new(stream), shape, source);
let mut device_lost = false;
while !player.finished() {
match events.recv_timeout(Duration::from_millis(100)).map(react) {
Ok(Reaction::Pause(reason)) => {
log::warn!("{reason}");
device_lost = true;
break;
}
Ok(Reaction::Failed(error)) => {
device_lost = error == Error::DeviceLost;
log::warn!("the stream failed: {error}");
break;
}
_ => {}
}
}
log::info!("{}", status_line(player.ring(), true, false));
shutdown(player, dac, device_lost)
}
fn main() {
println!("guide_player is a compile-checked example of docs/sdk/guide-rust.md; it needs a DAC to run.");
}