Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Audio: reconnect after PipeWire or pipewire-pulse restarts

oxydizera63b8bd26b2c
diff --git a/src/audio/bass.c b/src/audio/bass.c
index 4dc359f..d71ae5b 100644
--- a/src/audio/bass.c
+++ b/src/audio/bass.c
@@ -2,7 +2,13 @@
* default output without rewriting the user's default device or stream targets.
* All graph changes and debounced state writes run on the PipeWire loop. The
* DSP is bass_dsp.c, a LADSPA plugin installed in lib/rediwm/ladspa next to
- * the binaries. */
+ * the binaries.
+ *
+ * A PipeWire daemon that goes away (restart, crash) kills the core: the
+ * filter is rebuilt on a new one once the daemon and its policy manager are
+ * back. Reconnects back off from 250 ms to 32 s and stop after
+ * RECONNECT_MAX_FAILURES, so a daemon that stays gone costs no wakeups;
+ * rediwm_bass_reconnect (the PulseAudio side reconnecting) retries then. */
#define _POSIX_C_SOURCE 200809L
#include "bass.h"
#include "../platform/self_exe.h"
@@ -20,6 +26,10 @@
#include <sys/stat.h>
#include <unistd.h>
+#define RECONNECT_BASE_MS 250u
+#define RECONNECT_MAX_SHIFT 7 /* 32 s */
+#define RECONNECT_MAX_FAILURES 12
+
struct rediwm_bass {
struct pw_thread_loop *loop;
struct pw_context *context;
@@ -29,12 +39,16 @@ struct rediwm_bass {
struct pw_node *node;
struct pw_metadata *filters;
struct spa_hook registry_listener, core_listener, module_listener, node_listener;
- struct spa_source *save_timer, *mute_event;
+ struct spa_source *save_timer, *mute_event, *reconnect_timer, *retry_event;
uint32_t node_id, metadata_id;
enum pw_node_state node_state;
char name[80], state_path[4096], plugin[4096];
float gain, treble;
bool started, failed, dirty, save_failed;
+ /* The core died (`core_lost`) and a new one is scheduled
+ * (`reconnecting`); failures count attempts that never saw a global. */
+ bool core_lost, reconnecting;
+ unsigned reconnect_failures;
/* Written from any thread by rediwm_bass_set_mute; `live` mirrors
* node && filters && !failed for it. */
atomic_bool muted, live;
@@ -157,6 +171,8 @@ static void global(void *data, uint32_t id, uint32_t permissions,
const char *type, uint32_t version, const struct spa_dict *props) {
(void)permissions; (void)version;
struct rediwm_bass *b = data;
+ /* The daemon answers: a later loss starts backing off afresh. */
+ b->reconnect_failures = 0;
if (!props) return;
const char *name;
if (strcmp(type, PW_TYPE_INTERFACE_Metadata) == 0 && !b->filters &&
@@ -196,6 +212,20 @@ static const struct pw_registry_events registry_events = {
PW_VERSION_REGISTRY_EVENTS, .global = global, .global_remove = global_remove,
};
+static void schedule_reconnect(struct rediwm_bass *b) {
+ if (b->reconnecting) return;
+ if (b->reconnect_failures >= RECONNECT_MAX_FAILURES) {
+ fprintf(stderr, "bass boost: PipeWire still unreachable; giving up after %u attempts\n", b->reconnect_failures);
+ return;
+ }
+ unsigned shift = b->reconnect_failures < RECONNECT_MAX_SHIFT ? b->reconnect_failures : RECONNECT_MAX_SHIFT;
+ uint64_t ms = (uint64_t)RECONNECT_BASE_MS << shift;
+ struct timespec delay = { .tv_sec = (time_t)(ms / 1000), .tv_nsec = (long)(ms % 1000) * 1000000 };
+ b->reconnect_failures++;
+ b->reconnecting = true;
+ pw_loop_update_timer(pw_thread_loop_get_loop(b->loop), b->reconnect_timer, &delay, NULL, false);
+}
+
static void core_error(void *data, uint32_t id, int seq, int res, const char *message) {
(void)seq;
struct rediwm_bass *b = data;
@@ -203,11 +233,88 @@ static void core_error(void *data, uint32_t id, int seq, int res, const char *me
if (id == PW_ID_CORE || (b->node && id == pw_proxy_get_id((struct pw_proxy *)b->node))) {
b->failed = true;
if (b->module) pw_impl_module_destroy(b->module);
+ /* Usually the daemon is gone (-EPIPE, -ECONNRESET); after any core
+ * error only a new core can carry the filter again. The dead one is
+ * torn down in reconnect(), not from inside its own event. */
+ if (id == PW_ID_CORE && !b->core_lost) {
+ b->core_lost = true;
+ schedule_reconnect(b);
+ }
changed(b);
}
}
static const struct pw_core_events core_events = { PW_VERSION_CORE_EVENTS, .error = core_error };
+/* Drops the filter and every proxy on the core, then the core. */
+static void disconnect_core(struct rediwm_bass *b) {
+ if (b->module) pw_impl_module_destroy(b->module);
+ if (b->node) {
+ spa_hook_remove(&b->node_listener);
+ pw_proxy_destroy((struct pw_proxy *)b->node);
+ b->node = NULL;
+ }
+ if (b->filters) {
+ pw_proxy_destroy((struct pw_proxy *)b->filters);
+ b->filters = NULL;
+ }
+ if (b->registry) {
+ spa_hook_remove(&b->registry_listener);
+ pw_proxy_destroy((struct pw_proxy *)b->registry);
+ b->registry = NULL;
+ }
+ if (b->core) {
+ spa_hook_remove(&b->core_listener);
+ pw_core_disconnect(b->core);
+ b->core = NULL;
+ }
+}
+
+/* The filter, its node and the "filters" metadata arrive through the
+ * registry once the policy manager is up (global()). */
+static int connect_core(struct rediwm_bass *b) {
+ b->core = pw_context_connect(b->context, NULL, 0);
+ if (!b->core) return -errno;
+ /* Let filter-chain open its own core connection. Controlling an exported
+ * node through its owning connection deadlocks the server's set-param
+ * busy/ping handshake (the acknowledgement queues behind the command). */
+ pw_core_add_listener(b->core, &b->core_listener, &core_events, b);
+ b->registry = pw_core_get_registry(b->core, PW_VERSION_REGISTRY, 0);
+ if (!b->registry) {
+ disconnect_core(b);
+ return -ENOMEM;
+ }
+ pw_registry_add_listener(b->registry, &b->registry_listener, &registry_events, b);
+ return 0;
+}
+
+static void reconnect(void *data, uint64_t expirations) {
+ (void)expirations;
+ struct rediwm_bass *b = data;
+ b->reconnecting = false;
+ disconnect_core(b);
+ int res = connect_core(b);
+ if (res < 0) {
+ fprintf(stderr, "bass boost: PipeWire reconnect failed: %s\n", strerror(-res));
+ schedule_reconnect(b);
+ return;
+ }
+ fprintf(stderr, "bass boost: reconnected to PipeWire\n");
+ b->core_lost = false;
+ /* A plugin that is missing fails again in load_filter. */
+ b->failed = false;
+ changed(b);
+}
+
+static void retry_event(void *data, uint64_t count) {
+ (void)count;
+ struct rediwm_bass *b = data;
+ if (!b->core_lost) return;
+ /* Re-arms a long backoff, or a given-up connection, at the base delay. */
+ b->reconnect_failures = 0;
+ b->reconnecting = false;
+ schedule_reconnect(b);
+}
+
/* The DSP plugin is installed in lib/rediwm/ladspa beside bin/. */
static void find_plugin(struct rediwm_bass *b) {
char exe[sizeof(b->plugin)];
@@ -246,18 +353,19 @@ struct rediwm_bass *rediwm_bass_create(void (*notify)(void *), void *data) {
if (!b->loop) goto fail;
b->context = pw_context_new(pw_thread_loop_get_loop(b->loop), NULL, 0);
if (!b->context) goto fail;
- b->core = pw_context_connect(b->context, NULL, 0);
- if (!b->core) goto fail;
- /* Let filter-chain open its own core connection. Controlling an exported
- * node through its owning connection deadlocks the server's set-param
- * busy/ping handshake (the acknowledgement queues behind the command). */
- pw_core_add_listener(b->core, &b->core_listener, &core_events, b);
- b->registry = pw_core_get_registry(b->core, PW_VERSION_REGISTRY, 0);
- if (!b->registry) goto fail;
- pw_registry_add_listener(b->registry, &b->registry_listener, &registry_events, b);
- b->save_timer = pw_loop_add_timer(pw_thread_loop_get_loop(b->loop), save_timer, b);
- b->mute_event = pw_loop_add_event(pw_thread_loop_get_loop(b->loop), mute_event, b);
- if (!b->save_timer || !b->mute_event || pw_thread_loop_start(b->loop) < 0) goto fail;
+ struct pw_loop *loop = pw_thread_loop_get_loop(b->loop);
+ b->save_timer = pw_loop_add_timer(loop, save_timer, b);
+ b->mute_event = pw_loop_add_event(loop, mute_event, b);
+ b->reconnect_timer = pw_loop_add_timer(loop, reconnect, b);
+ b->retry_event = pw_loop_add_event(loop, retry_event, b);
+ if (!b->save_timer || !b->mute_event || !b->reconnect_timer || !b->retry_event) goto fail;
+ /* A daemon that is not up yet is retried like a lost one. */
+ if (connect_core(b) < 0) {
+ b->core_lost = true;
+ b->failed = true;
+ schedule_reconnect(b);
+ }
+ if (pw_thread_loop_start(b->loop) < 0) goto fail;
b->started = true;
return b;
fail:
@@ -270,13 +378,12 @@ void rediwm_bass_destroy(struct rediwm_bass *b) {
if (b->started) pw_thread_loop_stop(b->loop);
b->notify = NULL;
save_state(b);
- if (b->save_timer) pw_loop_destroy_source(pw_thread_loop_get_loop(b->loop), b->save_timer);
- if (b->mute_event) pw_loop_destroy_source(pw_thread_loop_get_loop(b->loop), b->mute_event);
- if (b->module) pw_impl_module_destroy(b->module);
- if (b->node) pw_proxy_destroy((struct pw_proxy *)b->node);
- if (b->filters) pw_proxy_destroy((struct pw_proxy *)b->filters);
- if (b->registry) pw_proxy_destroy((struct pw_proxy *)b->registry);
- if (b->core) pw_core_disconnect(b->core);
+ struct pw_loop *loop = b->loop ? pw_thread_loop_get_loop(b->loop) : NULL;
+ if (b->save_timer) pw_loop_destroy_source(loop, b->save_timer);
+ if (b->mute_event) pw_loop_destroy_source(loop, b->mute_event);
+ if (b->reconnect_timer) pw_loop_destroy_source(loop, b->reconnect_timer);
+ if (b->retry_event) pw_loop_destroy_source(loop, b->retry_event);
+ disconnect_core(b);
if (b->context) pw_context_destroy(b->context);
if (b->loop) pw_thread_loop_destroy(b->loop);
free(b);
@@ -329,3 +436,8 @@ bool rediwm_bass_set_mute(struct rediwm_bass *b, bool muted) {
if (atomic_exchange(&b->muted, muted) != muted) pw_loop_signal_event(pw_thread_loop_get_loop(b->loop), b->mute_event);
return atomic_load(&b->live);
}
+
+/* Same locking rule as rediwm_bass_set_mute. */
+void rediwm_bass_reconnect(struct rediwm_bass *b) {
+ if (b) pw_loop_signal_event(pw_thread_loop_get_loop(b->loop), b->retry_event);
+}
diff --git a/src/audio/bass.h b/src/audio/bass.h
index 12efc0b..cc2ac5f 100644
--- a/src/audio/bass.h
+++ b/src/audio/bass.h
@@ -12,3 +12,7 @@ bool rediwm_bass_set_treble(struct rediwm_bass *bass, float treble);
/* Fades the filter's output out (true) or back in. Safe from any thread and
* under any lock. Returns whether the filter is live, i.e. a fade will play. */
bool rediwm_bass_set_mute(struct rediwm_bass *bass, bool muted);
+/* PipeWire is evidently up again (the PulseAudio connection came back):
+ * retry a lost connection that backed off or gave up. Same thread and lock
+ * rules as rediwm_bass_set_mute. */
+void rediwm_bass_reconnect(struct rediwm_bass *bass);
diff --git a/src/audio/pipewire.zig b/src/audio/pipewire.zig
index fb0931a..c40e51c 100644
--- a/src/audio/pipewire.zig
+++ b/src/audio/pipewire.zig
@@ -21,6 +21,13 @@
// needing to read `sinks`/`sources`/`sink_inputs` must hold `lock()` for the
// duration of the read and copy out anything needed before `unlock()` —
// those lists are mutated in place, under the same lock, by PA's own thread.
+//
+// libpulse never revives a failed context, and the server goes away whenever
+// pipewire-pulse restarts. A lost connection drops the device lists (the UI
+// then shows no audio rather than stale levels) and connects a new context
+// (`connectionLostLocked`, `reconnectCallback`); it waits for the server with
+// `PA_CONTEXT_NOFAIL`, which watches org.pulseaudio.Server on D-Bus, so a
+// missing server costs no wakeups.
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -34,6 +41,7 @@ extern fn rediwm_bass_get(bass: ?*Bass, gain: *f32, treble: *f32) c_int;
extern fn rediwm_bass_set(bass: ?*Bass, gain: f32) bool;
extern fn rediwm_bass_set_treble(bass: ?*Bass, treble: f32) bool;
extern fn rediwm_bass_set_mute(bass: ?*Bass, muted: bool) bool;
+extern fn rediwm_bass_reconnect(bass: ?*Bass) void;
/// How long a mute waits for the bass filter's fade before muting the sink:
/// the fade (bass_dsp.c MUTE_FADE_OUT, 200 ms) plus time for its last samples
@@ -41,6 +49,14 @@ extern fn rediwm_bass_set_mute(bass: ?*Bass, muted: bool) bool;
/// device buffer). The sink reads as muted throughout.
const mute_fade_delay_us: pa.pa_usec_t = 350_000;
+/// Reconnect delays after a failure double from this up to `<< 7` (32 s),
+/// so a server that crashes as it starts is not hammered.
+const reconnect_base_us: pa.pa_usec_t = 250_000;
+/// Consecutive failures without ever reaching READY before giving up. Only a
+/// server that keeps failing counts: one that is absent leaves a NOFAIL
+/// context connecting, not failed (unless there is no D-Bus to watch it on).
+const reconnect_max_failures = 12;
+
/// `gain` is the bass boost (0..12 dB), `treble` a cut or boost (-6..6 dB).
pub const BassState = struct { gain: f32, treble: f32, available: bool, save_failed: bool };
@@ -111,6 +127,11 @@ pub const AudioManager = struct {
/// this fires (`muteTimerCallback`), and reads as muted until then.
mute_timer: ?*pa.pa_time_event = null,
pending_mute_sink: u32 = 0,
+ /// Pending replacement of a failed context (`reconnectCallback`).
+ reconnect_timer: ?*pa.pa_time_event = null,
+ reconnect_failures: u8 = 0,
+ /// Set by `deinit`: the context terminating then is not a lost server.
+ shutting_down: bool = false,
sinks: std.ArrayList(SinkInfo) = .empty,
sources: std.ArrayList(SourceInfo) = .empty,
@@ -132,22 +153,13 @@ pub const AudioManager = struct {
return self.default_source_name[0..self.default_source_name_len];
}
- /// Connects to PipeWire's PulseAudio-compat socket and does an initial
- /// synchronous population of `sinks`/`sources`/`sink_inputs`. Returns an
- /// error (never crashes) if no socket is reachable — callers should log
- /// a warning and leave audio support disabled, matching every other
- /// optional subsystem in this compositor.
- pub fn create(allocator: Allocator) !*AudioManager {
- return createWithMode(allocator, true);
- }
-
/// Connect and populate on PA's existing thread. A slow or unresponsive
- /// sound server must not delay the first frame or the compositor event loop.
+ /// sound server must not delay the first frame or the compositor event
+ /// loop; one that is not running yet is waited for. Returns an error
+ /// (never crashes) only if libpulse itself cannot start — callers log a
+ /// warning and leave audio support disabled, matching every other
+ /// optional subsystem in this compositor.
pub fn createAsync(allocator: Allocator) !*AudioManager {
- return createWithMode(allocator, false);
- }
-
- fn createWithMode(allocator: Allocator, wait: bool) !*AudioManager {
const mainloop = pa.pa_threaded_mainloop_new() orelse return error.MainloopCreateFailed;
errdefer pa.pa_threaded_mainloop_free(mainloop);
@@ -161,44 +173,23 @@ pub const AudioManager = struct {
.allocator = allocator,
.mainloop = mainloop,
.context = context,
- .initial_population_pending = !wait,
+ .initial_population_pending = true,
.wake_fd = -1,
};
pa.pa_context_set_state_callback(context, stateCallback, self);
- if (pa.pa_context_connect(context, null, pa.PA_CONTEXT_NOFLAGS, null) < 0) {
- return error.ConnectFailed;
- }
+ // A server that refuses now (NOFAIL cannot wait on D-Bus with
+ // PULSE_SERVER set, or without a bus) is retried like a lost one.
+ // PA's thread is not running yet, so no lock is needed.
+ if (pa.pa_context_connect(context, null, pa.PA_CONTEXT_NOFAIL, null) < 0) self.connectionLostLocked();
if (pa.pa_threaded_mainloop_start(mainloop) < 0) return error.MainloopStartFailed;
- errdefer pa.pa_threaded_mainloop_stop(mainloop);
-
- if (!wait) {
- self.bass = rediwm_bass_create(bassChanged, self);
- return self;
- }
-
- pa.pa_threaded_mainloop_lock(mainloop);
- errdefer pa.pa_threaded_mainloop_unlock(mainloop);
-
- while (true) {
- const state = pa.pa_context_get_state(context);
- if (state == pa.PA_CONTEXT_READY) break;
- if (state == pa.PA_CONTEXT_FAILED or state == pa.PA_CONTEXT_TERMINATED) {
- return error.ConnectFailed;
- }
- pa.pa_threaded_mainloop_wait(mainloop);
- }
-
- self.populateLocked(true);
-
- log.info("connected to PipeWire/PulseAudio; default sink '{s}'", .{self.defaultSinkNameSlice()});
- pa.pa_threaded_mainloop_unlock(mainloop);
self.bass = rediwm_bass_create(bassChanged, self);
return self;
}
- fn populateLocked(self: *AudioManager, wait: bool) void {
+ /// Runs on PA's thread for every connection that becomes ready.
+ fn populateLocked(self: *AudioManager) void {
pa.pa_context_set_subscribe_callback(self.context, subscribeCallback, self);
const mask: pa.pa_subscription_mask_t = pa.PA_SUBSCRIPTION_MASK_SINK |
pa.PA_SUBSCRIPTION_MASK_SOURCE | pa.PA_SUBSCRIPTION_MASK_SINK_INPUT |
@@ -206,10 +197,10 @@ pub const AudioManager = struct {
// Fire-and-forget: see the module doc comment on why this must not wait.
if (pa.pa_context_subscribe(self.context, mask, null, null)) |op| pa.pa_operation_unref(op);
- self.refreshServerInfoLocked(wait);
- self.refreshSinksLocked(wait);
- self.refreshSourcesLocked(wait);
- self.refreshSinkInputsLocked(wait);
+ self.refreshServerInfoLocked(false);
+ self.refreshSinksLocked(false);
+ self.refreshSourcesLocked(false);
+ self.refreshSinkInputsLocked(false);
// Bumped once so `generation` starts at 1: every fresh consumer
// (a Taskbar's `audio_generation_seen` defaults to 0) then sees a
// mismatch on its very first check and reads the real initial state,
@@ -220,6 +211,9 @@ pub const AudioManager = struct {
pub fn deinit(self: *AudioManager) void {
pa.pa_threaded_mainloop_lock(self.mainloop);
+ // Before the lock is next released: a failure from now on must not
+ // schedule (or run) a reconnect.
+ self.shutting_down = true;
// A mute still fading out happens now: the fade dies with the filter.
if (self.mute_timer != null) {
self.cancelSinkMute();
@@ -236,24 +230,24 @@ pub const AudioManager = struct {
rediwm_bass_destroy(bass);
pa.pa_threaded_mainloop_lock(self.mainloop);
self.initial_population_pending = false;
+ if (self.reconnect_timer) |timer| {
+ const api = pa.pa_threaded_mainloop_get_api(self.mainloop);
+ if (api.*.time_free) |free_fn| free_fn(timer);
+ self.reconnect_timer = null;
+ }
pa.pa_context_disconnect(self.context);
pa.pa_threaded_mainloop_unlock(self.mainloop);
pa.pa_threaded_mainloop_stop(self.mainloop);
pa.pa_context_unref(self.context);
pa.pa_threaded_mainloop_free(self.mainloop);
- freeSinks(self.allocator, self.sinks.items);
+ // Shutdown can interrupt asynchronous list responses (scratch lists).
+ self.clearDevicesLocked();
self.sinks.deinit(self.allocator);
- freeSources(self.allocator, self.sources.items);
self.sources.deinit(self.allocator);
- freeSinkInputs(self.allocator, self.sink_inputs.items);
self.sink_inputs.deinit(self.allocator);
- // Shutdown can interrupt the initial asynchronous list responses.
- freeSinks(self.allocator, self.sinks_scratch.items);
self.sinks_scratch.deinit(self.allocator);
- freeSources(self.allocator, self.sources_scratch.items);
self.sources_scratch.deinit(self.allocator);
- freeSinkInputs(self.allocator, self.sink_inputs_scratch.items);
self.sink_inputs_scratch.deinit(self.allocator);
if (self.wake_fd >= 0) _ = std.posix.system.close(self.wake_fd);
@@ -303,6 +297,54 @@ pub const AudioManager = struct {
_ = std.posix.system.write(self.wake_fd, @ptrCast(&increment), @sizeOf(u64));
}
+ /// Frees every device list, partial (scratch) ones included.
+ fn clearDevicesLocked(self: *AudioManager) void {
+ freeSinks(self.allocator, self.sinks.items);
+ self.sinks.clearRetainingCapacity();
+ freeSinks(self.allocator, self.sinks_scratch.items);
+ self.sinks_scratch.clearRetainingCapacity();
+ freeSources(self.allocator, self.sources.items);
+ self.sources.clearRetainingCapacity();
+ freeSources(self.allocator, self.sources_scratch.items);
+ self.sources_scratch.clearRetainingCapacity();
+ freeSinkInputs(self.allocator, self.sink_inputs.items);
+ self.sink_inputs.clearRetainingCapacity();
+ freeSinkInputs(self.allocator, self.sink_inputs_scratch.items);
+ self.sink_inputs_scratch.clearRetainingCapacity();
+ self.default_sink_name_len = 0;
+ self.default_source_name_len = 0;
+ }
+
+ /// The context failed (on PA's thread): forget the old server's state and
+ /// schedule a new context. Its pending operations were cancelled without
+ /// callbacks, so the action in flight is dropped here.
+ fn connectionLostLocked(self: *AudioManager) void {
+ if (self.shutting_down or self.reconnect_timer != null) return;
+ // Presses queued now would land long after they were made.
+ self.initial_population_pending = false;
+ self.action_current = null;
+ self.action_len = 0;
+ // The sink a fade-out was for is gone, never muted; the filter
+ // follows the reconnected server's mute state from its first list.
+ if (self.mute_timer != null) {
+ self.cancelSinkMute();
+ _ = rediwm_bass_set_mute(self.bass, false);
+ }
+ self.clearDevicesLocked();
+ _ = self.generation.fetchAdd(1, .monotonic);
+ self.wake();
+
+ const reason = std.mem.span(pa.pa_strerror(pa.pa_context_errno(self.context)));
+ if (self.reconnect_failures >= reconnect_max_failures) {
+ log.warn("PipeWire/PulseAudio connection failed ({s}); giving up after {d} attempts", .{ reason, self.reconnect_failures });
+ return;
+ }
+ const delay = reconnect_base_us << @intCast(@min(self.reconnect_failures, 7));
+ self.reconnect_failures += 1;
+ self.reconnect_timer = pa.pa_context_rttime_new(self.context, pa.pa_rtclock_now() + delay, reconnectCallback, self);
+ log.warn("PipeWire/PulseAudio connection lost ({s}); reconnecting in {d} ms", .{ reason, delay / 1000 });
+ }
+
// ---- Refresh (query) operations. `wait`: block until the initial list
// is populated (safe only when called from a thread other than PA's
// own — see the module doc comment); `false` fires the query
@@ -698,24 +740,53 @@ fn volumeToPa(volume: f32) pa.pa_volume_t {
fn stateCallback(context: ?*pa.pa_context, userdata: ?*anyopaque) callconv(.c) void {
const self: *AudioManager = @ptrCast(@alignCast(userdata.?));
- if (self.initial_population_pending) {
- switch (pa.pa_context_get_state(context)) {
- pa.PA_CONTEXT_READY => {
- self.initial_population_pending = false;
- self.populateLocked(false);
- self.nextActionLocked();
- log.info("connected to PipeWire/PulseAudio; loading devices asynchronously", .{});
- },
- pa.PA_CONTEXT_FAILED, pa.PA_CONTEXT_TERMINATED => {
- self.initial_population_pending = false;
- log.warn("PipeWire/PulseAudio connection failed during startup", .{});
- },
- else => {},
- }
+ switch (pa.pa_context_get_state(context)) {
+ pa.PA_CONTEXT_READY => {
+ const first = self.initial_population_pending;
+ self.initial_population_pending = false;
+ self.reconnect_failures = 0;
+ self.populateLocked();
+ self.nextActionLocked();
+ if (first)
+ log.info("connected to PipeWire/PulseAudio; loading devices asynchronously", .{})
+ else {
+ log.info("reconnected to PipeWire/PulseAudio", .{});
+ // pipewire-pulse runs on PipeWire: if the filter lost the
+ // daemon too, it is worth retrying now (lock-free call).
+ rediwm_bass_reconnect(self.bass);
+ }
+ },
+ pa.PA_CONTEXT_FAILED, pa.PA_CONTEXT_TERMINATED => self.connectionLostLocked(),
+ else => {},
}
pa.pa_threaded_mainloop_signal(self.mainloop, 0);
}
+/// Replaces the failed context with a new one (on PA's thread). The old
+/// one's callbacks are detached first: it must never report into `self`.
+fn reconnectCallback(api: ?*pa.pa_mainloop_api, e: ?*pa.pa_time_event, tv: ?*const pa.struct_timeval, userdata: ?*anyopaque) callconv(.c) void {
+ _ = tv;
+ const self: *AudioManager = @ptrCast(@alignCast(userdata.?));
+ if (e) |timer| {
+ if (api) |a| if (a.time_free) |free_fn| free_fn(timer);
+ }
+ self.reconnect_timer = null;
+ if (self.shutting_down) return;
+ const context = pa.pa_context_new(pa.pa_threaded_mainloop_get_api(self.mainloop), "rediwm") orelse {
+ self.connectionLostLocked();
+ return;
+ };
+ const old = self.context;
+ pa.pa_context_set_state_callback(old, null, null);
+ pa.pa_context_set_subscribe_callback(old, null, null);
+ self.context = context;
+ pa.pa_context_unref(old);
+ pa.pa_context_set_state_callback(context, stateCallback, self);
+ // A synchronous failure has already reported FAILED; the timer guard in
+ // `connectionLostLocked` keeps this from scheduling twice.
+ if (pa.pa_context_connect(context, null, pa.PA_CONTEXT_NOFAIL, null) < 0) self.connectionLostLocked();
+}
+
/// Fires on any subscribed state change, running on the PA thread — must
/// never wait or call into compositor code directly (see module doc
/// comment). Re-issues the relevant async (non-waiting) refresh and bumps
diff --git a/tests/audio_mute_fade.py b/tests/audio_mute_fade.py
index 0fb8cb9..16eb400 100644
--- a/tests/audio_mute_fade.py
+++ b/tests/audio_mute_fade.py
@@ -65,16 +65,21 @@ def run(tmp):
def device_muted():
return "yes" in command("pactl", "get-sink-mute", "fade_test")
- try:
- for args in (["pipewire", "-c", "/usr/share/pipewire/pipewire.conf"], ["pipewire-pulse"]):
- procs.append(subprocess.Popen(args, env=env, stdout=audio_log, stderr=audio_log))
+ def start_audio():
+ """PipeWire, pipewire-pulse and WirePlumber with the test sink."""
+ started = [subprocess.Popen(args, env=env, stdout=audio_log, stderr=audio_log)
+ for args in (["pipewire", "-c", "/usr/share/pipewire/pipewire.conf"], ["pipewire-pulse"])]
wait(lambda: subprocess.run(["pactl", "info"], env=env, capture_output=True).returncode == 0, "private audio")
# The policy-only profile has no ALSA, Bluetooth or camera monitors.
- procs.append(subprocess.Popen(["dbus-run-session", "--", "wireplumber", "--profile=policy"],
- env=env, stdout=audio_log, stderr=audio_log))
+ started.append(subprocess.Popen(["dbus-run-session", "--", "wireplumber", "--profile=policy"],
+ env=env, stdout=audio_log, stderr=audio_log))
command("pactl", "load-module", "module-null-sink", "sink_name=fade_test")
wait(lambda: "filters" in command("pw-metadata", "-l"), "smart-filter policy")
command("pactl", "set-default-sink", "fade_test")
+ return started
+
+ try:
+ procs.extend(start_audio())
extra = {key: env[key] for key in ("PIPEWIRE_RUNTIME_DIR", "PULSE_SERVER", "XDG_STATE_HOME", "XDG_CONFIG_HOME", "DBUS_SESSION_BUS_ADDRESS")}
config = '[compositor]\nxwayland = false\n[keybinds]\n"F12" = "quit"\n'
process, log = spawn_compositor(tmp, env_extra=extra, config_content=config)
@@ -168,6 +173,23 @@ def run(tmp):
print(f"fade out {fade_out} ms, device mute after {device_delay} ms, fade in {fade_in} ms, "
f"cancelled mute dipped to {min(flick):.0%}, external unmute fade {external} ms")
+ # The daemon dying (a crash, `systemctl restart pipewire`)
+ # takes the filter, pipewire-pulse and WirePlumber with it.
+ for proc in procs[:3]:
+ stop_process(proc)
+ procs[:3] = start_audio()
+ wait(bass_node, "bass filter after a PipeWire restart", timeout=20)
+ wait(lambda: ipc.action('get_audio_state')["default_sink"], "audio state after a PipeWire restart", timeout=10)
+ time.sleep(.5) # The node is listed before the compositor binds it.
+ # Only a live filter fades: the device mutes after it.
+ ipc.key_press("XF86AudioMute")
+ wait(muted, "muted after a PipeWire restart")
+ assert not device_muted(), "no fade after a PipeWire restart"
+ wait(device_muted, "device muted after the restarted filter's fade")
+ ipc.key_press("XF86AudioMute")
+ wait(lambda: not muted(), "unmuted after a PipeWire restart")
+ print("PASS: filter and audio state return after a PipeWire restart")
+
# Quitting mid-fade still leaves the device muted.
ipc.key_press("XF86AudioMute")
wait(muted, "muted before quit")
@@ -177,6 +199,8 @@ def run(tmp):
pass # It quit before replying.
process.wait(timeout=10)
assert device_muted(), "quitting during the fade left the device unmuted"
+ contents = (tmp / "compositor.log").read_text()
+ assert "bass boost: reconnected to PipeWire" in contents, "no filter reconnect logged"
print("PASS: mute fades out before the device mutes, unmute fades in, cancel and quit are clean")
except Exception:
log.flush()
diff --git a/tests/hardware_keys.py b/tests/hardware_keys.py
index 8cf4025..b56baff 100644
--- a/tests/hardware_keys.py
+++ b/tests/hardware_keys.py
@@ -38,9 +38,9 @@ def private_audio(tmp):
with (runtime / 'log').open('w') as log:
def pactl(*args):
return subprocess.check_output(['pactl', *args], env=env, text=True).strip()
- try:
- for args in (['pipewire', '-c', str(config)], ['pipewire-pulse']):
- procs.append(subprocess.Popen(args, env=env, stdout=log, stderr=log))
+
+ def start_pulse():
+ procs.append(subprocess.Popen(['pipewire-pulse'], env=env, stdout=log, stderr=log))
wait(lambda: subprocess.run(['pactl', 'info'], env=env, capture_output=True).returncode == 0, 'private audio startup')
pactl('load-module', 'module-null-sink', 'sink_name=osd_test')
pactl('load-module', 'module-remap-source', 'source_name=osd_mic', 'master=osd_test.monitor')
@@ -50,6 +50,15 @@ def private_audio(tmp):
pactl('set-sink-volume', 'osd_test', '50%')
pactl('set-sink-mute', 'osd_test', '0')
pactl('set-source-mute', 'osd_mic', '0')
+
+ def restart_pulse():
+ """Like systemd restarting pipewire-pulse: its devices go with it."""
+ stop_process(procs.pop())
+ start_pulse()
+ pactl.restart_pulse = restart_pulse
+ try:
+ procs.append(subprocess.Popen(['pipewire', '-c', str(config)], env=env, stdout=log, stderr=log))
+ start_pulse()
yield env, pactl
finally:
for p in reversed(procs):
@@ -198,6 +207,13 @@ print('fixture,backlight,700,70%,1000')
pactl('set-sink-volume', 'osd_test', '25%')
wait(lambda: abs(audio()['master_volume'] - .25) < .002, 'external adjustment')
assert red_count(capture('external-volume')) < red_count(volume) * .6
+ # A restarted sound server is reconnected to: keys must not
+ # keep showing (and failing to change) the old server's level.
+ pactl.restart_pulse()
+ wait(lambda: abs(audio()['master_volume'] - .5) < .002, 'state after pulse restart', timeout=10)
+ client.key_press('XF86AudioRaiseVolume')
+ wait(lambda: abs(audio()['master_volume'] - .55) < .002, 'volume key after pulse restart')
+ assert pactl('get-sink-volume', 'osd_test').count('55%') == 2, 'server volume after pulse restart'
# Failed helpers never invent a level, and hung helpers do
# not block IPC or keep queueing indefinitely.
time.sleep(1.5)
@@ -229,7 +245,8 @@ print('fixture,backlight,700,70%,1000')
log.close()
contents = (tmp / 'compositor.log').read_text()
assert 'panic:' not in contents, contents
- print('PASS: hardware keys, confirmed OSD pixels, repeats, menu routing, helper failures; scale=' + scale)
+ assert 'reconnected to PipeWire/PulseAudio' in contents, 'no audio reconnect logged'
+ print('PASS: hardware keys, confirmed OSD pixels, repeats, menu routing, helper failures, pulse restart; scale=' + scale)
if __name__ == '__main__':