Skip to main content

capture_system_or_process_audio_linux/
discovery.rs

1#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
2
3use crate::core::{
4    discovery::{
5        BackendRawInventory, DeviceDirection, DiscoveryFilter, DiscoveryQuery, DiscoveryService,
6        DiscoverySubscription, RawBackendDeviceRecord, RawBackendProcessRecord, RawProcessRecord,
7        TargetCatalog,
8    },
9    schema::{BackendId, Backends, CaptureTarget, OnRootExit, PlatformOs, ProcessScope},
10    traits::{CapabilityError, DefaultEndpointObserver, DiscoveryBackend},
11};
12use crate::loader::LinuxClientPaths;
13use crate::procfs::{collect_proc_table, inspect_process_executable};
14use std::collections::BTreeMap;
15use std::path::Path;
16use std::sync::{
17    Arc, Mutex, OnceLock,
18    atomic::{AtomicBool, Ordering::SeqCst},
19};
20use std::thread::{self, JoinHandle};
21use std::time::Duration;
22
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub struct PulseSinkRecord {
25    pub index: u32,
26    pub name: String,
27    pub description: Option<String>,
28    pub is_default: bool,
29}
30
31#[derive(Clone, Debug, Eq, PartialEq)]
32pub struct PulseSinkInputRecord {
33    pub index: u32,
34    pub sink_index: u32,
35    pub client_index: u32,
36    pub pid: Option<u32>,
37    pub rate_hz: u32,
38    pub channels: u8,
39    pub corked: bool,
40}
41
42#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct PipeWireOutputNodeRecord {
44    pub node_id: u32,
45    pub client_id: Option<u32>,
46    pub pid: Option<u32>,
47    pub node_name: Option<String>,
48    pub active: bool,
49    pub fl_port_id: Option<u32>,
50    pub fr_port_id: Option<u32>,
51}
52
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct PulseSourceRecord {
55    pub index: u32,
56    pub name: String,
57    pub description: Option<String>,
58    pub sample_format: i32,
59    pub rate_hz: u32,
60    pub channels: u8,
61    pub is_monitor: bool,
62    pub is_default: bool,
63}
64
65#[derive(Clone, Debug, Default, Eq, PartialEq)]
66pub struct PipeWireGraphSnapshot {
67    pub default_sink_name: Option<String>,
68    pub default_source_name: Option<String>,
69    pub sinks: Vec<(u32, String, Option<String>)>,
70    pub sources: Vec<(u32, String, Option<String>)>,
71    pub client_pids: BTreeMap<u32, u32>,
72    pub output_nodes: Vec<PipeWireOutputNodeRecord>,
73    pub link_pairs: Vec<(u32, u32, u32, u32, u32)>,
74}
75
76pub type PulseAudioStateSnapshot = (
77    Vec<PulseSinkRecord>,
78    BTreeMap<u32, bool>,
79    Vec<PulseSinkInputRecord>,
80);
81
82pub type PulseAudioFullStateSnapshot = (
83    Vec<PulseSinkRecord>,
84    Vec<PulseSourceRecord>,
85    BTreeMap<u32, bool>,
86    Vec<PulseSinkInputRecord>,
87);
88
89#[cfg(any(target_os = "linux", test))]
90pub(crate) fn is_internal_mixer_endpoint_name(name: &str) -> bool {
91    name.starts_with("cspa-mix-")
92}
93
94/// Use the node or client `application.process.id`, never `pipewire.sec.pid`.
95pub fn resolve_pipewire_node_pid(
96    node_app_pid: Option<u32>,
97    node_client_id: Option<u32>,
98    client_app_pids: &BTreeMap<u32, u32>,
99    _client_sec_pids_ignored: &BTreeMap<u32, u32>,
100) -> Option<u32> {
101    if let Some(pid) = node_app_pid.filter(|&p| p > 0) {
102        return Some(pid);
103    }
104    if let Some(cid) = node_client_id
105        && let Some(&pid) = client_app_pids.get(&cid)
106        && pid > 0
107    {
108        return Some(pid);
109    }
110    None
111}
112
113/// Parse PipeWire `default` metadata property values (`{"name":"<sink_name>"}` SPA JSON or plain string).
114pub fn parse_pipewire_default_sink_metadata(raw: &str) -> Option<String> {
115    let trimmed = raw.trim();
116    if trimmed.is_empty() {
117        return None;
118    }
119    if !trimmed.starts_with('{') {
120        let plain = trimmed.trim_matches('"').trim();
121        return (!plain.is_empty()).then(|| plain.to_owned());
122    }
123    for key_pat in ["\"name\"", "name"] {
124        if let Some(pos) = trimmed.find(key_pat) {
125            let after_key = &trimmed[pos + key_pat.len()..];
126            if let Some(colon) = after_key.find(':') {
127                let after_colon = after_key[colon + 1..].trim_start();
128                if let Some(rest) = after_colon.strip_prefix('"') {
129                    let mut out = String::new();
130                    let mut escaped = false;
131                    for ch in rest.chars() {
132                        if escaped {
133                            out.push(ch);
134                            escaped = false;
135                        } else if ch == '\\' {
136                            escaped = true;
137                        } else if ch == '"' {
138                            return (!out.is_empty()).then_some(out);
139                        } else {
140                            out.push(ch);
141                        }
142                    }
143                }
144            }
145        }
146    }
147    None
148}
149
150#[cfg(target_os = "linux")]
151#[allow(unsafe_code)]
152mod imp {
153    use super::*;
154    use crate::loader::{
155        PA_CONTEXT_FAILED, PA_CONTEXT_NOAUTOSPAWN, PA_CONTEXT_READY, PA_CONTEXT_TERMINATED,
156        PA_INVALID_INDEX, PaClientInfo, PaServerInfo, PaSinkInfo, PaSinkInputInfo, PaSourceInfo,
157        PipeWireLibrary, PulseLibrary, PwClientEvents, PwClientInfo, PwCoreEvents, PwCoreInfo,
158        PwNodeEvents, PwNodeInfo, PwRegistryEvents, SpaDict, SpaHook, probe_pulse_server,
159    };
160    use std::ffi::{CStr, c_char, c_int, c_void};
161
162    #[repr(C)]
163    struct PwMetadataEvents {
164        version: u32,
165        property: Option<
166            unsafe extern "C" fn(
167                data: *mut c_void,
168                subject: u32,
169                key: *const c_char,
170                type_: *const c_char,
171                value: *const c_char,
172            ) -> c_int,
173        >,
174    }
175
176    pub fn collect_pipewire_graph(
177        paths: &LinuxClientPaths,
178    ) -> Result<PipeWireGraphSnapshot, CapabilityError> {
179        let lib = PipeWireLibrary::load(paths).map_err(|err| {
180            err.into_capability_error(BackendId::PipeWire, paths.pipewire_min_version)
181        })?;
182
183        type RawNodeMap = BTreeMap<u32, (Option<u32>, Option<u32>, Option<String>, bool)>;
184
185        struct BoundProxy {
186            proxy: *mut c_void,
187            _hook: Box<SpaHook>,
188        }
189
190        struct PwSnapState<'a> {
191            lib: &'a PipeWireLibrary,
192            core: *mut c_void,
193            registry: *mut c_void,
194            loop_ptr: *mut c_void,
195            quit_fn: unsafe extern "C" fn(*mut c_void) -> c_int,
196            sync_seq: c_int,
197            phase: u8,
198            failed: bool,
199            metadata_default_sink: Option<String>,
200            metadata_default_source: Option<String>,
201            sinks: Vec<(u32, String, Option<String>)>,
202            sources: Vec<(u32, String, Option<String>)>,
203            client_app_pids: BTreeMap<u32, u32>,
204            client_sec_pids: BTreeMap<u32, u32>,
205            raw_nodes: RawNodeMap,
206            fl_ports: BTreeMap<u32, u32>,
207            fr_ports: BTreeMap<u32, u32>,
208            links: Vec<(u32, u32, u32, u32, u32)>,
209            bound_proxies: Vec<BoundProxy>,
210        }
211
212        static NODE_EVENTS: PwNodeEvents = PwNodeEvents {
213            version: 0,
214            info: Some(on_node_info),
215            param: None,
216        };
217
218        static CLIENT_EVENTS: PwClientEvents = PwClientEvents {
219            version: 0,
220            info: Some(on_client_info),
221            permissions: None,
222        };
223
224        static METADATA_EVENTS: PwMetadataEvents = PwMetadataEvents {
225            version: 0,
226            property: Some(on_metadata_property),
227        };
228
229        unsafe extern "C" fn on_metadata_property(
230            data: *mut c_void,
231            subject: u32,
232            key: *const c_char,
233            _type_: *const c_char,
234            value: *const c_char,
235        ) -> c_int {
236            // SAFETY: `data` points to `PwSnapState` and `key`/`value` are valid during callback.
237            unsafe {
238                if subject != 0 || key.is_null() || value.is_null() {
239                    return 0;
240                }
241                let Ok(key_str) = CStr::from_ptr(key).to_str() else {
242                    return 0;
243                };
244                let is_sink_key =
245                    key_str == "default.audio.sink" || key_str == "default.configured.audio.sink";
246                let is_source_key = key_str == "default.audio.source"
247                    || key_str == "default.configured.audio.source";
248                if !is_sink_key && !is_source_key {
249                    return 0;
250                }
251                let Ok(val_str) = CStr::from_ptr(value).to_str() else {
252                    return 0;
253                };
254                if let Some(parsed) = parse_pipewire_default_sink_metadata(val_str) {
255                    let st = &mut *(data as *mut PwSnapState<'_>);
256                    if is_sink_key {
257                        if key_str == "default.audio.sink" || st.metadata_default_sink.is_none() {
258                            st.metadata_default_sink = Some(parsed);
259                        }
260                    } else if key_str == "default.audio.source"
261                        || st.metadata_default_source.is_none()
262                    {
263                        st.metadata_default_source = Some(parsed);
264                    }
265                }
266                0
267            }
268        }
269
270        unsafe extern "C" fn on_node_info(data: *mut c_void, info: *const PwNodeInfo) {
271            // SAFETY: `data` points to `PwSnapState` and `info` is valid during callback.
272            unsafe {
273                if info.is_null() {
274                    return;
275                }
276                let st = &mut *(data as *mut PwSnapState<'_>);
277                let inf = &*info;
278                if inf.props.is_null() {
279                    return;
280                }
281                let app_pid = SpaDict::lookup(inf.props, "application.process.id")
282                    .and_then(|s| s.trim().parse::<u32>().ok());
283                let client_id = SpaDict::lookup(inf.props, "client.id")
284                    .and_then(|s| s.trim().parse::<u32>().ok());
285                let app_name = SpaDict::lookup(inf.props, "application.name")
286                    .or_else(|| SpaDict::lookup(inf.props, "node.name"));
287                let pulse_corked = SpaDict::lookup(inf.props, "pulse.corked");
288                if let Some(entry) = st.raw_nodes.get_mut(&inf.id) {
289                    if app_pid.is_some() {
290                        entry.1 = app_pid;
291                    }
292                    if client_id.is_some() {
293                        entry.0 = client_id;
294                    }
295                    if app_name.is_some() {
296                        entry.2 = app_name;
297                    }
298                    if let Some(corked_txt) = pulse_corked {
299                        entry.3 = corked_txt.trim() != "true";
300                    } else if inf.state == 2 {
301                        entry.3 = false;
302                    }
303                }
304            }
305        }
306
307        unsafe extern "C" fn on_client_info(data: *mut c_void, info: *const PwClientInfo) {
308            // SAFETY: `data` points to `PwSnapState` and `info` is valid during callback.
309            unsafe {
310                if info.is_null() {
311                    return;
312                }
313                let st = &mut *(data as *mut PwSnapState<'_>);
314                let inf = &*info;
315                if inf.props.is_null() {
316                    return;
317                }
318                if let Some(pid_txt) = SpaDict::lookup(inf.props, "application.process.id")
319                    && let Ok(pid) = pid_txt.trim().parse::<u32>()
320                {
321                    st.client_app_pids.insert(inf.id, pid);
322                }
323                if let Some(sec_txt) = SpaDict::lookup(inf.props, "pipewire.sec.pid")
324                    && let Ok(sec_pid) = sec_txt.trim().parse::<u32>()
325                {
326                    st.client_sec_pids.insert(inf.id, sec_pid);
327                }
328            }
329        }
330
331        unsafe extern "C" fn on_core_done(data: *mut c_void, id: u32, seq: c_int) {
332            // SAFETY: `data` points to `PwSnapState`.
333            unsafe {
334                let st = &mut *(data as *mut PwSnapState<'_>);
335                if id == 0 && seq == st.sync_seq {
336                    if st.phase == 0 {
337                        st.phase = 1;
338                        st.sync_seq = st.lib.core_sync(st.core, 0, 2);
339                    } else {
340                        (st.quit_fn)(st.loop_ptr);
341                    }
342                }
343            }
344        }
345
346        unsafe extern "C" fn on_core_error(
347            data: *mut c_void,
348            _id: u32,
349            _seq: c_int,
350            _res: c_int,
351            _msg: *const c_char,
352        ) {
353            // SAFETY: `data` points to `PwSnapState`.
354            unsafe {
355                let st = &mut *(data as *mut PwSnapState<'_>);
356                st.failed = true;
357                (st.quit_fn)(st.loop_ptr);
358            }
359        }
360
361        unsafe extern "C" fn on_global(
362            data: *mut c_void,
363            id: u32,
364            _permissions: u32,
365            type_ptr: *const c_char,
366            _version: u32,
367            props: *const SpaDict,
368        ) {
369            // SAFETY: `data` points to `PwSnapState` and `type_ptr`/`props` are valid during callback.
370            unsafe {
371                if type_ptr.is_null() || props.is_null() {
372                    return;
373                }
374                let st = &mut *(data as *mut PwSnapState<'_>);
375                let Ok(type_str) = CStr::from_ptr(type_ptr).to_str() else {
376                    return;
377                };
378                match type_str {
379                    "PipeWire:Interface:Client" => {
380                        if let Some(pid_txt) = SpaDict::lookup(props, "application.process.id")
381                            && let Ok(pid) = pid_txt.trim().parse::<u32>()
382                        {
383                            st.client_app_pids.insert(id, pid);
384                        }
385                        if let Some(sec_txt) = SpaDict::lookup(props, "pipewire.sec.pid")
386                            && let Ok(sec_pid) = sec_txt.trim().parse::<u32>()
387                        {
388                            st.client_sec_pids.insert(id, sec_pid);
389                        }
390                        let proxy = st.lib.registry_bind(
391                            st.registry,
392                            id,
393                            c"PipeWire:Interface:Client".as_ptr(),
394                            3,
395                            0,
396                        );
397                        if !proxy.is_null() {
398                            let mut hook = Box::new(SpaHook::default());
399                            (st.lib.pw_proxy_add_object_listener)(
400                                proxy,
401                                &mut *hook,
402                                (&CLIENT_EVENTS as *const PwClientEvents).cast(),
403                                data,
404                            );
405                            st.bound_proxies.push(BoundProxy { proxy, _hook: hook });
406                        }
407                    }
408                    "PipeWire:Interface:Node" => {
409                        let media_class = SpaDict::lookup(props, "media.class").unwrap_or_default();
410                        let node_name = SpaDict::lookup(props, "node.name");
411                        let node_desc = SpaDict::lookup(props, "node.description")
412                            .or_else(|| SpaDict::lookup(props, "node.nick"));
413                        if media_class == "Audio/Sink" {
414                            if let Some(name) = node_name
415                                && !is_internal_mixer_endpoint_name(&name)
416                            {
417                                st.sinks.push((id, name, node_desc));
418                            }
419                        } else if media_class == "Audio/Source"
420                            || media_class == "Audio/Source/Virtual"
421                        {
422                            if let Some(name) = node_name
423                                && !name.ends_with(".monitor")
424                                && !is_internal_mixer_endpoint_name(&name)
425                            {
426                                st.sources.push((id, name, node_desc));
427                            }
428                        } else if media_class == "Stream/Output/Audio" {
429                            let client_id = SpaDict::lookup(props, "client.id")
430                                .and_then(|s| s.trim().parse::<u32>().ok());
431                            let app_pid = SpaDict::lookup(props, "application.process.id")
432                                .and_then(|s| s.trim().parse::<u32>().ok());
433                            let app_or_node_name =
434                                SpaDict::lookup(props, "application.name").or(node_name);
435                            let is_corked = SpaDict::lookup(props, "pulse.corked")
436                                .is_some_and(|v| v.trim() == "true");
437                            st.raw_nodes
438                                .insert(id, (client_id, app_pid, app_or_node_name, !is_corked));
439                            let proxy = st.lib.registry_bind(
440                                st.registry,
441                                id,
442                                c"PipeWire:Interface:Node".as_ptr(),
443                                3,
444                                0,
445                            );
446                            if !proxy.is_null() {
447                                let mut hook = Box::new(SpaHook::default());
448                                (st.lib.pw_proxy_add_object_listener)(
449                                    proxy,
450                                    &mut *hook,
451                                    (&NODE_EVENTS as *const PwNodeEvents).cast(),
452                                    data,
453                                );
454                                st.bound_proxies.push(BoundProxy { proxy, _hook: hook });
455                            }
456                        }
457                    }
458                    "PipeWire:Interface:Port" => {
459                        let Some(node_id) = SpaDict::lookup(props, "node.id")
460                            .and_then(|s| s.trim().parse::<u32>().ok())
461                        else {
462                            return;
463                        };
464                        let direction =
465                            SpaDict::lookup(props, "port.direction").unwrap_or_default();
466                        let channel = SpaDict::lookup(props, "audio.channel").unwrap_or_default();
467                        if direction == "out" {
468                            if channel == "FL" || channel == "MONO" {
469                                st.fl_ports.insert(node_id, id);
470                            } else if channel == "FR" {
471                                st.fr_ports.insert(node_id, id);
472                            }
473                        }
474                    }
475                    "PipeWire:Interface:Link" => {
476                        let out_node = SpaDict::lookup(props, "link.output.node")
477                            .and_then(|s| s.trim().parse::<u32>().ok());
478                        let out_port = SpaDict::lookup(props, "link.output.port")
479                            .and_then(|s| s.trim().parse::<u32>().ok());
480                        let in_node = SpaDict::lookup(props, "link.input.node")
481                            .and_then(|s| s.trim().parse::<u32>().ok());
482                        let in_port = SpaDict::lookup(props, "link.input.port")
483                            .and_then(|s| s.trim().parse::<u32>().ok());
484                        if let (Some(on), Some(op), Some(inn), Some(ip)) =
485                            (out_node, out_port, in_node, in_port)
486                        {
487                            st.links.push((id, on, op, inn, ip));
488                        }
489                    }
490                    "PipeWire:Interface:Metadata"
491                        if SpaDict::lookup(props, "metadata.name").as_deref()
492                            == Some("default") =>
493                    {
494                        let proxy = st.lib.registry_bind(
495                            st.registry,
496                            id,
497                            c"PipeWire:Interface:Metadata".as_ptr(),
498                            3,
499                            0,
500                        );
501                        if !proxy.is_null() {
502                            let mut hook = Box::new(SpaHook::default());
503                            (st.lib.pw_proxy_add_object_listener)(
504                                proxy,
505                                &mut *hook,
506                                (&METADATA_EVENTS as *const PwMetadataEvents).cast(),
507                                data,
508                            );
509                            st.bound_proxies.push(BoundProxy { proxy, _hook: hook });
510                        }
511                    }
512                    _ => {}
513                }
514            }
515        }
516
517        // SAFETY: creates, runs, and destroys a single-thread `pw_main_loop` snapshot.
518        unsafe {
519            let main_loop = (lib.pw_main_loop_new)(std::ptr::null());
520            if main_loop.is_null() {
521                return Err(CapabilityError::ServerUnavailable);
522            }
523            let loop_obj = (lib.pw_main_loop_get_loop)(main_loop);
524            let context = (lib.pw_context_new)(loop_obj, std::ptr::null_mut(), 0);
525            if context.is_null() {
526                (lib.pw_main_loop_destroy)(main_loop);
527                return Err(CapabilityError::ServerUnavailable);
528            }
529            let core = (lib.pw_context_connect)(context, std::ptr::null_mut(), 0);
530            if core.is_null() {
531                (lib.pw_context_destroy)(context);
532                (lib.pw_main_loop_destroy)(main_loop);
533                return Err(CapabilityError::ServerUnavailable);
534            }
535            let registry = lib.core_get_registry(core, 3, 0);
536            if registry.is_null() {
537                (lib.pw_core_disconnect)(core);
538                (lib.pw_context_destroy)(context);
539                (lib.pw_main_loop_destroy)(main_loop);
540                return Err(CapabilityError::ServerUnavailable);
541            }
542
543            let mut state = PwSnapState {
544                lib: &lib,
545                core,
546                registry,
547                loop_ptr: main_loop,
548                quit_fn: lib.pw_main_loop_quit,
549                sync_seq: 0,
550                phase: 0,
551                failed: false,
552                metadata_default_sink: None,
553                metadata_default_source: None,
554                sinks: Vec::new(),
555                sources: Vec::new(),
556                client_app_pids: BTreeMap::new(),
557                client_sec_pids: BTreeMap::new(),
558                raw_nodes: BTreeMap::new(),
559                fl_ports: BTreeMap::new(),
560                fr_ports: BTreeMap::new(),
561                links: Vec::new(),
562                bound_proxies: Vec::new(),
563            };
564            let core_events = PwCoreEvents {
565                version: 0,
566                info: None::<unsafe extern "C" fn(*mut c_void, *const PwCoreInfo)>,
567                done: Some(on_core_done),
568                ping: None,
569                error: Some(on_core_error),
570                remove_id: None,
571                bound_id: None,
572                add_mem: None,
573                remove_mem: None,
574                bound_props: None,
575            };
576            let reg_events = PwRegistryEvents {
577                version: 0,
578                global: Some(on_global),
579                global_remove: None,
580            };
581            let mut core_hook = SpaHook::default();
582            let mut reg_hook = SpaHook::default();
583            let state_ptr: *mut c_void = (&mut state as *mut PwSnapState<'_>).cast();
584            lib.core_add_listener(core, &mut core_hook, &core_events, state_ptr);
585            lib.registry_add_listener(registry, &mut reg_hook, &reg_events, state_ptr);
586            state.sync_seq = lib.core_sync(core, 0, 1);
587            (lib.pw_main_loop_run)(main_loop);
588
589            for bp in state.bound_proxies {
590                if !bp.proxy.is_null() {
591                    (lib.pw_proxy_destroy)(bp.proxy);
592                }
593            }
594            (lib.pw_proxy_destroy)(registry);
595            (lib.pw_core_disconnect)(core);
596            (lib.pw_context_destroy)(context);
597            (lib.pw_main_loop_destroy)(main_loop);
598
599            if state.failed {
600                return Err(CapabilityError::ServerUnavailable);
601            }
602
603            let pa_probe = probe_pulse_server(paths).ok();
604            let default_sink_name = state
605                .metadata_default_sink
606                .filter(|meta_name| state.sinks.iter().any(|(_, n, _)| n == meta_name))
607                .or_else(|| {
608                    pa_probe
609                        .as_ref()
610                        .and_then(|p| p.default_sink_name.clone())
611                        .filter(|pa_name| state.sinks.iter().any(|(_, n, _)| n == pa_name))
612                })
613                .or_else(|| state.sinks.first().map(|(_, name, _)| name.clone()));
614            let default_source_name = state
615                .metadata_default_source
616                .filter(|meta_name| state.sources.iter().any(|(_, n, _)| n == meta_name))
617                .or_else(|| {
618                    pa_probe
619                        .and_then(|p| p.default_source_name)
620                        .filter(|pa_name| state.sources.iter().any(|(_, n, _)| n == pa_name))
621                })
622                .or_else(|| state.sources.first().map(|(_, name, _)| name.clone()));
623            let mut output_nodes = Vec::new();
624            for (node_id, (client_id, node_app_pid, node_name, active)) in state.raw_nodes {
625                let resolved_pid = resolve_pipewire_node_pid(
626                    node_app_pid,
627                    client_id,
628                    &state.client_app_pids,
629                    &state.client_sec_pids,
630                );
631                output_nodes.push(PipeWireOutputNodeRecord {
632                    node_id,
633                    client_id,
634                    pid: resolved_pid,
635                    node_name,
636                    active,
637                    fl_port_id: state.fl_ports.get(&node_id).copied(),
638                    fr_port_id: state.fr_ports.get(&node_id).copied(),
639                });
640            }
641
642            Ok(PipeWireGraphSnapshot {
643                default_sink_name,
644                default_source_name,
645                sinks: state.sinks,
646                sources: state.sources,
647                client_pids: state.client_app_pids,
648                output_nodes,
649                link_pairs: state.links,
650            })
651        }
652    }
653
654    pub fn query_pipewire_default_sink_only(
655        paths: &LinuxClientPaths,
656    ) -> Result<Option<String>, CapabilityError> {
657        query_pipewire_defaults_only(paths).map(|(sink, _)| sink)
658    }
659
660    pub fn query_pipewire_defaults_only(
661        paths: &LinuxClientPaths,
662    ) -> Result<(Option<String>, Option<String>), CapabilityError> {
663        let lib = PipeWireLibrary::load(paths).map_err(|err| {
664            err.into_capability_error(BackendId::PipeWire, paths.pipewire_min_version)
665        })?;
666
667        struct BoundProxy {
668            proxy: *mut c_void,
669            _hook: Box<SpaHook>,
670        }
671
672        struct PwDefaultsOnlyState<'a> {
673            lib: &'a PipeWireLibrary,
674            core: *mut c_void,
675            registry: *mut c_void,
676            loop_ptr: *mut c_void,
677            quit_fn: unsafe extern "C" fn(*mut c_void) -> c_int,
678            sync_seq: c_int,
679            phase: u8,
680            failed: bool,
681            metadata_default_sink: Option<String>,
682            metadata_default_source: Option<String>,
683            sinks: Vec<String>,
684            sources: Vec<String>,
685            bound_proxies: Vec<BoundProxy>,
686        }
687
688        static METADATA_EVENTS: PwMetadataEvents = PwMetadataEvents {
689            version: 0,
690            property: Some(on_metadata_property),
691        };
692
693        unsafe extern "C" fn on_metadata_property(
694            data: *mut c_void,
695            subject: u32,
696            key: *const c_char,
697            _type_: *const c_char,
698            value: *const c_char,
699        ) -> c_int {
700            // SAFETY: `data` points to `PwDefaultsOnlyState` and `key`/`value` are valid during callback.
701            unsafe {
702                if subject != 0 || key.is_null() || value.is_null() {
703                    return 0;
704                }
705                let Ok(key_str) = CStr::from_ptr(key).to_str() else {
706                    return 0;
707                };
708                let is_sink_key =
709                    key_str == "default.audio.sink" || key_str == "default.configured.audio.sink";
710                let is_source_key = key_str == "default.audio.source"
711                    || key_str == "default.configured.audio.source";
712                if !is_sink_key && !is_source_key {
713                    return 0;
714                }
715                let Ok(val_str) = CStr::from_ptr(value).to_str() else {
716                    return 0;
717                };
718                if let Some(parsed) = parse_pipewire_default_sink_metadata(val_str) {
719                    let st = &mut *(data as *mut PwDefaultsOnlyState<'_>);
720                    if is_sink_key {
721                        if key_str == "default.audio.sink" || st.metadata_default_sink.is_none() {
722                            st.metadata_default_sink = Some(parsed);
723                        }
724                    } else if key_str == "default.audio.source"
725                        || st.metadata_default_source.is_none()
726                    {
727                        st.metadata_default_source = Some(parsed);
728                    }
729                }
730                0
731            }
732        }
733
734        unsafe extern "C" fn on_core_done(data: *mut c_void, id: u32, seq: c_int) {
735            // SAFETY: `data` points to `PwDefaultsOnlyState`.
736            unsafe {
737                let st = &mut *(data as *mut PwDefaultsOnlyState<'_>);
738                if id == 0 && seq == st.sync_seq {
739                    if st.phase == 0 && !st.bound_proxies.is_empty() {
740                        st.phase = 1;
741                        st.sync_seq = st.lib.core_sync(st.core, 0, 2);
742                    } else {
743                        (st.quit_fn)(st.loop_ptr);
744                    }
745                }
746            }
747        }
748
749        unsafe extern "C" fn on_core_error(
750            data: *mut c_void,
751            _id: u32,
752            _seq: c_int,
753            _res: c_int,
754            _msg: *const c_char,
755        ) {
756            // SAFETY: `data` points to `PwDefaultsOnlyState`.
757            unsafe {
758                let st = &mut *(data as *mut PwDefaultsOnlyState<'_>);
759                st.failed = true;
760                (st.quit_fn)(st.loop_ptr);
761            }
762        }
763
764        unsafe extern "C" fn on_global(
765            data: *mut c_void,
766            id: u32,
767            _permissions: u32,
768            type_ptr: *const c_char,
769            _version: u32,
770            props: *const SpaDict,
771        ) {
772            // SAFETY: `data` points to `PwDefaultsOnlyState` and `type_ptr`/`props` are valid during callback.
773            unsafe {
774                if type_ptr.is_null() || props.is_null() {
775                    return;
776                }
777                let st = &mut *(data as *mut PwDefaultsOnlyState<'_>);
778                let Ok(type_str) = CStr::from_ptr(type_ptr).to_str() else {
779                    return;
780                };
781                match type_str {
782                    "PipeWire:Interface:Node" => {
783                        let media_class = SpaDict::lookup(props, "media.class").unwrap_or_default();
784                        if media_class == "Audio/Sink" {
785                            if let Some(name) = SpaDict::lookup(props, "node.name")
786                                && !is_internal_mixer_endpoint_name(&name)
787                            {
788                                st.sinks.push(name);
789                            }
790                        } else if (media_class == "Audio/Source"
791                            || media_class == "Audio/Source/Virtual")
792                            && let Some(name) = SpaDict::lookup(props, "node.name")
793                            && !name.ends_with(".monitor")
794                            && !is_internal_mixer_endpoint_name(&name)
795                        {
796                            st.sources.push(name);
797                        }
798                    }
799                    "PipeWire:Interface:Metadata"
800                        if SpaDict::lookup(props, "metadata.name").as_deref()
801                            == Some("default") =>
802                    {
803                        let proxy = st.lib.registry_bind(
804                            st.registry,
805                            id,
806                            c"PipeWire:Interface:Metadata".as_ptr(),
807                            3,
808                            0,
809                        );
810                        if !proxy.is_null() {
811                            let mut hook = Box::new(SpaHook::default());
812                            (st.lib.pw_proxy_add_object_listener)(
813                                proxy,
814                                &mut *hook,
815                                (&METADATA_EVENTS as *const PwMetadataEvents).cast(),
816                                data,
817                            );
818                            st.bound_proxies.push(BoundProxy { proxy, _hook: hook });
819                        }
820                    }
821                    _ => {}
822                }
823            }
824        }
825
826        // SAFETY: creates, runs, and destroys a single-thread `pw_main_loop` metadata snapshot.
827        unsafe {
828            let main_loop = (lib.pw_main_loop_new)(std::ptr::null());
829            if main_loop.is_null() {
830                return Err(CapabilityError::ServerUnavailable);
831            }
832            let loop_obj = (lib.pw_main_loop_get_loop)(main_loop);
833            let context = (lib.pw_context_new)(loop_obj, std::ptr::null_mut(), 0);
834            if context.is_null() {
835                (lib.pw_main_loop_destroy)(main_loop);
836                return Err(CapabilityError::ServerUnavailable);
837            }
838            let core = (lib.pw_context_connect)(context, std::ptr::null_mut(), 0);
839            if core.is_null() {
840                (lib.pw_context_destroy)(context);
841                (lib.pw_main_loop_destroy)(main_loop);
842                return Err(CapabilityError::ServerUnavailable);
843            }
844            let registry = lib.core_get_registry(core, 3, 0);
845            if registry.is_null() {
846                (lib.pw_core_disconnect)(core);
847                (lib.pw_context_destroy)(context);
848                (lib.pw_main_loop_destroy)(main_loop);
849                return Err(CapabilityError::ServerUnavailable);
850            }
851
852            let mut state = PwDefaultsOnlyState {
853                lib: &lib,
854                core,
855                registry,
856                loop_ptr: main_loop,
857                quit_fn: lib.pw_main_loop_quit,
858                sync_seq: 0,
859                phase: 0,
860                failed: false,
861                metadata_default_sink: None,
862                metadata_default_source: None,
863                sinks: Vec::new(),
864                sources: Vec::new(),
865                bound_proxies: Vec::new(),
866            };
867            let core_events = PwCoreEvents {
868                version: 0,
869                info: None::<unsafe extern "C" fn(*mut c_void, *const PwCoreInfo)>,
870                done: Some(on_core_done),
871                ping: None,
872                error: Some(on_core_error),
873                remove_id: None,
874                bound_id: None,
875                add_mem: None,
876                remove_mem: None,
877                bound_props: None,
878            };
879            let reg_events = PwRegistryEvents {
880                version: 0,
881                global: Some(on_global),
882                global_remove: None,
883            };
884            let mut core_hook = SpaHook::default();
885            let mut reg_hook = SpaHook::default();
886            let state_ptr: *mut c_void = (&mut state as *mut PwDefaultsOnlyState<'_>).cast();
887            lib.core_add_listener(core, &mut core_hook, &core_events, state_ptr);
888            lib.registry_add_listener(registry, &mut reg_hook, &reg_events, state_ptr);
889            state.sync_seq = lib.core_sync(core, 0, 1);
890            (lib.pw_main_loop_run)(main_loop);
891
892            for bp in state.bound_proxies {
893                if !bp.proxy.is_null() {
894                    (lib.pw_proxy_destroy)(bp.proxy);
895                }
896            }
897            (lib.pw_proxy_destroy)(registry);
898            (lib.pw_core_disconnect)(core);
899            (lib.pw_context_destroy)(context);
900            (lib.pw_main_loop_destroy)(main_loop);
901
902            if state.failed {
903                return Err(CapabilityError::ServerUnavailable);
904            }
905
906            let pa_probe = probe_pulse_server(paths).ok();
907            let default_sink_name = state
908                .metadata_default_sink
909                .filter(|meta_name| state.sinks.iter().any(|n| n == meta_name))
910                .or_else(|| {
911                    pa_probe
912                        .as_ref()
913                        .and_then(|p| p.default_sink_name.clone())
914                        .filter(|pa_name| state.sinks.iter().any(|n| n == pa_name))
915                })
916                .or_else(|| state.sinks.first().cloned());
917            let default_source_name = state
918                .metadata_default_source
919                .filter(|meta_name| state.sources.iter().any(|n| n == meta_name))
920                .or_else(|| {
921                    pa_probe
922                        .and_then(|p| p.default_source_name)
923                        .filter(|pa_name| state.sources.iter().any(|n| n == pa_name))
924                })
925                .or_else(|| state.sources.first().cloned());
926
927            Ok((default_sink_name, default_source_name))
928        }
929    }
930
931    pub fn collect_pulse_state(
932        paths: &LinuxClientPaths,
933    ) -> Result<PulseAudioStateSnapshot, CapabilityError> {
934        let (devs, _sources, pids, sink_inputs) = collect_pulse_full_state(paths)?;
935        Ok((devs, pids, sink_inputs))
936    }
937
938    pub fn collect_pulse_full_state(
939        paths: &LinuxClientPaths,
940    ) -> Result<PulseAudioFullStateSnapshot, CapabilityError> {
941        let lib = PulseLibrary::load(paths).map_err(|err| {
942            err.into_capability_error(BackendId::PulseAudio, paths.pulse_min_version)
943        })?;
944
945        struct PulseState {
946            mainloop: *mut c_void,
947            signal_fn: unsafe extern "C" fn(*mut c_void, c_int),
948            proplist_gets: unsafe extern "C" fn(*const c_void, *const c_char) -> *const c_char,
949            default_sink: Option<String>,
950            default_source: Option<String>,
951            sinks: Vec<(u32, String, Option<String>)>,
952            sources: Vec<PulseSourceRecord>,
953            client_pids: BTreeMap<u32, u32>,
954            sink_inputs: Vec<PulseSinkInputRecord>,
955            pending_ops: std::sync::atomic::AtomicUsize,
956        }
957
958        unsafe extern "C" fn on_ctx_state(_ctx: *mut c_void, userdata: *mut c_void) {
959            // SAFETY: `userdata` points to `PulseState`.
960            unsafe {
961                let st = &*(userdata as *const PulseState);
962                (st.signal_fn)(st.mainloop, 0);
963            }
964        }
965
966        unsafe extern "C" fn on_server_info(
967            _ctx: *mut c_void,
968            info: *const PaServerInfo,
969            userdata: *mut c_void,
970        ) {
971            // SAFETY: `userdata` points to `PulseState`.
972            unsafe {
973                let st = &mut *(userdata as *mut PulseState);
974                if !info.is_null() {
975                    let inf = &*info;
976                    if !inf.default_sink_name.is_null() {
977                        st.default_sink = Some(
978                            CStr::from_ptr(inf.default_sink_name)
979                                .to_string_lossy()
980                                .into_owned(),
981                        );
982                    }
983                    if !inf.default_source_name.is_null() {
984                        st.default_source = Some(
985                            CStr::from_ptr(inf.default_source_name)
986                                .to_string_lossy()
987                                .into_owned(),
988                        );
989                    }
990                }
991                st.pending_ops
992                    .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
993                (st.signal_fn)(st.mainloop, 0);
994            }
995        }
996
997        unsafe extern "C" fn on_sink_info(
998            _ctx: *mut c_void,
999            info: *const PaSinkInfo,
1000            eol: c_int,
1001            userdata: *mut c_void,
1002        ) {
1003            // SAFETY: `userdata` points to `PulseState`.
1004            unsafe {
1005                let st = &mut *(userdata as *mut PulseState);
1006                if eol != 0 {
1007                    st.pending_ops
1008                        .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
1009                    (st.signal_fn)(st.mainloop, 0);
1010                    return;
1011                }
1012                if !info.is_null() {
1013                    let inf = &*info;
1014                    if !inf.name.is_null() {
1015                        let name = CStr::from_ptr(inf.name).to_string_lossy().into_owned();
1016                        if !is_internal_mixer_endpoint_name(&name) {
1017                            let desc = if inf.description.is_null() {
1018                                None
1019                            } else {
1020                                Some(
1021                                    CStr::from_ptr(inf.description)
1022                                        .to_string_lossy()
1023                                        .into_owned(),
1024                                )
1025                            };
1026                            st.sinks.push((inf.index, name, desc));
1027                        }
1028                    }
1029                }
1030            }
1031        }
1032
1033        unsafe extern "C" fn on_source_info(
1034            _ctx: *mut c_void,
1035            info: *const PaSourceInfo,
1036            eol: c_int,
1037            userdata: *mut c_void,
1038        ) {
1039            // SAFETY: `userdata` points to `PulseState`.
1040            unsafe {
1041                let st = &mut *(userdata as *mut PulseState);
1042                if eol != 0 {
1043                    st.pending_ops
1044                        .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
1045                    (st.signal_fn)(st.mainloop, 0);
1046                    return;
1047                }
1048                if !info.is_null() {
1049                    let inf = &*info;
1050                    if !inf.name.is_null() {
1051                        let name = CStr::from_ptr(inf.name).to_string_lossy().into_owned();
1052                        if !is_internal_mixer_endpoint_name(&name) {
1053                            let desc = if inf.description.is_null() {
1054                                None
1055                            } else {
1056                                Some(
1057                                    CStr::from_ptr(inf.description)
1058                                        .to_string_lossy()
1059                                        .into_owned(),
1060                                )
1061                            };
1062                            let is_monitor = inf.monitor_of_sink != PA_INVALID_INDEX
1063                                || name.ends_with(".monitor");
1064                            st.sources.push(PulseSourceRecord {
1065                                index: inf.index,
1066                                name,
1067                                description: desc,
1068                                sample_format: inf.sample_spec.format,
1069                                rate_hz: inf.sample_spec.rate,
1070                                channels: inf.sample_spec.channels,
1071                                is_monitor,
1072                                is_default: false,
1073                            });
1074                        }
1075                    }
1076                }
1077            }
1078        }
1079
1080        unsafe extern "C" fn on_client_info(
1081            _ctx: *mut c_void,
1082            info: *const PaClientInfo,
1083            eol: c_int,
1084            userdata: *mut c_void,
1085        ) {
1086            // SAFETY: `userdata` points to `PulseState`.
1087            unsafe {
1088                let st = &mut *(userdata as *mut PulseState);
1089                if eol != 0 {
1090                    st.pending_ops
1091                        .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
1092                    (st.signal_fn)(st.mainloop, 0);
1093                    return;
1094                }
1095                if !info.is_null() {
1096                    let inf = &*info;
1097                    if !inf.proplist.is_null() {
1098                        let pid_ptr =
1099                            (st.proplist_gets)(inf.proplist, c"application.process.id".as_ptr());
1100                        if !pid_ptr.is_null()
1101                            && let Ok(pid_txt) = CStr::from_ptr(pid_ptr).to_str()
1102                            && let Ok(pid) = pid_txt.trim().parse::<u32>()
1103                        {
1104                            st.client_pids.insert(inf.index, pid);
1105                        }
1106                    }
1107                }
1108            }
1109        }
1110
1111        unsafe extern "C" fn on_sink_input_info(
1112            _ctx: *mut c_void,
1113            info: *const PaSinkInputInfo,
1114            eol: c_int,
1115            userdata: *mut c_void,
1116        ) {
1117            // SAFETY: `userdata` points to `PulseState`.
1118            unsafe {
1119                let st = &mut *(userdata as *mut PulseState);
1120                if eol != 0 {
1121                    st.pending_ops
1122                        .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
1123                    (st.signal_fn)(st.mainloop, 0);
1124                    return;
1125                }
1126                if !info.is_null() {
1127                    let inf = &*info;
1128                    let mut pid = None;
1129                    if !inf.proplist.is_null() {
1130                        let pid_ptr =
1131                            (st.proplist_gets)(inf.proplist, c"application.process.id".as_ptr());
1132                        if !pid_ptr.is_null()
1133                            && let Ok(pid_txt) = CStr::from_ptr(pid_ptr).to_str()
1134                        {
1135                            pid = pid_txt.trim().parse::<u32>().ok();
1136                        }
1137                    }
1138                    st.sink_inputs.push(PulseSinkInputRecord {
1139                        index: inf.index,
1140                        sink_index: inf.sink,
1141                        client_index: inf.client,
1142                        pid,
1143                        rate_hz: inf.sample_spec.rate,
1144                        channels: inf.sample_spec.channels,
1145                        corked: inf.corked != 0,
1146                    });
1147                }
1148            }
1149        }
1150
1151        // SAFETY: `pa_threaded_mainloop` and `pa_context` follow standard locking and unref rules.
1152        unsafe {
1153            let mainloop = (lib.pa_threaded_mainloop_new)();
1154            if mainloop.is_null() {
1155                return Err(CapabilityError::ServerUnavailable);
1156            }
1157            let api = (lib.pa_threaded_mainloop_get_api)(mainloop);
1158            let ctx = (lib.pa_context_new)(api, c"cspa-discovery".as_ptr());
1159            if ctx.is_null() {
1160                (lib.pa_threaded_mainloop_free)(mainloop);
1161                return Err(CapabilityError::ServerUnavailable);
1162            }
1163            let mut st = Box::new(PulseState {
1164                mainloop,
1165                signal_fn: lib.pa_threaded_mainloop_signal,
1166                proplist_gets: lib.pa_proplist_gets,
1167                default_sink: None,
1168                default_source: None,
1169                sinks: Vec::new(),
1170                sources: Vec::new(),
1171                client_pids: BTreeMap::new(),
1172                sink_inputs: Vec::new(),
1173                pending_ops: std::sync::atomic::AtomicUsize::new(5),
1174            });
1175            let st_ptr: *mut c_void = (&mut *st as *mut PulseState).cast();
1176            (lib.pa_context_set_state_callback)(ctx, Some(on_ctx_state), st_ptr);
1177            if (lib.pa_context_connect)(
1178                ctx,
1179                std::ptr::null(),
1180                PA_CONTEXT_NOAUTOSPAWN,
1181                std::ptr::null(),
1182            ) < 0
1183            {
1184                (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1185                (lib.pa_context_unref)(ctx);
1186                (lib.pa_threaded_mainloop_free)(mainloop);
1187                return Err(CapabilityError::ServerUnavailable);
1188            }
1189            if (lib.pa_threaded_mainloop_start)(mainloop) < 0 {
1190                (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1191                (lib.pa_context_disconnect)(ctx);
1192                (lib.pa_context_unref)(ctx);
1193                (lib.pa_threaded_mainloop_free)(mainloop);
1194                return Err(CapabilityError::ServerUnavailable);
1195            }
1196            (lib.pa_threaded_mainloop_lock)(mainloop);
1197            loop {
1198                let state = (lib.pa_context_get_state)(ctx);
1199                if state == PA_CONTEXT_READY {
1200                    break;
1201                }
1202                if state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED {
1203                    (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1204                    (lib.pa_threaded_mainloop_unlock)(mainloop);
1205                    (lib.pa_threaded_mainloop_stop)(mainloop);
1206                    (lib.pa_context_disconnect)(ctx);
1207                    (lib.pa_context_unref)(ctx);
1208                    (lib.pa_threaded_mainloop_free)(mainloop);
1209                    return Err(CapabilityError::ServerUnavailable);
1210                }
1211                (lib.pa_threaded_mainloop_wait)(mainloop);
1212            }
1213            let op1 = (lib.pa_context_get_server_info)(ctx, Some(on_server_info), st_ptr);
1214            let op2 = (lib.pa_context_get_sink_info_list)(ctx, Some(on_sink_info), st_ptr);
1215            let op3 = (lib.pa_context_get_source_info_list)(ctx, Some(on_source_info), st_ptr);
1216            let op4 = (lib.pa_context_get_client_info_list)(ctx, Some(on_client_info), st_ptr);
1217            let op5 =
1218                (lib.pa_context_get_sink_input_info_list)(ctx, Some(on_sink_input_info), st_ptr);
1219            while st.pending_ops.load(std::sync::atomic::Ordering::SeqCst) > 0 {
1220                (lib.pa_threaded_mainloop_wait)(mainloop);
1221            }
1222            for op in [op1, op2, op3, op4, op5] {
1223                if !op.is_null() {
1224                    (lib.pa_operation_unref)(op);
1225                }
1226            }
1227            (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1228            (lib.pa_context_disconnect)(ctx);
1229            (lib.pa_threaded_mainloop_unlock)(mainloop);
1230            (lib.pa_threaded_mainloop_stop)(mainloop);
1231            (lib.pa_context_unref)(ctx);
1232            (lib.pa_threaded_mainloop_free)(mainloop);
1233
1234            let mut devices = Vec::new();
1235            for (idx, name, desc) in &st.sinks {
1236                let is_default = st.default_sink.as_deref() == Some(name.as_str());
1237                devices.push(PulseSinkRecord {
1238                    index: *idx,
1239                    name: name.clone(),
1240                    description: desc.clone(),
1241                    is_default,
1242                });
1243            }
1244
1245            let mut any_default_src = false;
1246            for src in &mut st.sources {
1247                if !src.is_monitor && st.default_source.as_deref() == Some(src.name.as_str()) {
1248                    src.is_default = true;
1249                    any_default_src = true;
1250                }
1251            }
1252            if !any_default_src
1253                && let Some(first_non_mon) = st.sources.iter_mut().find(|s| !s.is_monitor)
1254            {
1255                first_non_mon.is_default = true;
1256            }
1257
1258            let mut pid_audio: BTreeMap<u32, bool> = BTreeMap::new();
1259            for input in &mut st.sink_inputs {
1260                if input.pid.is_none()
1261                    && let Some(&client_pid) = st.client_pids.get(&input.client_index)
1262                {
1263                    input.pid = Some(client_pid);
1264                }
1265                if let Some(pid) = input.pid.filter(|&p| p > 0) {
1266                    let entry = pid_audio.entry(pid).or_insert(false);
1267                    if !input.corked {
1268                        *entry = true;
1269                    }
1270                }
1271            }
1272
1273            Ok((devices, st.sources, pid_audio, st.sink_inputs))
1274        }
1275    }
1276
1277    pub fn spawn_pulse_server_event_listener(
1278        paths: &LinuxClientPaths,
1279        latest_sink: Arc<Mutex<Option<String>>>,
1280        dirty: Arc<AtomicBool>,
1281        wake: thread::Thread,
1282        stop: Arc<AtomicBool>,
1283        include_stream_events: bool,
1284    ) -> Option<JoinHandle<()>> {
1285        spawn_pulse_server_event_listener_ext(
1286            paths,
1287            Some(latest_sink),
1288            None,
1289            dirty,
1290            wake,
1291            stop,
1292            include_stream_events,
1293            false,
1294        )
1295    }
1296
1297    #[allow(clippy::too_many_arguments)]
1298    pub fn spawn_pulse_server_event_listener_ext(
1299        paths: &LinuxClientPaths,
1300        latest_sink: Option<Arc<Mutex<Option<String>>>>,
1301        latest_source: Option<Arc<Mutex<Option<String>>>>,
1302        dirty: Arc<AtomicBool>,
1303        wake: thread::Thread,
1304        stop: Arc<AtomicBool>,
1305        include_stream_events: bool,
1306        watch_sources: bool,
1307    ) -> Option<JoinHandle<()>> {
1308        let lib = PulseLibrary::load(paths).ok()?;
1309        Some(thread::spawn(move || {
1310            const PA_SUB_MASK_SINK_AND_SERVER: c_int = 0x0081;
1311            const PA_SUB_MASK_SOURCE_AND_SERVER: c_int = 0x0082;
1312            const PA_SUB_MASK_DISCOVERY: c_int = 0x00A7;
1313
1314            struct SubState {
1315                mainloop: *mut c_void,
1316                signal_fn: unsafe extern "C" fn(*mut c_void, c_int),
1317                get_server_info: unsafe extern "C" fn(
1318                    *mut c_void,
1319                    Option<unsafe extern "C" fn(*mut c_void, *const PaServerInfo, *mut c_void)>,
1320                    *mut c_void,
1321                ) -> *mut c_void,
1322                op_unref: unsafe extern "C" fn(*mut c_void),
1323                latest_sink: Option<Arc<Mutex<Option<String>>>>,
1324                latest_source: Option<Arc<Mutex<Option<String>>>>,
1325                dirty: Arc<AtomicBool>,
1326                wake: thread::Thread,
1327            }
1328
1329            unsafe extern "C" fn on_state(_ctx: *mut c_void, userdata: *mut c_void) {
1330                if !userdata.is_null() {
1331                    // SAFETY: `userdata` points to `SubState`.
1332                    unsafe {
1333                        let st = &*(userdata as *const SubState);
1334                        (st.signal_fn)(st.mainloop, 0);
1335                    }
1336                }
1337            }
1338
1339            unsafe extern "C" fn on_server_info(
1340                _ctx: *mut c_void,
1341                info: *const PaServerInfo,
1342                userdata: *mut c_void,
1343            ) {
1344                if userdata.is_null() {
1345                    return;
1346                }
1347                // SAFETY: `userdata` points to `SubState` and `info` is valid during callback.
1348                unsafe {
1349                    let st = &*(userdata as *const SubState);
1350                    if !info.is_null() {
1351                        let inf = &*info;
1352                        if let Some(ref sink_cell) = st.latest_sink
1353                            && !inf.default_sink_name.is_null()
1354                        {
1355                            let sink = CStr::from_ptr(inf.default_sink_name)
1356                                .to_string_lossy()
1357                                .into_owned();
1358                            if !sink.is_empty() {
1359                                *sink_cell.lock().unwrap_or_else(|e| e.into_inner()) = Some(sink);
1360                            }
1361                        }
1362                        if let Some(ref src_cell) = st.latest_source
1363                            && !inf.default_source_name.is_null()
1364                        {
1365                            let src = CStr::from_ptr(inf.default_source_name)
1366                                .to_string_lossy()
1367                                .into_owned();
1368                            if !src.is_empty() && !src.ends_with(".monitor") {
1369                                *src_cell.lock().unwrap_or_else(|e| e.into_inner()) = Some(src);
1370                            }
1371                        }
1372                    }
1373                    st.dirty.store(true, SeqCst);
1374                    st.wake.unpark();
1375                    (st.signal_fn)(st.mainloop, 0);
1376                }
1377            }
1378
1379            unsafe extern "C" fn on_subscribe(
1380                ctx: *mut c_void,
1381                event_type: c_int,
1382                _idx: u32,
1383                userdata: *mut c_void,
1384            ) {
1385                if userdata.is_null() || ctx.is_null() {
1386                    return;
1387                }
1388                // SAFETY: `userdata` points to `SubState`; queries updated server info on sink/source/server event.
1389                unsafe {
1390                    let st = &*(userdata as *const SubState);
1391                    st.dirty.store(true, SeqCst);
1392                    let facility = event_type & 0x000F;
1393                    if facility == 0x0000 || facility == 0x0001 || facility == 0x0007 {
1394                        let op = (st.get_server_info)(ctx, Some(on_server_info), userdata);
1395                        if !op.is_null() {
1396                            (st.op_unref)(op);
1397                        }
1398                    }
1399                    st.wake.unpark();
1400                }
1401            }
1402
1403            // SAFETY: manages dedicated `pa_threaded_mainloop` + `pa_context_subscribe` until `stop` is set.
1404            unsafe {
1405                let mainloop = (lib.pa_threaded_mainloop_new)();
1406                if mainloop.is_null() {
1407                    return;
1408                }
1409                let api = (lib.pa_threaded_mainloop_get_api)(mainloop);
1410                let ctx = (lib.pa_context_new)(api, c"cspa-sub".as_ptr());
1411                if ctx.is_null() {
1412                    (lib.pa_threaded_mainloop_free)(mainloop);
1413                    return;
1414                }
1415                let mut st = Box::new(SubState {
1416                    mainloop,
1417                    signal_fn: lib.pa_threaded_mainloop_signal,
1418                    get_server_info: lib.pa_context_get_server_info,
1419                    op_unref: lib.pa_operation_unref,
1420                    latest_sink,
1421                    latest_source,
1422                    dirty,
1423                    wake,
1424                });
1425                let st_ptr: *mut c_void = (&mut *st as *mut SubState).cast();
1426                (lib.pa_context_set_state_callback)(ctx, Some(on_state), st_ptr);
1427                if (lib.pa_context_connect)(
1428                    ctx,
1429                    std::ptr::null(),
1430                    PA_CONTEXT_NOAUTOSPAWN,
1431                    std::ptr::null(),
1432                ) < 0
1433                {
1434                    (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1435                    (lib.pa_context_unref)(ctx);
1436                    (lib.pa_threaded_mainloop_free)(mainloop);
1437                    return;
1438                }
1439                if (lib.pa_threaded_mainloop_start)(mainloop) < 0 {
1440                    (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1441                    (lib.pa_context_disconnect)(ctx);
1442                    (lib.pa_context_unref)(ctx);
1443                    (lib.pa_threaded_mainloop_free)(mainloop);
1444                    return;
1445                }
1446                (lib.pa_threaded_mainloop_lock)(mainloop);
1447                let mut ready = false;
1448                while !stop.load(SeqCst) {
1449                    let state = (lib.pa_context_get_state)(ctx);
1450                    if state == PA_CONTEXT_READY {
1451                        ready = true;
1452                        break;
1453                    }
1454                    if state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED {
1455                        break;
1456                    }
1457                    (lib.pa_threaded_mainloop_wait)(mainloop);
1458                }
1459                if ready {
1460                    (lib.pa_context_set_subscribe_callback)(ctx, Some(on_subscribe), st_ptr);
1461                    let mask = if include_stream_events {
1462                        PA_SUB_MASK_DISCOVERY
1463                    } else if watch_sources {
1464                        PA_SUB_MASK_SOURCE_AND_SERVER
1465                    } else {
1466                        PA_SUB_MASK_SINK_AND_SERVER
1467                    };
1468                    let sub_op = (lib.pa_context_subscribe)(ctx, mask, None, st_ptr);
1469                    if !sub_op.is_null() {
1470                        (lib.pa_operation_unref)(sub_op);
1471                    }
1472                    let info_op =
1473                        (lib.pa_context_get_server_info)(ctx, Some(on_server_info), st_ptr);
1474                    if !info_op.is_null() {
1475                        (lib.pa_operation_unref)(info_op);
1476                    }
1477                }
1478                (lib.pa_threaded_mainloop_unlock)(mainloop);
1479
1480                while !stop.load(SeqCst) {
1481                    thread::sleep(Duration::from_millis(20));
1482                }
1483
1484                (lib.pa_threaded_mainloop_lock)(mainloop);
1485                (lib.pa_context_set_subscribe_callback)(ctx, None, std::ptr::null_mut());
1486                (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1487                (lib.pa_context_disconnect)(ctx);
1488                (lib.pa_threaded_mainloop_unlock)(mainloop);
1489                (lib.pa_threaded_mainloop_stop)(mainloop);
1490                (lib.pa_context_unref)(ctx);
1491                (lib.pa_threaded_mainloop_free)(mainloop);
1492            }
1493        }))
1494    }
1495
1496    pub fn spawn_pulse_new_sink_input_watcher(
1497        paths: &LinuxClientPaths,
1498        dirty: Arc<AtomicBool>,
1499        stop: Arc<AtomicBool>,
1500    ) -> Option<JoinHandle<()>> {
1501        let lib = PulseLibrary::load(paths).ok()?;
1502        Some(thread::spawn(move || {
1503            const PA_SUBSCRIPTION_MASK_SINK_INPUT: c_int = 0x0004;
1504            const PA_SUBSCRIPTION_EVENT_FACILITY_MASK: c_int = 0x000F;
1505            const PA_SUBSCRIPTION_EVENT_SINK_INPUT: c_int = 0x0002;
1506            const PA_SUBSCRIPTION_EVENT_TYPE_MASK: c_int = 0x0030;
1507            const PA_SUBSCRIPTION_EVENT_NEW: c_int = 0x0000;
1508
1509            struct NewSiState {
1510                mainloop: *mut c_void,
1511                signal_fn: unsafe extern "C" fn(*mut c_void, c_int),
1512                dirty: Arc<AtomicBool>,
1513            }
1514
1515            unsafe extern "C" fn on_state(_ctx: *mut c_void, userdata: *mut c_void) {
1516                if !userdata.is_null() {
1517                    // SAFETY: `userdata` points to `NewSiState`.
1518                    unsafe {
1519                        let st = &*(userdata as *const NewSiState);
1520                        (st.signal_fn)(st.mainloop, 0);
1521                    }
1522                }
1523            }
1524
1525            unsafe extern "C" fn on_subscribe(
1526                _ctx: *mut c_void,
1527                event_type: c_int,
1528                _idx: u32,
1529                userdata: *mut c_void,
1530            ) {
1531                if userdata.is_null() {
1532                    return;
1533                }
1534                if (event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
1535                    == PA_SUBSCRIPTION_EVENT_SINK_INPUT
1536                    && (event_type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW
1537                {
1538                    // SAFETY: `userdata` points to `NewSiState`; sets `dirty` only on newly created sink-inputs.
1539                    unsafe {
1540                        let st = &*(userdata as *const NewSiState);
1541                        st.dirty.store(true, SeqCst);
1542                    }
1543                }
1544            }
1545
1546            // SAFETY: manages dedicated `pa_threaded_mainloop` + `pa_context_subscribe` until `stop` is set.
1547            unsafe {
1548                let mainloop = (lib.pa_threaded_mainloop_new)();
1549                if mainloop.is_null() {
1550                    return;
1551                }
1552                let api = (lib.pa_threaded_mainloop_get_api)(mainloop);
1553                let ctx = (lib.pa_context_new)(api, c"cspa-si-watch".as_ptr());
1554                if ctx.is_null() {
1555                    (lib.pa_threaded_mainloop_free)(mainloop);
1556                    return;
1557                }
1558                let mut st = Box::new(NewSiState {
1559                    mainloop,
1560                    signal_fn: lib.pa_threaded_mainloop_signal,
1561                    dirty,
1562                });
1563                let st_ptr: *mut c_void = (&mut *st as *mut NewSiState).cast();
1564                (lib.pa_context_set_state_callback)(ctx, Some(on_state), st_ptr);
1565                if (lib.pa_context_connect)(
1566                    ctx,
1567                    std::ptr::null(),
1568                    PA_CONTEXT_NOAUTOSPAWN,
1569                    std::ptr::null(),
1570                ) < 0
1571                {
1572                    (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1573                    (lib.pa_context_unref)(ctx);
1574                    (lib.pa_threaded_mainloop_free)(mainloop);
1575                    return;
1576                }
1577                if (lib.pa_threaded_mainloop_start)(mainloop) < 0 {
1578                    (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1579                    (lib.pa_context_disconnect)(ctx);
1580                    (lib.pa_context_unref)(ctx);
1581                    (lib.pa_threaded_mainloop_free)(mainloop);
1582                    return;
1583                }
1584                (lib.pa_threaded_mainloop_lock)(mainloop);
1585                let mut ready = false;
1586                while !stop.load(SeqCst) {
1587                    let state = (lib.pa_context_get_state)(ctx);
1588                    if state == PA_CONTEXT_READY {
1589                        ready = true;
1590                        break;
1591                    }
1592                    if state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED {
1593                        break;
1594                    }
1595                    (lib.pa_threaded_mainloop_wait)(mainloop);
1596                }
1597                if ready {
1598                    (lib.pa_context_set_subscribe_callback)(ctx, Some(on_subscribe), st_ptr);
1599                    let sub_op = (lib.pa_context_subscribe)(
1600                        ctx,
1601                        PA_SUBSCRIPTION_MASK_SINK_INPUT,
1602                        None,
1603                        st_ptr,
1604                    );
1605                    if !sub_op.is_null() {
1606                        (lib.pa_operation_unref)(sub_op);
1607                    }
1608                }
1609                (lib.pa_threaded_mainloop_unlock)(mainloop);
1610
1611                while !stop.load(SeqCst) {
1612                    thread::sleep(Duration::from_millis(20));
1613                }
1614
1615                (lib.pa_threaded_mainloop_lock)(mainloop);
1616                (lib.pa_context_set_subscribe_callback)(ctx, None, std::ptr::null_mut());
1617                (lib.pa_context_set_state_callback)(ctx, None, std::ptr::null_mut());
1618                (lib.pa_context_disconnect)(ctx);
1619                (lib.pa_threaded_mainloop_unlock)(mainloop);
1620                (lib.pa_threaded_mainloop_stop)(mainloop);
1621                (lib.pa_context_unref)(ctx);
1622                (lib.pa_threaded_mainloop_free)(mainloop);
1623            }
1624        }))
1625    }
1626}
1627
1628#[cfg(target_os = "linux")]
1629pub use imp::{
1630    collect_pipewire_graph, collect_pulse_full_state, collect_pulse_state,
1631    query_pipewire_default_sink_only, query_pipewire_defaults_only,
1632    spawn_pulse_new_sink_input_watcher, spawn_pulse_server_event_listener,
1633    spawn_pulse_server_event_listener_ext,
1634};
1635
1636#[cfg(not(target_os = "linux"))]
1637pub fn spawn_pulse_new_sink_input_watcher(
1638    _paths: &LinuxClientPaths,
1639    _dirty: Arc<AtomicBool>,
1640    _stop: Arc<AtomicBool>,
1641) -> Option<JoinHandle<()>> {
1642    None
1643}
1644
1645#[cfg(not(target_os = "linux"))]
1646pub fn spawn_pulse_server_event_listener(
1647    _paths: &LinuxClientPaths,
1648    _latest_sink: Arc<Mutex<Option<String>>>,
1649    _dirty: Arc<AtomicBool>,
1650    _wake: thread::Thread,
1651    _stop: Arc<AtomicBool>,
1652    _include_stream_events: bool,
1653) -> Option<JoinHandle<()>> {
1654    None
1655}
1656
1657#[cfg(not(target_os = "linux"))]
1658#[allow(clippy::too_many_arguments)]
1659pub fn spawn_pulse_server_event_listener_ext(
1660    _paths: &LinuxClientPaths,
1661    _latest_sink: Option<Arc<Mutex<Option<String>>>>,
1662    _latest_source: Option<Arc<Mutex<Option<String>>>>,
1663    _dirty: Arc<AtomicBool>,
1664    _wake: thread::Thread,
1665    _stop: Arc<AtomicBool>,
1666    _include_stream_events: bool,
1667    _watch_sources: bool,
1668) -> Option<JoinHandle<()>> {
1669    None
1670}
1671
1672#[cfg(not(target_os = "linux"))]
1673pub fn query_pipewire_default_sink_only(
1674    paths: &LinuxClientPaths,
1675) -> Result<Option<String>, CapabilityError> {
1676    Err(
1677        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1678            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1679    )
1680}
1681
1682#[cfg(not(target_os = "linux"))]
1683pub fn query_pipewire_defaults_only(
1684    paths: &LinuxClientPaths,
1685) -> Result<(Option<String>, Option<String>), CapabilityError> {
1686    Err(
1687        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1688            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1689    )
1690}
1691
1692#[cfg(not(target_os = "linux"))]
1693pub fn collect_pipewire_graph(
1694    paths: &LinuxClientPaths,
1695) -> Result<PipeWireGraphSnapshot, CapabilityError> {
1696    Err(
1697        crate::loader::ClientLoadError::LibraryAbsent(paths.pipewire_so.clone())
1698            .into_capability_error(BackendId::PipeWire, paths.pipewire_min_version),
1699    )
1700}
1701
1702#[cfg(not(target_os = "linux"))]
1703pub fn collect_pulse_state(
1704    paths: &LinuxClientPaths,
1705) -> Result<PulseAudioStateSnapshot, CapabilityError> {
1706    Err(
1707        crate::loader::ClientLoadError::LibraryAbsent(paths.pulse_so.clone())
1708            .into_capability_error(BackendId::PulseAudio, paths.pulse_min_version),
1709    )
1710}
1711
1712#[cfg(not(target_os = "linux"))]
1713pub fn collect_pulse_full_state(
1714    paths: &LinuxClientPaths,
1715) -> Result<PulseAudioFullStateSnapshot, CapabilityError> {
1716    Err(
1717        crate::loader::ClientLoadError::LibraryAbsent(paths.pulse_so.clone())
1718            .into_capability_error(BackendId::PulseAudio, paths.pulse_min_version),
1719    )
1720}
1721
1722fn is_ignored_audio_stream_name(raw: &str) -> bool {
1723    let trimmed = raw.trim();
1724    if trimmed.is_empty() {
1725        return true;
1726    }
1727    let lower = trimmed.to_ascii_lowercase();
1728    lower.starts_with("cspa-")
1729        || matches!(
1730            lower.as_str(),
1731            "pactl"
1732                | "pw-cli"
1733                | "pw-cat"
1734                | "pw-play"
1735                | "pw-record"
1736                | "paplay"
1737                | "parec"
1738                | "pacat"
1739                | "playback stream"
1740                | "audio stream"
1741        )
1742        || crate::core::discovery::is_runtime_interpreter_stem(&lower)
1743}
1744
1745/// Collect input devices, output devices, and processes from configured Linux backends.
1746pub fn collect_linux_backend_inventory_with_paths(
1747    paths: &LinuxClientPaths,
1748    backends: &Backends,
1749) -> Result<BackendRawInventory, CapabilityError> {
1750    let proc_table = collect_proc_table(Path::new("/proc"))?;
1751    let mut backend_devices = Vec::new();
1752    let mut pid_audio: BTreeMap<u32, bool> = BTreeMap::new();
1753    let mut pw_pids: Option<BTreeMap<u32, bool>> = None;
1754    let mut pa_pids: Option<BTreeMap<u32, bool>> = None;
1755    let mut pid_audio_name: BTreeMap<u32, String> = BTreeMap::new();
1756    let mut active_backends_ok = Vec::new();
1757    let mut last_err = CapabilityError::InvalidBackend;
1758
1759    for &backend in backends.for_os(PlatformOs::Linux) {
1760        match backend {
1761            BackendId::PipeWire => match collect_pipewire_graph(paths) {
1762                Ok(graph) => {
1763                    active_backends_ok.push(BackendId::PipeWire);
1764                    let mut this_pw_pids: BTreeMap<u32, bool> = BTreeMap::new();
1765                    for (_id, name, desc) in &graph.sinks {
1766                        let is_def = graph.default_sink_name.as_deref() == Some(name.as_str());
1767                        let friendly: Arc<str> =
1768                            desc.clone().unwrap_or_else(|| name.clone()).into();
1769                        backend_devices.push(RawBackendDeviceRecord {
1770                            backend: BackendId::PipeWire,
1771                            direction: DeviceDirection::Output,
1772                            device_id: name.clone().into(),
1773                            name: Some(friendly),
1774                            is_default: is_def,
1775                            is_monitor_sink: false,
1776                        });
1777                    }
1778                    for (_id, name, desc) in &graph.sources {
1779                        let is_def = graph.default_source_name.as_deref() == Some(name.as_str());
1780                        let friendly: Arc<str> =
1781                            desc.clone().unwrap_or_else(|| name.clone()).into();
1782                        backend_devices.push(RawBackendDeviceRecord {
1783                            backend: BackendId::PipeWire,
1784                            direction: DeviceDirection::Input,
1785                            device_id: name.clone().into(),
1786                            name: Some(friendly),
1787                            is_default: is_def,
1788                            is_monitor_sink: name.ends_with(".monitor"),
1789                        });
1790                    }
1791                    for node in &graph.output_nodes {
1792                        if let Some(pid) = node.pid.filter(|&p| p > 0) {
1793                            let entry = pid_audio.entry(pid).or_insert(false);
1794                            let pw_entry = this_pw_pids.entry(pid).or_insert(false);
1795                            if node.active {
1796                                *entry = true;
1797                                *pw_entry = true;
1798                            }
1799                            if let Some(ref n) = node.node_name
1800                                && !is_ignored_audio_stream_name(n)
1801                            {
1802                                pid_audio_name.entry(pid).or_insert_with(|| n.clone());
1803                            }
1804                        }
1805                    }
1806                    pw_pids = Some(this_pw_pids);
1807                }
1808                Err(err) => {
1809                    last_err = err;
1810                }
1811            },
1812            BackendId::PulseAudio => match collect_pulse_full_state(paths) {
1813                Ok((pa_devs, pa_sources, pa_pid_map, _inputs)) => {
1814                    active_backends_ok.push(BackendId::PulseAudio);
1815                    for d in &pa_devs {
1816                        let friendly: Arc<str> = d
1817                            .description
1818                            .clone()
1819                            .unwrap_or_else(|| d.name.clone())
1820                            .into();
1821                        backend_devices.push(RawBackendDeviceRecord {
1822                            backend: BackendId::PulseAudio,
1823                            direction: DeviceDirection::Output,
1824                            device_id: d.name.clone().into(),
1825                            name: Some(friendly),
1826                            is_default: d.is_default,
1827                            is_monitor_sink: false,
1828                        });
1829                    }
1830                    for src in &pa_sources {
1831                        let friendly: Arc<str> = src
1832                            .description
1833                            .clone()
1834                            .unwrap_or_else(|| src.name.clone())
1835                            .into();
1836                        backend_devices.push(RawBackendDeviceRecord {
1837                            backend: BackendId::PulseAudio,
1838                            direction: DeviceDirection::Input,
1839                            device_id: src.name.clone().into(),
1840                            name: Some(friendly),
1841                            is_default: src.is_default,
1842                            is_monitor_sink: src.is_monitor,
1843                        });
1844                    }
1845                    for (&pid, &active) in &pa_pid_map {
1846                        let entry = pid_audio.entry(pid).or_insert(false);
1847                        if active {
1848                            *entry = true;
1849                        }
1850                    }
1851                    pa_pids = Some(pa_pid_map);
1852                }
1853                Err(err) => {
1854                    last_err = err;
1855                }
1856            },
1857            _ => {}
1858        }
1859    }
1860
1861    if active_backends_ok.is_empty() {
1862        return Err(last_err);
1863    }
1864
1865    let mut backend_processes = Vec::new();
1866    for (pid, (stat, exe_opt)) in proc_table {
1867        let parent_pid = (stat.ppid > 0 && stat.ppid != pid).then_some(stat.ppid);
1868        let exe_str = exe_opt.unwrap_or_else(|| stat.comm.clone());
1869        let cgroup_app_id = crate::procfs::inspect_process_cgroup_app_id(Path::new("/proc"), pid);
1870        let audio_name = pid_audio_name.remove(&pid);
1871
1872        let comm_lower = stat.comm.to_ascii_lowercase();
1873        let display_name = match &audio_name {
1874            Some(an)
1875                if crate::core::discovery::is_runtime_interpreter_stem(&comm_lower)
1876                    || an.to_ascii_lowercase().starts_with(&comm_lower) =>
1877            {
1878                an.clone()
1879            }
1880            _ => stat.comm.clone(),
1881        };
1882
1883        let app_id_str = if let Some(cg_id) = cgroup_app_id {
1884            cg_id
1885        } else if let Some(ref an) = audio_name
1886            && an.contains('.')
1887            && !an.contains(['/', '\\', ' ', '\t'])
1888        {
1889            an.clone()
1890        } else if display_name.contains('.') && !display_name.contains(['/', '\\', ' ', '\t']) {
1891            display_name.clone()
1892        } else {
1893            exe_str.clone()
1894        };
1895
1896        let name_arc: Arc<str> = display_name.into();
1897        let exe_arc: Arc<str> = exe_str.into();
1898        let app_id_arc: Arc<str> = app_id_str.into();
1899        let active_audio = pid_audio.get(&pid).copied();
1900        let base_rec = RawProcessRecord {
1901            identity: crate::core::schema::ProcessIdentity {
1902                pid,
1903                generation: stat.starttime_ticks,
1904            },
1905            parent_pid,
1906            app_id: Some(app_id_arc),
1907            name: Some(name_arc),
1908            executable_path: Some(exe_arc),
1909            active_audio,
1910        };
1911        for &ok_backend in &active_backends_ok {
1912            let mut per_b = base_rec.clone();
1913            per_b.active_audio = match ok_backend {
1914                BackendId::PipeWire => pw_pids.as_ref().and_then(|m| m.get(&pid).copied()),
1915                BackendId::PulseAudio => pa_pids.as_ref().and_then(|m| m.get(&pid).copied()),
1916                _ => active_audio,
1917            };
1918            backend_processes.push(RawBackendProcessRecord {
1919                backend: ok_backend,
1920                process: per_b,
1921            });
1922        }
1923    }
1924
1925    Ok(BackendRawInventory {
1926        processes: backend_processes,
1927        devices: backend_devices,
1928    })
1929}
1930
1931struct WatcherWorker {
1932    stop: Arc<AtomicBool>,
1933    join: Option<JoinHandle<()>>,
1934}
1935
1936impl WatcherWorker {
1937    fn stop_and_join(&mut self) {
1938        self.stop.store(true, SeqCst);
1939        if let Some(handle) = self.join.take() {
1940            handle.thread().unpark();
1941            let _ = handle.join();
1942        }
1943    }
1944}
1945
1946impl Drop for WatcherWorker {
1947    fn drop(&mut self) {
1948        self.stop_and_join();
1949    }
1950}
1951
1952/// One-shot calls never spawn background watcher threads.
1953#[derive(Clone)]
1954pub struct PlatformDiscovery {
1955    service: DiscoveryService,
1956    paths: LinuxClientPaths,
1957    backends: Backends,
1958    watcher: Arc<Mutex<Option<WatcherWorker>>>,
1959}
1960
1961impl Default for PlatformDiscovery {
1962    fn default() -> Self {
1963        <Self as DiscoveryBackend>::new()
1964    }
1965}
1966
1967impl PlatformDiscovery {
1968    pub(crate) fn from_config(paths: LinuxClientPaths, backends: Backends) -> Self {
1969        Self {
1970            service: DiscoveryService::new_for_os(PlatformOs::Linux),
1971            paths,
1972            backends,
1973            watcher: Arc::new(Mutex::new(None)),
1974        }
1975    }
1976
1977    #[cfg(any(test, feature = "native-tests"))]
1978    pub fn with_config(
1979        paths: LinuxClientPaths,
1980        backends: Backends,
1981    ) -> Result<Self, CapabilityError> {
1982        backends.validate()?;
1983        Ok(Self::from_config(paths, backends))
1984    }
1985
1986    fn ensure_watcher_started(&self) {
1987        let mut guard = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
1988        if guard.is_some() {
1989            return;
1990        }
1991        let stop = Arc::new(AtomicBool::new(false));
1992        let stop_bg = stop.clone();
1993        let service = self.service.clone();
1994        let paths = self.paths.clone();
1995        let backends = self.backends.clone();
1996
1997        let join = thread::spawn(move || {
1998            let dirty = Arc::new(AtomicBool::new(true));
1999            let latest_sink = Arc::new(Mutex::new(None));
2000            let sub_handle = spawn_pulse_server_event_listener(
2001                &paths,
2002                latest_sink,
2003                dirty.clone(),
2004                thread::current(),
2005                stop_bg.clone(),
2006                true,
2007            );
2008            let mut last_scan = std::time::Instant::now()
2009                .checked_sub(Duration::from_secs(1))
2010                .unwrap_or_else(std::time::Instant::now);
2011
2012            let linux_query =
2013                DiscoveryQuery::all_for_os(PlatformOs::Linux).with_backends(backends.clone());
2014
2015            while !stop_bg.load(SeqCst) {
2016                if service.active_subscriber_count() == 0 {
2017                    stop_bg.store(true, SeqCst);
2018                    break;
2019                }
2020                let is_dirty = dirty.swap(false, SeqCst);
2021                if is_dirty || last_scan.elapsed() >= Duration::from_millis(500) {
2022                    if let Ok(backend_inv) =
2023                        collect_linux_backend_inventory_with_paths(&paths, &backends)
2024                    {
2025                        let _ = service.ingest_backend_inventory(backend_inv, &linux_query);
2026                    }
2027                    last_scan = std::time::Instant::now();
2028                }
2029                if !dirty.load(SeqCst) && !stop_bg.load(SeqCst) {
2030                    thread::park_timeout(Duration::from_millis(50));
2031                }
2032            }
2033
2034            if let Some(h) = sub_handle {
2035                let _ = h.join();
2036            }
2037        });
2038
2039        *guard = Some(WatcherWorker {
2040            stop,
2041            join: Some(join),
2042        });
2043    }
2044
2045    pub fn stop_watcher(&self) {
2046        if let Some(mut worker) = self
2047            .watcher
2048            .lock()
2049            .unwrap_or_else(|e| e.into_inner())
2050            .take()
2051        {
2052            worker.stop_and_join();
2053        }
2054    }
2055}
2056
2057impl DiscoveryBackend for PlatformDiscovery {
2058    fn new() -> Self {
2059        Self::from_config(LinuxClientPaths::default(), Backends::default())
2060    }
2061
2062    fn with_backends(backends: Backends) -> Result<Self, CapabilityError> {
2063        backends.validate()?;
2064        Ok(Self::from_config(LinuxClientPaths::default(), backends))
2065    }
2066
2067    #[inline]
2068    fn service(&self) -> &DiscoveryService {
2069        &self.service
2070    }
2071
2072    #[inline]
2073    fn backends(&self) -> &Backends {
2074        &self.backends
2075    }
2076
2077    fn is_watcher_running(&self) -> bool {
2078        let mut guard = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
2079        if self.service.active_subscriber_count() == 0
2080            && let Some(mut worker) = guard.take()
2081        {
2082            worker.stop_and_join();
2083        }
2084        guard.is_some()
2085    }
2086
2087    fn refresh_once(&self) -> Result<u64, CapabilityError> {
2088        let inv = collect_linux_backend_inventory_with_paths(&self.paths, &self.backends)?;
2089        let query =
2090            DiscoveryQuery::all_for_os(PlatformOs::Linux).with_backends(self.backends.clone());
2091        self.service
2092            .update_backend_inventory(inv, &query)
2093            .map_err(CapabilityError::from)
2094    }
2095
2096    fn default_output_device_id(&self) -> Result<Option<Arc<str>>, CapabilityError> {
2097        if !self.is_watcher_running() {
2098            self.refresh_once()?;
2099        }
2100        Ok(self.service.default_output_device_id())
2101    }
2102
2103    fn default_input_device_id(&self) -> Result<Option<Arc<str>>, CapabilityError> {
2104        if !self.is_watcher_running() {
2105            self.refresh_once()?;
2106        }
2107        Ok(self.service.default_input_device_id())
2108    }
2109
2110    fn process(
2111        &self,
2112        pid: u32,
2113        scope: ProcessScope,
2114        on_root_exit: OnRootExit,
2115    ) -> Result<CaptureTarget, CapabilityError> {
2116        let (identity, exe) = inspect_process_executable(pid)?;
2117        let name = exe.rsplit('/').next().unwrap_or(exe.as_str()).to_owned();
2118        let target = CaptureTarget::process(identity, scope, on_root_exit)?;
2119        Ok(target.with_metadata(None, Some(name.into()), Some(exe.into()), None))
2120    }
2121
2122    fn discover_query(&self, query: &DiscoveryQuery) -> Result<TargetCatalog, CapabilityError> {
2123        query.backends.validate()?;
2124        let inv = collect_linux_backend_inventory_with_paths(&self.paths, &query.backends)?;
2125        self.service
2126            .update_backend_inventory(inv, query)
2127            .map_err(CapabilityError::from)?;
2128        self.service
2129            .discover_query(query)
2130            .map_err(CapabilityError::from)
2131    }
2132
2133    fn subscribe(
2134        &self,
2135        filter: DiscoveryFilter,
2136        max_discovery_queue: usize,
2137    ) -> Result<DiscoverySubscription, CapabilityError> {
2138        let _ = self.refresh_once();
2139        let sub = self.service.subscribe(filter, max_discovery_queue)?;
2140        self.ensure_watcher_started();
2141        Ok(sub)
2142    }
2143
2144    fn subscribe_query(
2145        &self,
2146        query: DiscoveryQuery,
2147        max_discovery_queue: usize,
2148    ) -> Result<DiscoverySubscription, CapabilityError> {
2149        query.backends.validate()?;
2150        if let Ok(inv) = collect_linux_backend_inventory_with_paths(&self.paths, &query.backends) {
2151            let _ = self.service.update_backend_inventory(inv, &query);
2152        }
2153        let sub = self.service.subscribe_query(query, max_discovery_queue)?;
2154        self.ensure_watcher_started();
2155        Ok(sub)
2156    }
2157}
2158
2159struct DefaultEndpointObserverState {
2160    ref_count: usize,
2161    latest_pw_endpoint: Arc<Mutex<Option<String>>>,
2162    latest_pa_endpoint: Arc<Mutex<Option<String>>>,
2163    worker: Option<WatcherWorker>,
2164}
2165
2166static LINUX_DEFAULT_SINK_OBSERVER: OnceLock<Mutex<DefaultEndpointObserverState>> = OnceLock::new();
2167static LINUX_DEFAULT_SOURCE_OBSERVER: OnceLock<Mutex<DefaultEndpointObserverState>> =
2168    OnceLock::new();
2169
2170fn linux_observer_state() -> &'static Mutex<DefaultEndpointObserverState> {
2171    LINUX_DEFAULT_SINK_OBSERVER.get_or_init(|| {
2172        Mutex::new(DefaultEndpointObserverState {
2173            ref_count: 0,
2174            latest_pw_endpoint: Arc::new(Mutex::new(None)),
2175            latest_pa_endpoint: Arc::new(Mutex::new(None)),
2176            worker: None,
2177        })
2178    })
2179}
2180
2181fn linux_source_observer_state() -> &'static Mutex<DefaultEndpointObserverState> {
2182    LINUX_DEFAULT_SOURCE_OBSERVER.get_or_init(|| {
2183        Mutex::new(DefaultEndpointObserverState {
2184            ref_count: 0,
2185            latest_pw_endpoint: Arc::new(Mutex::new(None)),
2186            latest_pa_endpoint: Arc::new(Mutex::new(None)),
2187            worker: None,
2188        })
2189    })
2190}
2191
2192pub fn query_linux_default_sink_now(
2193    backend: BackendId,
2194    paths: &LinuxClientPaths,
2195) -> Option<String> {
2196    match backend {
2197        BackendId::PipeWire => query_pipewire_default_sink_only(paths).ok().flatten(),
2198        BackendId::PulseAudio => crate::loader::probe_pulse_server(paths)
2199            .ok()
2200            .and_then(|info| info.default_sink_name),
2201        _ => None,
2202    }
2203}
2204
2205pub fn query_linux_default_source_now(
2206    backend: BackendId,
2207    paths: &LinuxClientPaths,
2208) -> Option<String> {
2209    match backend {
2210        BackendId::PipeWire => query_pipewire_defaults_only(paths)
2211            .ok()
2212            .and_then(|(_, src)| src),
2213        BackendId::PulseAudio => crate::loader::probe_pulse_server(paths)
2214            .ok()
2215            .and_then(|info| info.default_source_name)
2216            .filter(|s| !s.ends_with(".monitor")),
2217        _ => None,
2218    }
2219}
2220
2221/// Shared background observer for default output sink names.
2222pub struct PlatformDefaultOutputObserver {
2223    backend: Option<BackendId>,
2224    latest_pw_sink: Arc<Mutex<Option<String>>>,
2225    latest_pa_sink: Arc<Mutex<Option<String>>>,
2226}
2227
2228impl PlatformDefaultOutputObserver {
2229    pub(crate) fn acquire_for_backend(backend: Option<BackendId>, paths: LinuxClientPaths) -> Self {
2230        let mut guard = linux_observer_state()
2231            .lock()
2232            .unwrap_or_else(|e| e.into_inner());
2233        if guard.ref_count == 0 {
2234            let init_pw = query_linux_default_sink_now(BackendId::PipeWire, &paths);
2235            let init_pa = query_linux_default_sink_now(BackendId::PulseAudio, &paths);
2236            *guard
2237                .latest_pw_endpoint
2238                .lock()
2239                .unwrap_or_else(|e| e.into_inner()) = init_pw;
2240            *guard
2241                .latest_pa_endpoint
2242                .lock()
2243                .unwrap_or_else(|e| e.into_inner()) = init_pa;
2244
2245            let stop = Arc::new(AtomicBool::new(false));
2246            let stop_bg = stop.clone();
2247            let pw_bg = guard.latest_pw_endpoint.clone();
2248            let pa_bg = guard.latest_pa_endpoint.clone();
2249            let join = thread::spawn(move || {
2250                let dirty = Arc::new(AtomicBool::new(false));
2251                let sub_handle = spawn_pulse_server_event_listener(
2252                    &paths,
2253                    pa_bg.clone(),
2254                    dirty.clone(),
2255                    thread::current(),
2256                    stop_bg.clone(),
2257                    false,
2258                );
2259                let has_event_sub = sub_handle.is_some();
2260                while !stop_bg.load(SeqCst) {
2261                    if dirty.swap(false, SeqCst) || !has_event_sub {
2262                        if let Some(pw) = query_linux_default_sink_now(BackendId::PipeWire, &paths)
2263                        {
2264                            *pw_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(pw);
2265                        }
2266                        if !has_event_sub
2267                            && let Some(pa) =
2268                                query_linux_default_sink_now(BackendId::PulseAudio, &paths)
2269                        {
2270                            *pa_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(pa);
2271                        }
2272                    }
2273                    if !dirty.load(SeqCst) && !stop_bg.load(SeqCst) {
2274                        thread::park_timeout(Duration::from_millis(500));
2275                    }
2276                }
2277                if let Some(h) = sub_handle {
2278                    let _ = h.join();
2279                }
2280            });
2281            guard.worker = Some(WatcherWorker {
2282                stop,
2283                join: Some(join),
2284            });
2285        }
2286        guard.ref_count += 1;
2287        Self {
2288            backend,
2289            latest_pw_sink: guard.latest_pw_endpoint.clone(),
2290            latest_pa_sink: guard.latest_pa_endpoint.clone(),
2291        }
2292    }
2293
2294    fn select_cell(&self) -> Option<&Arc<Mutex<Option<String>>>> {
2295        match self.backend {
2296            Some(BackendId::PipeWire) => Some(&self.latest_pw_sink),
2297            Some(BackendId::PulseAudio) => Some(&self.latest_pa_sink),
2298            Some(_) => None,
2299            None => {
2300                if self
2301                    .latest_pw_sink
2302                    .lock()
2303                    .unwrap_or_else(|e| e.into_inner())
2304                    .is_some()
2305                {
2306                    Some(&self.latest_pw_sink)
2307                } else {
2308                    Some(&self.latest_pa_sink)
2309                }
2310            }
2311        }
2312    }
2313}
2314
2315impl DefaultEndpointObserver for PlatformDefaultOutputObserver {
2316    fn acquire() -> Self {
2317        Self::acquire_for_backend(None, LinuxClientPaths::default())
2318    }
2319
2320    fn latest_endpoint_id(&self) -> Option<String> {
2321        let cell = self.select_cell()?;
2322        cell.lock().unwrap_or_else(|e| e.into_inner()).clone()
2323    }
2324
2325    fn changed_from(&self, expected_id: Option<&str>) -> Option<String> {
2326        let cell = self.select_cell()?;
2327        let guard = cell.lock().unwrap_or_else(|e| e.into_inner());
2328        match guard.as_deref() {
2329            Some(name) if Some(name) != expected_id => Some(name.to_owned()),
2330            _ => None,
2331        }
2332    }
2333}
2334
2335impl Drop for PlatformDefaultOutputObserver {
2336    fn drop(&mut self) {
2337        let mut guard = linux_observer_state()
2338            .lock()
2339            .unwrap_or_else(|e| e.into_inner());
2340        guard.ref_count = guard.ref_count.saturating_sub(1);
2341        if guard.ref_count == 0
2342            && let Some(mut worker) = guard.worker.take()
2343        {
2344            worker.stop_and_join();
2345        }
2346    }
2347}
2348
2349/// Shared background observer for default input source names.
2350pub struct PlatformDefaultInputObserver {
2351    backend: Option<BackendId>,
2352    latest_pw_source: Arc<Mutex<Option<String>>>,
2353    latest_pa_source: Arc<Mutex<Option<String>>>,
2354}
2355
2356impl PlatformDefaultInputObserver {
2357    pub(crate) fn acquire_for_backend(backend: Option<BackendId>, paths: LinuxClientPaths) -> Self {
2358        let mut guard = linux_source_observer_state()
2359            .lock()
2360            .unwrap_or_else(|e| e.into_inner());
2361        if guard.ref_count == 0 {
2362            let init_pw = query_linux_default_source_now(BackendId::PipeWire, &paths);
2363            let init_pa = query_linux_default_source_now(BackendId::PulseAudio, &paths);
2364            *guard
2365                .latest_pw_endpoint
2366                .lock()
2367                .unwrap_or_else(|e| e.into_inner()) = init_pw;
2368            *guard
2369                .latest_pa_endpoint
2370                .lock()
2371                .unwrap_or_else(|e| e.into_inner()) = init_pa;
2372
2373            let stop = Arc::new(AtomicBool::new(false));
2374            let stop_bg = stop.clone();
2375            let pw_bg = guard.latest_pw_endpoint.clone();
2376            let pa_bg = guard.latest_pa_endpoint.clone();
2377            let join = thread::spawn(move || {
2378                let dirty = Arc::new(AtomicBool::new(false));
2379                let sub_handle = spawn_pulse_server_event_listener_ext(
2380                    &paths,
2381                    None,
2382                    Some(pa_bg.clone()),
2383                    dirty.clone(),
2384                    thread::current(),
2385                    stop_bg.clone(),
2386                    false,
2387                    true,
2388                );
2389                let has_event_sub = sub_handle.is_some();
2390                while !stop_bg.load(SeqCst) {
2391                    if dirty.swap(false, SeqCst) || !has_event_sub {
2392                        if let Some(pw) =
2393                            query_linux_default_source_now(BackendId::PipeWire, &paths)
2394                        {
2395                            *pw_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(pw);
2396                        }
2397                        if !has_event_sub
2398                            && let Some(pa) =
2399                                query_linux_default_source_now(BackendId::PulseAudio, &paths)
2400                        {
2401                            *pa_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(pa);
2402                        }
2403                    }
2404                    if !dirty.load(SeqCst) && !stop_bg.load(SeqCst) {
2405                        thread::park_timeout(Duration::from_millis(500));
2406                    }
2407                }
2408                if let Some(h) = sub_handle {
2409                    let _ = h.join();
2410                }
2411            });
2412            guard.worker = Some(WatcherWorker {
2413                stop,
2414                join: Some(join),
2415            });
2416        }
2417        guard.ref_count += 1;
2418        Self {
2419            backend,
2420            latest_pw_source: guard.latest_pw_endpoint.clone(),
2421            latest_pa_source: guard.latest_pa_endpoint.clone(),
2422        }
2423    }
2424
2425    fn select_cell(&self) -> Option<&Arc<Mutex<Option<String>>>> {
2426        match self.backend {
2427            Some(BackendId::PipeWire) => Some(&self.latest_pw_source),
2428            Some(BackendId::PulseAudio) => Some(&self.latest_pa_source),
2429            Some(_) => None,
2430            None => {
2431                if self
2432                    .latest_pw_source
2433                    .lock()
2434                    .unwrap_or_else(|e| e.into_inner())
2435                    .is_some()
2436                {
2437                    Some(&self.latest_pw_source)
2438                } else {
2439                    Some(&self.latest_pa_source)
2440                }
2441            }
2442        }
2443    }
2444}
2445
2446impl DefaultEndpointObserver for PlatformDefaultInputObserver {
2447    fn acquire() -> Self {
2448        Self::acquire_for_backend(None, LinuxClientPaths::default())
2449    }
2450
2451    fn latest_endpoint_id(&self) -> Option<String> {
2452        let cell = self.select_cell()?;
2453        cell.lock().unwrap_or_else(|e| e.into_inner()).clone()
2454    }
2455
2456    fn changed_from(&self, expected_id: Option<&str>) -> Option<String> {
2457        let cell = self.select_cell()?;
2458        let guard = cell.lock().unwrap_or_else(|e| e.into_inner());
2459        match guard.as_deref() {
2460            Some(name) if Some(name) != expected_id => Some(name.to_owned()),
2461            _ => None,
2462        }
2463    }
2464}
2465
2466impl Drop for PlatformDefaultInputObserver {
2467    fn drop(&mut self) {
2468        let mut guard = linux_source_observer_state()
2469            .lock()
2470            .unwrap_or_else(|e| e.into_inner());
2471        guard.ref_count = guard.ref_count.saturating_sub(1);
2472        if guard.ref_count == 0
2473            && let Some(mut worker) = guard.worker.take()
2474        {
2475            worker.stop_and_join();
2476        }
2477    }
2478}
2479
2480#[cfg(test)]
2481mod tests {
2482    use super::*;
2483
2484    #[test]
2485    fn resolve_pipewire_pid_uses_application_process_id_and_ignores_sec_pid() {
2486        let mut client_app_pids = BTreeMap::new();
2487        client_app_pids.insert(55, 22313);
2488        let mut client_sec_pids = BTreeMap::new();
2489        // Bridged PulseAudio client has pipewire.sec.pid == 2046 (pipewire-pulse daemon)
2490        client_sec_pids.insert(55, 2046);
2491        client_sec_pids.insert(56, 2046);
2492
2493        assert_eq!(
2494            resolve_pipewire_node_pid(None, Some(55), &client_app_pids, &client_sec_pids),
2495            Some(22313)
2496        );
2497        assert_eq!(
2498            resolve_pipewire_node_pid(None, Some(56), &client_app_pids, &client_sec_pids),
2499            None
2500        );
2501    }
2502
2503    #[test]
2504    fn parse_pipewire_default_sink_metadata_handles_spa_json_and_plain_names() {
2505        assert_eq!(
2506            parse_pipewire_default_sink_metadata(
2507                r#"{"name":"alsa_output.pci-0000_00_1f.3.analog-stereo"}"#
2508            ),
2509            Some("alsa_output.pci-0000_00_1f.3.analog-stereo".to_owned())
2510        );
2511        assert_eq!(
2512            parse_pipewire_default_sink_metadata(
2513                r#"{ "name" : "bluez_output.AA_BB_CC_DD_EE_FF.1" }"#
2514            ),
2515            Some("bluez_output.AA_BB_CC_DD_EE_FF.1".to_owned())
2516        );
2517        assert_eq!(
2518            parse_pipewire_default_sink_metadata("alsa_output.usb-dac-00.analog-stereo"),
2519            Some("alsa_output.usb-dac-00.analog-stereo".to_owned())
2520        );
2521        assert_eq!(parse_pipewire_default_sink_metadata("   "), None);
2522        assert_eq!(parse_pipewire_default_sink_metadata("{}"), None);
2523    }
2524
2525    #[test]
2526    fn internal_mixer_endpoint_filter_excludes_only_cspa_mix_prefix() {
2527        assert!(is_internal_mixer_endpoint_name("cspa-mix-1234-1"));
2528        assert!(!is_internal_mixer_endpoint_name("cspa_test_sink"));
2529        assert!(!is_internal_mixer_endpoint_name("cspa-user-sink"));
2530        assert!(!is_internal_mixer_endpoint_name(
2531            "alsa_output.pci-0000_00_1f.3.analog-stereo"
2532        ));
2533    }
2534}