Skip to main content

capture_system_or_process_audio_linux/
pulse_stream.rs

1#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
2
3use crate::capabilities::PulseServerKind;
4use crate::core::{
5    StorageLimits,
6    manager::{StorageBudget, StorageReservation},
7    measurements::Trace,
8    ordering::{self, ControlHandle, Failure, Overflow, Producer, Stop},
9    reads::{Cancellation, ReadError, ReadResult, ReadStream},
10    schema::{
11        AggregateManagerBudgets, BackendId, Backends, ByteOrder, CaptureTarget, Channel, Format,
12        Layout, PlatformOs, ProcessTreeRange, SampleType, TargetKind,
13    },
14    storage::Pool,
15    stream_runtime::{
16        EndReason, ReadySignal, StreamReadContext, poll_read_stream, poll_read_stream_into,
17        signal_stream_stop,
18    },
19    traits::{AudioStreamBackend, CapabilityError, OpenableStreamBackend, TimingRequirement},
20};
21use crate::discovery::{collect_pulse_full_state, query_linux_default_sink_now};
22use crate::loader::{LinuxClientPaths, probe_pulse_server};
23use crate::pipewire_stream::{
24    PipeWireStream, linux_endpoint_clock_domain, open_pipewire_point, open_pipewire_source_point,
25    publish_linux_packet,
26};
27use std::sync::{
28    Arc, Mutex,
29    atomic::{AtomicBool, AtomicU32, Ordering::SeqCst},
30};
31use std::thread::{self, JoinHandle};
32use std::time::{Duration, Instant};
33
34const POOL_SLOTS: usize = 8;
35const QUEUE_SLOTS: usize = 4;
36const MAX_FRAMES_PER_SLOT: usize = 4096;
37const SESSION_METADATA_BYTES: usize = 16_384;
38
39pub struct PulseStream {
40    format: Arc<Format>,
41    trace: Option<Arc<Trace>>,
42    reads: ReadStream,
43    control: ControlHandle,
44    default_cancel: Cancellation,
45    armed: Arc<AtomicBool>,
46    stop: Arc<AtomicBool>,
47    ready: Arc<ReadySignal>,
48    ended: Arc<AtomicU32>,
49    #[cfg_attr(not(any(test, feature = "native-tests")), allow(dead_code))]
50    server_kind: PulseServerKind,
51    worker: Mutex<Option<JoinHandle<()>>>,
52    _reservation: StorageReservation,
53}
54
55impl PulseStream {
56    pub(crate) fn arm(&self) {
57        self.armed.store(true, SeqCst);
58    }
59
60    #[cfg(any(test, feature = "native-tests"))]
61    pub(crate) fn server_kind(&self) -> PulseServerKind {
62        self.server_kind
63    }
64
65    pub(crate) fn poll_read_with_cancel(
66        &self,
67        frames: usize,
68        timeout: Duration,
69        cancel: Cancellation,
70    ) -> Result<ReadResult, ReadError> {
71        self.arm();
72        let ctx = StreamReadContext {
73            reads: &self.reads,
74            ready: &self.ready,
75            trace: self.trace.as_ref(),
76        };
77        poll_read_stream(ctx, frames, timeout, cancel)
78    }
79
80    pub(crate) fn poll_read_into_with_cancel(
81        &self,
82        destination: &mut [u8],
83        frames: usize,
84        timeout: Duration,
85        cancel: Cancellation,
86    ) -> Result<ReadResult, ReadError> {
87        self.arm();
88        let ctx = StreamReadContext {
89            reads: &self.reads,
90            ready: &self.ready,
91            trace: self.trace.as_ref(),
92        };
93        poll_read_stream_into(
94            ctx,
95            self.format.clone(),
96            destination,
97            frames,
98            timeout,
99            cancel,
100        )
101    }
102}
103
104impl AudioStreamBackend for PulseStream {
105    #[inline]
106    fn format(&self) -> &Arc<Format> {
107        &self.format
108    }
109
110    #[inline]
111    fn trace(&self) -> Option<&Arc<Trace>> {
112        self.trace.as_ref()
113    }
114
115    #[inline]
116    fn control_handle(&self) -> ControlHandle {
117        self.control.clone()
118    }
119
120    #[inline]
121    fn default_cancel(&self) -> Cancellation {
122        self.default_cancel.clone()
123    }
124
125    fn end_reason(&self) -> Option<EndReason> {
126        if let Some(failure) = self.control.snapshot().failure {
127            return Some(EndReason::Failed(failure));
128        }
129        match self.ended.load(SeqCst) {
130            1 => Some(EndReason::Stopped),
131            2 => Some(EndReason::TargetExited),
132            3 => Some(EndReason::Failed(Failure::Backend)),
133            _ => None,
134        }
135    }
136
137    fn read_with_cancel(
138        &mut self,
139        frames: usize,
140        timeout: Duration,
141        cancel: Cancellation,
142    ) -> Result<ReadResult, ReadError> {
143        self.poll_read_with_cancel(frames, timeout, cancel)
144    }
145
146    fn read_into_with_cancel(
147        &mut self,
148        destination: &mut [u8],
149        frames: usize,
150        timeout: Duration,
151        cancel: Cancellation,
152    ) -> Result<ReadResult, ReadError> {
153        self.poll_read_into_with_cancel(destination, frames, timeout, cancel)
154    }
155
156    fn stop(&self, mode: Stop) {
157        let _ = self.ended.compare_exchange(0, 1, SeqCst, SeqCst);
158        signal_stream_stop(&self.control, &self.stop, &self.ready, mode);
159    }
160
161    fn resources_done(&self) -> bool {
162        let mut guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
163        if guard.as_ref().is_some_and(JoinHandle::is_finished)
164            && let Some(handle) = guard.take()
165        {
166            let _ = handle.join();
167        }
168        guard.is_none()
169    }
170
171    fn wait_cleanup(&self, timeout: Duration) -> bool {
172        self.stop.store(true, SeqCst);
173        self.ready.notify();
174        let started = Instant::now();
175        while !self.resources_done() && started.elapsed() < timeout {
176            thread::sleep(Duration::from_millis(1));
177        }
178        self.resources_done()
179    }
180}
181
182impl Drop for PulseStream {
183    fn drop(&mut self) {
184        self.stop(Stop::Abort);
185    }
186}
187
188#[cfg(target_os = "linux")]
189#[allow(unsafe_code)]
190mod imp {
191    use super::*;
192    use crate::loader::{
193        PA_CONTEXT_FAILED, PA_CONTEXT_NOAUTOSPAWN, PA_CONTEXT_READY, PA_CONTEXT_TERMINATED,
194        PA_SAMPLE_FLOAT32LE, PA_SAMPLE_S16LE, PA_SAMPLE_S24LE, PA_SAMPLE_S32LE,
195        PA_STREAM_ADJUST_LATENCY, PA_STREAM_FAILED, PA_STREAM_READY, PA_STREAM_TERMINATED,
196        PaBufferAttr, PaSampleSpec, PulseLibrary,
197    };
198    use std::ffi::{CString, c_int, c_void};
199
200    pub fn open_pulse_point(
201        paths: &LinuxClientPaths,
202        monitor_source: Option<&str>,
203        monitor_sink_input_index: Option<u32>,
204        overflow: Overflow,
205        timing: TimingRequirement,
206        budget: &StorageBudget,
207        observed: bool,
208    ) -> Result<PulseStream, CapabilityError> {
209        if timing == TimingRequirement::Precise {
210            return Err(CapabilityError::PreciseTimingUnqualified);
211        }
212        let server_info = probe_pulse_server(paths)?;
213        if monitor_sink_input_index.is_none()
214            && let Some(explicit_sink) = monitor_source
215            && !explicit_sink.ends_with(".monitor")
216            && let Ok((devs, _, _, _)) = collect_pulse_full_state(paths)
217            && !devs.iter().any(|d| d.name == explicit_sink)
218        {
219            return Err(CapabilityError::InvalidTarget);
220        }
221        let resolved_source = match monitor_source {
222            Some(name) if name.ends_with(".monitor") => Some(name.to_owned()),
223            Some(name) => Some(format!("{name}.monitor")),
224            None => server_info
225                .default_sink_name
226                .as_ref()
227                .map(|s| format!("{s}.monitor")),
228        };
229        let format = Format::new(
230            SampleType::F32,
231            ByteOrder::Little,
232            48_000,
233            2,
234            Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
235        )
236        .map_err(|_| CapabilityError::InvalidTarget)?;
237        open_pulse_stream_internal(
238            paths,
239            server_info.server_kind,
240            resolved_source,
241            monitor_sink_input_index,
242            format,
243            1,
244            overflow,
245            timing,
246            budget,
247            observed,
248        )
249    }
250
251    pub fn open_pulse_source_point(
252        paths: &LinuxClientPaths,
253        source_name: Option<&str>,
254        format_override: Option<Format>,
255        overflow: Overflow,
256        timing: TimingRequirement,
257        budget: &StorageBudget,
258        observed: bool,
259    ) -> Result<PulseStream, CapabilityError> {
260        if timing == TimingRequirement::Precise {
261            return Err(CapabilityError::PreciseTimingUnqualified);
262        }
263        if source_name.is_some_and(|s| s.is_empty() || s.ends_with(".monitor")) {
264            return Err(CapabilityError::InvalidTarget);
265        }
266        let server_info = probe_pulse_server(paths)?;
267        let (_devs, sources, _pids, _si) = collect_pulse_full_state(paths)?;
268        let matched = match source_name {
269            Some(explicit) => sources
270                .into_iter()
271                .find(|s| s.name == explicit && !s.is_monitor)
272                .ok_or(CapabilityError::InvalidTarget)?,
273            None => sources
274                .iter()
275                .find(|s| s.is_default && !s.is_monitor)
276                .or_else(|| sources.iter().find(|s| !s.is_monitor))
277                .cloned()
278                .ok_or(CapabilityError::ServerUnavailable)?,
279        };
280        let format = match format_override {
281            Some(fmt) => fmt,
282            None => {
283                let sample = match matched.sample_format {
284                    PA_SAMPLE_S16LE => SampleType::I16,
285                    PA_SAMPLE_S24LE => SampleType::I24,
286                    PA_SAMPLE_S32LE => SampleType::I32,
287                    PA_SAMPLE_FLOAT32LE => SampleType::F32,
288                    _ => SampleType::F32,
289                };
290                let (ch, layout) = if matched.channels == 1 {
291                    (1u16, Layout::Known(Arc::from([Channel::Mono])))
292                } else {
293                    (
294                        2u16,
295                        Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
296                    )
297                };
298                let rate = if (8_000..=192_000).contains(&matched.rate_hz) {
299                    matched.rate_hz
300                } else {
301                    48_000
302                };
303                Format::new(sample, ByteOrder::Little, rate, ch, layout)
304                    .map_err(|_| CapabilityError::InvalidTarget)?
305            }
306        };
307        let domain = linux_endpoint_clock_domain(&matched.name);
308        open_pulse_stream_internal(
309            paths,
310            server_info.server_kind,
311            Some(matched.name),
312            None,
313            format,
314            domain,
315            overflow,
316            timing,
317            budget,
318            observed,
319        )
320    }
321
322    #[allow(clippy::too_many_arguments)]
323    fn open_pulse_stream_internal(
324        paths: &LinuxClientPaths,
325        server_kind: PulseServerKind,
326        resolved_source: Option<String>,
327        monitor_sink_input_index: Option<u32>,
328        format: Format,
329        clock_domain: u64,
330        overflow: Overflow,
331        timing: TimingRequirement,
332        budget: &StorageBudget,
333        observed: bool,
334    ) -> Result<PulseStream, CapabilityError> {
335        if timing == TimingRequirement::Precise {
336            return Err(CapabilityError::PreciseTimingUnqualified);
337        }
338        let pa_fmt = match format.sample() {
339            SampleType::I16 => PA_SAMPLE_S16LE,
340            SampleType::I24 => PA_SAMPLE_S24LE,
341            SampleType::I32 => PA_SAMPLE_S32LE,
342            SampleType::F32 => PA_SAMPLE_FLOAT32LE,
343        };
344        let pa_channels =
345            u8::try_from(format.channels()).map_err(|_| CapabilityError::InvalidTarget)?;
346        let pa_rate = format.rate();
347        let coalesce_frames = ((pa_rate / 100) as usize).clamp(64, 960);
348
349        let lib = Arc::new(PulseLibrary::load(paths).map_err(|err| {
350            err.into_capability_error(BackendId::PulseAudio, paths.pulse_min_version)
351        })?);
352        let format = Arc::new(format);
353        let stride = format.bytes_per_frame();
354        let limits = StorageLimits::new(
355            POOL_SLOTS,
356            MAX_FRAMES_PER_SLOT,
357            stride,
358            POOL_SLOTS * MAX_FRAMES_PER_SLOT * stride,
359        )
360        .map_err(|_| CapabilityError::CapacityExceeded)?;
361        let trace = if observed {
362            Some(Arc::new(Trace::new_compact()))
363        } else {
364            None
365        };
366        let metadata_bytes = trace.as_ref().map_or(6024usize, |t| {
367            6024usize
368                .saturating_add(t.storage_bytes())
369                .min(SESSION_METADATA_BYTES)
370        });
371        let reservation = budget
372            .reserve(limits, metadata_bytes)
373            .map_err(|_| CapabilityError::CapacityExceeded)?;
374        let retained_reservation = reservation.retain();
375        let pool = Pool::new_reserved(limits, MAX_FRAMES_PER_SLOT, format.clone(), reservation)
376            .map_err(|_| CapabilityError::CapacityExceeded)?;
377        let (producer, reader) = if let Some(ref tr) = trace {
378            ordering::channel_observed(pool, QUEUE_SLOTS, tr.clone())
379        } else {
380            ordering::channel(pool, QUEUE_SLOTS)
381        }
382        .map_err(|_| CapabilityError::CapacityExceeded)?;
383
384        let armed = Arc::new(AtomicBool::new(false));
385        let stop = Arc::new(AtomicBool::new(false));
386        let ready = Arc::new(ReadySignal::default());
387        let ended = Arc::new(AtomicU32::new(0));
388        let armed_worker = armed.clone();
389        let stop_worker = stop.clone();
390        let ready_worker = ready.clone();
391        let ended_worker = ended.clone();
392
393        let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel::<Result<(), CapabilityError>>(1);
394
395        let worker = thread::spawn(move || {
396            struct PaReadCtx {
397                mainloop: *mut c_void,
398                signal_fn: unsafe extern "C" fn(*mut c_void, c_int),
399                peek_fn: unsafe extern "C" fn(*mut c_void, *mut *const c_void, *mut usize) -> c_int,
400                drop_fn: unsafe extern "C" fn(*mut c_void) -> c_int,
401                get_time_fn: unsafe extern "C" fn(*mut c_void, *mut u64) -> c_int,
402                producer: Producer,
403                policy: Overflow,
404                ready: Arc<ReadySignal>,
405                clock_domain: u64,
406                coalesce_frames: usize,
407                sequence: u64,
408                segment: u64,
409                frame_cursor: u64,
410                armed: Arc<AtomicBool>,
411                coalesce_buf: [u8; 960 * 8],
412                coalesce_len: usize,
413                failed: AtomicBool,
414            }
415
416            unsafe extern "C" fn on_ctx_state(_ctx: *mut c_void, userdata: *mut c_void) {
417                // SAFETY: `userdata` points to `PaReadCtx`.
418                unsafe {
419                    let ctx = &*(userdata as *const PaReadCtx);
420                    (ctx.signal_fn)(ctx.mainloop, 0);
421                }
422            }
423
424            unsafe extern "C" fn on_stream_state(_stream: *mut c_void, userdata: *mut c_void) {
425                // SAFETY: `userdata` points to `PaReadCtx`.
426                unsafe {
427                    let ctx = &*(userdata as *const PaReadCtx);
428                    (ctx.signal_fn)(ctx.mainloop, 0);
429                }
430            }
431
432            unsafe extern "C" fn on_stream_read(
433                stream: *mut c_void,
434                _nbytes: usize,
435                userdata: *mut c_void,
436            ) {
437                // SAFETY: `userdata` points to `PaReadCtx`; no heap allocations occur inside callback.
438                unsafe {
439                    let ctx = &mut *(userdata as *mut PaReadCtx);
440                    loop {
441                        let mut data_ptr: *const c_void = std::ptr::null();
442                        let mut nbytes: usize = 0;
443                        if (ctx.peek_fn)(stream, &mut data_ptr, &mut nbytes) < 0 {
444                            ctx.failed.store(true, SeqCst);
445                            break;
446                        }
447                        if nbytes == 0 {
448                            break;
449                        }
450                        if !ctx.armed.load(SeqCst) {
451                            let _ = (ctx.drop_fn)(stream);
452                            continue;
453                        }
454                        let acquired = ctx.producer.trace().map(|_| Instant::now());
455                        let bpf = ctx.producer.pool().format().bytes_per_frame();
456                        if nbytes.is_multiple_of(bpf) {
457                            let mut usec: u64 = 0;
458                            let ts_ns = if (ctx.get_time_fn)(stream, &mut usec) == 0 && usec > 0 {
459                                Some(usec.saturating_mul(1_000))
460                            } else {
461                                None
462                            };
463                            let target_chunk_bytes = ctx.coalesce_frames * bpf;
464                            let mut byte_off = 0usize;
465                            while byte_off < nbytes {
466                                let space = target_chunk_bytes - ctx.coalesce_len;
467                                let take = space.min(nbytes - byte_off);
468                                if data_ptr.is_null() {
469                                    ctx.coalesce_buf[ctx.coalesce_len..ctx.coalesce_len + take]
470                                        .fill(0);
471                                } else {
472                                    let src = (data_ptr as *const u8).add(byte_off);
473                                    let slice = std::slice::from_raw_parts(src, take);
474                                    ctx.coalesce_buf[ctx.coalesce_len..ctx.coalesce_len + take]
475                                        .copy_from_slice(slice);
476                                }
477                                ctx.coalesce_len += take;
478                                byte_off += take;
479                                if ctx.coalesce_len == target_chunk_bytes {
480                                    publish_linux_packet(
481                                        &mut ctx.producer,
482                                        &ctx.coalesce_buf[..target_chunk_bytes],
483                                        false,
484                                        false,
485                                        ctx.coalesce_frames,
486                                        ts_ns,
487                                        ctx.clock_domain,
488                                        &mut ctx.sequence,
489                                        &mut ctx.segment,
490                                        &mut ctx.frame_cursor,
491                                        ctx.policy,
492                                        acquired,
493                                    );
494                                    ctx.coalesce_len = 0;
495                                    ctx.ready.notify();
496                                }
497                            }
498                        }
499                        let _ = (ctx.drop_fn)(stream);
500                    }
501                }
502            }
503
504            // SAFETY: owns `pa_threaded_mainloop`, `pa_context`, and `pa_stream` for this session.
505            unsafe {
506                let mainloop = (lib.pa_threaded_mainloop_new)();
507                if mainloop.is_null() {
508                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
509                    return;
510                }
511                let api = (lib.pa_threaded_mainloop_get_api)(mainloop);
512                let context = (lib.pa_context_new)(api, c"cspa-pa-stream".as_ptr());
513                if context.is_null() {
514                    (lib.pa_threaded_mainloop_free)(mainloop);
515                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
516                    return;
517                }
518
519                let mut read_ctx = Box::new(PaReadCtx {
520                    mainloop,
521                    signal_fn: lib.pa_threaded_mainloop_signal,
522                    peek_fn: lib.pa_stream_peek,
523                    drop_fn: lib.pa_stream_drop,
524                    get_time_fn: lib.pa_stream_get_time,
525                    producer,
526                    policy: overflow,
527                    ready: ready_worker.clone(),
528                    clock_domain,
529                    coalesce_frames,
530                    sequence: 0,
531                    segment: 1,
532                    frame_cursor: 0,
533                    armed: armed_worker,
534                    coalesce_buf: [0u8; 960 * 8],
535                    coalesce_len: 0,
536                    failed: AtomicBool::new(false),
537                });
538                let ctx_ptr: *mut c_void = (&mut *read_ctx as *mut PaReadCtx).cast();
539                (lib.pa_context_set_state_callback)(context, Some(on_ctx_state), ctx_ptr);
540
541                if (lib.pa_context_connect)(
542                    context,
543                    std::ptr::null(),
544                    PA_CONTEXT_NOAUTOSPAWN,
545                    std::ptr::null(),
546                ) < 0
547                    || (lib.pa_threaded_mainloop_start)(mainloop) < 0
548                {
549                    (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
550                    (lib.pa_context_disconnect)(context);
551                    (lib.pa_context_unref)(context);
552                    (lib.pa_threaded_mainloop_free)(mainloop);
553                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
554                    return;
555                }
556
557                (lib.pa_threaded_mainloop_lock)(mainloop);
558                loop {
559                    let st = (lib.pa_context_get_state)(context);
560                    if st == PA_CONTEXT_READY {
561                        break;
562                    }
563                    if st == PA_CONTEXT_FAILED || st == PA_CONTEXT_TERMINATED {
564                        (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
565                        (lib.pa_threaded_mainloop_unlock)(mainloop);
566                        (lib.pa_threaded_mainloop_stop)(mainloop);
567                        (lib.pa_context_disconnect)(context);
568                        (lib.pa_context_unref)(context);
569                        (lib.pa_threaded_mainloop_free)(mainloop);
570                        let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
571                        return;
572                    }
573                    (lib.pa_threaded_mainloop_wait)(mainloop);
574                }
575
576                let spec = PaSampleSpec {
577                    format: pa_fmt,
578                    rate: pa_rate,
579                    channels: pa_channels,
580                };
581                let stream = (lib.pa_stream_new)(
582                    context,
583                    c"cspa-pa-capture".as_ptr(),
584                    &spec,
585                    std::ptr::null(),
586                );
587                if stream.is_null() {
588                    (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
589                    (lib.pa_context_disconnect)(context);
590                    (lib.pa_threaded_mainloop_unlock)(mainloop);
591                    (lib.pa_threaded_mainloop_stop)(mainloop);
592                    (lib.pa_context_unref)(context);
593                    (lib.pa_threaded_mainloop_free)(mainloop);
594                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
595                    return;
596                }
597
598                if let Some(sink_input_idx) = monitor_sink_input_index
599                    && (lib.pa_stream_set_monitor_stream)(stream, sink_input_idx) < 0
600                {
601                    (lib.pa_stream_unref)(stream);
602                    (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
603                    (lib.pa_context_disconnect)(context);
604                    (lib.pa_threaded_mainloop_unlock)(mainloop);
605                    (lib.pa_threaded_mainloop_stop)(mainloop);
606                    (lib.pa_context_unref)(context);
607                    (lib.pa_threaded_mainloop_free)(mainloop);
608                    let _ = ready_tx.send(Err(CapabilityError::InvalidTarget));
609                    return;
610                }
611
612                (lib.pa_stream_set_state_callback)(stream, Some(on_stream_state), ctx_ptr);
613                (lib.pa_stream_set_read_callback)(stream, Some(on_stream_read), ctx_ptr);
614
615                let chunk_bytes_u32 = (coalesce_frames * stride) as u32;
616                let attr = PaBufferAttr {
617                    maxlength: (QUEUE_SLOTS as u32) * chunk_bytes_u32,
618                    tlength: u32::MAX,
619                    prebuf: u32::MAX,
620                    minreq: u32::MAX,
621                    fragsize: chunk_bytes_u32,
622                };
623                let dev_cstring = resolved_source
624                    .as_deref()
625                    .and_then(|s| CString::new(s).ok());
626                let dev_ptr = if monitor_sink_input_index.is_some() {
627                    std::ptr::null()
628                } else {
629                    dev_cstring
630                        .as_ref()
631                        .map_or(std::ptr::null(), |c| c.as_ptr())
632                };
633
634                if (lib.pa_stream_connect_record)(stream, dev_ptr, &attr, PA_STREAM_ADJUST_LATENCY)
635                    < 0
636                {
637                    (lib.pa_stream_set_state_callback)(stream, None, std::ptr::null_mut());
638                    (lib.pa_stream_set_read_callback)(stream, None, std::ptr::null_mut());
639                    (lib.pa_stream_unref)(stream);
640                    (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
641                    (lib.pa_context_disconnect)(context);
642                    (lib.pa_threaded_mainloop_unlock)(mainloop);
643                    (lib.pa_threaded_mainloop_stop)(mainloop);
644                    (lib.pa_context_unref)(context);
645                    (lib.pa_threaded_mainloop_free)(mainloop);
646                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
647                    return;
648                }
649
650                loop {
651                    let st = (lib.pa_stream_get_state)(stream);
652                    if st == PA_STREAM_READY {
653                        break;
654                    }
655                    if st == PA_STREAM_FAILED || st == PA_STREAM_TERMINATED {
656                        (lib.pa_stream_set_state_callback)(stream, None, std::ptr::null_mut());
657                        (lib.pa_stream_set_read_callback)(stream, None, std::ptr::null_mut());
658                        (lib.pa_stream_unref)(stream);
659                        (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
660                        (lib.pa_context_disconnect)(context);
661                        (lib.pa_threaded_mainloop_unlock)(mainloop);
662                        (lib.pa_threaded_mainloop_stop)(mainloop);
663                        (lib.pa_context_unref)(context);
664                        (lib.pa_threaded_mainloop_free)(mainloop);
665                        let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
666                        return;
667                    }
668                    (lib.pa_threaded_mainloop_wait)(mainloop);
669                }
670                loop {
671                    let mut data_ptr: *const c_void = std::ptr::null();
672                    let mut nbytes: usize = 0;
673                    if (lib.pa_stream_peek)(stream, &mut data_ptr, &mut nbytes) < 0 || nbytes == 0 {
674                        break;
675                    }
676                    let _ = (lib.pa_stream_drop)(stream);
677                }
678                (lib.pa_threaded_mainloop_unlock)(mainloop);
679
680                let _ = ready_tx.send(Ok(()));
681
682                while !stop_worker.load(SeqCst)
683                    && !read_ctx.producer.control_handle().stopping()
684                    && !read_ctx.failed.load(SeqCst)
685                {
686                    thread::sleep(Duration::from_millis(5));
687                }
688
689                (lib.pa_threaded_mainloop_lock)(mainloop);
690                (lib.pa_stream_set_read_callback)(stream, None, std::ptr::null_mut());
691                (lib.pa_stream_set_state_callback)(stream, None, std::ptr::null_mut());
692                let _ = (lib.pa_stream_disconnect)(stream);
693                (lib.pa_stream_unref)(stream);
694                (lib.pa_context_set_state_callback)(context, None, std::ptr::null_mut());
695                (lib.pa_context_disconnect)(context);
696                (lib.pa_threaded_mainloop_unlock)(mainloop);
697                (lib.pa_threaded_mainloop_stop)(mainloop);
698                (lib.pa_context_unref)(context);
699                (lib.pa_threaded_mainloop_free)(mainloop);
700
701                if read_ctx.failed.load(SeqCst) {
702                    let _ = ended_worker.compare_exchange(0, 3, SeqCst, SeqCst);
703                    read_ctx.producer.fail_capture(Failure::Backend);
704                } else {
705                    let _ = ended_worker.compare_exchange(0, 1, SeqCst, SeqCst);
706                }
707                read_ctx.producer.close();
708                ready_worker.notify();
709            }
710        });
711
712        match ready_rx.recv_timeout(Duration::from_secs(5)) {
713            Ok(Ok(())) => {
714                let control = reader.control_handle();
715                Ok(PulseStream {
716                    format,
717                    trace,
718                    reads: ReadStream::new(reader),
719                    control,
720                    default_cancel: Cancellation::default(),
721                    armed,
722                    stop,
723                    ready,
724                    ended,
725                    server_kind,
726                    worker: Mutex::new(Some(worker)),
727                    _reservation: retained_reservation,
728                })
729            }
730            Ok(Err(err)) => {
731                stop.store(true, SeqCst);
732                let _ = worker.join();
733                Err(err)
734            }
735            Err(_) => {
736                stop.store(true, SeqCst);
737                let _ = worker.join();
738                Err(CapabilityError::ServerUnavailable)
739            }
740        }
741    }
742}
743
744#[cfg(target_os = "linux")]
745pub use imp::{open_pulse_point, open_pulse_source_point};
746
747#[cfg(not(target_os = "linux"))]
748pub fn open_pulse_source_point(
749    paths: &LinuxClientPaths,
750    _source_name: Option<&str>,
751    _format_override: Option<Format>,
752    _overflow: Overflow,
753    _timing: TimingRequirement,
754    _budget: &StorageBudget,
755    _observed: bool,
756) -> Result<PulseStream, CapabilityError> {
757    let _ = (
758        collect_pulse_full_state,
759        probe_pulse_server,
760        linux_endpoint_clock_domain("stub"),
761    );
762    Err(
763        crate::loader::ClientLoadError::LibraryAbsent(paths.pulse_so.clone())
764            .into_capability_error(BackendId::PulseAudio, paths.pulse_min_version),
765    )
766}
767
768#[cfg(not(target_os = "linux"))]
769pub fn open_pulse_point(
770    paths: &LinuxClientPaths,
771    _monitor_source: Option<&str>,
772    _monitor_sink_input_index: Option<u32>,
773    _overflow: Overflow,
774    _timing: TimingRequirement,
775    _budget: &StorageBudget,
776    _observed: bool,
777) -> Result<PulseStream, CapabilityError> {
778    let _ = (
779        POOL_SLOTS,
780        QUEUE_SLOTS,
781        MAX_FRAMES_PER_SLOT,
782        SESSION_METADATA_BYTES,
783        PulseServerKind::StandalonePulseAudio,
784        Channel::FrontLeft,
785        ByteOrder::Little,
786        Layout::Unknown,
787        SampleType::F32,
788        StorageLimits::new(8, 4096, 8, 262_144),
789        Pool::new_reserved,
790        ordering::channel,
791        ReadStream::new,
792        publish_linux_packet
793            as fn(
794                &mut Producer,
795                &[u8],
796                bool,
797                bool,
798                usize,
799                Option<u64>,
800                u64,
801                &mut u64,
802                &mut u64,
803                &mut u64,
804                Overflow,
805                Option<Instant>,
806            ),
807    );
808    Err(
809        crate::loader::ClientLoadError::LibraryAbsent(paths.pulse_so.clone())
810            .into_capability_error(BackendId::PulseAudio, paths.pulse_min_version),
811    )
812}
813
814/// Single-session stream backed by PipeWire or PulseAudio.
815pub enum PlatformStream {
816    PipeWire(PipeWireStream),
817    Pulse(PulseStream),
818}
819
820impl PlatformStream {
821    pub fn open(target: &CaptureTarget, overflow: Overflow) -> Result<Self, CapabilityError> {
822        Self::open_with_options(
823            target,
824            ProcessTreeRange::default(),
825            &Backends::default(),
826            overflow,
827            TimingRequirement::Raw,
828        )
829    }
830
831    pub fn open_with_options(
832        target: &CaptureTarget,
833        tree_range: ProcessTreeRange,
834        backends: &Backends,
835        overflow: Overflow,
836        timing: TimingRequirement,
837    ) -> Result<Self, CapabilityError> {
838        Self::open_with_permission_policy(
839            target,
840            tree_range,
841            backends,
842            overflow,
843            timing,
844            crate::core::schema::PermissionPolicy::AutoRequest,
845        )
846    }
847
848    pub fn open_with_permission_policy(
849        target: &CaptureTarget,
850        tree_range: ProcessTreeRange,
851        backends: &Backends,
852        overflow: Overflow,
853        timing: TimingRequirement,
854        _permission_policy: crate::core::schema::PermissionPolicy,
855    ) -> Result<Self, CapabilityError> {
856        target.validate()?;
857        tree_range.validate()?;
858        backends.validate()?;
859        if timing == TimingRequirement::Precise {
860            return Err(CapabilityError::PreciseTimingUnqualified);
861        }
862        if matches!(target.kind(), TargetKind::Process | TargetKind::Application) {
863            return Err(CapabilityError::NotImplemented);
864        }
865
866        let linux_backends = backends.for_os(PlatformOs::Linux);
867        if linux_backends.is_empty() {
868            return Err(CapabilityError::InvalidBackend);
869        }
870        let pinned_slice;
871        let candidates: &[BackendId] = match target.backend() {
872            Some(b @ (BackendId::PipeWire | BackendId::PulseAudio)) => {
873                pinned_slice = [b];
874                &pinned_slice
875            }
876            Some(_) => return Err(CapabilityError::InvalidBackend),
877            None => linux_backends,
878        };
879
880        let paths = LinuxClientPaths::default();
881        crate::permissions::ensure_linux_socket_permissions(backends, &paths)?;
882        let budget = StorageBudget::new(2, AggregateManagerBudgets::default().max_total_pcm_memory)
883            .map_err(|_| CapabilityError::CapacityExceeded)?;
884        let clean_id = target.clean_device_id();
885        let mut first_err: Option<CapabilityError> = None;
886
887        for &backend in candidates {
888            let res = match (backend, target.kind()) {
889                (BackendId::PipeWire, TargetKind::Device | TargetKind::DefaultOutput) => {
890                    let dev = clean_id
891                        .map(str::to_owned)
892                        .or_else(|| query_linux_default_sink_now(BackendId::PipeWire, &paths));
893                    open_pipewire_point(
894                        &paths,
895                        dev.as_deref(),
896                        true,
897                        overflow,
898                        timing,
899                        &budget,
900                        false,
901                    )
902                    .map(Self::PipeWire)
903                }
904                (BackendId::PipeWire, TargetKind::InputDevice | TargetKind::DefaultInput) => {
905                    open_pipewire_source_point(
906                        &paths, clean_id, None, overflow, timing, &budget, false,
907                    )
908                    .map(Self::PipeWire)
909                }
910                (BackendId::PulseAudio, TargetKind::Device | TargetKind::DefaultOutput) => {
911                    open_pulse_point(&paths, clean_id, None, overflow, timing, &budget, false)
912                        .map(Self::Pulse)
913                }
914                (BackendId::PulseAudio, TargetKind::InputDevice | TargetKind::DefaultInput) => {
915                    open_pulse_source_point(
916                        &paths, clean_id, None, overflow, timing, &budget, false,
917                    )
918                    .map(Self::Pulse)
919                }
920                _ => Err(CapabilityError::NotImplemented),
921            };
922            match res {
923                Ok(stream) => return Ok(stream),
924                Err(err) => {
925                    let allow_fb = err.allows_cross_backend_fallback();
926                    if first_err.is_none() {
927                        first_err = Some(err.clone());
928                    }
929                    if !allow_fb {
930                        return Err(err);
931                    }
932                }
933            }
934        }
935
936        Err(first_err.unwrap_or(CapabilityError::NotImplemented))
937    }
938
939    pub(crate) fn arm(&self) {
940        match self {
941            Self::PipeWire(s) => s.arm(),
942            Self::Pulse(s) => s.arm(),
943        }
944    }
945
946    #[cfg(any(test, feature = "native-tests"))]
947    pub fn pulse_server_kind(&self) -> Option<PulseServerKind> {
948        match self {
949            Self::PipeWire(_) => None,
950            Self::Pulse(s) => Some(s.server_kind()),
951        }
952    }
953}
954
955impl AudioStreamBackend for PlatformStream {
956    #[inline]
957    fn format(&self) -> &Arc<Format> {
958        match self {
959            Self::PipeWire(s) => s.format(),
960            Self::Pulse(s) => s.format(),
961        }
962    }
963
964    #[inline]
965    fn trace(&self) -> Option<&Arc<Trace>> {
966        match self {
967            Self::PipeWire(s) => s.trace(),
968            Self::Pulse(s) => s.trace(),
969        }
970    }
971
972    #[inline]
973    fn control_handle(&self) -> ControlHandle {
974        match self {
975            Self::PipeWire(s) => s.control_handle(),
976            Self::Pulse(s) => s.control_handle(),
977        }
978    }
979
980    #[inline]
981    fn default_cancel(&self) -> Cancellation {
982        match self {
983            Self::PipeWire(s) => s.default_cancel(),
984            Self::Pulse(s) => s.default_cancel(),
985        }
986    }
987
988    #[inline]
989    fn end_reason(&self) -> Option<EndReason> {
990        match self {
991            Self::PipeWire(s) => s.end_reason(),
992            Self::Pulse(s) => s.end_reason(),
993        }
994    }
995
996    #[inline]
997    fn read_with_cancel(
998        &mut self,
999        frames: usize,
1000        timeout: Duration,
1001        cancel: Cancellation,
1002    ) -> Result<ReadResult, ReadError> {
1003        match self {
1004            Self::PipeWire(s) => s.read_with_cancel(frames, timeout, cancel),
1005            Self::Pulse(s) => s.read_with_cancel(frames, timeout, cancel),
1006        }
1007    }
1008
1009    #[inline]
1010    fn read_into_with_cancel(
1011        &mut self,
1012        destination: &mut [u8],
1013        frames: usize,
1014        timeout: Duration,
1015        cancel: Cancellation,
1016    ) -> Result<ReadResult, ReadError> {
1017        match self {
1018            Self::PipeWire(s) => s.read_into_with_cancel(destination, frames, timeout, cancel),
1019            Self::Pulse(s) => s.read_into_with_cancel(destination, frames, timeout, cancel),
1020        }
1021    }
1022
1023    #[inline]
1024    fn stop(&self, mode: Stop) {
1025        match self {
1026            Self::PipeWire(s) => s.stop(mode),
1027            Self::Pulse(s) => s.stop(mode),
1028        }
1029    }
1030
1031    #[inline]
1032    fn resources_done(&self) -> bool {
1033        match self {
1034            Self::PipeWire(s) => s.resources_done(),
1035            Self::Pulse(s) => s.resources_done(),
1036        }
1037    }
1038
1039    #[inline]
1040    fn wait_cleanup(&self, timeout: Duration) -> bool {
1041        match self {
1042            Self::PipeWire(s) => s.wait_cleanup(timeout),
1043            Self::Pulse(s) => s.wait_cleanup(timeout),
1044        }
1045    }
1046}
1047
1048impl OpenableStreamBackend for PlatformStream {
1049    #[inline]
1050    fn open_with_permission_policy(
1051        target: &CaptureTarget,
1052        tree_range: ProcessTreeRange,
1053        backends: &Backends,
1054        overflow: Overflow,
1055        timing: TimingRequirement,
1056        permission_policy: crate::core::schema::PermissionPolicy,
1057    ) -> Result<Self, CapabilityError> {
1058        Self::open_with_permission_policy(
1059            target,
1060            tree_range,
1061            backends,
1062            overflow,
1063            timing,
1064            permission_policy,
1065        )
1066    }
1067}