Fix PipeWire routing by temporarily changing default sink

PULSE_SINK environment variable approach was not working because
CPAL/rodio does not properly propagate it when creating streams.

New approach:
1. Save current default sink with pactl get-default-sink
2. Temporarily set default sink to target device
3. Create CPAL stream (will use current default)
4. Restore original default sink

This ensures audio routes to the selected device without permanently
changing the system default sink.

Tested approach is more reliable than PULSE_SINK env var.
This commit is contained in:
vicrodh committed 2026-01-17 15:43:39 -06:00
1 parent c65909930b
commit de8fbe8c33
1 file changed
+63 -20
+63 -20
View File
@@ -122,30 +122,52 @@ impl AudioBackend for PipeWireBackend {
&self, &self,
config: &BackendConfig, config: &BackendConfig,
) -> BackendResult<(OutputStream, OutputStreamHandle)> { ) -> BackendResult<(OutputStream, OutputStreamHandle)> {
// CRITICAL: Set PULSE_SINK environment variable BEFORE creating new host let target_sink = config.device_id.clone();
// This tells PulseAudio/PipeWire which sink to use for THIS process only
if let Some(device_id) = &config.device_id {
log::info!("[PipeWire Backend] Setting PULSE_SINK={}", device_id);
std::env::set_var("PULSE_SINK", device_id);
// Verify it was set correctly // Save current default sink (to restore later)
match std::env::var("PULSE_SINK") { let original_default = if target_sink.is_some() {
Ok(val) => log::info!("[PipeWire Backend] ✓ PULSE_SINK confirmed: {}", val), Command::new("pactl")
Err(e) => log::error!("[PipeWire Backend] ✗ PULSE_SINK verification failed: {:?}", e), .args(["get-default-sink"])
} .output()
.ok()
.and_then(|o| {
if o.status.success() {
String::from_utf8(o.stdout).ok().map(|s| s.trim().to_string())
} else {
None
}
})
} else { } else {
// Clear PULSE_SINK to use system default None
log::info!("[PipeWire Backend] Clearing PULSE_SINK (using system default)"); };
std::env::remove_var("PULSE_SINK");
// Temporarily set default sink to target (if specified)
if let Some(sink_name) = &target_sink {
log::info!("[PipeWire Backend] Temporarily setting default sink to: {}", sink_name);
let set_result = Command::new("pactl")
.args(["set-default-sink", sink_name])
.output();
match set_result {
Ok(output) if output.status.success() => {
log::info!("[PipeWire Backend] ✓ Default sink changed to {}", sink_name);
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
log::warn!("[PipeWire Backend] Failed to set default sink: {}", stderr);
}
Err(e) => {
log::warn!("[PipeWire Backend] Error executing pactl set-default-sink: {}", e);
}
}
} }
// CRITICAL: Create a NEW host AFTER setting PULSE_SINK // Create a NEW host (will use current default sink)
// The host connects to PulseAudio/PipeWire when created and reads PULSE_SINK at that time log::info!("[PipeWire Backend] Creating fresh CPAL host...");
log::info!("[PipeWire Backend] Creating fresh CPAL host to pick up PULSE_SINK...");
let fresh_host = rodio::cpal::default_host(); let fresh_host = rodio::cpal::default_host();
// Find the "pulse" or "pipewire" CPAL device from the fresh host // Find the "pulse" or "pipewire" CPAL device
// These are ALSA PCM devices that route to PulseAudio/PipeWire
let device = fresh_host let device = fresh_host
.output_devices() .output_devices()
.map_err(|e| format!("Failed to enumerate CPAL devices: {}", e))? .map_err(|e| format!("Failed to enumerate CPAL devices: {}", e))?
@@ -162,13 +184,34 @@ impl AudioBackend for PipeWireBackend {
let device_name = device.name().unwrap_or_else(|_| "unknown".to_string()); let device_name = device.name().unwrap_or_else(|_| "unknown".to_string());
log::info!("[PipeWire Backend] Using CPAL device: {}", device_name); log::info!("[PipeWire Backend] Using CPAL device: {}", device_name);
// Create output stream // Create output stream (will route to current default sink)
// CPAL will route to the sink specified in PULSE_SINK
let stream = OutputStream::try_from_device(&device) let stream = OutputStream::try_from_device(&device)
.map_err(|e| format!("Failed to create output stream: {}", e))?; .map_err(|e| format!("Failed to create output stream: {}", e))?;
log::info!("[PipeWire Backend] ✓ Output stream created successfully"); log::info!("[PipeWire Backend] ✓ Output stream created successfully");
// Restore original default sink (if we changed it)
if let Some(original) = original_default {
log::info!("[PipeWire Backend] Restoring original default sink: {}", original);
let restore_result = Command::new("pactl")
.args(["set-default-sink", &original])
.output();
match restore_result {
Ok(output) if output.status.success() => {
log::info!("[PipeWire Backend] ✓ Default sink restored to {}", original);
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
log::warn!("[PipeWire Backend] Failed to restore default sink: {}", stderr);
}
Err(e) => {
log::warn!("[PipeWire Backend] Error restoring default sink: {}", e);
}
}
}
Ok(stream) Ok(stream)
} }