headphones_reconnect.sh 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/bin/bash
  2. # headphones_reconnect.sh [--pulse-server]: HeadphonesDetector across a pipewire-pulse restart, on a private D-Bus +
  3. # PipeWire + pipewire-pulse in their own runtime dir (nothing reaches /run/user or the system bus). Prints the probe's
  4. # answers and every connect() to the pulse socket: after the kill the detector should wait for the server's
  5. # org.pulseaudio.Server name on D-Bus (no connects until the restart), with --pulse-server (PULSE_SERVER set, libpulse
  6. # can't wait on D-Bus then) it retries every 2 s. Needs strace and a built engine library
  7. HERE=$(cd "$(dirname "$0")" && pwd)
  8. REPO=$(cd "$HERE/../../.." && pwd)
  9. R=${TMPDIR:-/tmp}/lwe-hp-$$
  10. g++ -std=c++20 -O1 "$HERE/headphones_probe.cpp" -I"$REPO/src" -I"$REPO/build/generated" $(pkg-config --cflags libpulse) \
  11. -L"$REPO/build/output" -llinux-wallpaperengine-lib -Wl,-rpath,"$REPO/build/output" $(pkg-config --libs libpulse) \
  12. -o "$R.probe" || exit 1
  13. PS=(); [ "$1" = "--pulse-server" ] && PS=(PULSE_SERVER=unix:$R/native)
  14. rm -rf $R; mkdir -p $R/config $R/state $R/data; chmod 700 $R
  15. ADDR=$(dbus-daemon --session --fork --print-address=1 --print-pid=3 3>$R/dbus.pid)
  16. E=(env -i HOME=$R PATH=/usr/bin:/usr/sbin XDG_RUNTIME_DIR=$R PULSE_RUNTIME_PATH=$R PIPEWIRE_RUNTIME_DIR=$R
  17. XDG_CONFIG_HOME=$R/config XDG_STATE_HOME=$R/state XDG_DATA_HOME=$R/data DBUS_SESSION_BUS_ADDRESS=$ADDR
  18. DBUS_SYSTEM_BUS_ADDRESS=unix:path=/nonexistent ALSA_CONFIG_PATH=/dev/null)
  19. start_pulse () {
  20. "${E[@]}" setsid pipewire-pulse > $R/pipewire-pulse.log 2>&1 &
  21. echo $! > $R/pp.pid
  22. for i in $(seq 50); do "${E[@]}" pactl info >/dev/null 2>&1 && break; sleep 0.1; done
  23. "${E[@]}" pactl load-module module-null-sink sink_name=hp sink_properties=device.form_factor=headphone >/dev/null
  24. "${E[@]}" pactl set-default-sink hp
  25. }
  26. "${E[@]}" setsid pipewire > $R/pipewire.log 2>&1 &
  27. sleep 0.5
  28. "${E[@]}" setsid wireplumber > $R/wireplumber.log 2>&1 &
  29. sleep 0.5
  30. start_pulse
  31. echo "server up: $("${E[@]}" pactl get-default-sink)"
  32. "${E[@]}" "${PS[@]}" strace -f -tt -e trace=connect -o $R/strace.log "$R.probe" 16 &
  33. H=$!
  34. sleep 3
  35. echo "-- killing pipewire-pulse at $(date +%T.%N | cut -c1-12)"
  36. kill $(cat $R/pp.pid)
  37. sleep 6
  38. echo "-- restarting pipewire-pulse at $(date +%T.%N | cut -c1-12)"
  39. start_pulse
  40. wait $H
  41. for p in $(pgrep -x pipewire) $(pgrep -x wireplumber) $(pgrep -x pipewire-pulse); do
  42. { tr '\0' '\n' < /proc/$p/environ; } 2>/dev/null | grep -qx "XDG_RUNTIME_DIR=$R" && kill $p
  43. done
  44. kill $(cat $R/dbus.pid)
  45. echo "-- connects to the pulse socket:"
  46. grep -c "native" $R/strace.log
  47. grep "native" $R/strace.log | cut -c1-160
  48. rm -rf "$R" "$R.probe"