pub(crate) struct PaCaptureSession {
pub(crate) stream: Stream,
pub(crate) context: Context,
pub(crate) mainloop: Mainloop,
}Expand description
Own one whole capture run end to end on a dedicated thread — connect PulseAudio,
encode, and deliver — until stopped. It runs on its own thread because the PulseAudio
mainloop must be pumped continuously and independently of the caller: sharing the
caller’s thread would tie capture cadence to it and let any stall starve the audio.
The body handed to spawn_worker.
Publishes start_state for the handshake (RUNNING on entering the hot loop, FAILED
with a last_error on any terminal error, IDLE on a clean stop) and returns when
stop_state leaves STOP_NONE or on a fatal error. The startup sequence, in order:
- Seed the mirrors: copies the settings snapshot (already validated by
AudioCaptureSettings::validate) into theInnerper-frame atomics. - Buffer attr / latency: a configured
latency_msusesADJUST_LATENCYwithfragsizeset to that latency; otherwisefragsizeis floored at ~20 ms, which yields a prompt first frame and avoids PipeWire’s ~2 s default fragment. - Connect + probe: drives the context to
Readyon the bounded pump (re-checkingstop_pendingeach turn), and up-front validates a NAMED device via an introspect probe — an asyncconnect_recordwould not fail synchronously on a bad name. The probe closure is called from C inside mainloop dispatch, so its body iscatch_unwind-guarded to keep a panic from unwinding across the FFI boundary. - Encoder + record stream: creates the
PcmEncoder(mono/stereo or surround) and drives the record stream toReady. - Delivery thread: spawns the delivery thread that pops from the
DeliveryRingand calls the sink there, so a stalled sink cannot back up the PA pump. The buffer pool is sized to the worst-case body — RED prefix plus a max Opus packet, scaled by stream count for surround (one self-delimited packet per stream). A run without a sink spawns no delivery thread: its ring starts closed, so every encoded frame goes back to the pool and only the output socket is served. - Hot loop:
pumps on the ~20 ms bound, then drains every buffered fragment via peek/discard (aHoleis an xrun — the read index is just advanced), feeding each intoRunState. A stop is observed within the pump bound even when the source is wedged. On exit it disconnects the stream, drops the encoder, closes and joins the delivery ring, and reports any dropped stale frames.
One PulseAudio session for capture: mainloop, context, and the record stream, all recreated together on reconnect. Drop order matters (declaration order): the stream must die first, then its owning context, then the mainloop both pulse threads pump — the reverse of the build. A wrong order is a use-after-free on the libpulse side.
Fields§
§stream: Stream§context: ContextMust outlive the stream (the connection owns it); never read after open.
mainloop: Mainloop