Skip to main content

capture_system_or_process_audio_linux/
pipewire_stream.rs

1#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
2
3use crate::core::{
4    StorageLimits,
5    manager::{NativeTreeMixTopology, StorageBudget, StorageReservation},
6    measurements::Trace,
7    ordering::{self, ControlHandle, Failure, Overflow, Producer, Stop},
8    reads::{Cancellation, ReadError, ReadResult, ReadStream},
9    schema::{
10        BackendId, ByteOrder, CaptureTarget, Format, Header, Layout, Loss, ProcessIdentity,
11        ProcessScope, Provenance, SampleType, Stamp, TargetKind,
12    },
13    storage::Pool,
14    stream_runtime::{
15        EndReason, ReadySignal, StartupCleanup, StreamReadContext, endpoint_clock_domain,
16        poll_read_stream, poll_read_stream_into, signal_stream_stop,
17    },
18    traits::{AudioStreamBackend, CapabilityError, TimingRequirement, TopologyControllerBackend},
19};
20use crate::loader::LinuxClientPaths;
21use crate::procfs::{collect_proc_stat_table, inspect_process_in_proc_root, pid_belongs_to_target};
22use std::collections::BTreeMap;
23use std::path::Path;
24use std::sync::{
25    Arc, Mutex,
26    atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::SeqCst},
27};
28use std::thread::{self, JoinHandle};
29use std::time::{Duration, Instant};
30
31const POOL_SLOTS: usize = 8;
32const QUEUE_SLOTS: usize = 4;
33const MAX_FRAMES_PER_SLOT: usize = 4096;
34const SESSION_METADATA_BYTES: usize = 16_384;
35
36static MIX_SINK_COUNTER: AtomicU64 = AtomicU64::new(1);
37
38/// Manager-owned virtual sink and process membership controller; streams do not own it.
39pub struct PlatformTopologyController {
40    sink_name: String,
41    targets: Vec<CaptureTarget>,
42    shared_targets: Arc<Mutex<Vec<Option<CaptureTarget>>>>,
43    topology: Arc<Mutex<NativeTreeMixTopology>>,
44    dirty: Arc<AtomicBool>,
45    stop: Arc<AtomicBool>,
46    worker: Mutex<Option<JoinHandle<()>>>,
47    created_links_count: Arc<AtomicU64>,
48    active_links_count: Arc<AtomicU64>,
49}
50
51impl PlatformTopologyController {
52    pub fn sink_name(&self) -> &str {
53        &self.sink_name
54    }
55
56    pub fn created_links_count(&self) -> u64 {
57        self.created_links_count.load(SeqCst)
58    }
59
60    pub fn active_links_count(&self) -> u64 {
61        self.active_links_count.load(SeqCst)
62    }
63
64    pub fn is_finished(&self) -> bool {
65        let mut guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
66        if guard.as_ref().is_some_and(JoinHandle::is_finished)
67            && let Some(handle) = guard.take()
68        {
69            let _ = handle.join();
70        }
71        guard.is_none()
72    }
73
74    /// Update targets without reopening the stream, retaining shared links and unlinking retired ones.
75    pub fn update_targets(
76        &mut self,
77        new_targets: Vec<CaptureTarget>,
78    ) -> Result<Vec<Arc<str>>, CapabilityError> {
79        if new_targets.is_empty() {
80            return Err(CapabilityError::InvalidTarget);
81        }
82        for target in &new_targets {
83            if matches!(target.kind(), TargetKind::Process | TargetKind::Application) {
84                let pid = target.pid().ok_or(CapabilityError::InvalidTarget)?;
85                let expected_gen = target
86                    .process_start_time()
87                    .ok_or(CapabilityError::InvalidTarget)?;
88                let (stat, _) = inspect_process_in_proc_root(Path::new("/proc"), pid)?;
89                if expected_gen != 0 && stat.starttime_ticks != expected_gen {
90                    return Err(CapabilityError::PidReused);
91                }
92            }
93        }
94
95        let mut old_used = vec![false; self.targets.len()];
96        let mut mapping = Vec::with_capacity(new_targets.len());
97        for target in &new_targets {
98            let mut matched = None;
99            for (old_idx, old_target) in self.targets.iter().enumerate() {
100                if !old_used[old_idx]
101                    && old_target.logical_id() == target.logical_id()
102                    && old_target.scope() == target.scope()
103                {
104                    old_used[old_idx] = true;
105                    matched = Some(old_idx);
106                    break;
107                }
108            }
109            mapping.push(matched);
110        }
111
112        let unlinked = {
113            let mut shared = self
114                .shared_targets
115                .lock()
116                .unwrap_or_else(|e| e.into_inner());
117            let mut topo = self.topology.lock().unwrap_or_else(|e| e.into_inner());
118            let unlinked = topo.reconfigure_targets(&mapping);
119            *shared = new_targets.iter().cloned().map(Some).collect();
120            self.active_links_count
121                .store(topo.active_link_count() as u64, SeqCst);
122            unlinked
123        };
124        self.dirty.store(true, SeqCst);
125        self.targets = new_targets;
126        Ok(unlinked)
127    }
128}
129
130impl TopologyControllerBackend for PlatformTopologyController {
131    #[inline]
132    fn targets(&self) -> &[CaptureTarget] {
133        &self.targets
134    }
135
136    fn active_topology_link_count(&self) -> usize {
137        self.topology
138            .lock()
139            .unwrap_or_else(|e| e.into_inner())
140            .active_link_count()
141    }
142
143    fn retire_target(&self, target_index: usize) -> Vec<Arc<str>> {
144        if let Some(slot) = self
145            .shared_targets
146            .lock()
147            .unwrap_or_else(|e| e.into_inner())
148            .get_mut(target_index)
149        {
150            *slot = None;
151        }
152        let removed = self
153            .topology
154            .lock()
155            .unwrap_or_else(|e| e.into_inner())
156            .retire_target(target_index);
157        self.active_links_count.store(
158            self.topology
159                .lock()
160                .unwrap_or_else(|e| e.into_inner())
161                .active_link_count() as u64,
162            SeqCst,
163        );
164        self.dirty.store(true, SeqCst);
165        removed
166    }
167
168    fn shutdown(&self) {
169        self.stop.store(true, SeqCst);
170        if let Some(handle) = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take() {
171            let _ = handle.join();
172        }
173    }
174}
175
176impl Drop for PlatformTopologyController {
177    fn drop(&mut self) {
178        self.shutdown();
179    }
180}
181
182pub struct PipeWireStream {
183    format: Arc<Format>,
184    trace: Option<Arc<Trace>>,
185    reads: ReadStream,
186    control: ControlHandle,
187    default_cancel: Cancellation,
188    armed: Arc<AtomicBool>,
189    stop: Arc<AtomicBool>,
190    ready: Arc<ReadySignal>,
191    ended: Arc<AtomicU32>,
192    worker: Mutex<Option<JoinHandle<()>>>,
193    _reservation: StorageReservation,
194}
195
196impl PipeWireStream {
197    pub(crate) fn arm(&self) {
198        self.armed.store(true, SeqCst);
199    }
200
201    pub(crate) fn poll_read_with_cancel(
202        &self,
203        frames: usize,
204        timeout: Duration,
205        cancel: Cancellation,
206    ) -> Result<ReadResult, ReadError> {
207        self.arm();
208        let ctx = StreamReadContext {
209            reads: &self.reads,
210            ready: &self.ready,
211            trace: self.trace.as_ref(),
212        };
213        poll_read_stream(ctx, frames, timeout, cancel)
214    }
215
216    pub(crate) fn poll_read_into_with_cancel(
217        &self,
218        destination: &mut [u8],
219        frames: usize,
220        timeout: Duration,
221        cancel: Cancellation,
222    ) -> Result<ReadResult, ReadError> {
223        self.arm();
224        let ctx = StreamReadContext {
225            reads: &self.reads,
226            ready: &self.ready,
227            trace: self.trace.as_ref(),
228        };
229        poll_read_stream_into(
230            ctx,
231            self.format.clone(),
232            destination,
233            frames,
234            timeout,
235            cancel,
236        )
237    }
238
239    #[cfg(test)]
240    pub(crate) fn from_synthetic_packets(
241        format: Arc<Format>,
242        clock_domain: u64,
243        packets: Vec<(Vec<u8>, usize, u64)>,
244        budget: &StorageBudget,
245    ) -> Result<Self, CapabilityError> {
246        let stride = format.bytes_per_frame();
247        let limits = StorageLimits::new(
248            POOL_SLOTS,
249            MAX_FRAMES_PER_SLOT,
250            stride,
251            POOL_SLOTS * MAX_FRAMES_PER_SLOT * stride,
252        )
253        .map_err(|_| CapabilityError::CapacityExceeded)?;
254        let reservation = budget
255            .reserve(limits, 6024)
256            .map_err(|_| CapabilityError::CapacityExceeded)?;
257        let retained_reservation = reservation.retain();
258        let pool = Pool::new_reserved(limits, MAX_FRAMES_PER_SLOT, format.clone(), reservation)
259            .map_err(|_| CapabilityError::CapacityExceeded)?;
260        let (mut producer, reader) =
261            ordering::channel(pool, QUEUE_SLOTS).map_err(|_| CapabilityError::CapacityExceeded)?;
262        let control = reader.control_handle();
263        let stop = Arc::new(AtomicBool::new(false));
264        let stop_bg = stop.clone();
265        let ready = Arc::new(ReadySignal::new());
266        let ready_bg = ready.clone();
267        let ended = Arc::new(AtomicU32::new(0));
268        let ended_bg = ended.clone();
269        let worker = thread::spawn(move || {
270            let mut sequence = 0u64;
271            let mut segment = 1u64;
272            let mut cursor = 0u64;
273            for (bytes, frames, ts_ns) in packets {
274                if stop_bg.load(SeqCst) || producer.control_handle().stopping() {
275                    break;
276                }
277                while !stop_bg.load(SeqCst) && !producer.control_handle().stopping() {
278                    let snap = producer.control_handle().snapshot();
279                    if snap.queued < QUEUE_SLOTS as u64 {
280                        break;
281                    }
282                    thread::sleep(Duration::from_millis(1));
283                }
284                if stop_bg.load(SeqCst) || producer.control_handle().stopping() {
285                    break;
286                }
287                publish_linux_packet(
288                    &mut producer,
289                    &bytes,
290                    false,
291                    false,
292                    frames,
293                    Some(ts_ns),
294                    clock_domain,
295                    &mut sequence,
296                    &mut segment,
297                    &mut cursor,
298                    Overflow::DropOldest,
299                    None,
300                );
301                ready_bg.notify();
302            }
303            let _ = ended_bg.compare_exchange(0, 1, SeqCst, SeqCst);
304            producer.close();
305            ready_bg.notify();
306        });
307        Ok(Self {
308            format,
309            trace: None,
310            reads: ReadStream::new(reader),
311            control,
312            default_cancel: Cancellation::default(),
313            armed: Arc::new(AtomicBool::new(true)),
314            stop,
315            ready,
316            ended,
317            worker: Mutex::new(Some(worker)),
318            _reservation: retained_reservation,
319        })
320    }
321}
322
323impl AudioStreamBackend for PipeWireStream {
324    #[inline]
325    fn format(&self) -> &Arc<Format> {
326        &self.format
327    }
328
329    #[inline]
330    fn trace(&self) -> Option<&Arc<Trace>> {
331        self.trace.as_ref()
332    }
333
334    #[inline]
335    fn control_handle(&self) -> ControlHandle {
336        self.control.clone()
337    }
338
339    #[inline]
340    fn default_cancel(&self) -> Cancellation {
341        self.default_cancel.clone()
342    }
343
344    fn end_reason(&self) -> Option<EndReason> {
345        if let Some(failure) = self.control.snapshot().failure {
346            return Some(EndReason::Failed(failure));
347        }
348        match self.ended.load(SeqCst) {
349            1 => Some(EndReason::Stopped),
350            2 => Some(EndReason::TargetExited),
351            3 => Some(EndReason::Failed(Failure::Backend)),
352            _ => None,
353        }
354    }
355
356    fn read_with_cancel(
357        &mut self,
358        frames: usize,
359        timeout: Duration,
360        cancel: Cancellation,
361    ) -> Result<ReadResult, ReadError> {
362        self.poll_read_with_cancel(frames, timeout, cancel)
363    }
364
365    fn read_into_with_cancel(
366        &mut self,
367        destination: &mut [u8],
368        frames: usize,
369        timeout: Duration,
370        cancel: Cancellation,
371    ) -> Result<ReadResult, ReadError> {
372        self.poll_read_into_with_cancel(destination, frames, timeout, cancel)
373    }
374
375    fn stop(&self, mode: Stop) {
376        let _ = self.ended.compare_exchange(0, 1, SeqCst, SeqCst);
377        signal_stream_stop(&self.control, &self.stop, &self.ready, mode);
378    }
379
380    fn resources_done(&self) -> bool {
381        let mut guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
382        if guard.as_ref().is_some_and(JoinHandle::is_finished)
383            && let Some(handle) = guard.take()
384        {
385            let _ = handle.join();
386        }
387        guard.is_none()
388    }
389
390    fn wait_cleanup(&self, timeout: Duration) -> bool {
391        self.stop.store(true, SeqCst);
392        self.ready.notify();
393        let started = Instant::now();
394        while !self.resources_done() && started.elapsed() < timeout {
395            thread::sleep(Duration::from_millis(1));
396        }
397        self.resources_done()
398    }
399}
400
401impl Drop for PipeWireStream {
402    fn drop(&mut self) {
403        self.stop(Stop::Abort);
404    }
405}
406
407pub(crate) fn linux_endpoint_clock_domain(name: &str) -> u64 {
408    endpoint_clock_domain(name, 2)
409}
410
411#[allow(clippy::too_many_arguments)]
412pub(crate) fn publish_linux_packet(
413    producer: &mut Producer,
414    bytes: &[u8],
415    silent: bool,
416    discontinuity: bool,
417    frames: usize,
418    timestamp_ns: Option<u64>,
419    clock_domain: u64,
420    sequence: &mut u64,
421    segment: &mut u64,
422    frame_cursor: &mut u64,
423    policy: Overflow,
424    acquired: Option<Instant>,
425) {
426    if discontinuity {
427        *sequence = sequence.saturating_add(1);
428        *segment = segment.saturating_add(1);
429        let _ = producer.gap(
430            *sequence,
431            *segment,
432            Loss {
433                frames: None,
434                rate_hz: producer.pool().format().rate(),
435            },
436        );
437    }
438    *sequence = sequence.saturating_add(1);
439    if let Some(acq) = acquired
440        && let Some(trace) = producer.trace()
441    {
442        trace.record_at(crate::core::measurements::Stage::Acquired, *sequence, acq);
443    }
444    let pos = *frame_cursor;
445    *frame_cursor = frame_cursor.saturating_add(frames as u64);
446    let header = Header {
447        sequence: *sequence,
448        segment: *segment,
449        generation: producer.pool().generation(),
450        frames,
451        sample_position: Some(pos),
452        timestamp: timestamp_ns.filter(|&ns| ns > 0).map(|ns| Stamp {
453            ticks: ns,
454            ticks_per_second: 1_000_000_000,
455            clock_domain,
456            provenance: Provenance::Native,
457            uncertainty_ns: None,
458        }),
459    };
460    if silent {
461        let _ = producer.offer_silence(header, policy);
462    } else {
463        let _ = producer.offer(bytes, header, policy);
464    }
465}
466
467#[cfg(target_os = "linux")]
468#[allow(unsafe_code)]
469mod imp {
470    use super::*;
471    use crate::loader::{
472        PA_SAMPLE_FLOAT32LE, PA_SAMPLE_S16LE, PA_SAMPLE_S24LE, PA_SAMPLE_S32LE, PipeWireLibrary,
473        PwBuffer, PwClientEvents, PwClientInfo, PwNodeEvents, PwNodeInfo, PwRegistryEvents,
474        PwStreamEvents, PwTime, SpaDict, SpaHook, build_spa_audio_raw_pod,
475    };
476    use std::ffi::{CStr, c_char, c_int, c_uint, c_void};
477
478    const PW_DIRECTION_INPUT: c_uint = 0;
479    const PW_ID_ANY: u32 = 0xffff_ffff;
480    const PW_STREAM_FLAG_AUTOCONNECT: c_uint = 1 << 0;
481    const PW_STREAM_FLAG_MAP_BUFFERS: c_uint = 1 << 2;
482    const PW_STREAM_FLAG_RT_PROCESS: c_uint = 1 << 4;
483    const PW_STREAM_STATE_ERROR: c_int = -1;
484    const PW_STREAM_STATE_STREAMING: c_int = 4;
485    const SPA_CHUNK_FLAG_CORRUPTED: i32 = 1 << 0;
486    const SPA_CHUNK_FLAG_EMPTY: i32 = 1 << 1;
487
488    pub fn open_pipewire_point(
489        paths: &LinuxClientPaths,
490        target_object: Option<&str>,
491        capture_sink: bool,
492        overflow: Overflow,
493        timing: TimingRequirement,
494        budget: &StorageBudget,
495        observed: bool,
496    ) -> Result<PipeWireStream, CapabilityError> {
497        let format = Format::new(
498            SampleType::F32,
499            ByteOrder::Little,
500            48_000,
501            2,
502            Layout::Known(Arc::from([
503                crate::core::schema::Channel::FrontLeft,
504                crate::core::schema::Channel::FrontRight,
505            ])),
506        )
507        .map_err(|_| CapabilityError::InvalidTarget)?;
508        let clock_domain = if capture_sink {
509            1
510        } else {
511            linux_endpoint_clock_domain(target_object.unwrap_or("pw-default-source"))
512        };
513        open_pipewire_point_with_format(
514            paths,
515            target_object,
516            capture_sink,
517            format,
518            clock_domain,
519            overflow,
520            timing,
521            budget,
522            observed,
523        )
524    }
525
526    pub fn open_pipewire_source_point(
527        paths: &LinuxClientPaths,
528        source_name: Option<&str>,
529        format_override: Option<Format>,
530        overflow: Overflow,
531        timing: TimingRequirement,
532        budget: &StorageBudget,
533        observed: bool,
534    ) -> Result<PipeWireStream, CapabilityError> {
535        if timing == TimingRequirement::Precise {
536            return Err(CapabilityError::PreciseTimingUnqualified);
537        }
538        if source_name.is_some_and(|s| s.is_empty() || s.ends_with(".monitor")) {
539            return Err(CapabilityError::InvalidTarget);
540        }
541        let graph = crate::discovery::collect_pipewire_graph(paths)?;
542        let resolved_name = match source_name {
543            Some(explicit) => {
544                if !graph.sources.iter().any(|(_, n, _)| n == explicit) {
545                    return Err(CapabilityError::InvalidTarget);
546                }
547                explicit.to_owned()
548            }
549            None => graph
550                .default_source_name
551                .ok_or(CapabilityError::ServerUnavailable)?,
552        };
553
554        let resolved_format = match format_override {
555            Some(fmt) => fmt,
556            None => {
557                let pa_match = crate::discovery::collect_pulse_full_state(paths)
558                    .ok()
559                    .and_then(|(_, sources, _, _)| {
560                        sources
561                            .into_iter()
562                            .find(|s| !s.is_monitor && s.name == resolved_name)
563                    });
564                if let Some(src) = pa_match {
565                    let sample = match src.sample_format {
566                        PA_SAMPLE_S16LE => SampleType::I16,
567                        PA_SAMPLE_S24LE => SampleType::I24,
568                        PA_SAMPLE_S32LE => SampleType::I32,
569                        PA_SAMPLE_FLOAT32LE => SampleType::F32,
570                        _ => SampleType::F32,
571                    };
572                    let (ch, layout) = if src.channels == 1 {
573                        (
574                            1u16,
575                            Layout::Known(Arc::from([crate::core::schema::Channel::Mono])),
576                        )
577                    } else {
578                        (
579                            2u16,
580                            Layout::Known(Arc::from([
581                                crate::core::schema::Channel::FrontLeft,
582                                crate::core::schema::Channel::FrontRight,
583                            ])),
584                        )
585                    };
586                    let rate = if (8_000..=192_000).contains(&src.rate_hz) {
587                        src.rate_hz
588                    } else {
589                        48_000
590                    };
591                    Format::new(sample, ByteOrder::Little, rate, ch, layout)
592                        .map_err(|_| CapabilityError::InvalidTarget)?
593                } else {
594                    Format::new(
595                        SampleType::F32,
596                        ByteOrder::Little,
597                        48_000,
598                        2,
599                        Layout::Known(Arc::from([
600                            crate::core::schema::Channel::FrontLeft,
601                            crate::core::schema::Channel::FrontRight,
602                        ])),
603                    )
604                    .map_err(|_| CapabilityError::InvalidTarget)?
605                }
606            }
607        };
608
609        open_pipewire_point_with_format(
610            paths,
611            Some(&resolved_name),
612            false,
613            resolved_format,
614            linux_endpoint_clock_domain(&resolved_name),
615            overflow,
616            timing,
617            budget,
618            observed,
619        )
620    }
621
622    #[allow(clippy::too_many_arguments)]
623    pub fn open_pipewire_point_with_format(
624        paths: &LinuxClientPaths,
625        target_object: Option<&str>,
626        capture_sink: bool,
627        format: Format,
628        clock_domain: u64,
629        overflow: Overflow,
630        timing: TimingRequirement,
631        budget: &StorageBudget,
632        observed: bool,
633    ) -> Result<PipeWireStream, CapabilityError> {
634        if timing == TimingRequirement::Precise {
635            return Err(CapabilityError::PreciseTimingUnqualified);
636        }
637        if !capture_sink && target_object.is_some_and(|t| t.ends_with(".monitor")) {
638            return Err(CapabilityError::InvalidTarget);
639        }
640        if capture_sink
641            && let Some(explicit_sink) = target_object
642            && !explicit_sink.starts_with("cspa-mix-")
643            && let Ok(graph) = crate::discovery::collect_pipewire_graph(paths)
644            && !graph.sinks.iter().any(|(_, n, _)| n == explicit_sink)
645        {
646            return Err(CapabilityError::InvalidTarget);
647        }
648        let pod = build_spa_audio_raw_pod(format.sample(), format.rate(), format.channels())?;
649        let lib = Arc::new(PipeWireLibrary::load(paths).map_err(|err| {
650            err.into_capability_error(BackendId::PipeWire, paths.pipewire_min_version)
651        })?);
652        let format = Arc::new(format);
653        let stride = format.bytes_per_frame();
654        let limits = StorageLimits::new(
655            POOL_SLOTS,
656            MAX_FRAMES_PER_SLOT,
657            stride,
658            POOL_SLOTS * MAX_FRAMES_PER_SLOT * stride,
659        )
660        .map_err(|_| CapabilityError::CapacityExceeded)?;
661        let trace = if observed {
662            Some(Arc::new(Trace::new_compact()))
663        } else {
664            None
665        };
666        let metadata_bytes = trace.as_ref().map_or(6024usize, |t| {
667            6024usize
668                .saturating_add(t.storage_bytes())
669                .min(SESSION_METADATA_BYTES)
670        });
671        let reservation = budget
672            .reserve(limits, metadata_bytes)
673            .map_err(|_| CapabilityError::CapacityExceeded)?;
674        let retained_reservation = reservation.retain();
675        let pool = Pool::new_reserved(limits, MAX_FRAMES_PER_SLOT, format.clone(), reservation)
676            .map_err(|_| CapabilityError::CapacityExceeded)?;
677        let (producer, reader) = if let Some(ref tr) = trace {
678            ordering::channel_observed(pool, QUEUE_SLOTS, tr.clone())
679        } else {
680            ordering::channel(pool, QUEUE_SLOTS)
681        }
682        .map_err(|_| CapabilityError::CapacityExceeded)?;
683
684        let armed = Arc::new(AtomicBool::new(false));
685        let stop = Arc::new(AtomicBool::new(false));
686        let ready = Arc::new(ReadySignal::default());
687        let ended = Arc::new(AtomicU32::new(0));
688        let armed_worker = armed.clone();
689        let stop_worker = stop.clone();
690        let ready_worker = ready.clone();
691        let ended_worker = ended.clone();
692        let target_str = target_object.map(str::to_owned);
693        let (init_tx, init_rx) = std::sync::mpsc::sync_channel::<Result<(), CapabilityError>>(1);
694
695        let worker = thread::spawn(move || {
696            struct RtContext {
697                stream: *mut c_void,
698                dequeue_fn: unsafe extern "C" fn(*mut c_void) -> *mut PwBuffer,
699                queue_fn: unsafe extern "C" fn(*mut c_void, *mut PwBuffer) -> c_int,
700                get_time_fn: unsafe extern "C" fn(*mut c_void, *mut PwTime, usize) -> c_int,
701                producer: Producer,
702                policy: Overflow,
703                armed: Arc<AtomicBool>,
704                ready: Arc<ReadySignal>,
705                clock_domain: u64,
706                sequence: u64,
707                segment: u64,
708                frame_cursor: u64,
709                failed: AtomicBool,
710                streaming: AtomicBool,
711            }
712
713            unsafe extern "C" fn on_state_changed(
714                data: *mut c_void,
715                _old: c_int,
716                state: c_int,
717                _error: *const c_char,
718            ) {
719                // SAFETY: `data` points to `RtContext`.
720                unsafe {
721                    let ctx = &*(data as *const RtContext);
722                    if state == PW_STREAM_STATE_STREAMING {
723                        ctx.streaming.store(true, SeqCst);
724                    } else if state == PW_STREAM_STATE_ERROR {
725                        ctx.failed.store(true, SeqCst);
726                    }
727                }
728            }
729
730            unsafe extern "C" fn on_process(data: *mut c_void) {
731                // SAFETY: `data` points to `RtContext` pinned for the stream's lifetime;
732                // no heap allocations occur inside this RT callback.
733                unsafe {
734                    let ctx = &mut *(data as *mut RtContext);
735                    ctx.streaming.store(true, SeqCst);
736                    let buf = (ctx.dequeue_fn)(ctx.stream);
737                    if buf.is_null() {
738                        return;
739                    }
740                    if !ctx.armed.load(SeqCst) {
741                        let _ = (ctx.queue_fn)(ctx.stream, buf);
742                        return;
743                    }
744                    let acquired = ctx.producer.trace().map(|_| Instant::now());
745                    let pw_buf = &*buf;
746                    if !pw_buf.buffer.is_null() {
747                        let spa_buf = &*pw_buf.buffer;
748                        if spa_buf.n_datas >= 1 && !spa_buf.datas.is_null() {
749                            let plane = &*spa_buf.datas;
750                            if !plane.chunk.is_null() {
751                                let chunk = &*plane.chunk;
752                                let bytes = chunk.size as usize;
753                                let offset = chunk.offset as usize;
754                                let bpf = ctx.producer.pool().format().bytes_per_frame();
755                                if bytes > 0 && bytes.is_multiple_of(bpf) {
756                                    let total_frames = bytes / bpf;
757                                    let mut time_info = PwTime::default();
758                                    let ts_ns = if (ctx.get_time_fn)(
759                                        ctx.stream,
760                                        &mut time_info,
761                                        std::mem::size_of::<PwTime>(),
762                                    ) == 0
763                                        && time_info.now > 0
764                                    {
765                                        Some(time_info.now as u64)
766                                    } else {
767                                        None
768                                    };
769                                    let is_empty = (chunk.flags & SPA_CHUNK_FLAG_EMPTY) != 0
770                                        || plane.data.is_null();
771                                    let is_corrupt = (chunk.flags & SPA_CHUNK_FLAG_CORRUPTED) != 0;
772                                    let mut rem = total_frames;
773                                    let mut byte_off = offset;
774                                    let mut first = true;
775                                    while rem > 0 {
776                                        let chunk_frames = rem.min(MAX_FRAMES_PER_SLOT);
777                                        let chunk_bytes = chunk_frames * bpf;
778                                        if is_empty {
779                                            publish_linux_packet(
780                                                &mut ctx.producer,
781                                                &[],
782                                                true,
783                                                first && is_corrupt,
784                                                chunk_frames,
785                                                ts_ns,
786                                                ctx.clock_domain,
787                                                &mut ctx.sequence,
788                                                &mut ctx.segment,
789                                                &mut ctx.frame_cursor,
790                                                ctx.policy,
791                                                acquired,
792                                            );
793                                        } else if byte_off
794                                            .checked_add(chunk_bytes)
795                                            .is_some_and(|end| end <= plane.maxsize as usize)
796                                        {
797                                            let src_ptr = (plane.data as *const u8).add(byte_off);
798                                            let slice =
799                                                std::slice::from_raw_parts(src_ptr, chunk_bytes);
800                                            publish_linux_packet(
801                                                &mut ctx.producer,
802                                                slice,
803                                                false,
804                                                first && is_corrupt,
805                                                chunk_frames,
806                                                ts_ns,
807                                                ctx.clock_domain,
808                                                &mut ctx.sequence,
809                                                &mut ctx.segment,
810                                                &mut ctx.frame_cursor,
811                                                ctx.policy,
812                                                acquired,
813                                            );
814                                        }
815                                        first = false;
816                                        rem -= chunk_frames;
817                                        byte_off += chunk_bytes;
818                                    }
819                                    ctx.ready.notify();
820                                }
821                            }
822                        }
823                    }
824                    let _ = (ctx.queue_fn)(ctx.stream, buf);
825                }
826            }
827
828            // SAFETY: owns `pw_thread_loop`, `pw_context`, `pw_core`, and `pw_stream` for this session.
829            unsafe {
830                let tloop = (lib.pw_thread_loop_new)(c"cspa-pw-stream".as_ptr(), std::ptr::null());
831                if tloop.is_null() {
832                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
833                    return;
834                }
835                let loop_obj = (lib.pw_thread_loop_get_loop)(tloop);
836                let context = (lib.pw_context_new)(loop_obj, std::ptr::null_mut(), 0);
837                if context.is_null() || (lib.pw_thread_loop_start)(tloop) < 0 {
838                    if !context.is_null() {
839                        (lib.pw_context_destroy)(context);
840                    }
841                    (lib.pw_thread_loop_destroy)(tloop);
842                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
843                    return;
844                }
845                (lib.pw_thread_loop_lock)(tloop);
846                let core = (lib.pw_context_connect)(context, std::ptr::null_mut(), 0);
847                if core.is_null() {
848                    (lib.pw_thread_loop_unlock)(tloop);
849                    (lib.pw_thread_loop_stop)(tloop);
850                    (lib.pw_context_destroy)(context);
851                    (lib.pw_thread_loop_destroy)(tloop);
852                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
853                    return;
854                }
855
856                let mut prop_pairs = vec![
857                    ("media.type", "Audio"),
858                    ("media.category", "Capture"),
859                    ("node.want-driver", "false"),
860                    ("node.dont-reconnect", "true"),
861                ];
862                if capture_sink {
863                    prop_pairs.push(("stream.capture.sink", "true"));
864                }
865                if let Some(ref target) = target_str {
866                    prop_pairs.push(("target.object", target.as_str()));
867                }
868                let props = lib.new_properties(&prop_pairs);
869                let stream = (lib.pw_stream_new)(core, c"cspa-capture".as_ptr(), props);
870                if stream.is_null() {
871                    (lib.pw_core_disconnect)(core);
872                    (lib.pw_thread_loop_unlock)(tloop);
873                    (lib.pw_thread_loop_stop)(tloop);
874                    (lib.pw_context_destroy)(context);
875                    (lib.pw_thread_loop_destroy)(tloop);
876                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
877                    return;
878                }
879
880                let mut rt_ctx = Box::new(RtContext {
881                    stream,
882                    dequeue_fn: lib.pw_stream_dequeue_buffer,
883                    queue_fn: lib.pw_stream_queue_buffer,
884                    get_time_fn: lib.pw_stream_get_time_n,
885                    producer,
886                    policy: overflow,
887                    armed: armed_worker,
888                    ready: ready_worker.clone(),
889                    clock_domain,
890                    sequence: 0,
891                    segment: 1,
892                    frame_cursor: 0,
893                    failed: AtomicBool::new(false),
894                    streaming: AtomicBool::new(false),
895                });
896                let events = PwStreamEvents {
897                    version: 2,
898                    destroy: None,
899                    state_changed: Some(on_state_changed),
900                    control_info: None,
901                    io_changed: None,
902                    param_changed: None,
903                    add_buffer: None,
904                    remove_buffer: None,
905                    process: Some(on_process),
906                    drained: None,
907                    command: None,
908                    trigger_done: None,
909                };
910                let mut stream_hook = SpaHook::default();
911                let rt_ptr: *mut c_void = (&mut *rt_ctx as *mut RtContext).cast();
912                (lib.pw_stream_add_listener)(stream, &mut stream_hook, &events, rt_ptr);
913
914                let mut params: [*const c_void; 1] = [pod.0.as_ptr().cast()];
915                let flags = PW_STREAM_FLAG_AUTOCONNECT
916                    | PW_STREAM_FLAG_MAP_BUFFERS
917                    | PW_STREAM_FLAG_RT_PROCESS;
918                let conn_rc = (lib.pw_stream_connect)(
919                    stream,
920                    PW_DIRECTION_INPUT,
921                    PW_ID_ANY,
922                    flags,
923                    params.as_mut_ptr(),
924                    1,
925                );
926                (lib.pw_thread_loop_unlock)(tloop);
927
928                if conn_rc < 0 {
929                    (lib.pw_thread_loop_stop)(tloop);
930                    (lib.pw_stream_destroy)(stream);
931                    (lib.pw_core_disconnect)(core);
932                    (lib.pw_context_destroy)(context);
933                    (lib.pw_thread_loop_destroy)(tloop);
934                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
935                    return;
936                }
937
938                let start_wait = Instant::now();
939                while !rt_ctx.streaming.load(SeqCst)
940                    && !rt_ctx.failed.load(SeqCst)
941                    && start_wait.elapsed() < Duration::from_secs(3)
942                {
943                    thread::sleep(Duration::from_millis(5));
944                }
945                if rt_ctx.failed.load(SeqCst) {
946                    (lib.pw_thread_loop_stop)(tloop);
947                    (lib.pw_stream_destroy)(stream);
948                    (lib.pw_core_disconnect)(core);
949                    (lib.pw_context_destroy)(context);
950                    (lib.pw_thread_loop_destroy)(tloop);
951                    let _ = init_tx.send(Err(CapabilityError::ServerUnavailable));
952                    return;
953                }
954
955                let _ = init_tx.send(Ok(()));
956
957                while !stop_worker.load(SeqCst)
958                    && !rt_ctx.producer.control_handle().stopping()
959                    && !rt_ctx.failed.load(SeqCst)
960                {
961                    thread::sleep(Duration::from_millis(5));
962                }
963
964                (lib.pw_thread_loop_lock)(tloop);
965                let _ = (lib.pw_stream_disconnect)(stream);
966                (lib.pw_thread_loop_unlock)(tloop);
967                (lib.pw_thread_loop_stop)(tloop);
968
969                if rt_ctx.failed.load(SeqCst) {
970                    let _ = ended_worker.compare_exchange(0, 3, SeqCst, SeqCst);
971                    rt_ctx.producer.fail_capture(Failure::Backend);
972                } else {
973                    let _ = ended_worker.compare_exchange(0, 1, SeqCst, SeqCst);
974                }
975                rt_ctx.producer.close();
976                ready_worker.notify();
977
978                (lib.pw_stream_destroy)(stream);
979                (lib.pw_core_disconnect)(core);
980                (lib.pw_context_destroy)(context);
981                (lib.pw_thread_loop_destroy)(tloop);
982            }
983        });
984
985        match init_rx.recv_timeout(Duration::from_secs(5)) {
986            Ok(Ok(())) => {
987                let control = reader.control_handle();
988                Ok(PipeWireStream {
989                    format,
990                    trace,
991                    reads: ReadStream::new(reader),
992                    control,
993                    default_cancel: Cancellation::default(),
994                    armed,
995                    stop,
996                    ready,
997                    ended,
998                    worker: Mutex::new(Some(worker)),
999                    _reservation: retained_reservation,
1000                })
1001            }
1002            Ok(Err(err)) => {
1003                stop.store(true, SeqCst);
1004                let _ = worker.join();
1005                Err(err)
1006            }
1007            Err(_) => {
1008                stop.store(true, SeqCst);
1009                let cleanup = StartupCleanup::new(stop, worker);
1010                let _ = cleanup.wait(Duration::from_millis(500));
1011                Err(CapabilityError::ServerUnavailable)
1012            }
1013        }
1014    }
1015
1016    /// Start a `Manager`-owned `PlatformTopologyController` that creates a virtual
1017    /// `support.null-audio-sink` and maintains passive non-lingering `FL`/`FR` port links
1018    /// for all eligible nodes matching `targets` (`scope = "tree" | "exact"`).
1019    pub fn start_pipewire_topology_controller(
1020        paths: &LinuxClientPaths,
1021        targets: Vec<CaptureTarget>,
1022        max_links: usize,
1023    ) -> Result<PlatformTopologyController, CapabilityError> {
1024        if targets.is_empty() {
1025            return Err(CapabilityError::InvalidTarget);
1026        }
1027        for target in &targets {
1028            if matches!(target.kind(), TargetKind::Process | TargetKind::Application) {
1029                let pid = target.pid().ok_or(CapabilityError::InvalidTarget)?;
1030                let expected_gen = target
1031                    .process_start_time()
1032                    .ok_or(CapabilityError::InvalidTarget)?;
1033                let (stat, _) = inspect_process_in_proc_root(Path::new("/proc"), pid)?;
1034                if expected_gen != 0 && stat.starttime_ticks != expected_gen {
1035                    return Err(CapabilityError::PidReused);
1036                }
1037            }
1038        }
1039
1040        let lib = Arc::new(PipeWireLibrary::load(paths).map_err(|err| {
1041            err.into_capability_error(BackendId::PipeWire, paths.pipewire_min_version)
1042        })?);
1043        let seq = MIX_SINK_COUNTER.fetch_add(1, SeqCst);
1044        let sink_name = format!("cspa-mix-{}-{seq}", std::process::id());
1045        let topology = Arc::new(Mutex::new(
1046            NativeTreeMixTopology::new(max_links.clamp(1, 256))
1047                .map_err(|_| CapabilityError::CapacityExceeded)?,
1048        ));
1049        let dirty = Arc::new(AtomicBool::new(true));
1050        let stop = Arc::new(AtomicBool::new(false));
1051        let created_links_count = Arc::new(AtomicU64::new(0));
1052        let active_links_count = Arc::new(AtomicU64::new(0));
1053
1054        let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel::<Result<(), CapabilityError>>(1);
1055        let sink_name_worker = sink_name.clone();
1056        let shared_targets: Arc<Mutex<Vec<Option<CaptureTarget>>>> =
1057            Arc::new(Mutex::new(targets.iter().cloned().map(Some).collect()));
1058        let targets_worker = shared_targets.clone();
1059        let topology_worker = topology.clone();
1060        let dirty_worker = dirty.clone();
1061        let stop_worker = stop.clone();
1062        let created_worker = created_links_count.clone();
1063        let active_worker = active_links_count.clone();
1064
1065        let worker = thread::spawn(move || {
1066            struct BoundObj {
1067                proxy: *mut c_void,
1068                _hook: Box<SpaHook>,
1069            }
1070
1071            struct GraphState<'a> {
1072                lib: &'a PipeWireLibrary,
1073                registry: *mut c_void,
1074                sink_name: String,
1075                sink_node_id: Option<u32>,
1076                sink_in_fl: Option<u32>,
1077                sink_in_fr: Option<u32>,
1078                client_app_pids: BTreeMap<u32, u32>,
1079                client_sec_pids: BTreeMap<u32, u32>,
1080                output_nodes: BTreeMap<u32, (Option<u32>, Option<u32>)>,
1081                output_ports: BTreeMap<u32, (u32, usize)>,
1082                bound_objs: BTreeMap<u32, BoundObj>,
1083                dirty: Arc<AtomicBool>,
1084            }
1085
1086            static NODE_EVENTS: PwNodeEvents = PwNodeEvents {
1087                version: 0,
1088                info: Some(on_node_info),
1089                param: None,
1090            };
1091
1092            static CLIENT_EVENTS: PwClientEvents = PwClientEvents {
1093                version: 0,
1094                info: Some(on_client_info),
1095                permissions: None,
1096            };
1097
1098            unsafe extern "C" fn on_node_info(data: *mut c_void, info: *const PwNodeInfo) {
1099                // SAFETY: `data` points to `GraphState` and `info` is valid during callback.
1100                unsafe {
1101                    if info.is_null() {
1102                        return;
1103                    }
1104                    let st = &mut *(data as *mut GraphState<'_>);
1105                    let inf = &*info;
1106                    if inf.props.is_null() {
1107                        return;
1108                    }
1109                    let app_pid = SpaDict::lookup(inf.props, "application.process.id")
1110                        .and_then(|s| s.trim().parse::<u32>().ok());
1111                    let client_id = SpaDict::lookup(inf.props, "client.id")
1112                        .and_then(|s| s.trim().parse::<u32>().ok());
1113                    let entry = st.output_nodes.entry(inf.id).or_insert((None, None));
1114                    if client_id.is_some() {
1115                        entry.0 = client_id;
1116                    }
1117                    if app_pid.is_some() {
1118                        entry.1 = app_pid;
1119                    }
1120                    st.dirty.store(true, SeqCst);
1121                }
1122            }
1123
1124            unsafe extern "C" fn on_client_info(data: *mut c_void, info: *const PwClientInfo) {
1125                // SAFETY: `data` points to `GraphState` and `info` is valid during callback.
1126                unsafe {
1127                    if info.is_null() {
1128                        return;
1129                    }
1130                    let st = &mut *(data as *mut GraphState<'_>);
1131                    let inf = &*info;
1132                    if inf.props.is_null() {
1133                        return;
1134                    }
1135                    if let Some(pid_txt) = SpaDict::lookup(inf.props, "application.process.id")
1136                        && let Ok(pid) = pid_txt.trim().parse::<u32>()
1137                    {
1138                        st.client_app_pids.insert(inf.id, pid);
1139                    }
1140                    if let Some(sec_txt) = SpaDict::lookup(inf.props, "pipewire.sec.pid")
1141                        && let Ok(sec_pid) = sec_txt.trim().parse::<u32>()
1142                    {
1143                        st.client_sec_pids.insert(inf.id, sec_pid);
1144                    }
1145                    st.dirty.store(true, SeqCst);
1146                }
1147            }
1148
1149            unsafe extern "C" fn on_global(
1150                data: *mut c_void,
1151                id: u32,
1152                _permissions: u32,
1153                type_ptr: *const c_char,
1154                _version: u32,
1155                props: *const SpaDict,
1156            ) {
1157                // SAFETY: `data` points to `GraphState`.
1158                unsafe {
1159                    if type_ptr.is_null() || props.is_null() {
1160                        return;
1161                    }
1162                    let st = &mut *(data as *mut GraphState<'_>);
1163                    let Ok(type_str) = CStr::from_ptr(type_ptr).to_str() else {
1164                        return;
1165                    };
1166                    match type_str {
1167                        "PipeWire:Interface:Client" => {
1168                            if let Some(pid_txt) = SpaDict::lookup(props, "application.process.id")
1169                                && let Ok(pid) = pid_txt.trim().parse::<u32>()
1170                            {
1171                                st.client_app_pids.insert(id, pid);
1172                            }
1173                            if let Some(sec_txt) = SpaDict::lookup(props, "pipewire.sec.pid")
1174                                && let Ok(sec_pid) = sec_txt.trim().parse::<u32>()
1175                            {
1176                                st.client_sec_pids.insert(id, sec_pid);
1177                            }
1178                            let proxy = st.lib.registry_bind(
1179                                st.registry,
1180                                id,
1181                                c"PipeWire:Interface:Client".as_ptr(),
1182                                3,
1183                                0,
1184                            );
1185                            if !proxy.is_null() {
1186                                let mut hook = Box::new(SpaHook::default());
1187                                (st.lib.pw_proxy_add_object_listener)(
1188                                    proxy,
1189                                    &mut *hook,
1190                                    (&CLIENT_EVENTS as *const PwClientEvents).cast(),
1191                                    data,
1192                                );
1193                                st.bound_objs.insert(id, BoundObj { proxy, _hook: hook });
1194                            }
1195                            st.dirty.store(true, SeqCst);
1196                        }
1197                        "PipeWire:Interface:Node" => {
1198                            let name = SpaDict::lookup(props, "node.name").unwrap_or_default();
1199                            if name == st.sink_name {
1200                                st.sink_node_id = Some(id);
1201                                st.dirty.store(true, SeqCst);
1202                                return;
1203                            }
1204                            let media_class =
1205                                SpaDict::lookup(props, "media.class").unwrap_or_default();
1206                            if media_class == "Stream/Output/Audio" {
1207                                let client_id = SpaDict::lookup(props, "client.id")
1208                                    .and_then(|s| s.trim().parse::<u32>().ok());
1209                                let app_pid = SpaDict::lookup(props, "application.process.id")
1210                                    .and_then(|s| s.trim().parse::<u32>().ok());
1211                                st.output_nodes.insert(id, (client_id, app_pid));
1212                                let proxy = st.lib.registry_bind(
1213                                    st.registry,
1214                                    id,
1215                                    c"PipeWire:Interface:Node".as_ptr(),
1216                                    3,
1217                                    0,
1218                                );
1219                                if !proxy.is_null() {
1220                                    let mut hook = Box::new(SpaHook::default());
1221                                    (st.lib.pw_proxy_add_object_listener)(
1222                                        proxy,
1223                                        &mut *hook,
1224                                        (&NODE_EVENTS as *const PwNodeEvents).cast(),
1225                                        data,
1226                                    );
1227                                    st.bound_objs.insert(id, BoundObj { proxy, _hook: hook });
1228                                }
1229                                st.dirty.store(true, SeqCst);
1230                            }
1231                        }
1232                        "PipeWire:Interface:Port" => {
1233                            let Some(node_id) = SpaDict::lookup(props, "node.id")
1234                                .and_then(|s| s.trim().parse::<u32>().ok())
1235                            else {
1236                                return;
1237                            };
1238                            let direction =
1239                                SpaDict::lookup(props, "port.direction").unwrap_or_default();
1240                            let channel =
1241                                SpaDict::lookup(props, "audio.channel").unwrap_or_default();
1242                            let ch_idx = if channel == "FL" || channel == "MONO" {
1243                                Some(0)
1244                            } else if channel == "FR" {
1245                                Some(1)
1246                            } else {
1247                                None
1248                            };
1249                            let Some(ch) = ch_idx else {
1250                                return;
1251                            };
1252                            if Some(node_id) == st.sink_node_id && direction == "in" {
1253                                if ch == 0 {
1254                                    st.sink_in_fl = Some(id);
1255                                } else {
1256                                    st.sink_in_fr = Some(id);
1257                                }
1258                                st.dirty.store(true, SeqCst);
1259                            } else if direction == "out" {
1260                                st.output_ports.insert(id, (node_id, ch));
1261                                st.dirty.store(true, SeqCst);
1262                            }
1263                        }
1264                        _ => {}
1265                    }
1266                }
1267            }
1268
1269            unsafe extern "C" fn on_global_remove(data: *mut c_void, id: u32) {
1270                // SAFETY: `data` points to `GraphState`.
1271                unsafe {
1272                    let st = &mut *(data as *mut GraphState<'_>);
1273                    st.output_nodes.remove(&id);
1274                    st.output_ports.remove(&id);
1275                    st.client_app_pids.remove(&id);
1276                    if let Some(bound) = st.bound_objs.remove(&id)
1277                        && !bound.proxy.is_null()
1278                    {
1279                        (st.lib.pw_proxy_destroy)(bound.proxy);
1280                    }
1281                    st.dirty.store(true, SeqCst);
1282                }
1283            }
1284
1285            // SAFETY: owns `pw_thread_loop`, `pw_context`, `pw_core`, `registry`, `sink`, and `link` proxies.
1286            unsafe {
1287                let tloop = (lib.pw_thread_loop_new)(c"cspa-pw-topo".as_ptr(), std::ptr::null());
1288                if tloop.is_null() {
1289                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
1290                    return;
1291                }
1292                let loop_obj = (lib.pw_thread_loop_get_loop)(tloop);
1293                let context = (lib.pw_context_new)(loop_obj, std::ptr::null_mut(), 0);
1294                if context.is_null() || (lib.pw_thread_loop_start)(tloop) < 0 {
1295                    if !context.is_null() {
1296                        (lib.pw_context_destroy)(context);
1297                    }
1298                    (lib.pw_thread_loop_destroy)(tloop);
1299                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
1300                    return;
1301                }
1302
1303                (lib.pw_thread_loop_lock)(tloop);
1304                let core = (lib.pw_context_connect)(context, std::ptr::null_mut(), 0);
1305                if core.is_null() {
1306                    (lib.pw_thread_loop_unlock)(tloop);
1307                    (lib.pw_thread_loop_stop)(tloop);
1308                    (lib.pw_context_destroy)(context);
1309                    (lib.pw_thread_loop_destroy)(tloop);
1310                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
1311                    return;
1312                }
1313                let registry = lib.core_get_registry(core, 3, 0);
1314                let mut cb_state = Box::new(GraphState {
1315                    lib: &lib,
1316                    registry,
1317                    sink_name: sink_name_worker.clone(),
1318                    sink_node_id: None,
1319                    sink_in_fl: None,
1320                    sink_in_fr: None,
1321                    client_app_pids: BTreeMap::new(),
1322                    client_sec_pids: BTreeMap::new(),
1323                    output_nodes: BTreeMap::new(),
1324                    output_ports: BTreeMap::new(),
1325                    bound_objs: BTreeMap::new(),
1326                    dirty: dirty_worker.clone(),
1327                });
1328                let reg_events = PwRegistryEvents {
1329                    version: 0,
1330                    global: Some(on_global),
1331                    global_remove: Some(on_global_remove),
1332                };
1333                let mut reg_hook = SpaHook::default();
1334                lib.registry_add_listener(
1335                    registry,
1336                    &mut reg_hook,
1337                    &reg_events,
1338                    (&mut *cb_state as *mut GraphState<'_>).cast(),
1339                );
1340
1341                let sink_props = lib.new_properties(&[
1342                    ("factory.name", "support.null-audio-sink"),
1343                    ("node.name", sink_name_worker.as_str()),
1344                    ("media.class", "Stream/Input/Audio"),
1345                    ("node.virtual", "true"),
1346                    ("object.linger", "false"),
1347                    ("audio.channels", "2"),
1348                    ("audio.position", "[ FL FR ]"),
1349                ]);
1350                let sink_proxy = lib.core_create_object(
1351                    core,
1352                    c"adapter".as_ptr(),
1353                    c"PipeWire:Interface:Node".as_ptr(),
1354                    3,
1355                    &(*sink_props).dict,
1356                    0,
1357                );
1358                (lib.pw_properties_free)(sink_props);
1359                let _ = lib.core_sync(core, 0, 1);
1360                (lib.pw_thread_loop_unlock)(tloop);
1361
1362                if sink_proxy.is_null() {
1363                    (lib.pw_thread_loop_stop)(tloop);
1364                    (lib.pw_proxy_destroy)(registry);
1365                    (lib.pw_core_disconnect)(core);
1366                    (lib.pw_context_destroy)(context);
1367                    (lib.pw_thread_loop_destroy)(tloop);
1368                    let _ = ready_tx.send(Err(CapabilityError::ServerUnavailable));
1369                    return;
1370                }
1371
1372                let mut link_proxies: BTreeMap<Arc<str>, *mut c_void> = BTreeMap::new();
1373
1374                let mut reconcile_once = || {
1375                    let Ok(proc_map) = collect_proc_stat_table(Path::new("/proc")) else {
1376                        return;
1377                    };
1378
1379                    (lib.pw_thread_loop_lock)(tloop);
1380                    let (Some(in_fl), Some(in_fr)) = (cb_state.sink_in_fl, cb_state.sink_in_fr)
1381                    else {
1382                        cb_state.dirty.store(true, SeqCst);
1383                        (lib.pw_thread_loop_unlock)(tloop);
1384                        return;
1385                    };
1386                    let sink_inputs = [in_fl, in_fr];
1387                    let mut changed = false;
1388
1389                    {
1390                        let active_set: std::collections::BTreeSet<Arc<str>> = topology_worker
1391                            .lock()
1392                            .unwrap_or_else(|e| e.into_inner())
1393                            .active_sources()
1394                            .into_iter()
1395                            .collect();
1396                        let mut to_remove = Vec::new();
1397                        for key in link_proxies.keys() {
1398                            if !active_set.contains(key) {
1399                                to_remove.push(key.clone());
1400                            }
1401                        }
1402                        for key in to_remove {
1403                            if let Some(proxy) = link_proxies.remove(&key)
1404                                && !proxy.is_null()
1405                            {
1406                                (lib.pw_proxy_destroy)(proxy);
1407                                changed = true;
1408                            }
1409                        }
1410                    }
1411
1412                    for (&out_port_id, &(out_node_id, ch)) in &cb_state.output_ports {
1413                        let Some(&(client_id, node_app_pid)) =
1414                            cb_state.output_nodes.get(&out_node_id)
1415                        else {
1416                            continue;
1417                        };
1418                        let Some(node_pid) = crate::discovery::resolve_pipewire_node_pid(
1419                            node_app_pid,
1420                            client_id,
1421                            &cb_state.client_app_pids,
1422                            &cb_state.client_sec_pids,
1423                        ) else {
1424                            continue;
1425                        };
1426
1427                        let current_targets = targets_worker
1428                            .lock()
1429                            .unwrap_or_else(|e| e.into_inner())
1430                            .clone();
1431                        let mut matching_targets = Vec::new();
1432                        for (t_idx, target_opt) in current_targets.iter().enumerate() {
1433                            let Some(target) = target_opt else {
1434                                continue;
1435                            };
1436                            if let Some(root_pid) = target.pid() {
1437                                let root_id = ProcessIdentity {
1438                                    pid: root_pid,
1439                                    generation: target.process_start_time().unwrap_or(0),
1440                                };
1441                                let exact_only = target.scope() == ProcessScope::Exact;
1442                                if pid_belongs_to_target(&proc_map, root_id, exact_only, node_pid)
1443                                    == Ok(true)
1444                                {
1445                                    matching_targets.push(t_idx);
1446                                }
1447                            }
1448                        }
1449                        if matching_targets.is_empty() {
1450                            continue;
1451                        }
1452
1453                        let in_port_id = sink_inputs[ch];
1454                        let link_key: Arc<str> =
1455                            format!("{out_node_id}:{out_port_id}->{in_port_id}").into();
1456                        let mut created_in_topo = false;
1457                        {
1458                            let mut topo =
1459                                topology_worker.lock().unwrap_or_else(|e| e.into_inner());
1460                            for &t_idx in &matching_targets {
1461                                if let Ok(is_new) = topo.attach_source(t_idx, link_key.clone())
1462                                    && is_new
1463                                {
1464                                    created_in_topo = true;
1465                                }
1466                            }
1467                            active_worker.store(topo.active_link_count() as u64, SeqCst);
1468                        }
1469
1470                        if created_in_topo && !link_proxies.contains_key(&link_key) {
1471                            let out_node_s = out_node_id.to_string();
1472                            let out_port_s = out_port_id.to_string();
1473                            let in_node_s = cb_state.sink_node_id.unwrap_or(0).to_string();
1474                            let in_port_s = in_port_id.to_string();
1475                            let lprops = lib.new_properties(&[
1476                                ("object.linger", "false"),
1477                                ("link.output.node", out_node_s.as_str()),
1478                                ("link.output.port", out_port_s.as_str()),
1479                                ("link.input.node", in_node_s.as_str()),
1480                                ("link.input.port", in_port_s.as_str()),
1481                            ]);
1482                            let lproxy = lib.core_create_object(
1483                                core,
1484                                c"link-factory".as_ptr(),
1485                                c"PipeWire:Interface:Link".as_ptr(),
1486                                3,
1487                                &(*lprops).dict,
1488                                0,
1489                            );
1490                            (lib.pw_properties_free)(lprops);
1491                            if !lproxy.is_null() {
1492                                link_proxies.insert(link_key, lproxy);
1493                                created_worker.fetch_add(1, SeqCst);
1494                                changed = true;
1495                            }
1496                        }
1497                    }
1498                    if changed {
1499                        let _ = lib.core_sync(core, 0, 2);
1500                    }
1501                    (lib.pw_thread_loop_unlock)(tloop);
1502                };
1503
1504                // Wait up to 500ms for virtual sink FL/FR input ports and initial node links.
1505                let wait_start = Instant::now();
1506                loop {
1507                    let _ = dirty_worker.swap(false, SeqCst);
1508                    reconcile_once();
1509                    let linked = active_worker.load(SeqCst);
1510                    if linked > 0 || wait_start.elapsed() >= Duration::from_millis(500) {
1511                        break;
1512                    }
1513                    thread::sleep(Duration::from_millis(10));
1514                }
1515                let _ = ready_tx.send(Ok(()));
1516
1517                while !stop_worker.load(SeqCst) {
1518                    if dirty_worker.swap(false, SeqCst) {
1519                        reconcile_once();
1520                    }
1521                    thread::sleep(Duration::from_millis(10));
1522                }
1523
1524                (lib.pw_thread_loop_lock)(tloop);
1525                for (_k, proxy) in link_proxies {
1526                    if !proxy.is_null() {
1527                        (lib.pw_proxy_destroy)(proxy);
1528                    }
1529                }
1530                for (_id, bound) in std::mem::take(&mut cb_state.bound_objs) {
1531                    if !bound.proxy.is_null() {
1532                        (lib.pw_proxy_destroy)(bound.proxy);
1533                    }
1534                }
1535                (lib.pw_proxy_destroy)(sink_proxy);
1536                (lib.pw_proxy_destroy)(registry);
1537                (lib.pw_core_disconnect)(core);
1538                (lib.pw_thread_loop_unlock)(tloop);
1539                (lib.pw_thread_loop_stop)(tloop);
1540                (lib.pw_context_destroy)(context);
1541                (lib.pw_thread_loop_destroy)(tloop);
1542            }
1543        });
1544
1545        match ready_rx.recv_timeout(Duration::from_secs(5)) {
1546            Ok(Ok(())) => Ok(PlatformTopologyController {
1547                sink_name,
1548                targets,
1549                shared_targets,
1550                topology,
1551                dirty,
1552                stop,
1553                worker: Mutex::new(Some(worker)),
1554                created_links_count,
1555                active_links_count,
1556            }),
1557            Ok(Err(err)) => {
1558                stop.store(true, SeqCst);
1559                let _ = worker.join();
1560                Err(err)
1561            }
1562            Err(_) => {
1563                stop.store(true, SeqCst);
1564                let _ = worker.join();
1565                Err(CapabilityError::ServerUnavailable)
1566            }
1567        }
1568    }
1569}
1570
1571#[cfg(target_os = "linux")]
1572pub use imp::{
1573    open_pipewire_point, open_pipewire_source_point, start_pipewire_topology_controller,
1574};
1575
1576#[cfg(not(target_os = "linux"))]
1577#[allow(clippy::too_many_arguments)]
1578pub fn open_pipewire_point_with_format(
1579    paths: &LinuxClientPaths,
1580    _target_object: Option<&str>,
1581    _capture_sink: bool,
1582    _format: Format,
1583    _clock_domain: u64,
1584    _overflow: Overflow,
1585    _timing: TimingRequirement,
1586    _budget: &StorageBudget,
1587    _observed: bool,
1588) -> Result<PipeWireStream, CapabilityError> {
1589    let _ = linux_endpoint_clock_domain("stub");
1590    Err(
1591        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1592            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1593    )
1594}
1595
1596#[cfg(not(target_os = "linux"))]
1597pub fn open_pipewire_source_point(
1598    paths: &LinuxClientPaths,
1599    _source_name: Option<&str>,
1600    _format_override: Option<Format>,
1601    _overflow: Overflow,
1602    _timing: TimingRequirement,
1603    _budget: &StorageBudget,
1604    _observed: bool,
1605) -> Result<PipeWireStream, CapabilityError> {
1606    Err(
1607        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1608            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1609    )
1610}
1611
1612#[cfg(not(target_os = "linux"))]
1613pub fn open_pipewire_point(
1614    paths: &LinuxClientPaths,
1615    _target_object: Option<&str>,
1616    _capture_sink: bool,
1617    _overflow: Overflow,
1618    _timing: TimingRequirement,
1619    _budget: &StorageBudget,
1620    _observed: bool,
1621) -> Result<PipeWireStream, CapabilityError> {
1622    let _ = (
1623        POOL_SLOTS,
1624        QUEUE_SLOTS,
1625        MAX_FRAMES_PER_SLOT,
1626        SESSION_METADATA_BYTES,
1627        &MIX_SINK_COUNTER,
1628        StartupCleanup::new,
1629        publish_linux_packet
1630            as fn(
1631                &mut Producer,
1632                &[u8],
1633                bool,
1634                bool,
1635                usize,
1636                Option<u64>,
1637                u64,
1638                &mut u64,
1639                &mut u64,
1640                &mut u64,
1641                Overflow,
1642                Option<Instant>,
1643            ),
1644    );
1645    let _ = (
1646        collect_proc_stat_table,
1647        inspect_process_in_proc_root,
1648        pid_belongs_to_target,
1649    );
1650    let _ = (
1651        std::mem::size_of::<BTreeMap<u32, u32>>(),
1652        Path::new(""),
1653        ProcessIdentity {
1654            pid: 1,
1655            generation: 1,
1656        },
1657        ProcessScope::Tree,
1658        TargetKind::Process,
1659        Format::new(
1660            SampleType::F32,
1661            ByteOrder::Little,
1662            48_000,
1663            2,
1664            Layout::Unknown,
1665        ),
1666        StorageLimits::new(8, 4096, 8, 262_144),
1667        Pool::new_reserved,
1668        ordering::channel,
1669        ReadStream::new,
1670    );
1671    Err(
1672        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1673            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1674    )
1675}
1676
1677#[cfg(not(target_os = "linux"))]
1678pub fn start_pipewire_topology_controller(
1679    paths: &LinuxClientPaths,
1680    _targets: Vec<CaptureTarget>,
1681    _max_links: usize,
1682) -> Result<PlatformTopologyController, CapabilityError> {
1683    Err(
1684        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1685            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1686    )
1687}