Skip to content

Commit 795bd30

Browse files
authored
fix: survive the removal of the default PulseAudio device (#584)
* 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 * 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.
1 parent 3a39e66 commit 795bd30

10 files changed

Lines changed: 339 additions & 51 deletions

File tree

‎.github/actions/test-natives/action.yml‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ runs:
5757
name: natives-media-${{ inputs.platform-name }}
5858
path: natives
5959

60-
# PulseAudio, libudev and libdbus are deliberately not installed here: the
61-
# natives open them at runtime, and the armhf lane, whose image has none of
62-
# them, proves that they load without them.
60+
# PulseAudio, libudev and libdbus are deliberately not installed as runtime
61+
# libraries: the natives open them at runtime, and the armhf lane, whose
62+
# image has none of them, proves that they load without them.
6363
- name: Install 32-bit runtime libraries
6464
if: runner.os == 'Linux' && inputs.java-architecture == 'armv7'
6565
run: |
@@ -75,6 +75,18 @@ runs:
7575
sudo apt-get install -y libx11-6 libxext6 libxfixes3 libxdamage1 libxtst6 libxrandr2 libxcomposite1 libglib2.0-0 libgbm1 libdrm2
7676
shell: bash
7777

78+
# Not a runtime library either: DeviceBackendTests starts a PulseAudio
79+
# server of its own, with virtual devices only, to remove a default device
80+
# while the natives use it. The armhf lane keeps running without it. No
81+
# autospawn, so that the other tests still find no server running.
82+
- name: Install a PulseAudio server for the device tests
83+
if: runner.os == 'Linux' && inputs.java-architecture != 'armv7'
84+
run: |
85+
sudo apt-get install -y --no-install-recommends pulseaudio pulseaudio-utils
86+
mkdir -p ~/.config/pulse
87+
echo "autospawn = no" > ~/.config/pulse/client.conf
88+
shell: bash
89+
7890
- name: Set up JDK ${{ inputs.java-version }}
7991
uses: actions/setup-java@v6
8092
with:

‎docs/guide/media/media-devices.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,9 @@ for (VideoCaptureCapability capability : capabilities) {
122122

123123
## Hotplug Events
124124

125-
You can listen for device hotplug events to be notified when devices are connected or disconnected:
125+
You can listen for device hotplug events to be notified when devices are connected or disconnected.
126+
Listeners are called on a thread of the library, one change at a time and in order, so a listener may
127+
query `MediaDevices` again, for example for the new default device:
126128

127129
```java
128130
// Import required classes

‎webrtc-jni/src/main/cpp/include/api/JavaCallbackThread.h‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,20 @@ namespace jni
3333
// their media. So these observers are queued and called here instead, one
3434
// at a time and in the order they were posted.
3535
//
36-
// The thread starts on first use and is attached to the JVM as a daemon,
37-
// so that it never holds up the JVM's exit.
36+
// Device change listeners have a thread of their own, for the same reason:
37+
// the operating system notifies them on its own thread, a PulseAudio main
38+
// loop or an MMDevice notification thread, which the device queries they
39+
// make wait for. A separate one, so that a listener waiting for an observer
40+
// does not wait for itself.
41+
//
42+
// The threads start on first use and are attached to the JVM as daemons,
43+
// so that they never hold up the JVM's exit.
3844
class JavaCallbackThread
3945
{
4046
public:
4147
static void Post(absl::AnyInvocable<void(JNIEnv *) &&> callback);
48+
49+
static void PostDeviceChange(absl::AnyInvocable<void(JNIEnv *) &&> callback);
4250
};
4351
}
4452

‎webrtc-jni/src/main/cpp/include/media/DeviceChangeListener.h‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,17 @@
2222

2323
#include "media/DeviceHotplugListener.h"
2424

25+
#include <atomic>
2526
#include <jni.h>
2627
#include <memory>
2728

2829
namespace jni
2930
{
3031

31-
class DeviceChangeListener : public avdev::DeviceHotplugListener
32+
// Calls a Java DeviceChangeListener on the device change thread of
33+
// JavaCallbackThread, not on the thread of the operating system that
34+
// reports the change.
35+
class DeviceChangeListener : public avdev::DeviceHotplugListener, public std::enable_shared_from_this<DeviceChangeListener>
3236
{
3337
public:
3438
explicit DeviceChangeListener(JNIEnv * env, const JavaGlobalRef<jobject> & listener);
@@ -38,8 +42,13 @@ namespace jni
3842
void deviceConnected(avdev::DevicePtr device) override;
3943
void deviceDisconnected(avdev::DevicePtr device) override;
4044

45+
// Drops the changes that are still queued for the Java listener,
46+
// once it has been removed.
47+
void detach();
48+
4149
private:
4250
void notify(const avdev::DevicePtr & device, jmethodID method);
51+
void call(JNIEnv * env, const avdev::DevicePtr & device, jmethodID method);
4352

4453
private:
4554
class JavaDeviceChangeListenerClass : public JavaClass
@@ -54,6 +63,8 @@ namespace jni
5463
private:
5564
JavaGlobalRef<jobject> listener;
5665

66+
std::atomic<bool> detached;
67+
5768
const std::shared_ptr<JavaDeviceChangeListenerClass> javaClass;
5869
};
5970
}

‎webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_removeDeviceCha
6868
jni::WebRTCContext * context = static_cast<jni::WebRTCContext *>(javaContext);
6969
auto listener = javaContext->removeNativeRef<jni::DeviceChangeListener>(env, jni::JavaLocalRef<jobject>(env, jListener));
7070

71+
if (listener) {
72+
listener->detach();
73+
}
74+
7175
try {
7276
context->getAudioDeviceManager()->detachHotplugListener(listener);
7377
context->getVideoDeviceManager()->detachHotplugListener(listener);

‎webrtc-jni/src/main/cpp/src/api/JavaCallbackThread.cpp‎

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ namespace jni
3131
{
3232
struct Queue
3333
{
34+
const char * name;
3435
std::mutex mutex;
3536
std::condition_variable condition;
3637
std::deque<absl::AnyInvocable<void(JNIEnv *) &&>> callbacks;
@@ -43,7 +44,7 @@ namespace jni
4344

4445
JavaVMAttachArgs args;
4546
args.version = JNI_VERSION_1_6;
46-
args.name = const_cast<char *>("WebRTC-Callbacks");
47+
args.name = const_cast<char *>(queue->name);
4748
args.group = nullptr;
4849

4950
if (vm->AttachCurrentThreadAsDaemon(reinterpret_cast<void **>(&env), &args) != JNI_OK) {
@@ -77,32 +78,41 @@ namespace jni
7778
}
7879
}
7980

80-
Queue & GetQueue()
81+
// Never destroyed: its thread waits on it for as long as the process
82+
// runs.
83+
Queue * StartQueue(const char * name)
8184
{
82-
// Never destroyed: its thread waits on it for as long as the
83-
// process runs.
84-
static Queue * queue = [] {
85-
Queue * created = new Queue();
85+
Queue * queue = new Queue();
86+
queue->name = name;
8687

87-
std::thread(Run, created).detach();
88+
std::thread(Run, queue).detach();
8889

89-
return created;
90-
}();
90+
return queue;
91+
}
92+
93+
void Enqueue(Queue & queue, absl::AnyInvocable<void(JNIEnv *) &&> callback)
94+
{
95+
{
96+
std::lock_guard<std::mutex> lock(queue.mutex);
97+
98+
queue.callbacks.push_back(std::move(callback));
99+
}
91100

92-
return *queue;
101+
queue.condition.notify_one();
93102
}
94103
}
95104

96105
void JavaCallbackThread::Post(absl::AnyInvocable<void(JNIEnv *) &&> callback)
97106
{
98-
Queue & queue = GetQueue();
107+
static Queue * queue = StartQueue("WebRTC-Callbacks");
99108

100-
{
101-
std::lock_guard<std::mutex> lock(queue.mutex);
109+
Enqueue(*queue, std::move(callback));
110+
}
102111

103-
queue.callbacks.push_back(std::move(callback));
104-
}
112+
void JavaCallbackThread::PostDeviceChange(absl::AnyInvocable<void(JNIEnv *) &&> callback)
113+
{
114+
static Queue * queue = StartQueue("WebRTC-DeviceChanges");
105115

106-
queue.condition.notify_one();
116+
Enqueue(*queue, std::move(callback));
107117
}
108118
}

‎webrtc-jni/src/main/cpp/src/media/DeviceChangeListener.cpp‎

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
#include "media/DeviceChangeListener.h"
18+
#include "api/JavaCallbackThread.h"
1819
#include "api/WebRTCUtils.h"
1920
#include "media/audio/AudioDevice.h"
2021
#include "media/video/VideoDevice.h"
@@ -31,6 +32,7 @@ namespace jni
3132
{
3233
DeviceChangeListener::DeviceChangeListener(JNIEnv * env, const JavaGlobalRef<jobject> & listener) :
3334
listener(listener),
35+
detached(false),
3436
javaClass(JavaClasses::get<JavaDeviceChangeListenerClass>(env))
3537
{
3638
}
@@ -45,19 +47,41 @@ namespace jni
4547
notify(device, javaClass->deviceDisconnected);
4648
}
4749

50+
void DeviceChangeListener::detach()
51+
{
52+
detached = true;
53+
}
54+
4855
void DeviceChangeListener::notify(const avdev::DevicePtr & device, jmethodID method)
4956
{
50-
JNIEnv * env = AttachCurrentThread();
57+
// This runs on a thread the operating system owns (a CoreAudio queue, the MMDevice
58+
// notification thread, the PulseAudio main loop, ...), which has no handler for a C++
59+
// exception. A Java listener called here would also hold up the next change, and a device
60+
// query it makes would wait for the very thread it runs on: the PulseAudio main loop
61+
// answers only once the listener has returned. Attached to the JVM, the thread would
62+
// moreover keep it from ending, as these threads run as long as the process does.
63+
std::shared_ptr<DeviceChangeListener> self = weak_from_this().lock();
5164

52-
if (env == nullptr) {
65+
if (!self || detached) {
5366
return;
5467
}
5568

56-
// This runs on a thread the operating system owns (a CoreAudio queue, the MMDevice
57-
// notification thread, the PulseAudio main loop, ...), which has no handler for a C++
58-
// exception and never returns to Java. So nothing may be thrown from here, and what the
59-
// Java listener throws is reported and cleared: left pending, it would be there for the
60-
// next JNI call on this thread, which may be the next listener or the next event.
69+
try {
70+
JavaCallbackThread::PostDeviceChange([self, device, method](JNIEnv * env) {
71+
if (!self->detached) {
72+
self->call(env, device, method);
73+
}
74+
});
75+
}
76+
catch (...) {
77+
RTC_LOG(LS_ERROR) << "Device change notification failed";
78+
}
79+
}
80+
81+
void DeviceChangeListener::call(JNIEnv * env, const avdev::DevicePtr & device, jmethodID method)
82+
{
83+
// What the Java listener throws is reported and cleared: left pending, it would be there
84+
// for the next JNI call on this thread, which may be the next listener or the next event.
6185
try {
6286
JavaLocalRef<jobject> jdevice = nullptr;
6387

‎webrtc-jni/src/main/cpp/src/media/audio/linux/PulseAudioDeviceManager.cpp‎

Lines changed: 46 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -150,14 +150,24 @@ namespace jni
150150
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
151151
iterate(mainloop, op);
152152

153-
op = pa.pa_context_get_source_info_by_name(context, defaultCaptureName.c_str(), getSourceInfoCallback, this);
153+
// Without a source the server names no default, and an empty name is no query at all.
154+
if (defaultCaptureName.empty()) {
155+
defaultCaptureDescName.clear();
156+
}
157+
else {
158+
op = pa.pa_context_get_source_info_by_name(context, defaultCaptureName.c_str(), getSourceInfoCallback, this);
154159

155-
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
156-
iterate(mainloop, op);
160+
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
161+
iterate(mainloop, op);
162+
}
157163

158164
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
159165
pa.pa_threaded_mainloop_unlock(mainloop);
160166

167+
if (defaultCaptureName.empty() || defaultCaptureDescName.empty()) {
168+
return nullptr;
169+
}
170+
161171
AudioDevicePtr defaultDevice = std::make_shared<AudioDevice>(defaultCaptureDescName, defaultCaptureName);
162172
defaultDevice->directionType = AudioDeviceDirectionType::adtCapture;
163173
return defaultDevice;
@@ -191,14 +201,24 @@ namespace jni
191201
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
192202
iterate(mainloop, op);
193203

194-
op = pa.pa_context_get_sink_info_by_name(context, defaultPlaybackName.c_str(), getSinkInfoCallback, this);
204+
// Without a sink the server names no default, and an empty name is no query at all.
205+
if (defaultPlaybackName.empty()) {
206+
defaultPlaybackDescName.clear();
207+
}
208+
else {
209+
op = pa.pa_context_get_sink_info_by_name(context, defaultPlaybackName.c_str(), getSinkInfoCallback, this);
195210

196-
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
197-
iterate(mainloop, op);
211+
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
212+
iterate(mainloop, op);
213+
}
198214

199215
if (!pa.pa_threaded_mainloop_in_thread(mainloop))
200216
pa.pa_threaded_mainloop_unlock(mainloop);
201217

218+
if (defaultPlaybackName.empty() || defaultPlaybackDescName.empty()) {
219+
return nullptr;
220+
}
221+
202222
AudioDevicePtr defaultDevice = std::make_shared<AudioDevice>(defaultPlaybackDescName, defaultPlaybackName);
203223
defaultDevice->directionType = AudioDeviceDirectionType::adtRender;
204224
return defaultDevice;
@@ -226,12 +246,17 @@ namespace jni
226246

227247
auto& pa = PulseAudioLoader::instance();
228248

229-
if (last > 0) {
230-
pa.pa_threaded_mainloop_signal(engine->mainloop, 0);
249+
// A failed query, e.g. for a source removed after the server named it the default,
250+
// ends with last < 0 and no info, and nothing follows it.
251+
if (last < 0) {
252+
engine->defaultCaptureDescName.clear();
253+
}
254+
else if (last == 0 && info) {
255+
engine->defaultCaptureDescName = info->description ? info->description : "";
231256
return;
232257
}
233258

234-
engine->defaultCaptureDescName = info->description;
259+
pa.pa_threaded_mainloop_signal(engine->mainloop, 0);
235260
}
236261

237262
void PulseAudioDeviceManager::getSourceCallback(pa_context * ctx, const pa_source_info * info, int last, void * userdata)
@@ -266,13 +291,18 @@ namespace jni
266291
{
267292
PulseAudioDeviceManager * engine = reinterpret_cast<PulseAudioDeviceManager *>(userdata);
268293

269-
if (last > 0) {
270-
auto& pa = PulseAudioLoader::instance();
271-
pa.pa_threaded_mainloop_signal(engine->mainloop, 0);
294+
// A failed query, e.g. for a sink removed after the server named it the default,
295+
// ends with last < 0 and no info, and nothing follows it.
296+
if (last < 0) {
297+
engine->defaultPlaybackDescName.clear();
298+
}
299+
else if (last == 0 && info) {
300+
engine->defaultPlaybackDescName = info->description ? info->description : "";
272301
return;
273302
}
274303

275-
engine->defaultPlaybackDescName = info->description;
304+
auto& pa = PulseAudioLoader::instance();
305+
pa.pa_threaded_mainloop_signal(engine->mainloop, 0);
276306
}
277307

278308
void PulseAudioDeviceManager::getSinkCallback(pa_context * ctx, const pa_sink_info * info, int last, void * userdata)
@@ -350,8 +380,9 @@ namespace jni
350380
auto& pa = PulseAudioLoader::instance();
351381

352382
PulseAudioDeviceManager * engine = reinterpret_cast<PulseAudioDeviceManager *>(userdata);
353-
engine->defaultCaptureName = info->default_source_name;
354-
engine->defaultPlaybackName = info->default_sink_name;
383+
// A failed query has no info, and a server without sources or sinks names no default.
384+
engine->defaultCaptureName = info && info->default_source_name ? info->default_source_name : "";
385+
engine->defaultPlaybackName = info && info->default_sink_name ? info->default_sink_name : "";
355386

356387
pa.pa_threaded_mainloop_signal(engine->mainloop, 0);
357388
}

‎webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceChangeListener.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@
1919
/**
2020
* A device change listener is notified whenever a media device such as a
2121
* camera, microphone, or speaker is connected to or removed from the system.
22+
* <p>
23+
* Listeners are called on a thread of the library, not on the one the system
24+
* reports the change on, one change at a time and in the order they were
25+
* reported. A listener may query {@link MediaDevices}, which then reflects the
26+
* change. Once a listener has been removed, it gets no more changes, apart from
27+
* one it may be handling at that moment.
2228
*
2329
* @author Alex Andres
2430
*/

0 commit comments

Comments
 (0)