Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Shared audio output layer

This is the code behind OxiGuitar’s four audio output plugins: PipeWire, ALSA, WASAPI and Core Audio. It is a library for those plugins, not a plugin: nothing here is installed on its own.

It uploads nothing and downloads nothing. It only plays sound on your computer.

What an audio output does

OxiGuitar works out the sound of a song as a stream of numbers, about 48,000 of them a second for each speaker. Something has to hand those numbers to the sound card, in small batches, always on time: if a batch is late, you hear a click or a gap. That is the job of the operating system’s sound system, and of the output plugin that connects OxiGuitar to it.

Every system has its own sound system with its own way of being called. cpal, a Rust audio library, already speaks all of them; it calls each one a host. This layer does the whole job on top of one of cpal’s hosts:

  • it lists the outputs (speakers, headphones, USB interfaces) by name;
  • it opens a stream on the one the player picked, at 48,000 frames a second when the device takes that rate, else at the device’s own;
  • for every batch the device asks for, it asks OxiGuitar’s core to fill it, and tells the core how long the batch takes to reach the speaker, so the cursor follows what you hear;
  • it closes the stream when the player stops.

Each plugin then only says which host it uses: PipeWire’s, ALSA’s, WASAPI’s or Core Audio’s.

Two words come up when people talk about this:

  • Latency is the delay between OxiGuitar sending sound and you hearing it.
  • The buffer is how much sound is handed over at a time. A bigger buffer is safer against clicks on a busy computer, at the cost of more latency.

How to use it shows the code of a plugin built on it.

How to use it

An output plugin built on this layer is a few lines: the plugin offers one audio-device service, and that service is a CpalDevice on its host.

  1. Depend on the SDK and on this layer, at the tags its own Cargo.toml uses:

    [dependencies]
    oxiguitar-plugin = { git = "https://github.com/mateusrdp/oxiguitar", tag = "v0.25.0" }
    oxiguitar-audio-cpal = { git = "https://github.com/mateusrdp/oxiguitar-audio-cpal", tag = "v0.1.0" }
    # Turn on your host's cpal feature here, if it has one ("pipewire").
    cpal = { version = "0.18.2", default-features = false }
    

    The SDK’s tag must be the one this layer uses: the service it gives you is the SDK’s own type, and two tags make two types that don’t match.

  2. Make the service when the plugin starts, on your host:

    #![allow(unused)]
    fn main() {
    use oxiguitar_audio_cpal::CpalDevice;
    
    let device = CpalDevice::new(host, cpal::HostId::Alsa, "ALSA");
    }

    The name is the one messages use (“ALSA has no output”).

  3. Offer it as the audio-device service your manifest names, and nothing else. oxiguitar-alsa’s src/lib.rs is the whole of a plugin built this way.

The player then calls the service’s methods (devices, open, close) through the plugin interface; the plugin developer guide in OxiGuitar’s repository describes them.

What a plugin’s repository must do

Depending on this layer asks more of the plugin’s repository than a crate from crates.io would. Each point below was a build or CI failure when it was missed.

  • One SDK tag. oxiguitar-plugin must be at the tag this layer’s own Cargo.toml names. A second tag makes a second Host and Service type, and the build fails with types that look the same and do not match. Cargo does not warn when the tags differ in a lock file.
  • One cpal version, and the host’s feature on your own dependency. Use the same cpal version as this layer (0.18.2) with default-features = false, and turn on only your host’s feature (pipewire for PipeWire; ALSA, WASAPI and Core Audio need none). This layer turns on no host feature of its own.
  • Linux builds need libasound2-dev (alsa-lib-devel on Fedora) whatever the host, because cpal always builds its ALSA host there. The PipeWire host adds libpipewire-0.3-dev and libclang-dev. Those belong to the plugin’s build, not to this layer’s.
  • deny.toml must allow the source. With unknown-git = "deny", cargo-deny rejects this layer until allow-git lists https://github.com/mateusrdp/oxiguitar-audio-cpal next to https://github.com/mateusrdp/oxiguitar.
  • A new tag is not picked up by itself. Change the tag in Cargo.toml, then run cargo update -p oxiguitar-audio-cpal -p cpal and commit Cargo.lock.
  • Dependabot must leave both tags alone. Ignore oxiguitar-* in the plugin’s dependabot.yml; the tags move together, by hand.
  • Nothing goes on crates.io. This layer’s release is its v* tag: there is no GitHub Release page and no packages to download.

When the SDK tag moves

Do it in this order, so no plugin ever sees two tags:

  1. In this repository, change the SDK tag, run the tests, merge, and release with oxiguitar-packages’ Release button.
  2. In each of the four plugins, change the SDK tag and this layer’s tag to the new ones in the same pull request, and refresh Cargo.lock as above.

Architecture and strategy

CpalDevice is the audio-device service of the plugin interface on one of cpal’s hosts. The whole layer is one file, src/lib.rs.

  • One thread for the streams. A cpal stream may have to stay on the thread that made it, so the streams live on a thread of their own, started on first use. It sleeps until the player asks it to open or close a stream; nothing polls.
  • The callback waits for nothing. When the device wants a batch, its callback hands the core the buffer (AudioOut::render) with the delay to the speaker that cpal reports. It allocates nothing and takes no lock, because a late callback is a click.
  • The rate. 48 kHz when the device takes it (the rate OxiGuitar’s amp models are made for), else the device’s own, which the player then resamples to.
  • The samples. f32 when the device takes them. Devices that take only 16- or 32-bit integers get the f32 samples clamped to full scale and converted through a buffer made when the stream opens.
  • Stopping. Closing a stream drops it, which stops it: its callback isn’t called again once close returns.

The strategy is one plugin for each system’s own sound API, so each can be installed, updated and left out on its own, and one layer for what they have in common, so it is written and fixed once.

Current limitations

  • Delay as cpal reports it. The cursor follows the delay each host reports for a batch. A host that reports none gets a cursor a buffer early.
  • Sample formats. Only f32, 16-bit and 32-bit integer outputs are taken; a device that offers nothing else is refused with a message saying so.
  • No buffer size of our own. The device’s default buffer is used.
  • Your system’s sound must already work. The layer doesn’t repair or configure the sound system.

Left out on purpose

  • A sound library of our own. cpal already speaks every system’s sound API, so this layer stays small.
  • Living in OxiGuitar’s repository. It did until OxiGuitar 0.21.6, but the core itself never used it: being in the core’s workspace only made every core build compile cpal and need ALSA’s headers.
  • Recording. The outputs only play. OxiGuitar has no audio input.

Where you can help

  • Testing on real hardware, especially devices that take only integers, USB interfaces and Bluetooth headphones.
  • A chosen buffer size, for those who want lower latency.

Every change needs its tests and a row on the Features page; the Testing page says how to run them.

Features and their tests

Everything this layer does, and the tests that check it. The test names are the ones cargo test prints. scripts/test-all.py fails when a feature here names no test, or names a test that doesn’t exist, so a new feature gets its row and its tests in the same pull request (the Testing page says how to run them).

Hearing the sound needs a sound card, which CI doesn’t have, so the tests check everything up to it, on the host every system has (ALSA on Linux, WASAPI on Windows, Core Audio on macOS). Each output plugin’s contract suite checks the layer again inside its plugin file.

FeatureWhat it doesTests
Says when it can’t playProbing tells the player whether there’s an output, and why not when there isn’t.tests::probing_says_whether_there_is_an_output
Lists the outputsThe system’s output devices by name, for the footer’s output chooser.tests::listing_the_outputs_answers_with_or_without_a_device
Refuses wrong requestsA damaged request to open or close an output, or a method it doesn’t have, gets an error, never a crash.tests::wrong_requests_are_refused
Opens and closes streamsOpening needs OxiGuitar’s core to make the sound and says why when there is none; closing a stream that isn’t open is harmless.tests::opening_without_a_core_says_why, tests::closing_an_unknown_stream_is_harmless
Integer devicesDevices that take only 16- or 32-bit samples get them clamped to full scale, so a loud note doesn’t wrap round into a click.tests::samples_for_integer_devices_are_clamped_and_scaled

Testing

Every test of this repository runs with one command, on your own machine, and anyone can run it. When something fails, it tells you how to report it.

Run everything

python3 scripts/test-all.py

On Windows, type python instead of python3 if that’s what you have.

You need:

  • Rust, from rustup (the version in Cargo.toml’s rust-version or newer);
  • git, and Python 3.8 or newer (nothing to install with pip);
  • on Linux, the libraries a build needs: libasound2-dev on Debian and Ubuntu (alsa-lib-devel on Fedora), because cpal always builds its ALSA host on Linux;

It runs:

  1. every Rust test of the repository (cargo test over the whole workspace), with a progress bar;
  2. a check of the Features page: every feature names a test, and every test it names exists.

It tests the system and processor it runs on, and only those (as Rust sees them: rustc -vV’s host). Tests for other systems are left out and the summary says so; they are not failures.

What you get

A line per stage while it runs, then the result. In target/test-all/<date>-<time>/:

  • summary.md: the result, your system, what failed and why, short enough to paste into a GitHub issue;
  • test-all.log: everything that happened, every command and its output;

The script exits with 0 when everything passed, 1 when something failed, and 2 when it couldn’t start.

When something fails

  1. Update to the newest develop (git checkout develop && git pull) and run it again: it may be fixed already.
  2. Look for an issue about the same test at github.com/mateusrdp/oxiguitar-audio-cpal/issues.
  3. Otherwise open one: call it test-all: <the first failing test>, paste the whole summary.md, and attach test-all.log (drag it onto the text box; zip it first if it’s over 25 MB). Read the log first: it has your folder names, so change anything you’d rather keep private.
  4. You can also give summary.md and test-all.log to a language model along with this repository and ask it to find the cause.

Options

  • --release: an optimised test build: slower to build, faster corpus tests.
  • --ignore-rust-version: for a Rust older than rust-version (unsupported, but handy).
  • --out DIR: where the results go.

Adding a feature

A new feature comes with its tests and a row on the Features page, in the same pull request; a new corpus test uses tests/support/corpus.rs. The script fails until the row names tests that exist.

Credits

Thank you to the people whose work this layer is built on.

Code we use

ProjectAuthorsWhat it does hereLicence
OxiGuitar’s plugin SDK (oxiguitar-plugin)Mateus Rocha de Paula and the OxiGuitar contributorsThe plugin interface: the service, the host, the core’s audio callbackMIT OR Apache-2.0
cpalThe RustAudio contributorsDevices and the audio stream, on every systemApache-2.0
alsaDavid Henningsson and contributorscpal’s ALSA host, built on LinuxApache-2.0 OR MIT
Rust and its standard libraryThe Rust ProjectEverything elseMIT OR Apache-2.0

cpal’s other hosts bring their own bindings (PipeWire’s, Windows’, Apple’s) into the plugins that turn them on; each plugin’s own Credits page names them.

Tools

ToolUse
mdBookBuilds this manual
cargo-denyChecks the licences of everything we build with

Thanks

To the RustAudio community for cpal, which turns four very different sound systems into one.