Skip to content

Commit 4aa71b1

Browse files
committed
docs: add docs for backends, features, and examples
1 parent 6dbb4fb commit 4aa71b1

File tree

22 files changed

+558
-143
lines changed

22 files changed

+558
-143
lines changed

Cargo.toml

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,35 @@ edition = "2021"
1010
rust-version = "1.70"
1111

1212
[features]
13+
# ASIO backend for Windows
14+
# Provides low-latency audio I/O by bypassing the Windows audio stack
15+
# Requires: ASIO drivers and LLVM/Clang for build-time bindings
16+
# See README for detailed setup instructions
1317
asio = [
14-
"asio-sys",
15-
"num-traits",
16-
] # Only available on Windows. See README for setup instructions.
18+
"dep:asio-sys",
19+
"dep:num-traits",
20+
]
1721

18-
# Only available on web when atomics are enabled. See README for what it does.
22+
# JACK Audio Connection Kit backend for Linux/BSD
23+
# Provides low-latency connections between applications and audio hardware
24+
# Requires: JACK server and client libraries installed on the system
25+
# Platform: Linux, DragonFly BSD, FreeBSD, NetBSD only
26+
# Note: While JACK exists on Windows/macOS, CPAL's JACK backend is only implemented for Linux/BSD
27+
jack = ["dep:jack"]
28+
29+
# WebAssembly backend using wasm-bindgen
30+
# Enables the Web Audio API backend for browser-based audio
31+
# Required for any WebAssembly audio support
32+
# Platform: WebAssembly (wasm32-unknown-unknown)
33+
# Note: This is typically enabled automatically when targeting wasm32
34+
wasm-bindgen = ["dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
35+
36+
# Audio Worklet backend for WebAssembly
37+
# Provides lower-latency web audio processing compared to default Web Audio API
38+
# Requires: Build with atomics support and Cross-Origin headers for SharedArrayBuffer
39+
# Platform: WebAssembly (wasm32-unknown-unknown)
1940
audioworklet = [
20-
"dep:wasm-bindgen-futures",
41+
"wasm-bindgen",
2142
"web-sys/Blob",
2243
"web-sys/BlobPropertyBag",
2344
"web-sys/Url",
@@ -27,7 +48,9 @@ audioworklet = [
2748
]
2849

2950
# Support for user-defined custom hosts, devices, and streams
51+
# Allows integration with audio systems not natively supported by CPAL
3052
# See examples/custom.rs for usage
53+
# Platform: All platforms
3154
custom = []
3255

3356
[dependencies]
@@ -152,3 +175,20 @@ name = "record_wav"
152175

153176
[[example]]
154177
name = "synth_tones"
178+
179+
[package.metadata.docs.rs]
180+
all-features = true
181+
rustdoc-args = ["--cfg", "docsrs"]
182+
targets = [
183+
"x86_64-unknown-linux-gnu",
184+
"x86_64-pc-windows-msvc",
185+
"x86_64-apple-darwin",
186+
"aarch64-apple-darwin",
187+
"aarch64-apple-ios",
188+
"wasm32-unknown-unknown",
189+
"wasm32-unknown-emscripten",
190+
"aarch64-linux-android",
191+
"x86_64-unknown-freebsd",
192+
"x86_64-unknown-netbsd",
193+
"x86_64-unknown-dragonfly",
194+
]

README.md

Lines changed: 113 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -27,30 +27,75 @@ Note that on Linux, the ALSA development files are required. These are provided
2727
as part of the `libasound2-dev` package on Debian and Ubuntu distributions and
2828
`alsa-lib-devel` on Fedora.
2929

30-
## Compiling for Web Assembly
30+
## Compiling for WebAssembly
3131

32-
If you are interested in using CPAL with WASM, please see [this guide](https://github.com/RustAudio/cpal/wiki/Setting-up-a-new-CPAL-WASM-project) in our Wiki which walks through setting up a new project from scratch.
32+
If you are interested in using CPAL with WebAssembly, please see [this guide](https://github.com/RustAudio/cpal/wiki/Setting-up-a-new-CPAL-WASM-project) in our Wiki which walks through setting up a new project from scratch. Some of the examples in this repository also provide working configurations that you can use as reference.
3333

34-
## Feature flags for audio backends
34+
## Optional Features
3535

36-
Some audio backends are optional and will only be compiled with a [feature flag](https://doc.rust-lang.org/cargo/reference/features.html).
36+
CPAL provides the following optional features:
3737

38-
- JACK (on Linux): `jack`
39-
- ASIO (on Windows): `asio`
40-
- AudioWorklet (on Web): `audioworklet`
38+
### `asio`
4139

42-
For AudioWorklet backend usage see the README for the `audioworklet-beep` example.
40+
**Platform:** Windows
4341

44-
## ASIO on Windows
42+
Enables the ASIO (Audio Stream Input/Output) backend. ASIO provides low-latency audio I/O by bypassing the Windows audio stack.
43+
44+
**Requirements:**
45+
- ASIO drivers for your audio device
46+
- LLVM/Clang for build-time bindings generation
47+
48+
**Setup:** See the [ASIO setup guide](#asio-on-windows) below for detailed installation instructions.
49+
50+
### `jack`
51+
52+
**Platform:** Linux, DragonFly BSD, FreeBSD, NetBSD
53+
54+
Enables the JACK (JACK Audio Connection Kit) backend. JACK is an audio server providing low-latency connections between applications and audio hardware.
55+
56+
**Requirements:**
57+
- JACK server and client libraries must be installed on the system
58+
59+
**Usage:** See the [beep example](examples/beep.rs) for selecting the JACK host at runtime.
60+
61+
**Note:** While JACK is available on Windows and macOS, CPAL's JACK backend is currently only implemented for Linux and BSD systems. On other platforms, use the native backends (WASAPI/ASIO for Windows, CoreAudio for macOS).
62+
63+
### `wasm-bindgen`
64+
65+
**Platform:** WebAssembly (wasm32-unknown-unknown)
66+
67+
Enables the Web Audio API backend for browser-based audio. This is the base feature required for any WebAssembly audio support.
68+
69+
**Requirements:**
70+
- Target `wasm32-unknown-unknown`
71+
- Web browser with Web Audio API support
72+
73+
**Usage:** See the `wasm-beep` example for basic WebAssembly audio setup.
74+
75+
### `audioworklet`
76+
77+
**Platform:** WebAssembly (wasm32-unknown-unknown)
78+
79+
Enables the Audio Worklet backend for lower-latency web audio processing compared to the default Web Audio API backend.
80+
81+
**Requirements:**
82+
- The `wasm-bindgen` feature (automatically enabled)
83+
- Build with atomics support: `RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals"`
84+
- Web server must send Cross-Origin headers for SharedArrayBuffer support
85+
86+
**Setup:** See the `audioworklet-beep` example README for complete setup instructions.
87+
88+
**Note:** Audio Worklet provides better performance than the default Web Audio API by running audio processing on a separate thread.
89+
90+
### `custom`
91+
92+
**Platform:** All platforms
4593

46-
[ASIO](https://en.wikipedia.org/wiki/Audio_Stream_Input/Output) is an audio
47-
driver protocol by Steinberg. While it is available on multiple operating
48-
systems, it is most commonly used on Windows to work around limitations of
49-
WASAPI including access to large numbers of channels and lower-latency audio
50-
processing.
94+
Enables support for user-defined custom host implementations, allowing integration with audio systems not natively supported by CPAL.
5195

52-
CPAL allows for using the ASIO SDK as the audio host on Windows instead of
53-
WASAPI.
96+
**Usage:** See `examples/custom.rs` for implementation details.
97+
98+
## ASIO on Windows
5499

55100
### Locating the ASIO SDK
56101

@@ -64,78 +109,81 @@ The build script will try to find the ASIO SDK by following these steps in order
64109

65110
In an ideal situation you don't need to worry about this step.
66111

67-
### Preparing the build environment
112+
### Preparing the Build Environment
113+
114+
1. **Install LLVM/Clang**: `bindgen`, the library used to generate bindings to the C++ SDK, requires clang. Download and install LLVM from <http://releases.llvm.org/download.html> under the "Pre-Built Binaries" section.
68115

69-
1. `bindgen`, the library used to generate bindings to the C++ SDK, requires
70-
clang. **Download and install LLVM** from
71-
[here](http://releases.llvm.org/download.html) under the "Pre-Built Binaries"
72-
section. The version as of writing this is 17.0.1.
73-
2. Add the LLVM `bin` directory to a `LIBCLANG_PATH` environment variable. If
74-
you installed LLVM to the default directory, this should work in the command
75-
prompt:
116+
2. **Set LIBCLANG_PATH**: Add the LLVM `bin` directory to a `LIBCLANG_PATH` environment variable. If you installed LLVM to the default directory, this should work in the command prompt:
76117
```
77118
setx LIBCLANG_PATH "C:\Program Files\LLVM\bin"
78119
```
79-
3. If you don't have any ASIO devices or drivers available, you can [**download
80-
and install ASIO4ALL**](http://www.asio4all.org/). Be sure to enable the
81-
"offline" feature during installation despite what the installer says about
82-
it being useless.
83-
4. Our build script assumes that Microsoft Visual Studio is installed if the host OS for compilation is Windows. The script will try to find `vcvarsall.bat`
84-
and execute it with the right host and target machine architecture regardless of the Microsoft Visual Studio version.
85-
If there are any errors encountered in this process which is unlikely,
86-
you may find the `vcvarsall.bat` manually and execute it with your machine architecture as an argument.
87-
The script will detect this and skip the step.
88-
89-
A manually executed command example for 64 bit machines:
90120

121+
3. **Install ASIO Drivers** (optional for testing): If you don't have any ASIO devices or drivers available, you can download and install ASIO4ALL from <http://www.asio4all.org/>. Be sure to enable the "offline" feature during installation.
122+
123+
4. **Visual Studio**: The build script assumes Microsoft Visual Studio is installed. It will try to find `vcvarsall.bat` and execute it with the right host and target architecture. If needed, you can manually execute it:
91124
```
92125
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64
93126
```
127+
For more information see the [vcvarsall.bat documentation](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line).
94128

95-
For more information please refer to the documentation of [`vcvarsall.bat``](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-160#vcvarsall-syntax).
129+
### Using ASIO in Your Application
96130

97-
5. Select the ASIO host at the start of our program with the following code:
131+
1. **Enable the feature** in your `Cargo.toml`:
132+
```toml
133+
cpal = { version = "*", features = ["asio"] }
134+
```
98135

136+
2. **Select the ASIO host** in your code:
99137
```rust
100-
let host;
101-
#[cfg(target_os = "windows")]
102-
{
103-
host = cpal::host_from_id(cpal::HostId::Asio).expect("failed to initialise ASIO host");
104-
}
138+
let host = cpal::host_from_id(cpal::HostId::Asio)
139+
.expect("failed to initialise ASIO host");
105140
```
106141

107-
If you run into compilations errors produced by `asio-sys` or `bindgen`, make
108-
sure that `CPAL_ASIO_DIR` is set correctly and try `cargo clean`.
142+
### Troubleshooting
109143

110-
6. Make sure to enable the `asio` feature when building CPAL:
144+
If you encounter compilation errors from `asio-sys` or `bindgen`:
145+
- Verify `CPAL_ASIO_DIR` is set correctly
146+
- Try running `cargo clean`
147+
- Ensure LLVM/Clang is properly installed and `LIBCLANG_PATH` is set
111148

112-
```
113-
cargo build --features "asio"
114-
```
149+
### Cross-Compilation
115150

116-
or if you are using CPAL as a dependency in a downstream project, enable the
117-
feature like this:
151+
When Windows is the host and target OS, the build script supports all cross-compilation targets supported by the MSVC compiler.
118152

119-
```toml
120-
cpal = { version = "*", features = ["asio"] }
121-
```
153+
It is also possible to compile Windows applications with ASIO support on Linux and macOS using the MinGW-w64 toolchain.
122154

123-
_Updated as of ASIO version 2.3.3._
155+
**Requirements:**
156+
- Include the MinGW-w64 include directory in your `CPLUS_INCLUDE_PATH` environment variable
157+
- Include the LLVM include directory in your `CPLUS_INCLUDE_PATH` environment variable
124158

125-
### Cross compilation
159+
**Example for macOS** (targeting `x86_64-pc-windows-gnu` with `mingw-w64` installed via brew):
160+
```
161+
export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/opt/homebrew/Cellar/mingw-w64/11.0.1/toolchain-x86_64/x86_64-w64-mingw32/include"
162+
```
126163

127-
When Windows is the host and the target OS, the build script of `asio-sys` supports all cross compilation targets
128-
which are supported by the MSVC compiler. An exhaustive list of combinations could be found [here](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-160#vcvarsall-syntax) with the addition of undocumented `arm64`, `arm64_x86`, `arm64_amd64` and `arm64_arm` targets. (5.11.2023)
164+
## Troubleshooting
129165

130-
It is also possible to compile Windows applications with ASIO support on Linux and macOS.
166+
### No Default Device Available
131167

132-
For both platforms the common way to do this is to use the [MinGW-w64](https://www.mingw-w64.org/) toolchain.
168+
If you receive errors about no default input or output device:
133169

134-
Make sure that you have included the `MinGW-w64` include directory in your `CPLUS_INCLUDE_PATH` environment variable.
135-
Make sure that LLVM is installed and include directory is also included in your `CPLUS_INCLUDE_PATH` environment variable.
170+
- **Linux/ALSA:** Ensure your user is in the `audio` group and that ALSA is properly configured
171+
- **Linux/PulseAudio:** Check that PulseAudio is running: `pulseaudio --check`
172+
- **Windows:** Verify your audio device is enabled in Sound Settings
173+
- **macOS:** Check System Preferences > Sound for available devices
174+
- **Mobile (iOS/Android):** Ensure your app has microphone/audio permissions
136175

137-
Example for macOS for the target of `x86_64-pc-windows-gnu` where `mingw-w64` is installed via brew:
176+
### Buffer Size Issues
138177

139-
```
140-
export CPLUS_INCLUDE_PATH="$CPLUS_INCLUDE_PATH:/opt/homebrew/Cellar/mingw-w64/11.0.1/toolchain-x86_64/x86_64-w64-mingw32/include"
141-
```
178+
If you experience audio glitches or dropouts:
179+
180+
- Try `BufferSize::Default` first before requesting specific sizes
181+
- When using `BufferSize::Fixed`, query `SupportedBufferSize` to find valid ranges
182+
- Smaller buffers reduce latency but increase CPU load and risk dropouts
183+
- Ensure your audio callback completes quickly and avoids blocking operations
184+
185+
### Build Errors
186+
187+
- **ASIO on Windows:** Verify `LIBCLANG_PATH` is set and LLVM is installed
188+
- **ALSA on Linux:** Install development packages: `libasound2-dev` (Debian/Ubuntu) or `alsa-lib-devel` (Fedora)
189+
- **JACK:** Install JACK development libraries before enabling the `jack` feature

examples/beep.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
//! Plays a simple 440 Hz sine wave (beep) tone.
2+
//!
3+
//! This example demonstrates:
4+
//! - Selecting audio hosts (with optional JACK support on Linux)
5+
//! - Selecting devices by ID or using the default output device
6+
//! - Querying the default output configuration
7+
//! - Building and running an output stream with typed samples
8+
//! - Generating audio data in the stream callback
9+
//!
10+
//! Run with: `cargo run --example beep`
11+
//! With JACK (Linux): `cargo run --example beep --features jack -- --jack`
12+
//! With specific device: `cargo run --example beep -- --device "wasapi:device_id"`
13+
114
use clap::Parser;
215
use cpal::{
316
traits::{DeviceTrait, HostTrait, StreamTrait},

examples/enumerate.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,14 @@
1+
//! Enumerates all available audio hosts, devices, and their supported configurations.
2+
//!
3+
//! This example demonstrates:
4+
//! - Querying available audio hosts on the system
5+
//! - Enumerating all audio devices for each host
6+
//! - Retrieving device IDs for persistent identification
7+
//! - Getting device descriptions with metadata
8+
//! - Listing supported input and output stream configurations
9+
//!
10+
//! Run with: `cargo run --example enumerate`
11+
112
extern crate anyhow;
213
extern crate cpal;
314

src/device_description.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
//! Device metadata and description types.
2+
//!
3+
//! This module provides structured information about audio devices including manufacturer,
4+
//! device type, interface type, and connection details. Not all backends provide complete
5+
//! information - availability depends on platform capabilities.
6+
17
use std::fmt;
28

39
use crate::ChannelCount;
@@ -29,7 +35,7 @@ pub struct DeviceDescription {
2935
/// Physical address or connection identifier
3036
address: Option<String>,
3137

32-
/// Additional description lines with non-structured, detailed information
38+
/// Additional description lines with non-structured, detailed information.
3339
extended: Vec<String>,
3440
}
3541

src/error.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@ impl Error for HostUnavailable {}
2323
/// `panic!` caused by some unforeseen or unknown reason.
2424
///
2525
/// **Note:** If you notice a `BackendSpecificError` that you believe could be better handled in a
26-
/// cross-platform manner, please create an issue or submit a pull request with a patch that adds
27-
/// the necessary error variant to the appropriate error enum.
26+
/// cross-platform manner, please create an issue at <https://github.com/RustAudio/cpal/issues>
27+
/// with details about your use case, the backend you're using, and the error message. Or submit
28+
/// a pull request with a patch that adds the necessary error variant to the appropriate error enum.
2829
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
2930
pub struct BackendSpecificError {
3031
pub description: String,
@@ -65,7 +66,7 @@ impl From<BackendSpecificError> for DevicesError {
6566
}
6667
}
6768

68-
/// An error that may occur while attempting to retrieve a device id.
69+
/// An error that may occur while attempting to retrieve a device ID.
6970
#[derive(Clone, Debug, Eq, PartialEq)]
7071
pub enum DeviceIdError {
7172
/// See the [`BackendSpecificError`] docs for more information about this error variant.
@@ -79,7 +80,7 @@ impl Display for DeviceIdError {
7980
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
8081
match self {
8182
Self::BackendSpecific { err } => err.fmt(f),
82-
Self::UnsupportedPlatform => f.write_str("Device ids are unsupported for this OS"),
83+
Self::UnsupportedPlatform => f.write_str("Device IDs are unsupported for this OS"),
8384
}
8485
}
8586
}

src/host/aaudio/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
//! AAudio backend implementation.
2+
//!
3+
//! Default backend on Android.
4+
15
use std::cmp;
26
use std::convert::TryInto;
37
use std::sync::{Arc, Mutex};

src/host/alsa/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
//! ALSA backend implementation.
2+
//!
3+
//! Default backend on Linux and BSD systems.
4+
15
extern crate alsa;
26
extern crate libc;
37

0 commit comments

Comments
 (0)