From 381eafdf21dc8259408540b31081c01c47d49e5c Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 15 Jun 2026 19:31:37 -0600 Subject: [PATCH] feat(audio): native pw-dump enumeration with pactl fallback (HiFi wizard Slice 0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enumerate PipeWire sinks via `pw-dump` (the daemon's native socket) as the primary path, falling back to the existing `pactl` parser only when pw-dump is absent or empty. pw-dump needs only `pipewire-bin` — not `pipewire-pulse` (the Pulse server pactl talks to) nor `pipewire-alsa` (the bridge PCM CPAL relies on), which are commonly missing on PipeWire-only Ubuntu and produced the empty device list. As a bonus it yields the exact `alsa_output.*` node.name that the HiFi wizard otherwise asks the user to paste by hand. Discovery code only: `create_output_stream` and the protected sample-rate passthrough path are untouched. max_sample_rate stays None from pw-dump because its EnumFormat reports the currently negotiated rate, not the device maximum — the /proc/asound capability probe remains the honest source. Pure `parse_pw_dump_sinks` helper + 2 unit tests (fixture: USB DAC + PCI card + filtered-out capture source; garbage/empty JSON). cc --- crates/qbz-audio/src/pipewire_backend.rs | 258 +++++++++++++++++++++++ 1 file changed, 258 insertions(+) diff --git a/crates/qbz-audio/src/pipewire_backend.rs b/crates/qbz-audio/src/pipewire_backend.rs index a46a533d2..f349e8f5c 100644 --- a/crates/qbz-audio/src/pipewire_backend.rs +++ b/crates/qbz-audio/src/pipewire_backend.rs @@ -323,6 +323,167 @@ impl PipeWireBackend { Ok(devices) } + + /// Native-PipeWire enumeration via `pw-dump`. + /// + /// This talks to the PipeWire daemon over its own socket and needs ONLY + /// `pipewire-bin` (the `pw-*` tools) — it does NOT require `pipewire-pulse` + /// (the Pulse-protocol server `pactl` talks to) nor the `pipewire-alsa` + /// bridge PCM that CPAL relies on. On a PipeWire-only box missing those + /// packages (the reported Ubuntu "empty sink list" bug) the legacy `pactl` + /// and CPAL paths return nothing, but `pw-dump` still reports every sink — + /// and gives us the exact `alsa_output.*` `node.name` for free. + /// + /// Returns `None` when `pw-dump` is absent, fails, or finds no sink (so the + /// caller falls back to `pactl`). Discovery only — never touches the + /// stream-open path. + fn enumerate_via_pw_dump(&self) -> Option> { + let output = Command::new("pw-dump").output().ok()?; + if !output.status.success() { + return None; + } + let json = String::from_utf8_lossy(&output.stdout); + let devices = parse_pw_dump_sinks(&json); + if devices.is_empty() { + return None; + } + log::info!( + "[PipeWire Backend] Enumerated {} sink(s) via pw-dump (native, no pactl/pipewire-pulse needed)", + devices.len() + ); + for (idx, dev) in devices.iter().enumerate() { + log::info!( + " [{}] {} (id: {}, bus: {:?}, hw: {}, default: {})", + idx, dev.name, dev.id, dev.device_bus, dev.is_hardware, dev.is_default + ); + } + Some(devices) + } +} + +/// Parse `pw-dump` JSON into our `AudioDevice` list. Pure (no I/O) so it is +/// unit-testable against a captured fixture. +/// +/// Selects objects of `type == "PipeWire:Interface:Node"` whose +/// `info.props["media.class"] == "Audio/Sink"`. The `node.name` is the id the +/// HiFi wizard otherwise asks the user to paste by hand. `device.bus` is read +/// from the node props (present in practice) and, when absent, cross-referenced +/// via the node's `device.id` against the `PipeWire:Interface:Device` objects. +/// `max_sample_rate` is intentionally left `None`: `pw-dump`'s `EnumFormat` +/// reports the CURRENTLY negotiated rate, not the device maximum — the +/// capability probe (`/proc/asound/.../stream0`) is the honest source for that. +fn parse_pw_dump_sinks(json: &str) -> Vec { + let root: serde_json::Value = match serde_json::from_str(json) { + Ok(v) => v, + Err(e) => { + log::warn!("[PipeWire Backend] pw-dump JSON parse failed: {}", e); + return Vec::new(); + } + }; + let arr = match root.as_array() { + Some(a) => a, + None => return Vec::new(), + }; + + // Default sink name lives in the "default" Metadata object. + let mut default_sink: Option = None; + for obj in arr { + let is_default_meta = obj.get("type").and_then(|v| v.as_str()) + == Some("PipeWire:Interface:Metadata") + && obj + .get("props") + .and_then(|p| p.get("metadata.name")) + .and_then(|v| v.as_str()) + == Some("default"); + if !is_default_meta { + continue; + } + if let Some(entries) = obj.get("metadata").and_then(|m| m.as_array()) { + for entry in entries { + if entry.get("key").and_then(|v| v.as_str()) == Some("default.audio.sink") { + if let Some(name) = entry + .get("value") + .and_then(|v| v.get("name")) + .and_then(|v| v.as_str()) + { + default_sink = Some(name.to_string()); + } + } + } + } + } + + // device.id -> device.bus, used only when the bus is not on the node itself. + let mut device_bus: std::collections::HashMap = std::collections::HashMap::new(); + for obj in arr { + if obj.get("type").and_then(|v| v.as_str()) != Some("PipeWire:Interface:Device") { + continue; + } + if let Some(id) = obj.get("id").and_then(|v| v.as_i64()) { + if let Some(bus) = obj + .get("info") + .and_then(|i| i.get("props")) + .and_then(|p| p.get("device.bus")) + .and_then(|v| v.as_str()) + { + device_bus.insert(id, bus.to_string()); + } + } + } + + let mut devices = Vec::new(); + for obj in arr { + if obj.get("type").and_then(|v| v.as_str()) != Some("PipeWire:Interface:Node") { + continue; + } + let props = match obj.get("info").and_then(|i| i.get("props")) { + Some(p) => p, + None => continue, + }; + if props.get("media.class").and_then(|v| v.as_str()) != Some("Audio/Sink") { + continue; + } + let node_name = match props.get("node.name").and_then(|v| v.as_str()) { + Some(n) => n.to_string(), + None => continue, + }; + let name = props + .get("node.description") + .and_then(|v| v.as_str()) + .or_else(|| props.get("node.nick").and_then(|v| v.as_str())) + .map(|s| s.to_string()) + .unwrap_or_else(|| node_name.clone()); + let bus = props + .get("device.bus") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .or_else(|| { + props + .get("device.id") + .and_then(|v| v.as_i64()) + .and_then(|did| device_bus.get(&did).cloned()) + }); + // A real ALSA-backed sink = hardware (USB/PCI DAC, internal card). + let is_hardware = props.get("device.api").and_then(|v| v.as_str()) == Some("alsa") + || props + .get("factory.name") + .and_then(|v| v.as_str()) + .map(|f| f.contains("alsa")) + .unwrap_or(false); + let is_default = default_sink.as_deref() == Some(node_name.as_str()); + + devices.push(AudioDevice { + id: node_name, + name, + description: None, + is_default, + max_sample_rate: None, + supported_sample_rates: None, + device_bus: bus, + is_hardware, + }); + } + devices } impl AudioBackend for PipeWireBackend { @@ -331,6 +492,16 @@ impl AudioBackend for PipeWireBackend { } fn enumerate_devices(&self) -> BackendResult> { + // Primary: native PipeWire via `pw-dump`. Works on PipeWire-only systems + // that are missing `pipewire-alsa` / `pipewire-pulse` (the Ubuntu + // empty-list bug) and yields the exact `alsa_output.*` node.name. + if let Some(devices) = self.enumerate_via_pw_dump() { + return Ok(devices); + } + // Fallback: `pactl` (requires pipewire-pulse + pulseaudio-utils). + log::info!( + "[PipeWire Backend] pw-dump unavailable or empty — falling back to pactl enumeration" + ); self.enumerate_pipewire_sinks() } @@ -736,3 +907,90 @@ impl AudioBackend for PipeWireBackend { self } } + +#[cfg(test)] +mod pw_dump_tests { + use super::parse_pw_dump_sinks; + + // Minimal fixture mirroring the real `pw-dump` shape (Cambridge USB DAC + + // internal PCI card + a capture source that must be filtered out). + const FIXTURE: &str = r#"[ + { + "id": 30, + "type": "PipeWire:Interface:Metadata", + "props": { "metadata.name": "default" }, + "metadata": [ + { "subject": 0, "key": "default.audio.sink", "type": "Spa:String:JSON", + "value": { "name": "alsa_output.usb-Cambridge_Audio-00.analog-stereo" } } + ] + }, + { + "id": 52, "type": "PipeWire:Interface:Device", + "info": { "props": { "device.bus": "usb", "device.api": "alsa" } } + }, + { + "id": 53, "type": "PipeWire:Interface:Node", + "info": { "props": { + "media.class": "Audio/Sink", + "node.name": "alsa_output.usb-Cambridge_Audio-00.analog-stereo", + "node.description": "DacMagic Plus Analog Stereo", + "device.id": 52, "device.bus": "usb", "device.api": "alsa", + "factory.name": "api.alsa.pcm.sink" + } } + }, + { + "id": 60, "type": "PipeWire:Interface:Device", + "info": { "props": { "device.bus": "pci", "device.api": "alsa" } } + }, + { + "id": 61, "type": "PipeWire:Interface:Node", + "info": { "props": { + "media.class": "Audio/Sink", + "node.name": "alsa_output.pci-0000_00_1f.3.analog-stereo", + "node.description": "Built-in Audio Analog Stereo", + "device.id": 60, "device.api": "alsa", + "factory.name": "api.alsa.pcm.sink" + } } + }, + { + "id": 70, "type": "PipeWire:Interface:Node", + "info": { "props": { + "media.class": "Audio/Source", + "node.name": "alsa_input.usb-Cambridge_Audio-00.analog-stereo" + } } + } + ]"#; + + #[test] + fn parses_sinks_only_with_node_names_bus_and_default() { + let devs = parse_pw_dump_sinks(FIXTURE); + // The Audio/Source must be excluded. + assert_eq!(devs.len(), 2, "should parse exactly the two Audio/Sink nodes"); + + let usb = devs + .iter() + .find(|d| d.id == "alsa_output.usb-Cambridge_Audio-00.analog-stereo") + .expect("usb sink present"); + assert_eq!(usb.name, "DacMagic Plus Analog Stereo"); + assert_eq!(usb.device_bus.as_deref(), Some("usb")); // read from node props + assert!(usb.is_hardware); + assert!(usb.is_default, "usb sink is the default per Metadata"); + assert!(usb.max_sample_rate.is_none(), "rate comes from the capability probe, not pw-dump"); + + let pci = devs + .iter() + .find(|d| d.id == "alsa_output.pci-0000_00_1f.3.analog-stereo") + .expect("pci sink present"); + // Bus absent on the node -> cross-referenced via device.id 60. + assert_eq!(pci.device_bus.as_deref(), Some("pci")); + assert!(pci.is_hardware); + assert!(!pci.is_default); + } + + #[test] + fn empty_or_garbage_json_yields_no_devices() { + assert!(parse_pw_dump_sinks("not json").is_empty()); + assert!(parse_pw_dump_sinks("[]").is_empty()); + assert!(parse_pw_dump_sinks("{}").is_empty()); + } +}