From 522bfbd8d8389c3f3ec45484fb3fc10dbfbcee72 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 13:36:37 +0100 Subject: [PATCH] fix: keep device changes during startup and surface failed device queries Register the device listener before the first snapshot and serialize the reads, so a change during startup is no longer lost. Only the native layer's plain Error counts as "no such devices"; other query failures throw a MediaException, and JVM errors pass through. switchDevice keeps the refusal and restart failures as suppressed instead of letting one hide another. --- docs/guide/client-api.md | 2 +- .../dev/onvoid/webrtc/client/Devices.java | 10 +- .../dev/onvoid/webrtc/client/DevicesImpl.java | 262 +++++++++++++++--- .../webrtc/client/DeviceSwitchTests.java | 61 ++++ .../onvoid/webrtc/client/DevicesTests.java | 256 +++++++++++++++++ 5 files changed, 552 insertions(+), 39 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 7f9ca0e35..4ca7d5157 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -468,7 +468,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. `screens()` and `windows()` ask the system on each call. +`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. `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. ```java Devices devices = media.devices(); 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 214d5aaad..9aaf29551 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Devices.java @@ -29,22 +29,30 @@ * 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. + * 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. */ public interface Devices { /** * @return the cameras. + * + * @throws MediaException if the cameras could not be read. */ List cameras(); /** * @return the microphones. + * + * @throws MediaException if the microphones could not be read. */ List microphones(); /** * @return the speakers. + * + * @throws MediaException if the speakers could not be read. */ List speakers(); 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 0a697bbb0..16c682c61 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/DevicesImpl.java @@ -38,17 +38,73 @@ /** * The {@link Devices} of a runtime. The device lists are read once, then again - * on the media executor whenever the system reports a change. Where the system + * on the media executor whenever the system reports a change. The listener is + * registered before the first read, so that a change during that read queues + * another one rather than being missed, and the reads run one after another, + * so that the last one to start is the one that stays. Where the system * reports no changes, as a Linux machine without PulseAudio, the lists are - * read on each call instead. A list that cannot be read is empty: a machine - * without an audio system has no microphones to offer. + * 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. */ final class DevicesImpl implements Devices { + /** + * Where the devices, and the changes to them, come from. The runtime uses + * the system's, tests a source they control. + */ + interface Source { + + /** The devices of the system, through {@link MediaDevices}. */ + Source SYSTEM = new Source() { + + @Override + public List cameras() { + return MediaDevices.getVideoCaptureDevices(); + } + + @Override + public List microphones() { + return MediaDevices.getAudioCaptureDevices(); + } + + @Override + public List speakers() { + return MediaDevices.getAudioRenderDevices(); + } + + @Override + public void watch(DeviceChangeListener listener) { + MediaDevices.addDeviceChangeListener(listener); + } + + @Override + public void unwatch(DeviceChangeListener listener) { + MediaDevices.removeDeviceChangeListener(listener); + } + }; + + List cameras(); + + List microphones(); + + List speakers(); + + void watch(DeviceChangeListener listener); + + void unwatch(DeviceChangeListener listener); + + } + + private final LocalMediaImpl media; private final AudioDeviceModuleBase audioModule; + private final Source source; + private final Handlers handlers; private final DeviceChangeListener listener; @@ -56,20 +112,24 @@ final class DevicesImpl implements Devices { /** True while the system reports changes, which keep the snapshots current. */ private final boolean watching; - private volatile List cameras = Collections.emptyList(); + // Written in refresh(), under this. - private volatile List microphones = Collections.emptyList(); + private volatile Snapshot cameras = Snapshot.empty(); - private volatile List speakers = Collections.emptyList(); + private volatile Snapshot microphones = Snapshot.empty(); + + private volatile Snapshot speakers = Snapshot.empty(); DevicesImpl(LocalMediaImpl media, AudioDeviceModuleBase audioModule) { + this(media, audioModule, Source.SYSTEM); + } + + DevicesImpl(LocalMediaImpl media, AudioDeviceModuleBase audioModule, Source source) { this.media = media; this.audioModule = audioModule; + this.source = source; this.handlers = new Handlers<>(media.rtc::reportError); - - refresh(); - this.listener = new DeviceChangeListener() { @Override @@ -83,22 +143,35 @@ public void deviceDisconnected(Device device) { } }; - this.watching = watch(listener); + // Listening first: a change from here on queues a read behind this + // one, which then reflects it. + this.watching = watch(); + + if (watching) { + try { + refresh(); + } + catch (Throwable e) { + // An error of the JVM. No one would remove the listener. + unwatch(e); + throw e; + } + } } @Override public List cameras() { - return watching ? cameras : read(MediaDevices::getVideoCaptureDevices); + return (watching ? cameras : read("cameras", source::cameras)).get(); } @Override public List microphones() { - return watching ? microphones : read(MediaDevices::getAudioCaptureDevices); + return (watching ? microphones : read("microphones", source::microphones)).get(); } @Override public List speakers() { - return watching ? speakers : read(MediaDevices::getAudioRenderDevices); + return (watching ? speakers : read("speakers", source::speakers)).get(); } @Override @@ -155,19 +228,11 @@ public Subscription onChange(Consumer handler) { void dispose() { if (watching) { - MediaDevices.removeDeviceChangeListener(listener); + source.unwatch(listener); } handlers.clear(); } - /** Called on a thread of the system, so it only posts. */ - private void changed() { - media.executor.execute(() -> { - refresh(); - media.events.execute(() -> handlers.accept(this)); - }); - } - /** * Selects a device. Most platforms switch only while the module is stopped, * so a refused switch is tried again with the module stopped, and the @@ -176,57 +241,121 @@ private void changed() { *

* A device that is no longer there fails at once. Stopping the module * would not bring it back. + *

+ * Of what fails after the refusal, the stop or the second selection is + * thrown, else the restart. The other failures, the refusal among them, + * are suppressed in it. */ static void switchDevice(Runnable select, Runnable stop, Runnable start) { try { select.run(); + return; } catch (IllegalArgumentException e) { throw e; } - catch (Throwable e) { - stop.run(); + catch (Throwable refused) { + Throwable failure = null; try { + stop.run(); select.run(); } - finally { + catch (Throwable e) { + failure = e; + } + + try { start.run(); } + catch (Throwable e) { + failure = suppress(failure, e); + } + + if (failure != null) { + throw DevicesImpl.sneakyThrow(suppress(failure, refused)); + } } } - private void refresh() { - cameras = read(MediaDevices::getVideoCaptureDevices); - microphones = read(MediaDevices::getAudioCaptureDevices); - speakers = read(MediaDevices::getAudioRenderDevices); + /** + * 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; } - private List read(Supplier> query) { + /** Called on a thread of the system, so it only posts. */ + private void changed() { + media.executor.execute(() -> { + refresh(); + media.events.execute(() -> handlers.accept(this)); + }); + } + + /** + * Reads all lists. One read waits for another, so that an older read + * never overwrites one the listener queued after it. + */ + private synchronized void refresh() { + cameras = read("cameras", source::cameras); + microphones = read("microphones", source::microphones); + speakers = read("speakers", source::speakers); + } + + private static Snapshot read(String kind, Supplier> query) { try { List devices = query.get(); return devices == null - ? Collections.emptyList() - : Collections.unmodifiableList(new ArrayList<>(devices)); + ? Snapshot.empty() + : new Snapshot<>(Collections.unmodifiableList(new ArrayList<>(devices)), kind, null); } catch (Throwable e) { - // No device of the kind, such as without an audio system. - return Collections.emptyList(); + if (platformFailure(e)) { + // No device of the kind, such as without an audio system. + return Snapshot.empty(); + } + if (e instanceof Error) { + throw (Error) e; + } + + return new Snapshot<>(Collections.emptyList(), kind, e); } } - private static boolean watch(DeviceChangeListener listener) { + private boolean watch() { try { - MediaDevices.addDeviceChangeListener(listener); + source.watch(listener); return true; } catch (Throwable e) { - // The system reports no changes, as Linux without PulseAudio. + if (platformFailure(e)) { + // The system reports no changes, as Linux without PulseAudio. + return false; + } + if (e instanceof Error) { + throw (Error) e; + } + + media.rtc.reportError(new MediaException("Watching the devices failed, so they are read on each call: " + + e.getMessage(), e)); return false; } } + private void unwatch(Throwable failure) { + try { + source.unwatch(listener); + } + catch (Throwable e) { + suppress(failure, e); + } + } + private static List desktopSources(DesktopCapturer capturer) { try { List sources = capturer.getDesktopSources(); @@ -243,6 +372,30 @@ private static List desktopSources(DesktopCapturer capturer) { } } + /** + * @return the failure with the other one suppressed in it, or the other + * one if there is no failure yet. + */ + private static Throwable suppress(Throwable failure, Throwable other) { + if (failure == null) { + return other; + } + if (other != failure) { + failure.addSuppressed(other); + } + + return failure; + } + + /** + * Throws a throwable as it is, also a checked one that a native method + * threw without declaring it. + */ + @SuppressWarnings("unchecked") + private static E sneakyThrow(Throwable e) throws E { + throw (E) e; + } + /** * Runs a switch, which uses the audio module, on the media executor. It * is registered like the creation of a track, so that a runtime that @@ -283,4 +436,39 @@ private CompletableFuture onMediaExecutor(Supplier action) { return media.toPublic(result); } + + /** + * A list as it was read, or the failure of its query. The failure is + * thrown anew on each call, so that callers share no exception. + */ + private static final class Snapshot { + + private static final Snapshot EMPTY = new Snapshot<>(Collections.emptyList(), null, null); + + private final List devices; + + private final String kind; + + private final Throwable failure; + + + Snapshot(List devices, String kind, Throwable failure) { + this.devices = devices; + this.kind = kind; + this.failure = failure; + } + + @SuppressWarnings("unchecked") + static Snapshot empty() { + return (Snapshot) EMPTY; + } + + List get() { + if (failure != null) { + throw new MediaException("Reading the " + kind + " failed: " + failure.getMessage(), failure); + } + + return devices; + } + } } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/DeviceSwitchTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/DeviceSwitchTests.java index 708d1dae6..d72f2b325 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/DeviceSwitchTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/DeviceSwitchTests.java @@ -16,7 +16,9 @@ package dev.onvoid.webrtc.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; @@ -68,6 +70,51 @@ void deviceLostBeforeRetryRestarts() { assertEquals(Arrays.asList("select", "stop", "select", "start"), steps); } + @Test + void retryAndRestartFail() { + // The second selection fails, and so does the restart. Thrown is why + // the switch failed; the restart and the refusal are kept in it. + Error refused = new Error("busy"); + Error failed = new Error("still busy"); + Error restart = new Error("restart failed"); + + Error e = assertThrows(Error.class, () -> DevicesImpl.switchDevice( + select(refused, failed), stop(), start(restart))); + + assertSame(failed, e); + assertArrayEquals(new Throwable[] { restart, refused }, e.getSuppressed()); + assertEquals(Arrays.asList("select", "stop", "select", "start"), steps); + } + + @Test + void restartFailureKeepsRefusal() { + Error refused = new Error("busy"); + IllegalStateException restart = new IllegalStateException("restart failed"); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> DevicesImpl.switchDevice( + select(refused, null), stop(), start(restart))); + + assertSame(restart, e); + assertArrayEquals(new Throwable[] { refused }, e.getSuppressed()); + } + + @Test + void failedStopStillRestarts() { + // Not stopped, so not selected again, but started as best it can. + Error refused = new Error("busy"); + IllegalStateException stopped = new IllegalStateException("stop failed"); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> DevicesImpl.switchDevice( + select(refused, null), () -> { + steps.add("stop"); + throw stopped; + }, start())); + + assertSame(stopped, e); + assertArrayEquals(new Throwable[] { refused }, e.getSuppressed()); + assertEquals(Arrays.asList("select", "stop", "start"), steps); + } + /** * Selects by throwing the given errors, one per attempt, and succeeding * once they run out or the next one is null. @@ -98,4 +145,18 @@ private Runnable stop() { private Runnable start() { return () -> steps.add("start"); } + + private Runnable start(RuntimeException failure) { + return () -> { + steps.add("start"); + throw failure; + }; + } + + private Runnable start(Error failure) { + return () -> { + steps.add("start"); + throw failure; + }; + } } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java new file mode 100644 index 000000000..3a14fe9a2 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/DevicesTests.java @@ -0,0 +1,256 @@ +/* + * 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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; + +import dev.onvoid.webrtc.media.DeviceChangeListener; +import dev.onvoid.webrtc.media.audio.AudioDevice; +import dev.onvoid.webrtc.media.video.VideoDevice; + +import org.junit.jupiter.api.Test; + +/** + * Drives {@link DevicesImpl} with a source of devices the test controls: when + * devices change, and how a query fails. + */ +class DevicesTests extends ClientTestBase { + + @Test + void changeDuringFirstRead() throws Exception { + // A camera is plugged in after the system answered the first read, but + // before that read returned. The change queues a read behind it. + ManualExecutor control = new ManualExecutor(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .controlPool(control) + .build(); + TestSource source = new TestSource(); + source.cameras.add(camera("Built-in")); + source.duringCameraRead = () -> source.connect(camera("Plugged")); + + try { + DevicesImpl devices = new DevicesImpl((LocalMediaImpl) runtime.media(), null, source); + CompletableFuture> notified = new CompletableFuture<>(); + devices.onChange(changed -> notified.complete(names(changed.cameras()))); + + // The snapshot predates the change. + assertEquals(Arrays.asList("Built-in"), names(devices.cameras())); + + control.runAll(); + + assertEquals(Arrays.asList("Built-in", "Plugged"), names(devices.cameras())); + assertEquals(Arrays.asList("Built-in", "Plugged"), await(notified)); + + devices.dispose(); + assertTrue(source.listeners.isEmpty()); + } + finally { + CompletableFuture closed = runtime.closeAsync(); + control.runUntil(closed::isDone, TIMEOUT_SECONDS); + await(closed); + } + } + + @Test + void platformFailureIsEmpty() { + // What the native layer throws without an audio system. + TestSource source = new TestSource(); + source.microphoneFailure = new Error("PulseAudio: Library not found on system."); + + DevicesImpl devices = devices(source); + + assertEquals(Collections.emptyList(), devices.microphones()); + } + + @Test + void failedQueryThrows() { + TestSource source = new TestSource(); + source.cameraFailure = new IllegalStateException("enumeration failed"); + + DevicesImpl devices = devices(source); + + MediaException first = assertThrows(MediaException.class, devices::cameras); + MediaException second = assertThrows(MediaException.class, devices::cameras); + + assertSame(source.cameraFailure, first.getCause()); + assertTrue(first.getMessage().contains("enumeration failed"), first::getMessage); + assertNotSame(first, second); + } + + @Test + void jvmErrorPassesThrough() { + // The first read fails, after the listener was registered. + TestSource source = new TestSource(); + source.cameraFailure = new OutOfMemoryError("test"); + + OutOfMemoryError e = assertThrows(OutOfMemoryError.class, () -> devices(source)); + + assertSame(source.cameraFailure, e); + assertTrue(source.listeners.isEmpty()); + } + + @Test + void jvmErrorPassesThroughUnwatched() { + TestSource source = new TestSource(); + source.watchFailure = new Error("PulseAudio: Could not connect to the context"); + source.cameraFailure = new UnsatisfiedLinkError("getVideoCaptureDevices"); + + DevicesImpl devices = devices(source); + + assertSame(source.cameraFailure, assertThrows(UnsatisfiedLinkError.class, devices::cameras)); + } + + @Test + 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."); + + DevicesImpl devices = devices(source); + source.cameras.add(camera("Plugged")); + + assertEquals(Arrays.asList("Plugged"), names(devices.cameras())); + assertEquals(1, source.cameraReads); + } + + @Test + void failedWatchReported() { + TestSource source = new TestSource(); + source.watchFailure = new IllegalStateException("no listener slot"); + + DevicesImpl devices = devices(source); + + assertEquals(1, errors.size(), () -> "Errors: " + errors); + Throwable reported = errors.remove(0); + assertInstanceOf(MediaException.class, reported); + assertSame(source.watchFailure, reported.getCause()); + + // Read on each call instead. + source.cameras.add(camera("Plugged")); + assertEquals(Arrays.asList("Plugged"), names(devices.cameras())); + } + + @Test + void jvmErrorInWatch() { + TestSource source = new TestSource(); + source.watchFailure = new NoClassDefFoundError("dev/onvoid/webrtc/media/MediaDevices"); + + assertSame(source.watchFailure, assertThrows(NoClassDefFoundError.class, () -> devices(source))); + } + + private DevicesImpl devices(TestSource source) { + return new DevicesImpl((LocalMediaImpl) rtc.media(), null, source); + } + + private static List names(List devices) { + return devices.stream().map(VideoDevice::getName).collect(Collectors.toList()); + } + + private static VideoDevice camera(String name) { + return new VideoDevice(name, name.toLowerCase().replace(' ', '-')) { }; + } + + /** + * Throws what a test sets, as a native method may: also a checked + * exception, or an error. + */ + @SuppressWarnings("unchecked") + private static void raise(Throwable failure) throws E { + if (failure != null) { + throw (E) failure; + } + } + + + private static final class TestSource implements DevicesImpl.Source { + + final List cameras = new CopyOnWriteArrayList<>(); + + final List listeners = new CopyOnWriteArrayList<>(); + + Throwable cameraFailure; + + Throwable microphoneFailure; + + Throwable watchFailure; + + /** Runs once, after the cameras were read and before they are returned. */ + Runnable duringCameraRead; + + int cameraReads; + + + @Override + public List cameras() { + cameraReads++; + DevicesTests.raise(cameraFailure); + + List answer = new ArrayList<>(cameras); + Runnable during = duringCameraRead; + + duringCameraRead = null; + + if (during != null) { + during.run(); + } + + return answer; + } + + @Override + public List microphones() { + DevicesTests.raise(microphoneFailure); + return Collections.emptyList(); + } + + @Override + public List speakers() { + return Collections.emptyList(); + } + + @Override + public void watch(DeviceChangeListener listener) { + DevicesTests.raise(watchFailure); + listeners.add(listener); + } + + @Override + public void unwatch(DeviceChangeListener listener) { + listeners.remove(listener); + } + + void connect(VideoDevice camera) { + cameras.add(camera); + listeners.forEach(listener -> listener.deviceConnected(camera)); + } + } +}