wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
//! A dedicated DSP thread produces blocks for the output owned by Tokio's main thread.
use crate::engine;
use core::time::Duration;
use std::{io, path::Path, thread};
use tokio::{
    signal,
    sync::{mpsc, oneshot, watch},
    time,
};
use wavegraph_audio::{Block, FRAMES};
use wavegraph_compiler::CompiledPatch;
use wavegraph_remote::MidiCommand;

async fn output(
    headless: bool,
    mut blocks: mpsc::Receiver<Block>,
    accepted: watch::Sender<Option<u64>>,
) -> io::Result<()> {
    if headless {
        let period = Duration::from_secs(FRAMES as u64).div_f64(f64::from(engine::RATE));
        let mut clock = time::interval(period);
        clock.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
        let mut first = Some(accepted);
        while blocks.recv().await.is_some() {
            clock.tick().await;
            if let Some(accepted) = first.take() {
                accepted.send_replace(Some(0));
            }
        }
        return Ok(());
    }
    #[cfg(any(
        target_os = "macos",
        all(target_os = "linux", target_pointer_width = "64"),
        windows
    ))]
    return crate::audio::play(
        engine::RATE.try_into().expect("nonzero sample rate"),
        blocks,
        accepted,
    )
    .await;
    #[cfg(not(any(
        target_os = "macos",
        all(target_os = "linux", target_pointer_width = "64"),
        windows
    )))]
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "device playback requires macOS, 64-bit Linux or Windows; use --headless on this host",
    ))
}

pub(crate) async fn run(
    patch: CompiledPatch,
    tempo: u16,
    headless: bool,
    socket: Option<&Path>,
) -> io::Result<()> {
    let (commands, mut events) = mpsc::channel::<MidiCommand>(engine::MAX_COMMANDS);
    let (pcm, blocks) = mpsc::channel(2);
    let (ready, startup) = oneshot::channel();
    let dsp = thread::Builder::new()
        .name("wavegraph-dsp".into())
        .spawn(move || {
            engine::with_renderer(patch, tempo, |renderer, graph| {
                if ready.send(graph).is_err() {
                    return Ok(());
                }
                let mut batch = heapless::Vec::<_, { engine::MAX_COMMANDS }>::new();
                while !pcm.is_closed() {
                    batch.clear();
                    while !batch.is_full() {
                        let Ok(event) = events.try_recv() else { break };
                        let _ = batch.push(event);
                    }
                    let mut block = [[0; 2]; FRAMES];
                    renderer.render(&batch, &mut block)?;
                    if pcm.blocking_send(block).is_err() {
                        break;
                    }
                }
                Ok(())
            })
        })?;

    // Dropping this future's receiver wakes the DSP thread even when its PCM queue is full.
    let result = async move {
        let graph = startup
            .await
            .map_err(|_| io::Error::other("DSP worker failed to start"))?;
        let (accepted, first) = watch::channel(None);
        #[cfg(unix)]
        let shutdown = {
            let mut terminate = signal::unix::signal(signal::unix::SignalKind::terminate())?;
            let server = match socket {
                Some(path) => {
                    let server = crate::rpc::Server::bind(path, graph, commands, first)?;
                    tracing::info!(socket = %path.display(), "listening for wr clients");
                    Some(server)
                }
                None => None,
            };
            async move {
                tokio::select! {
                    result = async {
                        match server {
                            Some(server) => server.run().await,
                            None => core::future::pending().await,
                        }
                    } => result,
                    result = signal::ctrl_c() => result,
                    _ = terminate.recv() => Ok(()),
                }
            }
        };
        #[cfg(windows)]
        let shutdown = {
            // The Windows player has no local RPC listener.
            let _ = (socket, graph, commands, first);
            signal::ctrl_c()
        };
        tokio::select! {
            result = output(headless, blocks, accepted) => result,
            result = shutdown => result,
        }
    }
    .await;
    dsp.join()
        .map_err(|_| io::Error::other("DSP worker panicked"))??;
    result
}