From 16b61d9f84eff090e5487b5d230c28164004ab56 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 13:24:55 +0100 Subject: [PATCH] fix: reject a second desktop capture start and normalize encoded rotation A capturer owns its one callback, captureFrame reports ERROR_PERMANENT without a backend and throws before start. --- docs/tools/desktop/screen-capturer.md | 4 +- docs/tools/desktop/window-capturer.md | 4 +- .../media/video/desktop/DesktopCapturer.h | 20 +++- .../src/main/cpp/src/JNI_DesktopCapturer.cpp | 27 ++--- .../media/video/desktop/DesktopCapturer.cpp | 47 ++++++-- .../media/video/codec/EncodedImage.java | 10 +- .../media/video/desktop/DesktopCapturer.java | 17 ++- .../onvoid/webrtc/VideoCodecFactoryTests.java | 16 +++ .../video/desktop/DesktopCapturerTests.java | 101 ++++++++++++++++++ 9 files changed, 200 insertions(+), 46 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturerTests.java diff --git a/docs/tools/desktop/screen-capturer.md b/docs/tools/desktop/screen-capturer.md index 5775a476c..67b9219b1 100644 --- a/docs/tools/desktop/screen-capturer.md +++ b/docs/tools/desktop/screen-capturer.md @@ -16,8 +16,8 @@ Key methods (inherited from `DesktopCapturer`): - `void selectSource(DesktopSource source)` – choose the screen to capture - `void setFocusSelectedSource(boolean focus)` – try to focus the selected source during capture - `void setMaxFrameRate(int maxFrameRate)` – cap the capture FPS -- `void start(DesktopCaptureCallback callback)` – begin capturing; frames are delivered via callback -- `void captureFrame()` – request a single frame (manual capture) +- `void start(DesktopCaptureCallback callback)` – begin capturing; frames are delivered via callback. A capturer can be started once, a second call throws `IllegalStateException` +- `void captureFrame()` – request a single frame (manual capture) after `start`; without a capture backend, as on Linux without a display, the callback gets `ERROR_PERMANENT` - `void dispose()` – release resources ## Typical usage: enumerate screens diff --git a/docs/tools/desktop/window-capturer.md b/docs/tools/desktop/window-capturer.md index a92e4a3ac..6f533b5c6 100644 --- a/docs/tools/desktop/window-capturer.md +++ b/docs/tools/desktop/window-capturer.md @@ -16,8 +16,8 @@ Key methods (inherited from `DesktopCapturer`): - `void selectSource(DesktopSource source)` – choose which window to capture - `void setFocusSelectedSource(boolean focus)` – attempt to focus/raise the selected window - `void setMaxFrameRate(int maxFrameRate)` – limit the capture frame rate -- `void start(DesktopCaptureCallback callback)` – start capture, frames via callback -- `void captureFrame()` – request a single capture +- `void start(DesktopCaptureCallback callback)` – start capture, frames via callback. A capturer can be started once, a second call throws `IllegalStateException` +- `void captureFrame()` – request a single capture after `start`; without a capture backend, as on Linux without a display, the callback gets `ERROR_PERMANENT` - `void dispose()` – release resources ## Typical usage: enumerate windows diff --git a/webrtc-jni/src/main/cpp/include/media/video/desktop/DesktopCapturer.h b/webrtc-jni/src/main/cpp/include/media/video/desktop/DesktopCapturer.h index 06a4c2af6..0d95aeec3 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/desktop/DesktopCapturer.h +++ b/webrtc-jni/src/main/cpp/include/media/video/desktop/DesktopCapturer.h @@ -25,20 +25,31 @@ #include #include +#include namespace jni { + class DesktopCaptureCallback; + class DesktopCapturer { public: explicit DesktopCapturer(bool screenCapturer); ~DesktopCapturer(); + // Starts capturing and keeps the callback until this capturer is + // destroyed. Returns false if it has been started before: WebRTC's + // capturers take a single callback. + bool Start(std::unique_ptr callback); + + // Captures a frame. Without a capture backend, the callback gets + // ERROR_PERMANENT. Returns false if there is no callback yet, which + // a capturer of WebRTC would dereference. + bool CaptureFrame(); + // webrtc::DesktopCapturer implementations. - void Start(webrtc::DesktopCapturer::Callback * callback); void SetMaxFrameRate(uint32_t max_frame_rate); void SetSharedMemoryFactory(std::unique_ptr factory); - void CaptureFrame(); void SetExcludedWindow(webrtc::WindowId window); bool GetSourceList(webrtc::DesktopCapturer::SourceList * sources); bool SelectSource(webrtc::DesktopCapturer::SourceId id); @@ -47,6 +58,11 @@ namespace jni bool IsOccluded(const webrtc::DesktopVector & pos); protected: + std::mutex startMutex; + + // Declared before the capturer, which uses it until destroyed. + std::unique_ptr captureCallback; + std::unique_ptr capturer; bool focusSelectedSource; diff --git a/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp b/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp index b250e74e0..4339efaaa 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp @@ -36,15 +36,10 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapture return; } - auto callback = GetHandle(env, caller, "callbackHandle"); - - SetHandle(env, caller, "callbackHandle", nullptr); - // A captureFrame() running on another thread, or the one whose callback - // disposes the capturer, still uses both. - jni::ReleaseHandle(env, capturer, [capturer, callback](bool) { + // disposes the capturer, still uses it. + jni::ReleaseHandle(env, capturer, [capturer](bool) { delete capturer; - delete callback; }); }); } @@ -129,15 +124,10 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapture jni::NativeLease capturer(env, caller); CHECK_HANDLE(capturer); - auto callback = new jni::DesktopCaptureCallback(env, jni::JavaGlobalRef(env, jcallback)); - - try { - SetHandle(env, caller, "callbackHandle", callback); + auto callback = std::make_unique(env, jni::JavaGlobalRef(env, jcallback)); - capturer->Start(callback); - } - catch (...) { - ThrowCxxJavaException(env); + if (!capturer->Start(std::move(callback))) { + ThrowJavaException(env, "java/lang/IllegalStateException", "Capture has been started already"); } }); } @@ -149,11 +139,8 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapture jni::NativeLease capturer(env, caller); CHECK_HANDLE(capturer); - try { - capturer->CaptureFrame(); - } - catch (...) { - ThrowCxxJavaException(env); + if (!capturer->CaptureFrame()) { + ThrowJavaException(env, "java/lang/IllegalStateException", "Capture has not been started"); } }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCapturer.cpp b/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCapturer.cpp index 9262e75f8..9b8a49369 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCapturer.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCapturer.cpp @@ -15,6 +15,7 @@ */ #include "media/video/desktop/DesktopCapturer.h" +#include "media/video/desktop/DesktopCaptureCallback.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_capture_options.h" @@ -56,7 +57,8 @@ namespace jni "session without PipeWire support, or snap confinement." : "DesktopCapturer: CreateWindowCapturer returned null. " "Possible causes: missing X11/XFIXES extension or snap confinement."); - // Leave capturer as nullptr; callers check via GetSourceList returning false. + // Leave capturer as nullptr: GetSourceList returns false, and + // CaptureFrame reports ERROR_PERMANENT. return; } @@ -68,15 +70,25 @@ namespace jni capturer.reset(); } - void DesktopCapturer::Start(webrtc::DesktopCapturer::Callback * callback) + bool DesktopCapturer::Start(std::unique_ptr callback) { - if (!capturer) return; + std::lock_guard lock(startMutex); + + if (captureCallback) { + return false; + } - capturer->Start(callback); + if (capturer) { + capturer->Start(callback.get()); - if (focusSelectedSource) { - capturer->FocusOnSelectedSource(); + if (focusSelectedSource) { + capturer->FocusOnSelectedSource(); + } } + + captureCallback = std::move(callback); + + return true; } void DesktopCapturer::SetMaxFrameRate(uint32_t max_frame_rate) @@ -91,15 +103,34 @@ namespace jni capturer->SetSharedMemoryFactory(std::move(factory)); } - void DesktopCapturer::CaptureFrame() + bool DesktopCapturer::CaptureFrame() { - if (!capturer) return; + DesktopCaptureCallback * callback = nullptr; + + { + // Not held while capturing: the result may call back into this + // capturer on the same thread. + std::lock_guard lock(startMutex); + + callback = captureCallback.get(); + } + + if (callback == nullptr) { + return false; + } + + if (!capturer) { + callback->OnCaptureResult(webrtc::DesktopCapturer::Result::ERROR_PERMANENT, nullptr); + return true; + } #if defined(WEBRTC_MAC) CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true); #endif capturer->CaptureFrame(); + + return true; } void DesktopCapturer::SetExcludedWindow(webrtc::WindowId window) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/codec/EncodedImage.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/codec/EncodedImage.java index 855d4f965..91a5aa64a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/codec/EncodedImage.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/codec/EncodedImage.java @@ -142,7 +142,7 @@ public FrameType getFrameType() { } /** - * @return The rotation of the frame in degrees, a multiple of 90. + * @return The rotation of the frame in degrees: 0, 90, 180 or 270. */ public int getRotation() { return rotation; @@ -301,7 +301,7 @@ public Builder setFrameType(FrameType frameType) { /** * @param rotation The rotation of the frame in degrees, a multiple of - * 90. + * 90. It is normalized to 0, 90, 180 or 270. * * @return This builder. */ @@ -343,8 +343,12 @@ public EncodedImage build() { throw new IllegalArgumentException("Size must not be negative"); } + // Native code takes it for a webrtc::VideoRotation, which has only + // these four values. + int normalizedRotation = ((rotation % 360) + 360) % 360; + return new EncodedImage(buffer, encodedWidth, encodedHeight, - captureTimeNs, frameType, rotation, qp); + captureTimeNs, frameType, normalizedRotation, qp); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturer.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturer.java index 55b523963..10ecbd66d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturer.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturer.java @@ -70,14 +70,6 @@ public enum Result { } - /** - * The DesktopCapturer doesn't take ownership of the callback. When the - * DesktopCapturer is disposed, the callback will be disposed using this - * handle. - */ - private long callbackHandle; - - @Override public native void dispose(); @@ -110,15 +102,22 @@ public enum Result { public native void setMaxFrameRate(int maxFrameRate); /** - * Starts the desktop capture process with the provided callback. + * Starts the desktop capture process with the provided callback. A capturer + * can be started once and keeps its callback until it is disposed. * * @param callback The callback that receives capture events and frames. + * + * @throws IllegalStateException If the capturer has been started before. */ public native void start(DesktopCaptureCallback callback); /** * Captures a single frame manually. * The capture result will be delivered via the callback provided in {@link #start}. + * Where the platform offers no capture backend, for example on Linux without + * a display, the result is {@link Result#ERROR_PERMANENT}. + * + * @throws IllegalStateException If the capturer has not been started. */ public native void captureFrame(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/VideoCodecFactoryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/VideoCodecFactoryTests.java index e42694adf..7acaa1e50 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/VideoCodecFactoryTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/VideoCodecFactoryTests.java @@ -458,6 +458,22 @@ void encodedImageBuilderValidates() { assertEquals(7, (int) image.getQp()); } + @Test + void encodedImageRotationIsNormalized() { + assertEquals(270, encodedImageRotatedBy(-90)); + assertEquals(0, encodedImageRotatedBy(360)); + assertEquals(90, encodedImageRotatedBy(450)); + assertEquals(180, encodedImageRotatedBy(180)); + } + + private static int encodedImageRotatedBy(int rotation) { + return EncodedImage.builder() + .setBuffer(ByteBuffer.allocate(1)) + .setRotation(rotation) + .build() + .getRotation(); + } + private void assertFramesReceived(PeerConnectionFactory built, String codec) throws Exception { CountDownLatch received = new CountDownLatch(10); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturerTests.java new file mode 100644 index 000000000..5fc4eecd1 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/DesktopCapturerTests.java @@ -0,0 +1,101 @@ +/* + * 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.video.desktop; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import dev.onvoid.webrtc.TestBase; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +@Execution(ExecutionMode.SAME_THREAD) +class DesktopCapturerTests extends TestBase { + + @Test + void secondStartIsRejected() { + assumeNoPortalDialog(); + + ScreenCapturer capturer = new ScreenCapturer(); + + try { + capturer.start((result, frame) -> { }); + + assertThrows(IllegalStateException.class, () -> capturer.start((result, frame) -> { })); + } + finally { + capturer.dispose(); + } + } + + @Test + void captureBeforeStartIsRejected() { + ScreenCapturer capturer = new ScreenCapturer(); + + try { + assertThrows(IllegalStateException.class, capturer::captureFrame); + } + finally { + capturer.dispose(); + } + } + + @Test + void missingBackendReportsPermanentError() { + ScreenCapturer capturer = new ScreenCapturer(); + + try { + assumeTrue(hasNoBackend(capturer), "A capture backend is available"); + + List results = new ArrayList<>(); + + capturer.start((result, frame) -> results.add(result)); + capturer.captureFrame(); + + assertEquals(List.of(DesktopCapturer.Result.ERROR_PERMANENT), results); + } + finally { + capturer.dispose(); + } + } + + /** + * Starting a capturer in a Wayland session asks the user what to share. + */ + private static void assumeNoPortalDialog() { + assumeFalse("wayland".equals(System.getenv("XDG_SESSION_TYPE")), "Wayland session"); + } + + private static boolean hasNoBackend(DesktopCapturer capturer) { + try { + capturer.getDesktopSources(); + + return false; + } + catch (Error | RuntimeException e) { + // Without a display, as on headless Linux, listing fails. + return true; + } + } +}