Skip to main content

Crate capture_system_or_process_audio

Crate capture_system_or_process_audio 

Source
Expand description
capture-system-or-process-audio — Safe-Rust cross-platform system speaker loopback, single application/process, and microphone PCM audio capture library

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.

Official User Manual and Rust Handbook crates.io Version docs.rs Documentation Minimum Supported Rust Version: 1.88+ Supported Platforms: Windows 10/11, Linux, macOS License: MIT OR Apache-2.0


§Installation

cargo add capture-system-or-process-audio

capture-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-copy PassThrough path for single targets while owning multi-target native graph fan-in (SharedNativeGraphMix), drift-compensated software mixing (CspaMixer + pre-mix InputNormalizer + FrameReblocker), post-mix OutputConverter, automatic Follow default-device switching, OnRootExit::Wait relaunch tracking, and live two-tier update_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:

PlatformCrate BackendSupported Targets & CapabilitiesRuntime 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

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§

AggregateManagerBudgets
Backends
Cancellation
CapturePlanReport
CaptureRequest
CaptureTarget
Control
ControlHandle
DiscoveryEvent
DiscoveryFilter
DiscoveryQuery
DiscoverySubscription
Format
Header
InputDiagnosticSnapshot
InputStatusHandle
Status-only diagnostic input handle. Exposes read-only per-input status and metrics without competing raw PCM read methods or tee buffers.
Losses
MembershipDescriptor
MixedBlockMetadata
MixerConfig
OutputConverterConfig
OwnedRoute
Ownership record for a single stream, node, or device route modified when allow_reroute = true.
PacketAnchor
PermissionEntry
Per-domain recording permission status entry inside PermissionReport.
PermissionReport
Zero-heap-allocation permission report with entries ordered as [Microphone, SystemAudio, ScreenRecording].
ProcessIdentity
ProcessTreeRange
ReadResult
RouteRollbackGuard
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.
SessionBoundary
Slice
Stamp
StartupCleanup
StorageBudget
StorageLimits
TargetCatalog
TargetPlan
TargetSnapshot

Enums§

BackendId
BoundaryKind
ByteOrder
CapabilityError
Cross-platform capability, permission, liveness, and session error.
CapacityError
Channel
CombineMode
Session-level target combination policy owned by Manager.
CombineResolution
ControlKind
DefaultDeviceMode
DiscoveryDedupe
DiscoveryEventKind
DiscoveryOrder
DitherMode
EndReason
Failure
FindAppError
InputConversionPolicy
Layout
Mode
OnFormatChange
OnInputFailure
OnRootExit
Overflow
OverlapCombinationSemantics
PartialReason
ParticipationState
PermissionKind
OS recording-consent domain.
PermissionPolicy
Recording permission prompt policy during open(). Defaults to AutoRequest; CheckOnly disables prompting.
PermissionState
Recording permission status. Unprobed OS domains are never reported as Granted.
PlanError
PlatformOs
ProcessScope
ProcessTreeStrategy
Per-target process-tree acquisition strategy for Process and Application targets.
Provenance
ReadError
SampleType
Stop
TargetKind
TimingRequirement
Cross-platform sample-timing qualification level.

Traits§

AudioStreamBackend
A stream owns one backend capture session and never monitors process trees, dynamic membership, or default-device switches.
CaptureManagerBackend
Plans, monitors, mixes, converts, reconfigures, and reopens capture sessions.
DefaultEndpointObserver
Event-driven OS default endpoint observer, independent of reads.
DiscoveryBackend
Lazy discovery with shared methods that honor self.backends().
OpenableStreamBackend
A platform stream that can be opened directly from a single-point CaptureTarget.
PermissionsBackend
Recording-permissions inspection and interactive request contract.
TopologyControllerBackend
NativeTreeMix / SharedNativeGraphMix graph topology controller.

Functions§

capture
Open a CaptureManager session (PassThrough, SharedNativeGraphMix, or CspaMixer) for targets.
capture_single
Open a CaptureManager session for a single CaptureTarget.
check_permission_kinds
Non-prompting OS recording permission check for explicit PermissionKind domains.
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 targets honoring backends.
check_request_permissions
Non-prompting OS recording permission check for a configured CaptureRequest.
discover
Discover available targets matching filter without 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 AudioStream without dynamic process-tree or default-device monitoring.
open_stream_with_options
Open a single-point AudioStream with explicit ProcessTreeRange, Backends, Overflow, and TimingRequirement.
open_stream_with_permission_policy
Open a single-point AudioStream with explicit PermissionPolicy (AutoRequest vs CheckOnly).
request
Construct a CaptureRequest for targets ready for .inspect() or CaptureManager::open(...).
request_for_capture_request
Request OS recording permissions required by a configured CaptureRequest.
request_permission_kinds
Request OS recording permissions for explicit PermissionKind domains.
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 targets with explicit backends and optional Settings launch.
subscribe_discovery
Subscribe to bounded DiscoveryEvent updates matching query (max_discovery_queue in 32..=4096).

Type Aliases§

AudioStream
Unified zero-cost static-dispatch cross-platform AudioStream.
CaptureManager
Unified zero-cost static-dispatch cross-platform CaptureManager.
DefaultInputObserver
Active OS event-driven default input (microphone) endpoint observer.
DefaultOutputObserver
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.
PlatformDiscovery
Active OS discovery backend (PlatformDiscovery).
PlatformManager
Active OS multi-target / pass-through capture manager backend (PlatformManager).
PlatformPermissions
Active OS recording-permissions check & request backend (PlatformPermissions).
PlatformStream
Active OS single-point stream backend (PlatformStream).