From bff927d71f07105c575317ae941e2ae9d6086ce0 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 14:22:21 +0100 Subject: [PATCH 1/2] fix: bound the desktop capture frame rate and size, make its stop signal atomic The frame rate must be 1 to 1000, as 65536 reached the capture thread as 0. One scale factor now holds both size limits, and isCapturing is atomic. --- docs/guide/video/desktop-capture.md | 5 +- .../main/cpp/include/JNI_VideoDesktopSource.h | 4 +- .../media/video/VideoTrackDesktopSource.h | 4 +- .../main/cpp/src/JNI_VideoDesktopSource.cpp | 2 +- .../media/video/VideoTrackDesktopSource.cpp | 25 ++++--- .../onvoid/webrtc/client/ScreenOptions.java | 12 ++-- .../media/video/VideoDesktopSource.java | 32 ++++++++- .../dev/onvoid/webrtc/client/MediaTests.java | 12 ++++ .../media/video/VideoDesktopSourceTests.java | 66 +++++++++++++++++++ 9 files changed, 137 insertions(+), 25 deletions(-) diff --git a/docs/guide/video/desktop-capture.md b/docs/guide/video/desktop-capture.md index 067060b3f..3c127c7f0 100644 --- a/docs/guide/video/desktop-capture.md +++ b/docs/guide/video/desktop-capture.md @@ -53,10 +53,11 @@ import dev.onvoid.webrtc.media.video.VideoDesktopSource; VideoDesktopSource videoSource = new VideoDesktopSource(); // Configure the desktop video source -// Set frame rate (e.g., 30 fps) +// Set frame rate (e.g., 30 fps), from 1 to VideoDesktopSource.MAX_FRAME_RATE videoSource.setFrameRate(30); -// Set maximum frame size (e.g., 1920x1080) +// Set maximum frame size (e.g., 1920x1080). Frames are scaled down to fit +// both limits and keep their aspect ratio. videoSource.setMaxFrameSize(1920, 1080); // Select a specific source to capture diff --git a/webrtc-jni/src/main/cpp/include/JNI_VideoDesktopSource.h b/webrtc-jni/src/main/cpp/include/JNI_VideoDesktopSource.h index 9195b4b21..dee525209 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_VideoDesktopSource.h +++ b/webrtc-jni/src/main/cpp/include/JNI_VideoDesktopSource.h @@ -17,10 +17,10 @@ extern "C" { /* * Class: dev_onvoid_webrtc_media_video_VideoDesktopSource - * Method: setFrameRate + * Method: setFrameRateInternal * Signature: (I)V */ - JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRate + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRateInternal (JNIEnv*, jobject, jint); /* diff --git a/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h b/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h index 282d5adff..300bed405 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h +++ b/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h @@ -24,6 +24,8 @@ #include "media/video/VideoProcessorHost.h" +#include + namespace jni { class VideoTrackDesktopSource : public webrtc::AdaptedVideoTrackSource, public webrtc::DesktopCapturer::Callback, public VideoProcessorHost @@ -59,7 +61,7 @@ namespace jni private: uint16_t frameRate; - bool isCapturing; + std::atomic isCapturing; bool focusSelectedSource; webrtc::DesktopSize maxFrameSize; diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp index 85e765acc..4e07daba3 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp @@ -37,7 +37,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_set }); } -JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRate +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRateInternal (JNIEnv * env, jobject caller, jint frameRate) { jni::CallFromJava(env, [&]() { diff --git a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp index 996d8a517..17865293b 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp @@ -31,6 +31,9 @@ #include "modules/desktop_capture/desktop_and_cursor_composer.h" #include "modules/desktop_capture/mouse_cursor_monitor.h" +#include +#include + namespace jni { VideoTrackDesktopSource::VideoTrackDesktopSource() : @@ -207,20 +210,14 @@ namespace jni if (conversionResult >= 0) { if (!maxFrameSize.is_empty()) { - // Adapt frame size to contraints. - int max_width = maxFrameSize.width(); - int max_height = maxFrameSize.height(); - - if (adapted_width > max_width) { - double scale = max_width / (double)adapted_width; - adapted_width = max_width; - adapted_height = (int)(adapted_height * scale); - } - else if (adapted_height > max_height) { - double scale = max_height / (double)adapted_height; - adapted_width = (int)(adapted_width * scale); - adapted_height = max_height; - } + // One factor for both limits: the frame fits both and keeps its + // aspect ratio. A very narrow limit must not round a side to 0. + const double scale = std::min({ 1.0, + maxFrameSize.width() / static_cast(adapted_width), + maxFrameSize.height() / static_cast(adapted_height) }); + + adapted_width = std::max(1, static_cast(std::lround(adapted_width * scale))); + adapted_height = std::max(1, static_cast(std::lround(adapted_height * scale))); } if (adapted_width != width || adapted_height != height) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/ScreenOptions.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/ScreenOptions.java index 3dd765674..389b5ec80 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/ScreenOptions.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/ScreenOptions.java @@ -18,6 +18,7 @@ import static java.util.Objects.requireNonNull; +import dev.onvoid.webrtc.media.video.VideoDesktopSource; import dev.onvoid.webrtc.media.video.desktop.DesktopSource; /** @@ -87,13 +88,15 @@ private Builder(DesktopSource source, boolean window) { } /** - * @param frameRate the frames per second to capture. + * @param frameRate the frames per second to capture, 1 to {@value + * VideoDesktopSource#MAX_FRAME_RATE}. * * @return this builder. */ public Builder frameRate(int frameRate) { - if (frameRate <= 0) { - throw new IllegalArgumentException("The frame rate must be positive, got " + frameRate); + if (frameRate < 1 || frameRate > VideoDesktopSource.MAX_FRAME_RATE) { + throw new IllegalArgumentException("The frame rate must be between 1 and " + + VideoDesktopSource.MAX_FRAME_RATE + ", got " + frameRate); } this.frameRate = frameRate; @@ -101,7 +104,8 @@ public Builder frameRate(int frameRate) { } /** - * Scales captured frames down to fit, keeping their aspect ratio. + * Scales captured frames down to fit both limits, keeping their aspect + * ratio. * * @param width the largest width, in pixels. * @param height the largest height, in pixels. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoDesktopSource.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoDesktopSource.java index 528e5af50..b08006dbc 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoDesktopSource.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoDesktopSource.java @@ -18,6 +18,13 @@ public class VideoDesktopSource extends VideoTrackSource { + /** + * The highest frame rate. The capture thread paces itself in whole + * milliseconds, so anything higher would make it spin without a pause. + */ + public static final int MAX_FRAME_RATE = 1000; + + public VideoDesktopSource() { super(); @@ -26,8 +33,29 @@ public VideoDesktopSource() { public native void setSourceId(long sourceId, boolean isWindow); - public native void setFrameRate(int frameRate); + /** + * Sets the frames per second to capture, read when the capture starts. + * + * @param frameRate The frame rate, 1 to {@value #MAX_FRAME_RATE}. + * + * @throws IllegalArgumentException If the frame rate is out of range. + */ + public void setFrameRate(int frameRate) { + if (frameRate < 1 || frameRate > MAX_FRAME_RATE) { + throw new IllegalArgumentException( + "The frame rate must be between 1 and " + MAX_FRAME_RATE + ", got " + frameRate); + } + setFrameRateInternal(frameRate); + } + + /** + * Scales captured frames down to fit both limits, keeping their aspect + * ratio. + * + * @param width The largest width, in pixels. + * @param height The largest height, in pixels. + */ public native void setMaxFrameSize(int width, int height); public native void start(); @@ -41,6 +69,8 @@ public void dispose() { private native void initialize(); + private native void setFrameRateInternal(int frameRate); + private native void disposeInternal(); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java index 319e39b92..a91a84d8c 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java @@ -48,6 +48,7 @@ import dev.onvoid.webrtc.media.video.CustomVideoSource; import dev.onvoid.webrtc.media.video.NativeI420Buffer; import dev.onvoid.webrtc.media.video.VideoFrame; +import dev.onvoid.webrtc.media.video.desktop.DesktopSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -303,6 +304,17 @@ void fullQueueDropsOldest() throws Exception { } } + @Test + void screenFrameRateOutOfRangeRejected() { + ScreenOptions.Builder options = ScreenOptions.screen(new DesktopSource("screen", 0)); + + assertThrows(IllegalArgumentException.class, () -> options.frameRate(0)); + assertThrows(IllegalArgumentException.class, () -> options.frameRate(1001)); + assertThrows(IllegalArgumentException.class, () -> options.frameRate(65536)); + + assertEquals(1000, options.frameRate(1000).build().frameRate); + } + @Test void queueLimitBelowChunkRejected() { CustomAudio voice = rtc.media().customAudio("voice"); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java index 86b66c9af..4ca3cc495 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java @@ -16,6 +16,9 @@ package dev.onvoid.webrtc.media.video; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -33,6 +36,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -43,6 +48,67 @@ class VideoDesktopSourceTests extends TestBase { private static final String OS = System.getProperty("os.name").toLowerCase(Locale.ROOT); + @Test + void frameRateOutOfRangeRejected() { + VideoDesktopSource source = new VideoDesktopSource(); + + try { + // 65536 would reach the capture thread as 0, -1 as 65535. + for (int frameRate : new int[] { Integer.MIN_VALUE, -1, 0, 1001, 65536, Integer.MAX_VALUE }) { + assertThrows(IllegalArgumentException.class, () -> source.setFrameRate(frameRate)); + } + + assertDoesNotThrow(() -> source.setFrameRate(1)); + assertDoesNotThrow(() -> source.setFrameRate(VideoDesktopSource.MAX_FRAME_RATE)); + } + finally { + source.dispose(); + } + } + + @Test + void maxFrameSizeHoldsBothLimits() throws Exception { + // The portal would wait for the user to pick a source. + assumeFalse("wayland".equalsIgnoreCase(System.getenv("XDG_SESSION_TYPE")), "Wayland"); + assumeFalse(GraphicsEnvironment.isHeadless(), "No display"); + + DesktopSource screen = firstScreen(); + + VideoDesktopSource source = new VideoDesktopSource(); + source.setSourceId(screen.id, false); + // On any common screen, fitting the width leaves the height too large. + source.setMaxFrameSize(320, 60); + + VideoTrack track = factory.createVideoTrack("screen", source); + + CompletableFuture size = new CompletableFuture<>(); + + VideoTrackSink sink = frame -> { + size.complete(new int[] { frame.buffer.getWidth(), frame.buffer.getHeight() }); + frame.release(); + }; + + int[] first; + + try { + track.addSink(sink); + source.start(); + + first = size.completeOnTimeout(null, 10, TimeUnit.SECONDS).join(); + } + finally { + source.stop(); + track.removeSink(sink); + track.dispose(); + source.dispose(); + } + + assumeTrue(first != null, "The screen delivered no frames"); + + assertEquals(60, first[1]); + assertTrue(first[0] <= 320, "Width " + first[0] + " exceeds the limit"); + } + @Test void screenFramesFollowScreen() throws Exception { assumeTrue(OS.contains("mac"), "covers the macOS screen capturers"); From 2da833b36156870425110579d33d99aa690e2d57 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 14:32:42 +0100 Subject: [PATCH 2/2] fix: deliver processed frames without holding the sink monitor Delivering under the monitor could deadlock with a detach that holds the monitor of the source. The native lease now keeps the source alive, detach no longer waits for a running delivery, and a deferred release leaves the capture thread, which the destructor joins. --- docs/guide/video/camera-capture.md | 2 +- .../main/cpp/src/JNI_VideoDesktopSource.cpp | 21 +++- .../main/cpp/src/JNI_VideoDeviceSource.cpp | 21 +++- .../media/video/ProcessedFrameSink.java | 21 ++-- .../webrtc/media/video/VideoProcessor.java | 3 +- .../webrtc/media/video/VideoTrackSource.java | 14 ++- .../media/video/VideoProcessorTests.java | 112 ++++++++++++++++++ 7 files changed, 172 insertions(+), 22 deletions(-) diff --git a/docs/guide/video/camera-capture.md b/docs/guide/video/camera-capture.md index aeff3f2e2..088959683 100644 --- a/docs/guide/video/camera-capture.md +++ b/docs/guide/video/camera-capture.md @@ -362,7 +362,7 @@ Rules that keep this correct: - The pixels of a captured frame may be shared with the source. Write changes into a new buffer, as above, instead of into the captured one. - `onFrameCaptured()` runs on the capture thread and holds up capturing while it runs. An exception it throws goes to that thread's uncaught exception handler, and the frame is dropped. -`setVideoProcessor(null)` removes the processor. A `CustomVideoSource` does not take a processor: change the frames before pushing them. +`setVideoProcessor(null)` removes the processor. Neither that nor `dispose()` waits for a frame the processor is delivering at that moment, which may still reach the tracks; what it delivers later is dropped. A `CustomVideoSource` does not take a processor: change the frames before pushing them. ## Best Practices diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp index 4e07daba3..e7249cb33 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp @@ -26,6 +26,8 @@ #include "rtc_base/logging.h" #include "rtc_base/ref_counted_object.h" +#include + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setSourceId (JNIEnv * env, jobject caller, jlong sourceId, jboolean isWindow) { @@ -106,11 +108,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_dis videoSource->SetVideoProcessor(env, nullptr); SetHandle(env, caller, "processorHostHandle", nullptr); - jni::ReleaseHandle(env, videoSource, [videoSource](bool) { - webrtc::RefCountReleaseStatus status = videoSource->Release(); + jni::ReleaseHandle(env, videoSource, [videoSource](bool deferred) { + auto release = [videoSource]() { + webrtc::RefCountReleaseStatus status = videoSource->Release(); + + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }; - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + // The last call may be a processed frame on the capture thread, + // which the destructor of the source stops and cannot join itself. + if (deferred) { + std::thread(release).detach(); + } + else { + release(); } }); }); diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp index 5e9074f94..f1545bd7a 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp @@ -31,6 +31,8 @@ #include "JavaString.h" #include "JavaUtils.h" +#include + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_setVideoCaptureDevice (JNIEnv * env, jobject caller, jobject device) { @@ -148,11 +150,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_disp videoSource->SetVideoProcessor(env, nullptr); SetHandle(env, caller, "processorHostHandle", nullptr); - jni::ReleaseHandle(env, videoSource, [videoSource](bool) { - webrtc::RefCountReleaseStatus status = videoSource->Release(); + jni::ReleaseHandle(env, videoSource, [videoSource](bool deferred) { + auto release = [videoSource]() { + webrtc::RefCountReleaseStatus status = videoSource->Release(); + + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }; - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + // The last call may be a processed frame on the capture thread, + // which the destructor of the source stops and cannot join itself. + if (deferred) { + std::thread(release).detach(); + } + else { + release(); } }); }); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/ProcessedFrameSink.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/ProcessedFrameSink.java index cde3fb7d8..7220b85b7 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/ProcessedFrameSink.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/ProcessedFrameSink.java @@ -20,10 +20,17 @@ * The sink a {@link VideoProcessor} delivers processed frames to. It passes * them on to its source until it is detached, when the processor is replaced * or the source is disposed, and drops them afterwards. + *

+ * A delivery holds no lock: a callback further down may call into the source + * while another thread, holding the monitor of the source, detaches this sink. + * The native call keeps the native source alive by itself and drops the frame + * of a disposed source. So {@link #detach()} does not wait for a delivery that + * is running, which may still reach the tracks, and every delivery that starts + * after it returned is dropped. */ final class ProcessedFrameSink implements VideoTrackSink { - private VideoTrackSource source; + private volatile VideoTrackSource source; ProcessedFrameSink(VideoTrackSource source) { @@ -36,16 +43,14 @@ public void onVideoFrame(VideoFrame frame) { throw new NullPointerException("VideoFrame must not be null"); } - // Holding the lock while delivering keeps the source from being - // disposed during the native call. - synchronized (this) { - if (source != null) { - source.deliverProcessedFrame(frame); - } + VideoTrackSource target = source; + + if (target != null) { + target.deliverProcessedFrame(frame); } } - synchronized void detach() { + void detach() { source = null; } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoProcessor.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoProcessor.java index b1a3b351c..9a05947c7 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoProcessor.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoProcessor.java @@ -48,7 +48,8 @@ public interface VideoProcessor { * Gives the processor the sink to deliver processed frames to. Called by * {@link VideoTrackSource#setVideoProcessor} before the first frame * arrives. The sink does nothing once the processor is replaced or the - * source is disposed. + * source is disposed. A frame being delivered at that moment may still + * reach the tracks, as neither waits for the sink. * * @param sink The sink that passes frames on to the source's tracks. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrackSource.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrackSource.java index 64af0185c..304dfb659 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrackSource.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrackSource.java @@ -42,6 +42,10 @@ protected VideoTrackSource() { * they reach its tracks, replacing any processor set before. {@code null} * removes the processor, so frames go to the tracks unchanged. *

+ * This does not wait for a frame the previous processor is delivering at + * that moment, which may still reach the tracks. What it delivers later + * is dropped. + *

* Camera and desktop sources support a processor. A {@link * CustomVideoSource} does not: process the frames before pushing them. * @@ -66,7 +70,8 @@ public synchronized void setVideoProcessor(VideoProcessor processor) { setVideoProcessorNative(processor); - // Frames the previous processor delivers from now on are dropped. + // Frames the previous processor delivers from now on are dropped, a + // delivery already running may finish. if (processorSink != null) { processorSink.detach(); } @@ -76,9 +81,10 @@ public synchronized void setVideoProcessor(VideoProcessor processor) { /** * Detaches the sink of the current processor, so that it drops frames - * delivered while and after this source is disposed. Called by the - * sources that support a processor before they dispose of their native - * source, which removes the processor. + * delivered from now on. A delivery already running either finishes + * before the native source is disposed or is dropped by the native call. + * Called by the sources that support a processor before they dispose of + * their native source, which removes the processor. */ synchronized void detachVideoProcessor() { if (processorSink != null) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoProcessorTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoProcessorTests.java index 5b80e0453..98365e13a 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoProcessorTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoProcessorTests.java @@ -17,6 +17,7 @@ package dev.onvoid.webrtc.media.video; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -98,6 +99,93 @@ void staleSinkDropsFrames() { } } + @Test + void detachDuringDeliveryDoesNotDeadlock() throws Exception { + VideoDesktopSource source = new VideoDesktopSource(); + TestProcessor processor = new TestProcessor(); + + source.setVideoProcessor(processor); + + VideoTrack track = factory.createVideoTrack("desktop", source); + VideoFrame frame = new VideoFrame(NativeI420Buffer.allocate(64, 48), 0); + + CountDownLatch delivering = new CountDownLatch(1); + CountDownLatch monitorHeld = new CountDownLatch(1); + + // A callback of the delivery that needs the monitor of the source, + // while the thread holding it detaches the sink of the delivery. + VideoTrackSink trackSink = received -> { + received.release(); + delivering.countDown(); + await(monitorHeld); + source.setVideoProcessor(null); + }; + + track.addSink(trackSink); + + Thread deliverer = startThread(() -> processor.sink.onVideoFrame(frame)); + + await(delivering); + + Thread detacher = startThread(() -> { + synchronized (source) { + monitorHeld.countDown(); + source.detachVideoProcessor(); + } + }); + + assertEnds(detacher); + assertEnds(deliverer); + + track.removeSink(trackSink); + track.dispose(); + source.dispose(); + frame.release(); + } + + @Test + void disposeDoesNotWaitForDelivery() throws Exception { + VideoDesktopSource source = new VideoDesktopSource(); + TestProcessor processor = new TestProcessor(); + + source.setVideoProcessor(processor); + + VideoTrack track = factory.createVideoTrack("desktop", source); + VideoFrame frame = new VideoFrame(NativeI420Buffer.allocate(64, 48), 0); + + AtomicInteger received = new AtomicInteger(); + CountDownLatch delivering = new CountDownLatch(1); + CountDownLatch proceed = new CountDownLatch(1); + + VideoTrackSink trackSink = delivered -> { + delivered.release(); + received.incrementAndGet(); + delivering.countDown(); + await(proceed); + }; + + track.addSink(trackSink); + + Thread deliverer = startThread(() -> processor.sink.onVideoFrame(frame)); + + await(delivering); + + // The running delivery keeps the native source, and finishes. + assertEnds(startThread(source::dispose)); + assertTrue(deliverer.isAlive(), "The delivery ended before it was let go"); + + proceed.countDown(); + assertEnds(deliverer); + + // A delivery that starts now is dropped. + processor.sink.onVideoFrame(frame); + assertEquals(1, received.get()); + + track.removeSink(trackSink); + track.dispose(); + frame.release(); + } + @Test void acceptsCustomBufferLayouts() { VideoDesktopSource source = new VideoDesktopSource(); @@ -279,6 +367,30 @@ public void onFrameCaptured(VideoFrame frame) { } } + private static Thread startThread(Runnable task) { + Thread thread = new Thread(task); + + thread.setDaemon(true); + thread.start(); + + return thread; + } + + private static void assertEnds(Thread thread) throws InterruptedException { + thread.join(TimeUnit.SECONDS.toMillis(10)); + + assertFalse(thread.isAlive(), "The thread is stuck"); + } + + private static void await(CountDownLatch latch) { + try { + assertTrue(latch.await(10, TimeUnit.SECONDS)); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } + private static DesktopSource firstScreen() { ScreenCapturer capturer = new ScreenCapturer();