Expand description
capture-system-or-process-audio
Unified #![forbid(unsafe_code)] cross-platform system speaker, per-application/process, and microphone PCM audio capture & live mixer for Rust.
Native WASAPI · PipeWire · PulseAudio · Core Audio Process Taps · ScreenCaptureKit — zero virtual audio cables, zero steady-state allocations.
Created by @s0d3s — author of PyAudioWPatch (140k+ monthly PyPI downloads), rebuilt from scratch in safe Rust.
§Installation
cargo add capture-system-or-process-audiocapture-system-or-process-audio selects the active OS backend (WASAPI, PipeWire/PulseAudio, or Core Audio/ScreenCaptureKit) in one single place behind a 100% platform-agnostic safe-Rust API (#![forbid(unsafe_code)]) — your application crate never needs per-OS #[cfg] backend dispatch.
§Quick Start
§1. Capture Default Speakers & Zero-Allocation read_into
use capture_system_or_process_audio::{
CapabilityError, CaptureTarget, DefaultDeviceMode, Stop, capture_single,
};
use std::time::Duration;
fn main() -> Result<(), CapabilityError> {
// Follows OS default speaker/headphone switches automatically (or pass DefaultDeviceMode::Pin):
let target = CaptureTarget::default_output(DefaultDeviceMode::Follow);
let mut manager = capture_single(target)?;
let fmt = manager.output_format().expect("active output format").clone();
let mut pcm_buf = vec![0u8; 480 * fmt.bytes_per_frame()];
// Warmed read_into performs 0 steady-state heap allocations:
let res = manager
.read_into(&mut pcm_buf, 480, Duration::from_millis(200))
.expect("read PCM block");
println!(
"Read {} frames ({} Hz, {} ch, {:?})",
res.frames,
fmt.rate(),
fmt.channels(),
fmt.sample()
);
manager.stop(Stop::Drain);
manager.wait_cleanup(Duration::from_secs(2));
Ok(())
}§2. List, Filter & Capture CaptureTargets Deterministically (discover_query)
Discovery::find_app("Name", ...) is a single-match shortcut that fails if multiple instances run or display names differ across locales/packaging. Enumerating discover_query lets you inspect every available CaptureTarget (applications, processes, output_devices, input_devices), filter deterministically on active_audio(), pid(), app_id(), executable_path(), or clean_device_id(), refine with .with_gain(...) / .with_backend(...), and pass the selected targets directly into CaptureManager:
use capture_system_or_process_audio::{
CapabilityError, CaptureManager, CaptureTarget, DefaultDeviceMode, DiscoveryQuery,
MixerConfig, Stop, discover_query, request,
};
use std::time::Duration;
fn main() -> Result<(), CapabilityError> {
let catalog = discover_query(&DiscoveryQuery::default())?;
for t in &catalog.targets {
println!(
"kind={:?} name={:?} pid={:?} active={:?} id={}",
t.kind(),
t.name().map(|s| s.as_ref()),
t.pid(),
t.active_audio(),
t.logical_id()
);
}
let self_pid = std::process::id();
let mut selected: Vec<CaptureTarget> = catalog
.applications
.iter()
.filter(|app| app.active_audio() == Some(true) && app.pid() != Some(self_pid))
.take(2)
.filter_map(|app| app.clone().with_gain(0.85).ok())
.collect();
if selected.is_empty() {
selected.push(CaptureTarget::default_output(DefaultDeviceMode::Follow));
}
let req = request(selected).with_mixer_config(MixerConfig {
silence_on_idle: true,
..MixerConfig::default()
});
let mut manager = CaptureManager::open(req)?;
let block = manager.read(480, Duration::from_millis(200)).expect("read PCM block");
println!("Captured {} frames", block.frames);
manager.stop(Stop::Drain);
manager.wait_cleanup(Duration::from_secs(2));
Ok(())
}§3. Mix Microphone + Single Application at 16 kHz Mono I16
use capture_system_or_process_audio::{
ByteOrder, CapabilityError, CaptureManager, CaptureTarget, Channel, DefaultDeviceMode,
Discovery, DitherMode, Format, Layout, MixerConfig, OnRootExit, OutputConverterConfig,
ProcessScope, SampleType, Stop, request,
};
use std::{sync::Arc, time::Duration};
fn main() -> Result<(), CapabilityError> {
let mic = CaptureTarget::microphone(DefaultDeviceMode::Follow);
let app = Discovery::new()
.find_app("Spotify", ProcessScope::Tree, OnRootExit::Stop)
.map_err(|_| CapabilityError::NoSuchProcess)?;
let mono_16k = Format::new(
SampleType::I16,
ByteOrder::Little,
16_000,
1,
Layout::Known(Arc::from([Channel::Mono])),
)
.expect("valid 16 kHz mono format");
let req = request(vec![mic, app])
.with_mixer_config(MixerConfig {
silence_on_idle: true,
..MixerConfig::default()
})
.with_output_converter(Some(OutputConverterConfig::new(mono_16k, DitherMode::Tpdf)));
// Optional side-effect-free execution plan preview before opening OS streams:
let plan = req.inspect()?;
println!("Combine resolution: {:?} (streams={})", plan.combine_resolution, plan.estimated_active_streams);
let mut manager = CaptureManager::open(req)?;
let block = manager.read(1600, Duration::from_millis(200)).expect("read 100 ms mixed audio");
println!("Mixed {} frames", block.frames);
manager.stop(Stop::Drain);
manager.wait_cleanup(Duration::from_secs(2));
Ok(())
}§4. Check & Request OS Recording Permissions
use capture_system_or_process_audio::{
CapabilityError, CaptureTarget, DefaultDeviceMode, check_permissions, request_permissions,
};
use std::time::Duration;
fn main() -> Result<(), CapabilityError> {
let target = CaptureTarget::default_output(DefaultDeviceMode::Follow);
// Non-prompting preflight across Microphone, SystemAudio, and ScreenRecording:
let report = check_permissions(std::slice::from_ref(&target))?;
if !report.system_audio().is_granted() {
let _updated = request_permissions(std::slice::from_ref(&target), Duration::from_secs(30))?;
}
Ok(())
}§Choosing Between CaptureManager and AudioStream
CaptureManager(capture,capture_single,CaptureManager::open) — Recommended Default: Uses a zero-extra-copyPassThroughpath for single targets while owning multi-target native graph fan-in (SharedNativeGraphMix), drift-compensated software mixing (CspaMixer+ pre-mixInputNormalizer + FrameReblocker), post-mixOutputConverter, automaticFollowdefault-device switching,OnRootExit::Waitrelaunch tracking, and live two-tierupdate_targets(...)hot-swap.AudioStream(open_stream,AudioStream::open) — Lightweight Single Session: Owns a single native backend capture stream directly when you explicitly want zero discovery subscriptions, process-tree monitoring, or device-switch transitions.
§Platform & Native Backend Matrix
Unsupported scopes or OS versions fail explicitly with CapabilityError — never silently broadening from single-process capture to full-system loopback:
| Platform | Crate Backend | Supported Targets & Capabilities | Runtime Notes |
|---|---|---|---|
Windows 10 / 11 (x86_64, aarch64) | capture-system-or-process-audio-windows (WASAPI) | default_output & microphone (Follow/Pin), device & input_device (>= 19041); process & application ProcessScope::Tree (>= 20348). | ProcessScope::Exact rejects explicitly (CapabilityError::UnsupportedScope). |
Linux (x86_64, aarch64) | capture-system-or-process-audio-linux (PipeWire 0.3.65+, PulseAudio 15.0+) | Output endpoints, microphones (.monitor sinks excluded), PipeWire SharedNativeGraphMix virtual-sink fan-in, PulseAudio per-stream CspaMixer, and [PipeWire + PulseAudio] cross-backend mixing. | Loads libpipewire-0.3.so.0 & libpulse.so.0 via dlopen (0 compile-time NEEDED links). |
macOS (aarch64-apple-darwin) | capture-system-or-process-audio-macos (Core Audio, ScreenCaptureKit) | Core Audio Process Taps (macOS 14.2+), Core Audio HAL microphone input (macOS 13.0+), ScreenCaptureKit application (ProcessScope::Exact, macOS 13.0+), and [SCK + CoreAudio] cross-backend mixing. | Intel macOS (x86_64) and SCK ProcessScope::Tree reject explicitly. |
§Repository, Other SDKs & License
- Official Documentation, Manuals & Multi-SDK Reference: https://s0d3s.github.io/capture-system-or-process-audio/
- GitHub Repository (Python, C++17, C11 SDKs &
cspa-tui-demo): https://github.com/s0d3s/capture-system-or-process-audio - License: Dual-licensed under MIT or Apache-2.0, at your option.
Re-exports§
pub use capture_system_or_process_audio_core as core;
Modules§
- converter
- discovery
- lifecycle
- manager
- measurements
- mixer
- ordering
- planner
- reads
- routing
- schema
- storage
- stream_
runtime - traits
Structs§
- Aggregate
Manager Budgets - Backends
- Cancellation
- Capture
Plan Report - Capture
Request - Capture
Target - Control
- Control
Handle - Discovery
Event - Discovery
Filter - Discovery
Query - Discovery
Subscription - Format
- Header
- Input
Diagnostic Snapshot - Input
Status Handle - Status-only diagnostic input handle. Exposes read-only per-input status and metrics without competing raw PCM read methods or tee buffers.
- Losses
- Membership
Descriptor - Mixed
Block Metadata - Mixer
Config - Output
Converter Config - Owned
Route - Ownership record for a single stream, node, or device route modified when
allow_reroute = true. - Packet
Anchor - Permission
Entry - Per-domain recording permission status entry inside
PermissionReport. - Permission
Report - Zero-heap-allocation permission report with entries ordered as
[Microphone, SystemAudio, ScreenRecording]. - Process
Identity - Process
Tree Range - Read
Result - Route
Rollback Guard - Cross-platform route-restoration guard enforcing non-disruptive capture by default
(
allow_reroute = false) and restoring only library-owned route/mute/sink changes on partial-open failure or teardown without overwriting concurrent user route moves. - Session
Boundary - Slice
- Stamp
- Startup
Cleanup - Storage
Budget - Storage
Limits - Target
Catalog - Target
Plan - Target
Snapshot
Enums§
- Backend
Id - Boundary
Kind - Byte
Order - Capability
Error - Cross-platform capability, permission, liveness, and session error.
- Capacity
Error - Channel
- Combine
Mode - Session-level target combination policy owned by
Manager. - Combine
Resolution - Control
Kind - Default
Device Mode - Discovery
Dedupe - Discovery
Event Kind - Discovery
Order - Dither
Mode - EndReason
- Failure
- Find
AppError - Input
Conversion Policy - Layout
- Mode
- OnFormat
Change - OnInput
Failure - OnRoot
Exit - Overflow
- Overlap
Combination Semantics - Partial
Reason - Participation
State - Permission
Kind - OS recording-consent domain.
- Permission
Policy - Recording permission prompt policy during
open(). Defaults toAutoRequest;CheckOnlydisables prompting. - Permission
State - Recording permission status. Unprobed OS domains are never reported as
Granted. - Plan
Error - Platform
Os - Process
Scope - Process
Tree Strategy - Per-target process-tree acquisition strategy for
ProcessandApplicationtargets. - Provenance
- Read
Error - Sample
Type - Stop
- Target
Kind - Timing
Requirement - Cross-platform sample-timing qualification level.
Traits§
- Audio
Stream Backend - A stream owns one backend capture session and never monitors process trees, dynamic membership, or default-device switches.
- Capture
Manager Backend - Plans, monitors, mixes, converts, reconfigures, and reopens capture sessions.
- Default
Endpoint Observer - Event-driven OS default endpoint observer, independent of reads.
- Discovery
Backend - Lazy discovery with shared methods that honor
self.backends(). - Openable
Stream Backend - A platform stream that can be opened directly from a single-point
CaptureTarget. - Permissions
Backend - Recording-permissions inspection and interactive request contract.
- Topology
Controller Backend NativeTreeMix/SharedNativeGraphMixgraph topology controller.
Functions§
- capture
- Open a
CaptureManagersession (PassThrough,SharedNativeGraphMix, orCspaMixer) fortargets. - capture_
single - Open a
CaptureManagersession for a singleCaptureTarget. - check_
permission_ kinds - Non-prompting OS recording permission check for explicit
PermissionKinddomains. - check_
permissions - Non-prompting OS recording permission check for
targets(empty slice inspects all OS domains). - check_
permissions_ with_ backends - Non-prompting OS recording permission check for
targetshonoringbackends. - check_
request_ permissions - Non-prompting OS recording permission check for a configured
CaptureRequest. - discover
- Discover available targets matching
filterwithout starting a background watcher thread. - discover_
query - Execute a structured
DiscoveryQuery(backends,dedupe,order) without starting a watcher thread. - open_
stream - Open a single-point
AudioStreamwithout dynamic process-tree or default-device monitoring. - open_
stream_ with_ options - Open a single-point
AudioStreamwith explicitProcessTreeRange,Backends,Overflow, andTimingRequirement. - open_
stream_ with_ permission_ policy - Open a single-point
AudioStreamwith explicitPermissionPolicy(AutoRequestvsCheckOnly). - request
- Construct a
CaptureRequestfortargetsready for.inspect()orCaptureManager::open(...). - request_
for_ capture_ request - Request OS recording permissions required by a configured
CaptureRequest. - request_
permission_ kinds - Request OS recording permissions for explicit
PermissionKinddomains. - request_
permissions - Request OS recording permissions required by
targets(empty slice requests all promptable OS domains). - request_
permissions_ with_ options - Request OS recording permissions required by
targetswith explicitbackendsand optional Settings launch. - subscribe_
discovery - Subscribe to bounded
DiscoveryEventupdates matchingquery(max_discovery_queuein32..=4096).
Type Aliases§
- Audio
Stream - Unified zero-cost static-dispatch cross-platform
AudioStream. - Capture
Manager - Unified zero-cost static-dispatch cross-platform
CaptureManager. - Default
Input Observer - Active OS event-driven default input (microphone) endpoint observer.
- Default
Output Observer - Active OS event-driven default output endpoint observer.
- Discovery
- Unified zero-cost static-dispatch cross-platform
Discovery. - Permissions
- Unified zero-cost static-dispatch cross-platform
Permissions. - Platform
Discovery - Active OS discovery backend (
PlatformDiscovery). - Platform
Manager - Active OS multi-target / pass-through capture manager backend (
PlatformManager). - Platform
Permissions - Active OS recording-permissions check & request backend (
PlatformPermissions). - Platform
Stream - Active OS single-point stream backend (
PlatformStream).