wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
//! Service the default desktop output and follow device changes on the control thread.

use core::{num::NonZeroU32, time::Duration};
use std::io;
use tokio::{
    sync::{mpsc, watch},
    time::{self, MissedTickBehavior},
};
use wavegraph_audio::{
    Block, DeviceHost as _, Direction, Playback as _, Submission,
    cpal::{Host, Output, Route, Status},
};

pub(crate) fn devices() -> io::Result<()> {
    let devices = Host::new()?.devices()?;
    for device in devices
        .endpoints()
        .iter()
        .filter(|d| d.direction == Direction::Output)
    {
        println!(
            "{}  {} ({} channels, {} Hz)",
            device.id, device.name, device.channels, device.rate.0
        );
    }
    if let Some(name) = devices.default_output {
        println!("Default output: {name}");
    }
    Ok(())
}

pub(crate) async fn play(
    rate: NonZeroU32,
    mut blocks: mpsc::Receiver<Block>,
    accepted: watch::Sender<Option<u64>>,
) -> io::Result<()> {
    let host = Host::new()?;
    let mut output = Output::new(rate);
    let mut scan = time::interval(Duration::from_millis(250));
    scan.set_missed_tick_behavior(MissedTickBehavior::Skip);
    let mut online = false;
    let mut pending = None;
    let mut published = false;
    let mut last_warning = None;

    loop {
        if online && let Some(pcm) = &pending {
            match output.render(|out, ()| *out = *pcm) {
                Ok(Submission::Written) => {
                    pending = None;
                    if !published {
                        accepted.send_replace(Some(0));
                        published = true;
                    }
                }
                Ok(Submission::WouldBlock | Submission::Late) => (),
                Err(e) => {
                    // The backend closed the stream. Retain this block until it reopens.
                    online = false;
                    warn(&mut last_warning, e);
                }
            }
        }

        tokio::select! {
            biased;
            // WASAPI invalidates the stream when its default endpoint changes.
            _ = scan.tick(), if !cfg!(windows) || !online => {
                match host.devices() {
                    Ok(devices) => match output.sync(&host, &devices, Route::Default) {
                        Ok(Status::Opened) => {
                            let device = devices.default_output.as_deref().unwrap_or("default");
                            tracing::info!(device, "opened audio output");
                            online = true;
                            last_warning = None;
                        }
                        Ok(Status::Running) => online = true,
                        Ok(Status::Offline) => {
                            online = false;
                            warn(&mut last_warning, "waiting for a default output");
                        }
                        Err(e) => {
                            online = false;
                            warn(&mut last_warning, e);
                        }
                    },
                    // A failed device scan can leave the current stream usable.
                    Err(e) => warn(&mut last_warning, e),
                }
                if !online && blocks.is_closed() {
                    return Ok(());
                }
            }
            next = blocks.recv(), if pending.is_none() => match next {
                Some(block) => pending = Some(block),
                None => return Ok(()),
            },
            // Retry when the device callback has had time to consume queued PCM.
            _ = time::sleep(Duration::from_millis(1)), if online && pending.is_some() => (),
        }
    }
}

fn warn(last: &mut Option<time::Instant>, detail: impl core::fmt::Display) {
    if last.is_none_or(|at| at.elapsed() >= Duration::from_secs(30)) {
        tracing::warn!(%detail, "retrying audio output");
        *last = Some(time::Instant::now());
    }
}