diff --git a/flake.nix b/flake.nix index 30b68f08dd7..347a3b3d641 100644 --- a/flake.nix +++ b/flake.nix @@ -188,6 +188,8 @@ pkgs.alsa-plugins # A private clocked null device for native playback tests. (pkgs.lib.getBin pkgs.pulseaudio) + # A shared session bus for the concurrent private audio server test. + pkgs.dbus # moq-video's `pipewire` screen-capture feature: the pipewire crate # links libpipewire-0.3 via pkg-config and generates bindings at build # time (bindgenHook above provides libclang). Linux-only; macOS uses diff --git a/quest/m0/test-flakes-2/README.md b/quest/m0/test-flakes-2/README.md index dc17e7737bb..ebe71ca1b14 100644 --- a/quest/m0/test-flakes-2/README.md +++ b/quest/m0/test-flakes-2/README.md @@ -96,6 +96,5 @@ Public API: none. Wire: none. - [moq-ffi's panicked-origin supervision test survives load](/quest/m0/test-flakes-2/ffi-origin-panic.md) - a read the origin driver's panic ends always reports `MoqError::Task` - [The scheduled macOS WebSocket version test completes reliably](/quest/m0/test-flakes-2/macos-websocket.md) - fix the scheduled timeout while preserving newest-version negotiation assertions - [@moq/net's lite subscribe tests wait for the whole request](/quest/m0/test-flakes-2/js-subscribe-fixture.md) - the three lite subscribe-with-track cases pass under forced yields -- [Concurrent PulseAudio harness runs don't share a D-Bus name](/quest/m0/test-flakes-2/pulse-dbus.md) - parallel media runs no longer collide on `org.PulseAudio1` - [@moq/net's uni-stream flood test survives reruns](/quest/m0/test-flakes-2/js-stream-flood.md) - "a flood of uni streams yields" passes under `--rerun-each` and load - [The JS receive-credit qmux test never completes an oversized frame](/quest/m0/test-flakes-2/receive-credit-qmux.md) - `javascript_partial_frame_gives_way_qmux` stops completing a frame larger than the window on moq-transport-18 diff --git a/quest/m0/test-flakes-2/pulse-dbus.md b/quest/m0/test-flakes-2/pulse-dbus.md deleted file mode 100644 index 3b9db6d1777..00000000000 --- a/quest/m0/test-flakes-2/pulse-dbus.md +++ /dev/null @@ -1,27 +0,0 @@ -# [XS] Concurrent PulseAudio harness runs don't share a D-Bus name - -## Goal - -Two media harness runs on one host each start a private PulseAudio without -`D-Bus name org.PulseAudio1 already taken`, so a concurrent run never fails -before its browser launches. - -## Plan - -Decided 2026-11-03 (maintainer, /quest-plan of the follow-ups from -[moq-dev/moq#7716](https://github.com/moq-dev/moq/pull/7716)): milestone m0, -a child of the test-flakes epic, since parallel agent runs hit it. - -- `test/lib/pulse.py` (lines 44–53) isolates `XDG_RUNTIME_DIR`, `PULSE_*`, - `ALSA_CONFIG_PATH`, and `DISPLAY`. It passes `DBUS_SESSION_BUS_ADDRESS` - through, so every private daemon tries to claim the same session-bus name. - Callers: `test/interop/interop.sh:2118`, `test/audio-quality/run.sh:349`, - and native-play. -- Give each daemon no session bus. Unset the address or disable PulseAudio's - D-Bus module in the private config, after checking that the daemon starts - cleanly with no bus. If it doesn't, run it under its own - `dbus-run-session`. -- Add a test that starts two `pulse.py` instances at once and plays through - each. - -Public API: none. Wire: none. diff --git a/test/justfile b/test/justfile index 79ab2b14ed6..af35432674b 100644 --- a/test/justfile +++ b/test/justfile @@ -45,6 +45,7 @@ default: # from plain `bun test` so unit tests do not launch a browser. harness: ./lib/harness.test.sh + python3 lib/pulse.test.py ./interop/relay-log.test.sh python3 interop/staging.test.py python3 ../rs/moq-gst/smoke.test.py diff --git a/test/lib/pulse.py b/test/lib/pulse.py index 4ddd3eb0ede..9f48abf17cd 100644 --- a/test/lib/pulse.py +++ b/test/lib/pulse.py @@ -51,6 +51,11 @@ def run(): "DISPLAY": "", "WAYLAND_DISPLAY": "", } + # The daemon claims org.PulseAudio1 even without a D-Bus module. With no + # session address (and no DISPLAY to autolaunch one), it uses only our socket. + # Keep the wrapped command's session bus available for its other services. + daemon_env = env.copy() + daemon_env.pop("DBUS_SESSION_BUS_ADDRESS", None) # By default the null sink renders 2 s ahead and sleeps through it, and a new stream does not # rewind that, so a stream's first callback waits up to 2 s: Firefox reports its AudioContext @@ -68,7 +73,7 @@ def run(): f"--load=module-native-protocol-unix socket={socket} auth-anonymous=1", "--load=module-null-sink sink_name=moq-null rate=48000 channels=2 norewinds=1", ], - env=env, + env=daemon_env, stderr=subprocess.PIPE, ) try: diff --git a/test/lib/pulse.test.py b/test/lib/pulse.test.py new file mode 100644 index 00000000000..0cd6b6b1ed0 --- /dev/null +++ b/test/lib/pulse.test.py @@ -0,0 +1,132 @@ +"""Private audio servers start together and play on their own sinks under one session bus.""" + +import array +import json +import math +import os +import signal +import string +import subprocess +import sys +import tempfile +import unittest +import wave +from contextlib import ExitStack +from pathlib import Path + +HERE = Path(__file__).resolve().parent +# Bytes a D-Bus address value may carry unescaped; the rest are %-encoded, including XML's `&` and `<`. +DBUS_SAFE = frozenset((string.ascii_letters + string.digits + "-_/.\\*").encode()) + + +def dbus_unix_path(path): + return "unix:path=" + "".join(chr(b) if b in DBUS_SAFE else f"%{b:02x}" for b in os.fsencode(path)) + + +def play(tone): + assert os.environ["DBUS_SESSION_BUS_ADDRESS"] + info = json.loads(subprocess.check_output(["pactl", "--format=json", "info"])) + assert info["server_string"] == os.environ["PULSE_SERVER"] + assert info["default_sink_name"] == "moq-null" + # Hold both daemons alive before either playback can finish and release its D-Bus name. + print("ready", flush=True) + assert sys.stdin.readline() == "play\n" + subprocess.run(["paplay", "--device=moq-null", str(tone)], check=True) + + +def parallel(root): + with ExitStack() as children: + runs = [ + children.enter_context( + subprocess.Popen( + [ + sys.executable, + str(HERE / "pulse.py"), + "--dir", + str(root / name), + "--", + sys.executable, + str(Path(__file__).resolve()), + "--play", + str(root / "tone.wav"), + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + ) + for name in ("one", "two") + ] + for child in runs: + line = child.stdout.readline() + if line != b"ready\n": + # Surface why, such as a startup rejection or a failed pactl check, not only that it failed. + output, _ = child.communicate() + raise AssertionError("private server exited before playback:\n" + (line + output).decode()) + for child in runs: + child.stdin.write(b"play\n") + child.stdin.flush() + for child in runs: + output, _ = child.communicate() + assert child.returncode == 0, output.decode() + + +@unittest.skipUnless(sys.platform == "linux", "private PulseAudio is Linux-only") +class Pulse(unittest.TestCase): + def test_parallel_playback(self): + # The system temp dir keeps both Unix sockets well inside sockaddr_un's 108 bytes, however deep the checkout. + with tempfile.TemporaryDirectory(prefix="pulse-") as directory: + root = Path(directory) + bus_config = root / "bus.conf" + bus_config.write_text( + f"session{dbus_unix_path(root / 'b')}EXTERNAL" + '' + '' + ) + with wave.open(str(root / "tone.wav"), "wb") as tone: + tone.setparams((1, 2, 48000, 0, "NONE", "not compressed")) + samples = array.array("h", (int(8000 * math.sin(2 * math.pi * 440 * i / 48000)) for i in range(12000))) + if sys.byteorder != "little": + samples.byteswap() + tone.writeframes(samples.tobytes()) + # The shared bus is private to this test, never the desktop's session bus. + with subprocess.Popen( + [ + "dbus-run-session", + f"--config-file={bus_config}", + "--", + sys.executable, + str(Path(__file__).resolve()), + "--parallel", + str(root), + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) as session: + timed_out = False + try: + # Each pulse.py may spend 30 s on startup alone; leave room for playback after it. + session.communicate(timeout=60) + except subprocess.TimeoutExpired: + timed_out = True + finally: + # Reap the whole test tree even if startup or a playback client hangs. + try: + os.killpg(session.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output, _ = session.communicate() + logs = "\n".join(f"{log}:\n{log.read_text()}" for log in root.glob("*/pulse.log")) + diagnostics = output.decode() + logs + self.assertFalse(timed_out, "private audio test timed out\n" + diagnostics) + self.assertEqual(session.returncode, 0, diagnostics) + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--play"]: + play(Path(sys.argv[2])) + elif sys.argv[1:2] == ["--parallel"]: + parallel(Path(sys.argv[2])) + else: + unittest.main()