Skip to content

Commit 9172f5c

Browse files
authored
fix: release codec wrappers and distinguish device failures (#562)
Release all queried transceivers when codec configuration fails and close receiver and track wrappers on every exit. Reject non-finite encoding values in the builder. Distinguish an unavailable audio backend from other native device failures, preserve failed queries as errors, and stop PulseAudio mainloops without holding their lock. Update device documentation and add regression coverage.
1 parent 3ec88a7 commit 9172f5c

15 files changed

Lines changed: 437 additions & 54 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,7 @@ The new camera keeps the resolution and frame rate of the old one, as far as it
508508

509509
### Devices
510510

511-
`media.devices()` returns the cameras, microphones and speakers. The first call reads them from the system; after that, the lists are snapshots kept current in the background, so reading them is cheap on any thread. Where the system reports no device changes, as on a Linux machine without PulseAudio, they are read on each call instead. `screens()` and `windows()` ask the system on each call. A kind of device the system cannot list, such as audio devices on a machine without an audio system, comes back as an empty list; a query that fails otherwise throws a `MediaException`, so an empty list means there are no such devices.
511+
`media.devices()` returns the cameras, microphones and speakers. The first call reads them from the system; after that, the lists are snapshots kept current in the background, so reading them is cheap on any thread. Where the system reports no device changes, as on a Linux machine without PulseAudio, they are read on each call instead. `screens()` and `windows()` ask the system on each call. A query that fails, including an unavailable audio backend, throws a `MediaException`, so an empty list means there are no such devices. Its cause is an `AudioBackendUnavailableException` when the audio backend is missing or unreachable, or a `DeviceException` for other native device failures.
512512

513513
```java
514514
Devices devices = media.devices();
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Copyright 2019 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#ifndef JNI_AUDIO_BACKEND_UNAVAILABLE_EXCEPTION_H_
18+
#define JNI_AUDIO_BACKEND_UNAVAILABLE_EXCEPTION_H_
19+
20+
#include <stdexcept>
21+
22+
namespace jni {
23+
// Expected backend absence, distinct from other device initialization failures.
24+
class AudioBackendUnavailableException : public std::runtime_error {
25+
public:
26+
using std::runtime_error::runtime_error;
27+
};
28+
}
29+
30+
#endif

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
#include "JavaArrayList.h"
1919
#include "JavaContext.h"
2020
#include "JavaError.h"
21+
#include "JavaUtils.h"
22+
#include "Exception.h"
23+
#include "media/AudioBackendUnavailableException.h"
24+
#include <new>
2125
#include "media/DeviceChangeListener.h"
2226
#include "media/audio/AudioDevice.h"
2327
#include "media/audio/AudioDeviceManager.h"
@@ -40,6 +44,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_addDeviceChange
4044

4145
javaContext->addNativeRef(env, jni::JavaLocalRef<jobject>(env, jListener), listenerPtr);
4246
}
47+
catch (const jni::AudioBackendUnavailableException & e) {
48+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
49+
}
50+
catch (const std::bad_alloc &) {
51+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
52+
}
53+
catch (const jni::Exception & e) {
54+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
55+
}
4356
catch (...) {
4457
ThrowCxxJavaException(env);
4558
}
@@ -55,6 +68,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_removeDeviceCha
5568
context->getAudioDeviceManager()->detachHotplugListener(listener);
5669
context->getVideoDeviceManager()->detachHotplugListener(listener);
5770
}
71+
catch (const jni::AudioBackendUnavailableException & e) {
72+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
73+
}
74+
catch (const std::bad_alloc &) {
75+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
76+
}
77+
catch (const jni::Exception & e) {
78+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
79+
}
5880
catch (...) {
5981
ThrowCxxJavaException(env);
6082
}
@@ -74,6 +96,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAu
7496

7597
return jni::AudioDevice::toJavaAudioDevice(env, device).release();
7698
}
99+
catch (const jni::AudioBackendUnavailableException & e) {
100+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
101+
}
102+
catch (const std::bad_alloc &) {
103+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
104+
}
105+
catch (const jni::Exception & e) {
106+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
107+
}
77108
catch (...) {
78109
ThrowCxxJavaException(env);
79110
}
@@ -95,6 +126,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAu
95126

96127
return jni::AudioDevice::toJavaAudioDevice(env, device).release();
97128
}
129+
catch (const jni::AudioBackendUnavailableException & e) {
130+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
131+
}
132+
catch (const std::bad_alloc &) {
133+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
134+
}
135+
catch (const jni::Exception & e) {
136+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
137+
}
98138
catch (...) {
99139
ThrowCxxJavaException(env);
100140
}
@@ -118,6 +158,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioRend
118158

119159
return deviceList.listObject().release();
120160
}
161+
catch (const jni::AudioBackendUnavailableException & e) {
162+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
163+
}
164+
catch (const std::bad_alloc &) {
165+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
166+
}
167+
catch (const jni::Exception & e) {
168+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
169+
}
121170
catch (...) {
122171
ThrowCxxJavaException(env);
123172
}
@@ -141,6 +190,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioCapt
141190

142191
return deviceList.listObject().release();
143192
}
193+
catch (const jni::AudioBackendUnavailableException & e) {
194+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
195+
}
196+
catch (const std::bad_alloc &) {
197+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
198+
}
199+
catch (const jni::Exception & e) {
200+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
201+
}
144202
catch (...) {
145203
ThrowCxxJavaException(env);
146204
}
@@ -164,6 +222,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCapt
164222

165223
return deviceList.listObject().release();
166224
}
225+
catch (const jni::AudioBackendUnavailableException & e) {
226+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
227+
}
228+
catch (const std::bad_alloc &) {
229+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
230+
}
231+
catch (const jni::Exception & e) {
232+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
233+
}
167234
catch (...) {
168235
ThrowCxxJavaException(env);
169236
}
@@ -193,6 +260,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCapt
193260

194261
return capabilityList.listObject().release();
195262
}
263+
catch (const jni::AudioBackendUnavailableException & e) {
264+
ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what());
265+
}
266+
catch (const std::bad_alloc &) {
267+
ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed");
268+
}
269+
catch (const jni::Exception & e) {
270+
ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what());
271+
}
196272
catch (...) {
197273
ThrowCxxJavaException(env);
198274
}

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include "media/audio/linux/PulseAudioDeviceManager.h"
1818
#include "media/audio/linux/PulseAudioLoader.h"
1919
#include "Exception.h"
20+
#include "media/AudioBackendUnavailableException.h"
2021

2122
namespace jni
2223
{
@@ -26,7 +27,7 @@ namespace jni
2627
{
2728
// Try to load PulseAudio symbols dynamically
2829
if (!PulseAudioLoader::instance().load()) {
29-
throw Exception("PulseAudio: Library not found on system.");
30+
throw AudioBackendUnavailableException("PulseAudio: Library not found on system.");
3031
}
3132

3233
// Use the loader instance for function calls
@@ -48,7 +49,7 @@ namespace jni
4849
context = pa.pa_context_new(mainloopApi, "MediaDevices");
4950

5051
if (!context) {
51-
pa.pa_threaded_mainloop_free(mainloop);
52+
dispose();
5253

5354
throw Exception("PulseAudio: Could not create context");
5455
}
@@ -59,18 +60,19 @@ namespace jni
5960
pa.pa_threaded_mainloop_lock(mainloop);
6061

6162
if (pa.pa_context_connect(context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) {
62-
pa.pa_context_unref(context);
63-
pa.pa_threaded_mainloop_free(mainloop);
63+
pa.pa_threaded_mainloop_unlock(mainloop);
64+
dispose();
6465

65-
throw Exception("PulseAudio: Could not connect to the context");
66+
throw AudioBackendUnavailableException("PulseAudio: Could not connect to the context");
6667
}
6768

6869
while (true) {
6970
pa_context_state_t contextState = pa.pa_context_get_state(context);
7071

7172
if (contextState == PA_CONTEXT_FAILED || contextState == PA_CONTEXT_TERMINATED) {
73+
pa.pa_threaded_mainloop_unlock(mainloop);
7274
dispose();
73-
return;
75+
throw AudioBackendUnavailableException("PulseAudio: Context connection failed");
7476
}
7577
if (contextState == PA_CONTEXT_READY) {
7678
break;
@@ -87,6 +89,7 @@ namespace jni
8789
pa.pa_threaded_mainloop_unlock(mainloop);
8890

8991
if (!op) {
92+
dispose();
9093
throw Exception("PulseAudio: Failed to subscribe context");
9194
}
9295
pa.pa_operation_unref(op);
@@ -114,6 +117,7 @@ namespace jni
114117
context = nullptr;
115118
}
116119

120+
pa.pa_threaded_mainloop_unlock(mainloop);
117121
pa.pa_threaded_mainloop_stop(mainloop);
118122
pa.pa_threaded_mainloop_free(mainloop);
119123

‎webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -81,28 +81,34 @@ void apply() {
8181
return;
8282
}
8383

84-
for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) {
85-
try {
84+
apply(peer.connection().getTransceivers(), codecs);
85+
}
86+
87+
/** Takes ownership of every wrapper, including those not reached on failure. */
88+
static void apply(RTCRtpTransceiver[] transceivers, Map<MediaKind, List<RTCRtpCodecCapability>> codecs) {
89+
try {
90+
for (RTCRtpTransceiver transceiver : transceivers) {
8691
if (transceiver.stopped()) {
8792
continue;
8893
}
8994

90-
RTCRtpReceiver receiver = transceiver.getReceiver();
91-
MediaStreamTrack track = receiver.getTrack();
92-
MediaKind kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind())
93-
? MediaKind.AUDIO
94-
: MediaKind.VIDEO;
95-
96-
track.dispose();
97-
receiver.dispose();
95+
MediaKind kind;
96+
try (RTCRtpReceiver receiver = transceiver.getReceiver();
97+
MediaStreamTrack track = receiver.getTrack()) {
98+
kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind())
99+
? MediaKind.AUDIO
100+
: MediaKind.VIDEO;
101+
}
98102

99103
List<RTCRtpCodecCapability> preferred = codecs.get(kind);
100104

101105
if (preferred != null) {
102106
transceiver.setCodecPreferences(preferred);
103107
}
104108
}
105-
finally {
109+
}
110+
finally {
111+
for (RTCRtpTransceiver transceiver : transceivers) {
106112
transceiver.dispose();
107113
}
108114
}

‎webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,8 @@
2828
* The media devices of the system. The lists are snapshots, kept current in
2929
* the background, so reading them is cheap on any thread. Where the system
3030
* reports no device changes, as a Linux machine without PulseAudio, they are
31-
* read on each call. A kind of device the system cannot list, such as audio
32-
* devices without an audio system, comes back as an empty list. A query that
33-
* fails otherwise throws a {@link MediaException}, so that an empty list means
34-
* that there are no such devices.
31+
* read on each call. A query that fails, including an unavailable audio backend,
32+
* throws a {@link MediaException}; an empty list means there are no such devices.
3533
*/
3634
public interface Devices {
3735

‎webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java‎

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.util.function.Consumer;
2626
import java.util.function.Supplier;
2727

28+
import dev.onvoid.webrtc.media.AudioBackendUnavailableException;
2829
import dev.onvoid.webrtc.media.Device;
2930
import dev.onvoid.webrtc.media.DeviceChangeListener;
3031
import dev.onvoid.webrtc.media.MediaDevices;
@@ -45,9 +46,8 @@
4546
* reports no changes, as a Linux machine without PulseAudio, the lists are
4647
* read on each call instead.
4748
* <p>
48-
* A list the platform cannot read is empty: a machine without an audio system
49-
* has no microphones to offer. A query that fails otherwise throws a {@link
50-
* MediaException} when the list is read, and errors of the JVM pass through.
49+
* A query that fails, including an unavailable audio backend, throws a
50+
* {@link MediaException} when the list is read. Errors of the JVM pass through.
5151
*/
5252
final class DevicesImpl implements Devices {
5353

@@ -278,16 +278,6 @@ static void switchDevice(Runnable select, Runnable stop, Runnable start) {
278278
}
279279
}
280280

281-
/**
282-
* Tells whether a query failed in the platform, which the native layer
283-
* reports as a plain {@code Error} with the message of the C++ exception,
284-
* as when there is no audio system. Its subclasses are errors of the JVM,
285-
* such as an {@code OutOfMemoryError} or an {@code UnsatisfiedLinkError}.
286-
*/
287-
static boolean platformFailure(Throwable e) {
288-
return e.getClass() == Error.class;
289-
}
290-
291281
/** Called on a thread of the system, so it only posts. */
292282
private void changed() {
293283
media.executor.execute(() -> {
@@ -315,10 +305,6 @@ private static <T> Snapshot<T> read(String kind, Supplier<List<T>> query) {
315305
: new Snapshot<>(Collections.unmodifiableList(new ArrayList<>(devices)), kind, null);
316306
}
317307
catch (Throwable e) {
318-
if (platformFailure(e)) {
319-
// No device of the kind, such as without an audio system.
320-
return Snapshot.empty();
321-
}
322308
if (e instanceof Error) {
323309
throw (Error) e;
324310
}
@@ -333,7 +319,7 @@ private boolean watch() {
333319
return true;
334320
}
335321
catch (Throwable e) {
336-
if (platformFailure(e)) {
322+
if (e instanceof AudioBackendUnavailableException) {
337323
// The system reports no changes, as Linux without PulseAudio.
338324
return false;
339325
}

‎webrtc/src/main/java/dev/onvoid/webrtc/client/Encoding.java‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,13 @@ public Builder maxBitrate(int bitsPerSecond) {
9090
}
9191

9292
/**
93-
* @param framesPerSecond the highest frame rate of a video track.
93+
* @param framesPerSecond the finite, positive highest frame rate of a video track.
9494
*
9595
* @return this builder.
9696
*/
9797
public Builder maxFrameRate(double framesPerSecond) {
98-
if (framesPerSecond <= 0) {
99-
throw new IllegalArgumentException("The frame rate must be positive, got " + framesPerSecond);
98+
if (!Double.isFinite(framesPerSecond) || framesPerSecond <= 0) {
99+
throw new IllegalArgumentException("The frame rate must be finite and positive, got " + framesPerSecond);
100100
}
101101

102102
this.maxFrameRate = framesPerSecond;
@@ -105,13 +105,13 @@ public Builder maxFrameRate(double framesPerSecond) {
105105

106106
/**
107107
* @param factor how much smaller than captured a video track is sent,
108-
* 1 or more.
108+
* finite and 1 or more.
109109
*
110110
* @return this builder.
111111
*/
112112
public Builder scaleDownBy(double factor) {
113-
if (factor < 1) {
114-
throw new IllegalArgumentException("The factor must be 1 or more, got " + factor);
113+
if (!Double.isFinite(factor) || factor < 1) {
114+
throw new IllegalArgumentException("The factor must be finite and 1 or more, got " + factor);
115115
}
116116

117117
this.scaleDownBy = factor;

0 commit comments

Comments
 (0)