# wavegraph-audio
[![crates.io][crate-badge]][crate]
[![docs.rs][docs-badge]][docs]
[![Build status][ci-badge]][ci]
[![Project Chat][chat-image]][chat-link]
Route a WaveGraph master to an audio device, or read a selected input into a graph.
The portable interface uses the FM-1's native render size, 128 stereo frames of
signed Q23 PCM in i32 accumulators. A graph can keep its mono buses and processor
state across device changes. It only borrows the output block during a refill.
## Desktop playback
The `cpal` feature enables CoreAudio on macOS 14.2 or later, ALSA on 64-bit
Linux, and WASAPI on Windows. On Debian and Ubuntu, install `libasound2-dev`
and `pkg-config` before building. On macOS, the Xcode command line tools suffice.
Existing macOS callers can keep the `coreaudio` feature and module path.
```sh
cargo run --release --locked -p wavegraph-audio --features cpal --example play -- --list
cargo run --release --locked -p wavegraph-audio --features cpal --example play
```
The second command plays a four-note monosynth phrase through a WaveGraph
bytecode patch with a gain node. Change the default output in the system audio settings
while it plays. To pin to channels 3/4 of an interface, append
`-- --output "Interface Name" 3`. The CLI uses one-based numbers. The Rust API
uses zero-based channel indices. Ctrl-C stops playback.
## Where mixing belongs
| Instrument levels, inserts, post-fader sends, return sum, master dynamics | WaveGraph owns the signal order and sample-timed controls. Use the existing `wavegraph-fx` nodes. | Run the same graph, including `ChannelMixer` and `MasterBus` where the patch uses them. |
| Mix this application's output with other clients | Submit one WaveGraph master to the selected output. The native audio system handles device sharing. | Firmware owns the DAC. Sum additional local sources in the staging mix before MASTER. `fm1_audio::mix_stereo` already adds planar I24 sources with i32 headroom. |
| Final level and device PCM | The adapter clips the stereo master at the output boundary and converts Q23 to the device's PCM format. | `fm1_audio::Output` applies the panel MASTER ramp and final Q23 clip once before copying to the released DMA half. |
| Clock and buffering | The graph chooses its rate. When the device clock differs, a preallocated sinc resampler converts on the graph side of the queue. Matching rates bypass it. | Tune to the exact `24_000_000 / 544` clock. CPU0 services timed refills. CPU1 keeps exclusive ownership of outstanding DSP work. |
| Device changes | The application scans endpoints by identity and reconciles the selected route. | The local adapter exposes one fixed stereo DAC. WaveGraph FM-1 also sends the pre-MASTER stereo mix to a connected computer over USB. |
Apple also ships mixer Audio Units. Substituting one for a WaveGraph track mixer
would change who implements the patch's gain law, headroom and automation.
The desktop example renders the patch in Rust. The backend receives the resulting master.
## Routing and lifetime
Import `DeviceHost` and use `host.devices()` on the control thread for input and output selectors. The
snapshot carries display names, session-local IDs, channel counts, backend-reported
rates, and the current default names. Keep the selected `Route` as application state.
Call `Input::sync` or `Output::sync` at startup, after a route selection and on a
periodic scan. The example scans every 250 ms and services PCM between scans.
- `Route::Default` follows the system default and uses its first stereo pair or mono channel.
- `Route::Device(id, Channels::Pair(2))` selects the third and fourth channels in
the endpoint's channel layout. A mono input is duplicated and a mono output averages L/R.
An explicit port goes offline when its device or channels disappear. A replug can
get a new instance ID and requires reselection. Display names can collide.
- `Playback::render` calls the renderer only when there is room. The desktop queue
targets two device periods with a floor of four graph blocks. `Written` means the
queue accepted PCM. It provides no DAC timestamp. Changing the selected route
can discard queued samples. Keep synth state outside the port.
- `Capture::read` yields a complete stereo block or leaves the destination alone.
Open an input only when recording is desired, drain it regularly and drop it when
finished. When the input queue fills, new frames are dropped. Opening a microphone requires macOS
permission. Input and output can have independent clocks. This release does not
provide drift-compensated monitoring between two devices.
- On FM-1, service `Dac(output, master).render(...)` in the ALNK0 task.
It passes the BSP's exact `RefillInterval` before sample selection, preserves
`Written`, `Late` and `WouldBlock`, and borrows the existing staging block.
The firmware's handoff rejects stale CPU1 completions, leaves the cleared half
silent on a miss, and acknowledges edits only for a current, written block.
To connect a capture port to a graph source, keep the block with the host and
hand it to the source node only after a full read. A desktop application can
enable the `cpal` feature and service the input as follows.
```rust,no_run
# #[cfg(all(feature = "cpal", any(target_os = "macos", all(target_os = "linux", target_pointer_width = "64"), windows)))]
# fn capture() -> std::io::Result<()> {
use core::num::NonZeroU32;
use wavegraph_audio::{Capture, DeviceHost, FRAMES, cpal::{Host, Input, Route}};
let host = Host::new()?;
let mut input = Input::new(NonZeroU32::new(48_000).unwrap());
input.sync(&host, &host.devices()?, Route::Default)?;
let mut block = [[0; 2]; FRAMES];
// In the application's audio service loop:
if input.read(&mut block)? {
let left = block.map(|[left, _]| left);
// The graph's input node can now consume the complete left plane.
# core::hint::black_box(left);
}
# Ok(())
# }
```
The crate forbids unsafe Rust. Each desktop port owns its stream and a bounded
single-producer, single-consumer queue. The CPAL data callback transfers frames
between the queue and the native buffer. It writes silence on underrun and on
unselected output channels. The application owns the renderer and its buffers.
The FM-1 adapter uses the CPU0 refill API in `fm1-audio`.
## Backend references
- [CPAL platform support and build dependencies](https://docs.rs/crate/cpal/0.18.2)
- [Apple guide to mixing and converting audio](https://developer.apple.com/library/archive/documentation/MusicAudio/Conceptual/CoreAudioOverview/ARoadmaptoCommonTasks/ARoadmaptoCommonTasks.html)
- [ALSA timestamp ABI on 32-bit Linux](https://github.com/RustAudio/cpal/issues/1134)
## License
The Rust code is licensed under either of
- [Apache License, Version 2.0][apache]
- [MIT License][mit]
at your option.
### Contribution
Unless you explicitly state otherwise, you license any contribution you
intentionally submit for inclusion in this work (as defined in the Apache-2.0
license) under both licenses above, without additional terms or conditions.
[crate-badge]: https://img.shields.io/crates/v/wavegraph-audio?logo=rust
[crate]: https://crates.io/crates/wavegraph-audio
[docs-badge]: https://docs.rs/wavegraph-audio/badge.svg
[docs]: https://docs.rs/wavegraph-audio/
[ci-badge]: https://github.com/fm1-rust/wavegraph/actions/workflows/wavegraph-audio.yml/badge.svg?branch=main&event=push
[ci]: https://github.com/fm1-rust/wavegraph/actions/workflows/wavegraph-audio.yml
[chat-image]: https://img.shields.io/badge/discord-join_chat-blue.svg
[chat-link]: https://discord.gg/bq8NYQWzm5
[apache]: https://github.com/fm1-rust/wavegraph/blob/main/wavegraph-audio/LICENSE-APACHE
[mit]: https://github.com/fm1-rust/wavegraph/blob/main/wavegraph-audio/LICENSE-MIT