wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
//! Run WaveGraph text patches on the desktop.
#![forbid(unsafe_code)]

extern crate alloc;

#[cfg(any(
    target_os = "macos",
    all(target_os = "linux", target_pointer_width = "64"),
    windows
))]
mod audio;
mod effects;
mod engine;
#[cfg(any(unix, windows))]
mod host;
mod nodes;
#[cfg(unix)]
mod rpc;
mod sequencer;
mod voices;

use clap::Parser;
use std::{fs, io, path::PathBuf, process::ExitCode};

/// Play a WaveGraph text patch. With no file, play the included 3389 rack.
#[derive(Parser)]
#[command(version, about)]
struct Args {
    /// Patch source (.wg).
    patch: Option<PathBuf>,
    /// Clock tempo in beats per minute.
    #[arg(long, default_value_t = 122, value_parser = clap::value_parser!(u16).range(30..=300))]
    tempo: u16,
    /// Override the per-user Unix socket used by wr.
    #[arg(long)]
    socket: Option<PathBuf>,
    /// Run without listening for wr clients.
    #[cfg(unix)]
    #[arg(long, conflicts_with = "socket")]
    no_socket: bool,
    /// Suppress remote commands and graph queries in the playback log.
    #[arg(short, long)]
    quiet: bool,
    /// Run the DSP at playback speed with a clocked null output.
    #[arg(long)]
    headless: bool,
    /// Compile the graph and bind all native processors, then exit.
    #[arg(long, conflicts_with_all = ["headless", "socket"])]
    check: bool,
    /// List audio output devices, then exit.
    #[arg(long, conflicts_with_all = ["patch", "headless", "check", "socket"])]
    list_outputs: bool,
}

fn main() -> ExitCode {
    match run(Args::parse()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("wavegraph: {error}");
            ExitCode::FAILURE
        }
    }
}

fn run(args: Args) -> io::Result<()> {
    if args.list_outputs {
        #[cfg(any(
            target_os = "macos",
            all(target_os = "linux", target_pointer_width = "64"),
            windows
        ))]
        return audio::devices();
        #[cfg(not(any(
            target_os = "macos",
            all(target_os = "linux", target_pointer_width = "64"),
            windows
        )))]
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "device enumeration requires macOS, 64-bit Linux or Windows",
        ));
    }

    #[cfg(not(unix))]
    if args.socket.is_some() {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "--socket requires Unix",
        ));
    }

    let path = args.patch.as_deref();
    let label = path.map_or_else(|| "3389.wg".into(), |p| p.display().to_string());
    let file_error = |e: io::Error| io::Error::new(e.kind(), format!("{label}: {e}"));
    let source = match path {
        Some(path) => fs::read_to_string(path).map_err(file_error)?,
        None => include_str!("../patches/3389.wg").into(),
    };
    let patch = engine::compile(&source).map_err(file_error)?;
    if args.check {
        return engine::with_renderer(patch, args.tempo, |_, graph| {
            println!(
                "{label}: {} native nodes, stereo buses {:?}",
                graph.nodes.len(),
                graph.outputs
            );
            Ok(())
        })
        .map_err(file_error);
    }

    #[cfg(any(unix, windows))]
    {
        #[cfg(unix)]
        let socket = if args.no_socket {
            None
        } else {
            Some(wavegraph_remote::socket_path(args.socket.as_deref())?)
        };
        #[cfg(windows)]
        let socket = args.socket;
        let _log_guard = init_tracing(args.quiet);
        tracing::info!(
            patch = %label,
            nodes = patch.nodes.len(),
            bpm = args.tempo,
            sample_rate = engine::RATE,
            block_frames = wavegraph_audio::FRAMES,
            headless = args.headless,
            "starting playback"
        );
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?
            .block_on(host::run(
                patch,
                args.tempo,
                args.headless,
                socket.as_deref(),
            ))?;
        tracing::info!("playback stopped");
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "live playback requires macOS, 64-bit Linux or Windows",
    ))
}

#[cfg(any(unix, windows))]
fn init_tracing(quiet: bool) -> tracing_appender::non_blocking::WorkerGuard {
    use std::io::IsTerminal as _;
    use tracing_subscriber::{
        EnvFilter,
        filter::{LevelFilter, Targets},
        prelude::*,
    };

    // A slow stderr consumer must not stall audio submission on the Tokio thread.
    let stderr = io::stderr();
    let ansi = stderr.is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty());
    let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
        .buffered_lines_limit(1024)
        .finish(stderr);
    let filter = EnvFilter::builder()
        .with_default_directive(LevelFilter::INFO.into())
        .from_env_lossy();
    let quiet_rpc = quiet.then(|| {
        Targets::new()
            .with_default(LevelFilter::TRACE)
            .with_target("wavegraph::rpc", LevelFilter::WARN)
    });
    tracing_subscriber::registry()
        .with(filter)
        .with(quiet_rpc)
        .with(
            tracing_subscriber::fmt::layer()
                .with_writer(writer)
                .with_ansi(ansi),
        )
        .init();
    guard
}