From 2a900c419fa6d41d85703f6fbec79574d14a3646 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 10 Nov 2026 23:05:16 +0100 Subject: [PATCH 1/2] fix: survive the removal of the default PulseAudio device A query for a default device removed meanwhile fails with no info, and a server without devices names no default. Both crashed the JVM; the default is now null instead. Fixes #580 --- .github/actions/test-natives/action.yml | 18 +- .../audio/linux/PulseAudioDeviceManager.cpp | 61 ++++-- .../webrtc/internal/DeviceBackendTests.java | 178 +++++++++++++++++- 3 files changed, 233 insertions(+), 24 deletions(-) diff --git a/.github/actions/test-natives/action.yml b/.github/actions/test-natives/action.yml index db5445f60..5bab853d2 100644 --- a/.github/actions/test-natives/action.yml +++ b/.github/actions/test-natives/action.yml @@ -57,9 +57,9 @@ runs: name: natives-media-${{ inputs.platform-name }} path: natives - # PulseAudio, libudev and libdbus are deliberately not installed here: the - # natives open them at runtime, and the armhf lane, whose image has none of - # them, proves that they load without them. + # PulseAudio, libudev and libdbus are deliberately not installed as runtime + # libraries: the natives open them at runtime, and the armhf lane, whose + # image has none of them, proves that they load without them. - name: Install 32-bit runtime libraries if: runner.os == 'Linux' && inputs.java-architecture == 'armv7' run: | @@ -75,6 +75,18 @@ runs: sudo apt-get install -y libx11-6 libxext6 libxfixes3 libxdamage1 libxtst6 libxrandr2 libxcomposite1 libglib2.0-0 libgbm1 libdrm2 shell: bash + # Not a runtime library either: DeviceBackendTests starts a PulseAudio + # server of its own, with virtual devices only, to remove a default device + # while the natives use it. The armhf lane keeps running without it. No + # autospawn, so that the other tests still find no server running. + - name: Install a PulseAudio server for the device tests + if: runner.os == 'Linux' && inputs.java-architecture != 'armv7' + run: | + sudo apt-get install -y --no-install-recommends pulseaudio pulseaudio-utils + mkdir -p ~/.config/pulse + echo "autospawn = no" > ~/.config/pulse/client.conf + shell: bash + - name: Set up JDK ${{ inputs.java-version }} uses: actions/setup-java@v6 with: diff --git a/webrtc-jni/src/main/cpp/src/media/audio/linux/PulseAudioDeviceManager.cpp b/webrtc-jni/src/main/cpp/src/media/audio/linux/PulseAudioDeviceManager.cpp index 84d5df3bc..64e5cd125 100644 --- a/webrtc-jni/src/main/cpp/src/media/audio/linux/PulseAudioDeviceManager.cpp +++ b/webrtc-jni/src/main/cpp/src/media/audio/linux/PulseAudioDeviceManager.cpp @@ -150,14 +150,24 @@ namespace jni if (!pa.pa_threaded_mainloop_in_thread(mainloop)) iterate(mainloop, op); - op = pa.pa_context_get_source_info_by_name(context, defaultCaptureName.c_str(), getSourceInfoCallback, this); + // Without a source the server names no default, and an empty name is no query at all. + if (defaultCaptureName.empty()) { + defaultCaptureDescName.clear(); + } + else { + op = pa.pa_context_get_source_info_by_name(context, defaultCaptureName.c_str(), getSourceInfoCallback, this); - if (!pa.pa_threaded_mainloop_in_thread(mainloop)) - iterate(mainloop, op); + if (!pa.pa_threaded_mainloop_in_thread(mainloop)) + iterate(mainloop, op); + } if (!pa.pa_threaded_mainloop_in_thread(mainloop)) pa.pa_threaded_mainloop_unlock(mainloop); + if (defaultCaptureName.empty() || defaultCaptureDescName.empty()) { + return nullptr; + } + AudioDevicePtr defaultDevice = std::make_shared(defaultCaptureDescName, defaultCaptureName); defaultDevice->directionType = AudioDeviceDirectionType::adtCapture; return defaultDevice; @@ -191,14 +201,24 @@ namespace jni if (!pa.pa_threaded_mainloop_in_thread(mainloop)) iterate(mainloop, op); - op = pa.pa_context_get_sink_info_by_name(context, defaultPlaybackName.c_str(), getSinkInfoCallback, this); + // Without a sink the server names no default, and an empty name is no query at all. + if (defaultPlaybackName.empty()) { + defaultPlaybackDescName.clear(); + } + else { + op = pa.pa_context_get_sink_info_by_name(context, defaultPlaybackName.c_str(), getSinkInfoCallback, this); - if (!pa.pa_threaded_mainloop_in_thread(mainloop)) - iterate(mainloop, op); + if (!pa.pa_threaded_mainloop_in_thread(mainloop)) + iterate(mainloop, op); + } if (!pa.pa_threaded_mainloop_in_thread(mainloop)) pa.pa_threaded_mainloop_unlock(mainloop); + if (defaultPlaybackName.empty() || defaultPlaybackDescName.empty()) { + return nullptr; + } + AudioDevicePtr defaultDevice = std::make_shared(defaultPlaybackDescName, defaultPlaybackName); defaultDevice->directionType = AudioDeviceDirectionType::adtRender; return defaultDevice; @@ -226,12 +246,17 @@ namespace jni auto& pa = PulseAudioLoader::instance(); - if (last > 0) { - pa.pa_threaded_mainloop_signal(engine->mainloop, 0); + // A failed query, e.g. for a source removed after the server named it the default, + // ends with last < 0 and no info, and nothing follows it. + if (last < 0) { + engine->defaultCaptureDescName.clear(); + } + else if (last == 0 && info) { + engine->defaultCaptureDescName = info->description ? info->description : ""; return; } - engine->defaultCaptureDescName = info->description; + pa.pa_threaded_mainloop_signal(engine->mainloop, 0); } void PulseAudioDeviceManager::getSourceCallback(pa_context * ctx, const pa_source_info * info, int last, void * userdata) @@ -266,13 +291,18 @@ namespace jni { PulseAudioDeviceManager * engine = reinterpret_cast(userdata); - if (last > 0) { - auto& pa = PulseAudioLoader::instance(); - pa.pa_threaded_mainloop_signal(engine->mainloop, 0); + // A failed query, e.g. for a sink removed after the server named it the default, + // ends with last < 0 and no info, and nothing follows it. + if (last < 0) { + engine->defaultPlaybackDescName.clear(); + } + else if (last == 0 && info) { + engine->defaultPlaybackDescName = info->description ? info->description : ""; return; } - engine->defaultPlaybackDescName = info->description; + auto& pa = PulseAudioLoader::instance(); + pa.pa_threaded_mainloop_signal(engine->mainloop, 0); } void PulseAudioDeviceManager::getSinkCallback(pa_context * ctx, const pa_sink_info * info, int last, void * userdata) @@ -350,8 +380,9 @@ namespace jni auto& pa = PulseAudioLoader::instance(); PulseAudioDeviceManager * engine = reinterpret_cast(userdata); - engine->defaultCaptureName = info->default_source_name; - engine->defaultPlaybackName = info->default_sink_name; + // A failed query has no info, and a server without sources or sinks names no default. + engine->defaultCaptureName = info && info->default_source_name ? info->default_source_name : ""; + engine->defaultPlaybackName = info && info->default_sink_name ? info->default_sink_name : ""; pa.pa_threaded_mainloop_signal(engine->mainloop, 0); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java index 3310a8efc..17377ecab 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java @@ -21,34 +21,96 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.ByteArrayOutputStream; +import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import dev.onvoid.webrtc.media.AudioBackendUnavailableException; import dev.onvoid.webrtc.media.Device; import dev.onvoid.webrtc.media.DeviceChangeListener; import dev.onvoid.webrtc.media.MediaDevices; +import dev.onvoid.webrtc.media.audio.AudioDevice; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; class DeviceBackendTests { + private static final String SINK = "webrtc_java_sink"; + + private static final String SOURCE = "webrtc_java_source"; + + @Test void unavailablePulseAudioIsTyped() throws Exception { - assumeTrue(System.getProperty("os.name").equals("Linux")); - ProcessBuilder builder = new ProcessBuilder( - Paths.get(System.getProperty("java.home"), "bin", "java").toString(), - "-cp", StandaloneLoadingTests.classPath(), UnavailableBackend.class.getName()); + assumeTrue(isLinux()); // A nonexistent Unix socket makes connection failure deterministic, // irrespective of the developer's running PulseAudio server. - builder.environment().put("PULSE_SERVER", "unix:/nonexistent/webrtc-java-test-pulse"); + runProbe(UnavailableBackend.class, Collections.singletonMap( + "PULSE_SERVER", "unix:/nonexistent/webrtc-java-test-pulse")); + } + + /** + * Issue #580: the default device is removed while an application asks for + * the default devices from a device change listener. + */ + @Test + void removedDefaultDeviceDoesNotCrash(@TempDir Path dir) throws Exception { + assumeTrue(isLinux()); + assumeTrue(onPath("pulseaudio") && onPath("pactl"), "no PulseAudio server and pactl"); + + // A server of its own, with no hardware, whose only sink and source are + // the defaults the probe removes. + Path socket = dir.resolve("native"); + ProcessBuilder builder = new ProcessBuilder("pulseaudio", "-n", "--daemonize=no", + "--exit-idle-time=-1", "--use-pid-file=no", "--log-target=stderr", + "--load=module-null-sink sink_name=" + SINK, + "--load=module-null-source source_name=" + SOURCE, + // Last, so that the socket appears once the devices are there. + "--load=module-native-protocol-unix auth-anonymous=1 socket=" + socket); + builder.environment().put("HOME", dir.toString()); + builder.environment().put("XDG_RUNTIME_DIR", dir.toString()); + builder.environment().put("XDG_CONFIG_HOME", dir.toString()); + // Keep it off the session bus of a desktop the tests may run on. + builder.environment().put("DBUS_SESSION_BUS_ADDRESS", "unix:path=" + dir.resolve("no-bus")); + Process server = builder.redirectErrorStream(true) + .redirectOutput(dir.resolve("pulseaudio.log").toFile()) + .start(); + try { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (!Files.exists(socket)) { + assertTrue(server.isAlive(), () -> "PulseAudio did not start:\n" + log(dir)); + assertTrue(System.nanoTime() < deadline, () -> "PulseAudio did not listen:\n" + log(dir)); + Thread.sleep(50); + } + runProbe(RemovedDefaultDevice.class, Collections.singletonMap( + "PULSE_SERVER", "unix:" + socket)); + } + finally { + server.destroy(); + if (!server.waitFor(10, TimeUnit.SECONDS)) { + server.destroyForcibly(); + } + } + } + + private static void runProbe(Class probe, Map environment) throws Exception { + ProcessBuilder builder = new ProcessBuilder( + Paths.get(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", StandaloneLoadingTests.classPath(), probe.getName()); + builder.environment().putAll(environment); Process process = builder.redirectErrorStream(true).start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); Thread reader = new Thread(() -> StandaloneLoadingTests.copy(process.getInputStream(), output)); reader.start(); try { - assertTrue(process.waitFor(30, TimeUnit.SECONDS), "Backend probe timed out"); + assertTrue(process.waitFor(30, TimeUnit.SECONDS), probe.getSimpleName() + " timed out"); reader.join(); assertEquals(0, process.exitValue(), new String(output.toByteArray(), StandardCharsets.UTF_8)); } @@ -57,6 +119,35 @@ void unavailablePulseAudioIsTyped() throws Exception { } } + private static boolean isLinux() { + return System.getProperty("os.name").equals("Linux"); + } + + private static boolean onPath(String program) { + String path = System.getenv("PATH"); + + if (path == null) { + return false; + } + for (String dir : path.split(File.pathSeparator)) { + if (Files.isExecutable(Paths.get(dir, program))) { + return true; + } + } + return false; + } + + private static String log(Path dir) { + try { + return new String(Files.readAllBytes(dir.resolve("pulseaudio.log")), StandardCharsets.UTF_8); + } + catch (Exception e) { + return e.toString(); + } + } + + + public static class UnavailableBackend { public static void main(String[] args) { @@ -82,4 +173,79 @@ private static void expectUnavailable(Runnable operation) { throw new AssertionError("Expected an unavailable audio backend"); } } + + + + public static class RemovedDefaultDevice { + + public static void main(String[] args) { + // PulseAudio's thread stays attached to the JVM once it has called + // the listener, and keeps the JVM from ending on its own. + try { + probe(); + } + catch (Throwable e) { + e.printStackTrace(); + System.exit(1); + } + System.exit(0); + } + + private static void probe() throws Exception { + // Known devices are the ones whose removal is reported. + MediaDevices.getAudioRenderDevices(); + MediaDevices.getAudioCaptureDevices(); + + expectDefault(SINK, MediaDevices.getDefaultAudioRenderDevice()); + expectDefault(SOURCE, MediaDevices.getDefaultAudioCaptureDevice()); + + CountDownLatch removed = new CountDownLatch(2); + + MediaDevices.addDeviceChangeListener(new DeviceChangeListener() { + @Override + public void deviceConnected(Device device) { } + @Override + public void deviceDisconnected(Device device) { + // The listener runs on PulseAudio's own thread, which does + // not wait for the answers: these ask for the device just + // removed, and the server answers that it does not exist. + MediaDevices.getDefaultAudioRenderDevice(); + MediaDevices.getDefaultAudioCaptureDevice(); + removed.countDown(); + } + }); + + pactl("unload-module", "module-null-sink"); + pactl("unload-module", "module-null-source"); + + if (!removed.await(10, TimeUnit.SECONDS)) { + throw new AssertionError("The removals were not reported"); + } + + // Answered after the failed queries, on the same connection: the + // server has no device left to name the default. + expectDefault(null, MediaDevices.getDefaultAudioRenderDevice()); + expectDefault(null, MediaDevices.getDefaultAudioCaptureDevice()); + } + + private static void expectDefault(String descriptor, AudioDevice device) { + String actual = device == null ? null : device.getDescriptor(); + + if (descriptor == null ? actual != null : !descriptor.equals(actual)) { + throw new AssertionError("Expected the default " + descriptor + ", got " + device); + } + } + + private static void pactl(String... args) throws Exception { + String[] command = new String[args.length + 1]; + command[0] = "pactl"; + System.arraycopy(args, 0, command, 1, args.length); + + Process process = new ProcessBuilder(command).inheritIO().start(); + + if (process.waitFor() != 0) { + throw new AssertionError("pactl " + String.join(" ", args) + " failed"); + } + } + } } From 309ca0f811637c147c972c8c56c2b069c45a9454 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 10 Nov 2026 23:22:27 +0100 Subject: [PATCH 2/2] fix: call device change listeners on a thread of their own On the system's thread, a listener's device queries could not wait for PulseAudio and answered with the defaults from before the change, and the attached thread kept the JVM from ending. Changes are now queued for a daemon thread; removed listeners drop the ones still queued. --- docs/guide/media/media-devices.md | 4 +- .../main/cpp/include/api/JavaCallbackThread.h | 12 ++++- .../cpp/include/media/DeviceChangeListener.h | 13 ++++- .../src/main/cpp/src/JNI_MediaDevices.cpp | 4 ++ .../main/cpp/src/api/JavaCallbackThread.cpp | 42 ++++++++++------ .../cpp/src/media/DeviceChangeListener.cpp | 38 +++++++++++--- .../webrtc/media/DeviceChangeListener.java | 6 +++ .../webrtc/internal/DeviceBackendTests.java | 50 ++++++++++++------- 8 files changed, 124 insertions(+), 45 deletions(-) diff --git a/docs/guide/media/media-devices.md b/docs/guide/media/media-devices.md index ae3613d26..2d54dc059 100644 --- a/docs/guide/media/media-devices.md +++ b/docs/guide/media/media-devices.md @@ -122,7 +122,9 @@ for (VideoCaptureCapability capability : capabilities) { ## Hotplug Events -You can listen for device hotplug events to be notified when devices are connected or disconnected: +You can listen for device hotplug events to be notified when devices are connected or disconnected. +Listeners are called on a thread of the library, one change at a time and in order, so a listener may +query `MediaDevices` again, for example for the new default device: ```java // Import required classes diff --git a/webrtc-jni/src/main/cpp/include/api/JavaCallbackThread.h b/webrtc-jni/src/main/cpp/include/api/JavaCallbackThread.h index f13c5406e..7101d10e8 100644 --- a/webrtc-jni/src/main/cpp/include/api/JavaCallbackThread.h +++ b/webrtc-jni/src/main/cpp/include/api/JavaCallbackThread.h @@ -33,12 +33,20 @@ namespace jni // their media. So these observers are queued and called here instead, one // at a time and in the order they were posted. // - // The thread starts on first use and is attached to the JVM as a daemon, - // so that it never holds up the JVM's exit. + // Device change listeners have a thread of their own, for the same reason: + // the operating system notifies them on its own thread, a PulseAudio main + // loop or an MMDevice notification thread, which the device queries they + // make wait for. A separate one, so that a listener waiting for an observer + // does not wait for itself. + // + // The threads start on first use and are attached to the JVM as daemons, + // so that they never hold up the JVM's exit. class JavaCallbackThread { public: static void Post(absl::AnyInvocable callback); + + static void PostDeviceChange(absl::AnyInvocable callback); }; } diff --git a/webrtc-jni/src/main/cpp/include/media/DeviceChangeListener.h b/webrtc-jni/src/main/cpp/include/media/DeviceChangeListener.h index d3230b488..77ed9cc5b 100644 --- a/webrtc-jni/src/main/cpp/include/media/DeviceChangeListener.h +++ b/webrtc-jni/src/main/cpp/include/media/DeviceChangeListener.h @@ -22,13 +22,17 @@ #include "media/DeviceHotplugListener.h" +#include #include #include namespace jni { - class DeviceChangeListener : public avdev::DeviceHotplugListener + // Calls a Java DeviceChangeListener on the device change thread of + // JavaCallbackThread, not on the thread of the operating system that + // reports the change. + class DeviceChangeListener : public avdev::DeviceHotplugListener, public std::enable_shared_from_this { public: explicit DeviceChangeListener(JNIEnv * env, const JavaGlobalRef & listener); @@ -38,8 +42,13 @@ namespace jni void deviceConnected(avdev::DevicePtr device) override; void deviceDisconnected(avdev::DevicePtr device) override; + // Drops the changes that are still queued for the Java listener, + // once it has been removed. + void detach(); + private: void notify(const avdev::DevicePtr & device, jmethodID method); + void call(JNIEnv * env, const avdev::DevicePtr & device, jmethodID method); private: class JavaDeviceChangeListenerClass : public JavaClass @@ -54,6 +63,8 @@ namespace jni private: JavaGlobalRef listener; + std::atomic detached; + const std::shared_ptr javaClass; }; } diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp index 140073cc5..46eab7040 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp @@ -68,6 +68,10 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_removeDeviceCha jni::WebRTCContext * context = static_cast(javaContext); auto listener = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener)); + if (listener) { + listener->detach(); + } + try { context->getAudioDeviceManager()->detachHotplugListener(listener); context->getVideoDeviceManager()->detachHotplugListener(listener); diff --git a/webrtc-jni/src/main/cpp/src/api/JavaCallbackThread.cpp b/webrtc-jni/src/main/cpp/src/api/JavaCallbackThread.cpp index fbf5da8a4..83aae976d 100644 --- a/webrtc-jni/src/main/cpp/src/api/JavaCallbackThread.cpp +++ b/webrtc-jni/src/main/cpp/src/api/JavaCallbackThread.cpp @@ -31,6 +31,7 @@ namespace jni { struct Queue { + const char * name; std::mutex mutex; std::condition_variable condition; std::deque> callbacks; @@ -43,7 +44,7 @@ namespace jni JavaVMAttachArgs args; args.version = JNI_VERSION_1_6; - args.name = const_cast("WebRTC-Callbacks"); + args.name = const_cast(queue->name); args.group = nullptr; if (vm->AttachCurrentThreadAsDaemon(reinterpret_cast(&env), &args) != JNI_OK) { @@ -77,32 +78,41 @@ namespace jni } } - Queue & GetQueue() + // Never destroyed: its thread waits on it for as long as the process + // runs. + Queue * StartQueue(const char * name) { - // Never destroyed: its thread waits on it for as long as the - // process runs. - static Queue * queue = [] { - Queue * created = new Queue(); + Queue * queue = new Queue(); + queue->name = name; - std::thread(Run, created).detach(); + std::thread(Run, queue).detach(); - return created; - }(); + return queue; + } + + void Enqueue(Queue & queue, absl::AnyInvocable callback) + { + { + std::lock_guard lock(queue.mutex); + + queue.callbacks.push_back(std::move(callback)); + } - return *queue; + queue.condition.notify_one(); } } void JavaCallbackThread::Post(absl::AnyInvocable callback) { - Queue & queue = GetQueue(); + static Queue * queue = StartQueue("WebRTC-Callbacks"); - { - std::lock_guard lock(queue.mutex); + Enqueue(*queue, std::move(callback)); + } - queue.callbacks.push_back(std::move(callback)); - } + void JavaCallbackThread::PostDeviceChange(absl::AnyInvocable callback) + { + static Queue * queue = StartQueue("WebRTC-DeviceChanges"); - queue.condition.notify_one(); + Enqueue(*queue, std::move(callback)); } } diff --git a/webrtc-jni/src/main/cpp/src/media/DeviceChangeListener.cpp b/webrtc-jni/src/main/cpp/src/media/DeviceChangeListener.cpp index 48b4cb530..978e24553 100644 --- a/webrtc-jni/src/main/cpp/src/media/DeviceChangeListener.cpp +++ b/webrtc-jni/src/main/cpp/src/media/DeviceChangeListener.cpp @@ -15,6 +15,7 @@ */ #include "media/DeviceChangeListener.h" +#include "api/JavaCallbackThread.h" #include "api/WebRTCUtils.h" #include "media/audio/AudioDevice.h" #include "media/video/VideoDevice.h" @@ -31,6 +32,7 @@ namespace jni { DeviceChangeListener::DeviceChangeListener(JNIEnv * env, const JavaGlobalRef & listener) : listener(listener), + detached(false), javaClass(JavaClasses::get(env)) { } @@ -45,19 +47,41 @@ namespace jni notify(device, javaClass->deviceDisconnected); } + void DeviceChangeListener::detach() + { + detached = true; + } + void DeviceChangeListener::notify(const avdev::DevicePtr & device, jmethodID method) { - JNIEnv * env = AttachCurrentThread(); + // This runs on a thread the operating system owns (a CoreAudio queue, the MMDevice + // notification thread, the PulseAudio main loop, ...), which has no handler for a C++ + // exception. A Java listener called here would also hold up the next change, and a device + // query it makes would wait for the very thread it runs on: the PulseAudio main loop + // answers only once the listener has returned. Attached to the JVM, the thread would + // moreover keep it from ending, as these threads run as long as the process does. + std::shared_ptr self = weak_from_this().lock(); - if (env == nullptr) { + if (!self || detached) { return; } - // This runs on a thread the operating system owns (a CoreAudio queue, the MMDevice - // notification thread, the PulseAudio main loop, ...), which has no handler for a C++ - // exception and never returns to Java. So nothing may be thrown from here, and what the - // Java listener throws is reported and cleared: left pending, it would be there for the - // next JNI call on this thread, which may be the next listener or the next event. + try { + JavaCallbackThread::PostDeviceChange([self, device, method](JNIEnv * env) { + if (!self->detached) { + self->call(env, device, method); + } + }); + } + catch (...) { + RTC_LOG(LS_ERROR) << "Device change notification failed"; + } + } + + void DeviceChangeListener::call(JNIEnv * env, const avdev::DevicePtr & device, jmethodID method) + { + // What the Java listener throws is reported and cleared: left pending, it would be there + // for the next JNI call on this thread, which may be the next listener or the next event. try { JavaLocalRef jdevice = nullptr; diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceChangeListener.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceChangeListener.java index 63c0abddd..ca28db724 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceChangeListener.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceChangeListener.java @@ -19,6 +19,12 @@ /** * A device change listener is notified whenever a media device such as a * camera, microphone, or speaker is connected to or removed from the system. + *

+ * Listeners are called on a thread of the library, not on the one the system + * reports the change on, one change at a time and in the order they were + * reported. A listener may query {@link MediaDevices}, which then reflects the + * change. Once a listener has been removed, it gets no more changes, apart from + * one it may be handling at that moment. * * @author Alex Andres */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java index 17377ecab..5d950581d 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java @@ -28,7 +28,8 @@ import java.nio.file.Paths; import java.util.Collections; import java.util.Map; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import dev.onvoid.webrtc.media.AudioBackendUnavailableException; @@ -179,8 +180,6 @@ private static void expectUnavailable(Runnable operation) { public static class RemovedDefaultDevice { public static void main(String[] args) { - // PulseAudio's thread stays attached to the JVM once it has called - // the listener, and keeps the JVM from ending on its own. try { probe(); } @@ -188,7 +187,8 @@ public static void main(String[] args) { e.printStackTrace(); System.exit(1); } - System.exit(0); + // Returns without System.exit: the JVM ends on its own only if + // no thread of PulseAudio has stayed attached to it. } private static void probe() throws Exception { @@ -199,37 +199,51 @@ private static void probe() throws Exception { expectDefault(SINK, MediaDevices.getDefaultAudioRenderDevice()); expectDefault(SOURCE, MediaDevices.getDefaultAudioCaptureDevice()); - CountDownLatch removed = new CountDownLatch(2); + BlockingQueue removals = new LinkedBlockingQueue<>(); MediaDevices.addDeviceChangeListener(new DeviceChangeListener() { @Override public void deviceConnected(Device device) { } @Override public void deviceDisconnected(Device device) { - // The listener runs on PulseAudio's own thread, which does - // not wait for the answers: these ask for the device just - // removed, and the server answers that it does not exist. - MediaDevices.getDefaultAudioRenderDevice(); - MediaDevices.getDefaultAudioCaptureDevice(); - removed.countDown(); + // The defaults the server names now that the device is + // gone, not the ones it named before. + try { + removals.add(device.getDescriptor() + + ": render=" + descriptor(MediaDevices.getDefaultAudioRenderDevice()) + + ", capture=" + descriptor(MediaDevices.getDefaultAudioCaptureDevice())); + } + catch (RuntimeException e) { + removals.add(device.getDescriptor() + ": " + e); + } } }); + // One after the other, so that each listener call sees one removal. pactl("unload-module", "module-null-sink"); - pactl("unload-module", "module-null-source"); + expectRemoval(SINK + ": render=null, capture=" + SOURCE, removals); - if (!removed.await(10, TimeUnit.SECONDS)) { - throw new AssertionError("The removals were not reported"); - } + pactl("unload-module", "module-null-source"); + expectRemoval(SOURCE + ": render=null, capture=null", removals); - // Answered after the failed queries, on the same connection: the - // server has no device left to name the default. expectDefault(null, MediaDevices.getDefaultAudioRenderDevice()); expectDefault(null, MediaDevices.getDefaultAudioCaptureDevice()); } + private static void expectRemoval(String expected, BlockingQueue removals) throws Exception { + String removal = removals.poll(10, TimeUnit.SECONDS); + + if (!expected.equals(removal)) { + throw new AssertionError("Expected the removal " + expected + ", got " + removal); + } + } + + private static String descriptor(AudioDevice device) { + return device == null ? null : device.getDescriptor(); + } + private static void expectDefault(String descriptor, AudioDevice device) { - String actual = device == null ? null : device.getDescriptor(); + String actual = descriptor(device); if (descriptor == null ? actual != null : !descriptor.equals(actual)) { throw new AssertionError("Expected the default " + descriptor + ", got " + device);