Skip to content

Real-Time Safety, Zero-Alloc Reads & Lifecycle

Audio capture runs alongside OS real-time audio threads (WASAPI MMCSS Capture, PipeWire PW_STREAM_FLAG_RT_PROCESS, Core Audio HAL IOProcs). A single mutex wait or unbounded heap allocation on the acquisition thread can glitch audio system-wide.


1. Bounded Slot Pools & AggregateManagerBudgets

Section titled “1. Bounded Slot Pools & AggregateManagerBudgets”

Every session reserves fixed PCM slot pools upfront under AggregateManagerBudgets:

Budget Parameter Default Role
max_targets 16 (1..=64) Maximum targets in a single CaptureRequest.
max_active_streams 16 (1..=64) Maximum concurrent native OS streams managed in one session.
max_total_pcm_memory 16 MiB Hard ceiling across all input slot pools plus MultiInputManager’s auxiliary out_pool.
max_discovery_queue 256 (32..=4096) Bounded cursor queue capacity for live discovery subscriptions.
cleanup_timeout_ms 2000 ms Default bounded teardown wait on with / async with / RAII scope exit.

Overflow Policies When a Consumer Falls Behind

Section titled “Overflow Policies When a Consumer Falls Behind”

Because native acquisition never blocks waiting for a slow caller, Overflow governs what happens when all preallocated queue slots are full:

  • DropOldest (Default): Evicts the oldest unread packet so the consumer always receives the freshest live audio (recording dropped counts in InputStatusHandle.dropped_frames).
  • DropNewest: Preserves queued contiguous history and discards incoming packets until the consumer drains space.
  • Fail: Marks the stream failed with FailureKind::QueueOverflow (CSPA_STATUS_NO_MEMORY / ReadError) so strict lossless test harnesses detect consumer stalls immediately.

Delivery Mode Steady-State Allocations Best For
read_into(buf, frames) 0 heap allocations across Rust, Python (3.11–3.15t -Xgil=0), C++17, & C11 Low-latency DSP, WebRTC/LiveKit frames, real-time visualizers, game engines, and preallocated NumPy/ring buffers.
read(frames) →\rightarrow PcmBlock Zero-copy slot retention (memoryview / to_numpy(copy=False) / cspa::PcmBlock) Python NumPy/Whisper pipelines and batch encoders; retained PcmBlock views stay valid even after stop()!
read_async(frames) / async for Releases thread to Python asyncio event loop; cancellable via Cancellation FastAPI / WebSocket / asyncio voice bots.
start_callback(fn) Dedicated off-acquisition worker thread (catch_unwind + single-shot exception containment) Push-oriented PortAudio/sounddevice-style event pipelines (user callbacks never run on the OS RT audio thread!).

3. Cancellation, Callbacks & Clean Shutdown (Drain vs Abort)

Section titled “3. Cancellation, Callbacks & Clean Shutdown (Drain vs Abort)”

Two distinct shutdown modes give you deterministic control over queued audio:

  1. Stop::Drain (stream.stop("drain") / stream.stop(false)): Signals native acquisition to stop while keeping all already-captured packets readable until PartialReason::Eof — ideal for saving complete recordings without clipping the final syllable.
  2. Stop::Abort (with / async with exit, Drop, or stream.stop("abort") / stream.stop(true)): Discards unread queued packets immediately and waits up to cleanup_timeout (2000 ms) for OS audio handles and worker threads to join cleanly.
import asyncio
import capture_system_or_process_audio as cspa
async def stream_with_cancellation() -> None:
cancel = cspa.Cancellation()
budgets = cspa.AggregateManagerBudgets(max_total_pcm_memory=8 * 1024 * 1024)
async with cspa.capture(
cspa.default_output(),
budgets=budgets,
overflow=cspa.Overflow.DROP_OLDEST,
silence_on_idle=True,
) as stream:
outcome = await stream.read_async(frames=480, timeout_ms=100, cancel=cancel)
print("Read frames:", outcome.frames, "reason:", outcome.reason.value)
cancel.cancel()
stream.stop(cspa.StopMode.DRAIN)
stream.wait_cleanup()
if False:
asyncio.run(stream_with_cancellation())

Continue to Platform Backends & Capability Matrix.