diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index e48944eae..3eddf1359 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -508,7 +508,7 @@ The new camera keeps the resolution and frame rate of the old one, as far as it ### Devices -`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. +`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. ```java Devices devices = media.devices(); diff --git a/webrtc-jni/src/main/cpp/include/media/AudioBackendUnavailableException.h b/webrtc-jni/src/main/cpp/include/media/AudioBackendUnavailableException.h new file mode 100644 index 000000000..61a771445 --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/media/AudioBackendUnavailableException.h @@ -0,0 +1,30 @@ +/* + * Copyright 2019 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JNI_AUDIO_BACKEND_UNAVAILABLE_EXCEPTION_H_ +#define JNI_AUDIO_BACKEND_UNAVAILABLE_EXCEPTION_H_ + +#include + +namespace jni { + // Expected backend absence, distinct from other device initialization failures. + class AudioBackendUnavailableException : public std::runtime_error { + public: + using std::runtime_error::runtime_error; + }; +} + +#endif diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp index f78aa1cb5..5557cafae 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp @@ -18,6 +18,10 @@ #include "JavaArrayList.h" #include "JavaContext.h" #include "JavaError.h" +#include "JavaUtils.h" +#include "Exception.h" +#include "media/AudioBackendUnavailableException.h" +#include #include "media/DeviceChangeListener.h" #include "media/audio/AudioDevice.h" #include "media/audio/AudioDeviceManager.h" @@ -40,6 +44,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_addDeviceChange javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), listenerPtr); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -55,6 +68,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_removeDeviceCha context->getAudioDeviceManager()->detachHotplugListener(listener); context->getVideoDeviceManager()->detachHotplugListener(listener); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -74,6 +96,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAu return jni::AudioDevice::toJavaAudioDevice(env, device).release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -95,6 +126,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAu return jni::AudioDevice::toJavaAudioDevice(env, device).release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -118,6 +158,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioRend return deviceList.listObject().release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -141,6 +190,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioCapt return deviceList.listObject().release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -164,6 +222,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCapt return deviceList.listObject().release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } @@ -193,6 +260,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCapt return capabilityList.listObject().release(); } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } catch (...) { ThrowCxxJavaException(env); } 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 bcdfd8c83..84d5df3bc 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 @@ -17,6 +17,7 @@ #include "media/audio/linux/PulseAudioDeviceManager.h" #include "media/audio/linux/PulseAudioLoader.h" #include "Exception.h" +#include "media/AudioBackendUnavailableException.h" namespace jni { @@ -26,7 +27,7 @@ namespace jni { // Try to load PulseAudio symbols dynamically if (!PulseAudioLoader::instance().load()) { - throw Exception("PulseAudio: Library not found on system."); + throw AudioBackendUnavailableException("PulseAudio: Library not found on system."); } // Use the loader instance for function calls @@ -48,7 +49,7 @@ namespace jni context = pa.pa_context_new(mainloopApi, "MediaDevices"); if (!context) { - pa.pa_threaded_mainloop_free(mainloop); + dispose(); throw Exception("PulseAudio: Could not create context"); } @@ -59,18 +60,19 @@ namespace jni pa.pa_threaded_mainloop_lock(mainloop); if (pa.pa_context_connect(context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) { - pa.pa_context_unref(context); - pa.pa_threaded_mainloop_free(mainloop); + pa.pa_threaded_mainloop_unlock(mainloop); + dispose(); - throw Exception("PulseAudio: Could not connect to the context"); + throw AudioBackendUnavailableException("PulseAudio: Could not connect to the context"); } while (true) { pa_context_state_t contextState = pa.pa_context_get_state(context); if (contextState == PA_CONTEXT_FAILED || contextState == PA_CONTEXT_TERMINATED) { + pa.pa_threaded_mainloop_unlock(mainloop); dispose(); - return; + throw AudioBackendUnavailableException("PulseAudio: Context connection failed"); } if (contextState == PA_CONTEXT_READY) { break; @@ -87,6 +89,7 @@ namespace jni pa.pa_threaded_mainloop_unlock(mainloop); if (!op) { + dispose(); throw Exception("PulseAudio: Failed to subscribe context"); } pa.pa_operation_unref(op); @@ -114,6 +117,7 @@ namespace jni context = nullptr; } + pa.pa_threaded_mainloop_unlock(mainloop); pa.pa_threaded_mainloop_stop(mainloop); pa.pa_threaded_mainloop_free(mainloop); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java index c44d47739..81b4d8563 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java @@ -81,20 +81,24 @@ void apply() { return; } - for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) { - try { + apply(peer.connection().getTransceivers(), codecs); + } + + /** Takes ownership of every wrapper, including those not reached on failure. */ + static void apply(RTCRtpTransceiver[] transceivers, Map> codecs) { + try { + for (RTCRtpTransceiver transceiver : transceivers) { if (transceiver.stopped()) { continue; } - RTCRtpReceiver receiver = transceiver.getReceiver(); - MediaStreamTrack track = receiver.getTrack(); - MediaKind kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind()) - ? MediaKind.AUDIO - : MediaKind.VIDEO; - - track.dispose(); - receiver.dispose(); + MediaKind kind; + try (RTCRtpReceiver receiver = transceiver.getReceiver(); + MediaStreamTrack track = receiver.getTrack()) { + kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind()) + ? MediaKind.AUDIO + : MediaKind.VIDEO; + } List preferred = codecs.get(kind); @@ -102,7 +106,9 @@ void apply() { transceiver.setCodecPreferences(preferred); } } - finally { + } + finally { + for (RTCRtpTransceiver transceiver : transceivers) { transceiver.dispose(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java index 9aaf29551..9af63fb18 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java @@ -28,10 +28,8 @@ * The media devices of the system. 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 a Linux machine without PulseAudio, they are - * read on each call. A kind of device the system cannot list, such as audio - * devices without an audio system, comes back as an empty list. A query that - * fails otherwise throws a {@link MediaException}, so that an empty list means - * that there are no such devices. + * read on each call. A query that fails, including an unavailable audio backend, + * throws a {@link MediaException}; an empty list means there are no such devices. */ public interface Devices { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java index 16c682c61..cd5547fcc 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java @@ -25,6 +25,7 @@ import java.util.function.Consumer; import java.util.function.Supplier; +import dev.onvoid.webrtc.media.AudioBackendUnavailableException; import dev.onvoid.webrtc.media.Device; import dev.onvoid.webrtc.media.DeviceChangeListener; import dev.onvoid.webrtc.media.MediaDevices; @@ -45,9 +46,8 @@ * reports no changes, as a Linux machine without PulseAudio, the lists are * read on each call instead. *

- * A list the platform cannot read is empty: a machine without an audio system - * has no microphones to offer. A query that fails otherwise throws a {@link - * MediaException} when the list is read, and errors of the JVM pass through. + * A query that fails, including an unavailable audio backend, throws a + * {@link MediaException} when the list is read. Errors of the JVM pass through. */ final class DevicesImpl implements Devices { @@ -278,16 +278,6 @@ static void switchDevice(Runnable select, Runnable stop, Runnable start) { } } - /** - * Tells whether a query failed in the platform, which the native layer - * reports as a plain {@code Error} with the message of the C++ exception, - * as when there is no audio system. Its subclasses are errors of the JVM, - * such as an {@code OutOfMemoryError} or an {@code UnsatisfiedLinkError}. - */ - static boolean platformFailure(Throwable e) { - return e.getClass() == Error.class; - } - /** Called on a thread of the system, so it only posts. */ private void changed() { media.executor.execute(() -> { @@ -315,10 +305,6 @@ private static Snapshot read(String kind, Supplier> query) { : new Snapshot<>(Collections.unmodifiableList(new ArrayList<>(devices)), kind, null); } catch (Throwable e) { - if (platformFailure(e)) { - // No device of the kind, such as without an audio system. - return Snapshot.empty(); - } if (e instanceof Error) { throw (Error) e; } @@ -333,7 +319,7 @@ private boolean watch() { return true; } catch (Throwable e) { - if (platformFailure(e)) { + if (e instanceof AudioBackendUnavailableException) { // The system reports no changes, as Linux without PulseAudio. return false; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Encoding.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Encoding.java index bbb5278fa..135fb63cd 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Encoding.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Encoding.java @@ -90,13 +90,13 @@ public Builder maxBitrate(int bitsPerSecond) { } /** - * @param framesPerSecond the highest frame rate of a video track. + * @param framesPerSecond the finite, positive highest frame rate of a video track. * * @return this builder. */ public Builder maxFrameRate(double framesPerSecond) { - if (framesPerSecond <= 0) { - throw new IllegalArgumentException("The frame rate must be positive, got " + framesPerSecond); + if (!Double.isFinite(framesPerSecond) || framesPerSecond <= 0) { + throw new IllegalArgumentException("The frame rate must be finite and positive, got " + framesPerSecond); } this.maxFrameRate = framesPerSecond; @@ -105,13 +105,13 @@ public Builder maxFrameRate(double framesPerSecond) { /** * @param factor how much smaller than captured a video track is sent, - * 1 or more. + * finite and 1 or more. * * @return this builder. */ public Builder scaleDownBy(double factor) { - if (factor < 1) { - throw new IllegalArgumentException("The factor must be 1 or more, got " + factor); + if (!Double.isFinite(factor) || factor < 1) { + throw new IllegalArgumentException("The factor must be finite and 1 or more, got " + factor); } this.scaleDownBy = factor; diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/AudioBackendUnavailableException.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/AudioBackendUnavailableException.java new file mode 100644 index 000000000..0d03e8d54 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/AudioBackendUnavailableException.java @@ -0,0 +1,30 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media; + +/** The platform audio backend is not installed or cannot be reached. */ +public class AudioBackendUnavailableException extends DeviceException { + + private static final long serialVersionUID = 1L; + + /** + * @param message the reason the operation failed. + */ + public AudioBackendUnavailableException(String message) { + super(message); + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceException.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceException.java new file mode 100644 index 000000000..fcb592742 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/DeviceException.java @@ -0,0 +1,30 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media; + +/** A native device query or device watcher failed. */ +public class DeviceException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * @param message the reason the operation failed. + */ + public DeviceException(String message) { + super(message); + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaDevices.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaDevices.java index ce36177cc..7dff3b1e5 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaDevices.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaDevices.java @@ -23,6 +23,13 @@ import java.util.List; +/** + * Queries the platform media devices and watches for device changes. + *

+ * Native device failures throw {@link DeviceException}. A missing or unreachable + * audio backend throws {@link AudioBackendUnavailableException}; it is not an + * empty device list. + */ public class MediaDevices { static { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/CodecPreferencesTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/CodecPreferencesTests.java new file mode 100644 index 000000000..f95e2a432 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/CodecPreferencesTests.java @@ -0,0 +1,69 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import dev.onvoid.webrtc.PeerConnectionObserver; +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCIceCandidate; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCRtpCodecCapability; +import dev.onvoid.webrtc.RTCRtpTransceiver; +import dev.onvoid.webrtc.RTCRtpTransceiverInit; +import dev.onvoid.webrtc.media.MediaType; + +import org.junit.jupiter.api.Test; + +class CodecPreferencesTests extends ClientTestBase { + + @Test + void releasesUnvisitedTransceivers() { + RTCPeerConnection connection = rtc.factory.createPeerConnection(new RTCConfiguration(), + new PeerConnectionObserver() { + @Override + public void onIceCandidate(RTCIceCandidate candidate) { } + }); + try { + for (int i = 0; i < 3; i++) { + connection.addTransceiver(MediaType.AUDIO, new RTCRtpTransceiverInit()).dispose(); + } + RTCRtpTransceiver[] transceivers = connection.getTransceivers(); + try { + // Video codecs on an audio transceiver fail in setCodecPreferences. + List video = rtc.factory.getRtpReceiverCapabilities(MediaType.VIDEO).getCodecs(); + Map> codecs = Collections.singletonMap(MediaKind.AUDIO, video); + assertThrows(Error.class, () -> CodecPreferences.apply(transceivers, codecs)); + for (RTCRtpTransceiver transceiver : transceivers) { + assertThrows(IllegalStateException.class, transceiver::getMid); + } + } + finally { + for (RTCRtpTransceiver transceiver : transceivers) { + transceiver.dispose(); + } + } + } + finally { + connection.close(); + } + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java index 3a14fe9a2..fac6eee17 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java @@ -32,6 +32,8 @@ import java.util.stream.Collectors; import dev.onvoid.webrtc.media.DeviceChangeListener; +import dev.onvoid.webrtc.media.AudioBackendUnavailableException; +import dev.onvoid.webrtc.media.DeviceException; import dev.onvoid.webrtc.media.audio.AudioDevice; import dev.onvoid.webrtc.media.video.VideoDevice; @@ -81,20 +83,21 @@ void changeDuringFirstRead() throws Exception { } @Test - void platformFailureIsEmpty() { + void unavailableBackendThrows() { // What the native layer throws without an audio system. TestSource source = new TestSource(); - source.microphoneFailure = new Error("PulseAudio: Library not found on system."); + source.microphoneFailure = new AudioBackendUnavailableException("PulseAudio: Library not found on system."); DevicesImpl devices = devices(source); - assertEquals(Collections.emptyList(), devices.microphones()); + assertSame(source.microphoneFailure, + assertThrows(MediaException.class, devices::microphones).getCause()); } @Test void failedQueryThrows() { TestSource source = new TestSource(); - source.cameraFailure = new IllegalStateException("enumeration failed"); + source.cameraFailure = new DeviceException("enumeration failed"); DevicesImpl devices = devices(source); @@ -108,11 +111,19 @@ void failedQueryThrows() { @Test void jvmErrorPassesThrough() { - // The first read fails, after the listener was registered. TestSource source = new TestSource(); source.cameraFailure = new OutOfMemoryError("test"); + assertSame(source.cameraFailure, assertThrows(OutOfMemoryError.class, () -> devices(source))); + assertTrue(source.listeners.isEmpty()); + } + + @Test + void plainErrorPassesThrough() { + // The first read fails, after the listener was registered. + TestSource source = new TestSource(); + source.cameraFailure = new Error("unexpected native failure"); - OutOfMemoryError e = assertThrows(OutOfMemoryError.class, () -> devices(source)); + Error e = assertThrows(Error.class, () -> devices(source)); assertSame(source.cameraFailure, e); assertTrue(source.listeners.isEmpty()); @@ -121,7 +132,7 @@ void jvmErrorPassesThrough() { @Test void jvmErrorPassesThroughUnwatched() { TestSource source = new TestSource(); - source.watchFailure = new Error("PulseAudio: Could not connect to the context"); + source.watchFailure = new AudioBackendUnavailableException("PulseAudio: Could not connect to the context"); source.cameraFailure = new UnsatisfiedLinkError("getVideoCaptureDevices"); DevicesImpl devices = devices(source); @@ -133,7 +144,7 @@ void jvmErrorPassesThroughUnwatched() { void unwatchedReadsEachCall() { // The system reports no changes, as Linux without PulseAudio. TestSource source = new TestSource(); - source.watchFailure = new Error("PulseAudio: Library not found on system."); + source.watchFailure = new AudioBackendUnavailableException("PulseAudio: Library not found on system."); DevicesImpl devices = devices(source); source.cameras.add(camera("Plugged")); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/EncodingTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/EncodingTests.java new file mode 100644 index 000000000..1809d4c11 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/EncodingTests.java @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class EncodingTests { + + @Test + void rejectsInvalidFrameRates() { + for (double value : new double[] { Double.NaN, Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, 0, -1 }) { + assertThrows(IllegalArgumentException.class, () -> Encoding.builder().maxFrameRate(value)); + } + } + + @Test + void rejectsInvalidScales() { + for (double value : new double[] { Double.NaN, Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, 0, 0.5 }) { + assertThrows(IllegalArgumentException.class, () -> Encoding.builder().scaleDownBy(value)); + } + } + + @Test + void acceptsFiniteBoundaries() { + Encoding encoding = Encoding.builder().maxFrameRate(Double.MIN_VALUE).scaleDownBy(1).build(); + assertEquals(Double.MIN_VALUE, encoding.maxFrameRate.doubleValue()); + assertEquals(1, encoding.scaleDownBy.doubleValue()); + encoding = Encoding.builder().maxFrameRate(Double.MAX_VALUE).scaleDownBy(Double.MAX_VALUE).build(); + assertEquals(Double.MAX_VALUE, encoding.maxFrameRate.doubleValue()); + assertEquals(Double.MAX_VALUE, encoding.scaleDownBy.doubleValue()); + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java new file mode 100644 index 000000000..3310a8efc --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/DeviceBackendTests.java @@ -0,0 +1,85 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +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 org.junit.jupiter.api.Test; + +class DeviceBackendTests { + + @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()); + // 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"); + 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"); + reader.join(); + assertEquals(0, process.exitValue(), new String(output.toByteArray(), StandardCharsets.UTF_8)); + } + finally { + process.destroyForcibly(); + } + } + + public static class UnavailableBackend { + + public static void main(String[] args) { + expectUnavailable(MediaDevices::getAudioCaptureDevices); + expectUnavailable(MediaDevices::getAudioRenderDevices); + expectUnavailable(MediaDevices::getDefaultAudioCaptureDevice); + expectUnavailable(MediaDevices::getDefaultAudioRenderDevice); + expectUnavailable(() -> MediaDevices.addDeviceChangeListener(new DeviceChangeListener() { + @Override + public void deviceConnected(Device device) { } + @Override + public void deviceDisconnected(Device device) { } + })); + } + + private static void expectUnavailable(Runnable operation) { + try { + operation.run(); + } + catch (AudioBackendUnavailableException expected) { + return; + } + throw new AssertionError("Expected an unavailable audio backend"); + } + } +}