From 1ceeb4520c123d9bd11e7ab655a9c5b1b4add555 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 23:55:16 +0100 Subject: [PATCH 1/2] fix: release VideoCapture natively, keep its sink and report start errors dispose() now deletes the capture through a virtual destructor, which stops capture and detaches the sink. The capture owns its sink and only lends it to WebRTC, so it is freed and survives a stop/start cycle. Errors are thrown as values; start() without a device throws IllegalStateException. --- docs/tools/video/video-capturer.md | 5 +- .../cpp/include/media/video/VideoCapture.h | 4 +- .../include/media/video/VideoCaptureBase.h | 10 +- .../media/video/macos/VideoCaptureMac.h | 12 +- .../src/main/cpp/src/JNI_VideoCapture.cpp | 16 ++- .../main/cpp/src/media/video/VideoCapture.cpp | 51 ++++++--- .../cpp/src/media/video/VideoCaptureBase.cpp | 5 + .../src/media/video/macos/VideoCaptureMac.cpp | 79 ++++++++++--- .../webrtc/media/video/VideoCapture.java | 9 +- .../webrtc/media/video/VideoCaptureTests.java | 104 ++++++++++++++++++ 10 files changed, 253 insertions(+), 42 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoCaptureTests.java diff --git a/docs/tools/video/video-capturer.md b/docs/tools/video/video-capturer.md index 77f8d8dad..5c721af24 100644 --- a/docs/tools/video/video-capturer.md +++ b/docs/tools/video/video-capturer.md @@ -91,7 +91,10 @@ If you need pixel format conversion, see `VideoBufferConverter`. ## Error handling and lifecycle - Constructor: Initializes native resources; failures may surface as runtime exceptions from native code. -- `IllegalStateException`: Thrown if methods are invoked after disposal or when prerequisites are missing. +- `IllegalStateException`: Thrown by `start()` if no device was selected with `setVideoCaptureDevice`. +- `NullPointerException`: Thrown if methods are invoked after disposal. +- Other native failures (e.g. the selected device is not available) surface as an `Error` carrying the native message. +- Restart: after `stop()`, `start()` can be called again; the sink set earlier stays registered. - Idempotency: `start()` and `stop()` are intended to be safe to call multiple times (implementation‑dependent no‑op if already in that state). - Always call `dispose()` in a `finally` block to avoid leaking native resources. diff --git a/webrtc-jni/src/main/cpp/include/media/video/VideoCapture.h b/webrtc-jni/src/main/cpp/include/media/video/VideoCapture.h index 66929aad1..fea9e40d6 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/VideoCapture.h +++ b/webrtc-jni/src/main/cpp/include/media/video/VideoCapture.h @@ -30,7 +30,9 @@ namespace jni VideoCapture(); ~VideoCapture(); - void start() override; + void setVideoSink(std::unique_ptr> sink) override; + + void start() override; void stop() override; void destroy() override; diff --git a/webrtc-jni/src/main/cpp/include/media/video/VideoCaptureBase.h b/webrtc-jni/src/main/cpp/include/media/video/VideoCaptureBase.h index ae171b004..02c7f0fcc 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/VideoCaptureBase.h +++ b/webrtc-jni/src/main/cpp/include/media/video/VideoCaptureBase.h @@ -28,11 +28,17 @@ namespace jni { public: VideoCaptureBase(); - ~VideoCaptureBase(); + // Virtual, since the capture is owned and deleted through this base. + virtual ~VideoCaptureBase(); void setDevice(const avdev::DevicePtr & device); + bool hasDevice() const; void setVideoCaptureCapability(const webrtc::VideoCaptureCapability & capability); - void setVideoSink(std::unique_ptr> sink); + + // Takes ownership of the sink. The capture only lends it to the + // platform capturer, so implementations override this to detach the + // previous sink from a running capture before it is destroyed. + virtual void setVideoSink(std::unique_ptr> sink); virtual void start() = 0; virtual void stop() = 0; diff --git a/webrtc-jni/src/main/cpp/include/media/video/macos/VideoCaptureMac.h b/webrtc-jni/src/main/cpp/include/media/video/macos/VideoCaptureMac.h index 0cce911cb..faa94284d 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/macos/VideoCaptureMac.h +++ b/webrtc-jni/src/main/cpp/include/media/video/macos/VideoCaptureMac.h @@ -19,6 +19,7 @@ #include "media/video/VideoCaptureBase.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/timestamp_aligner.h" #include "sdk/objc/base/RTCVideoCapturer.h" @@ -39,15 +40,20 @@ namespace jni VideoCaptureMac(); ~VideoCaptureMac(); - void start() override; + void setVideoSink(std::unique_ptr> sink) override; + + void start() override; void stop() override; void destroy() override; void OnCapturedFrame(RTC_OBJC_TYPE(RTCVideoFrame) * frame); private: - webrtc::TimestampAligner timestamp_aligner; - RTCCameraVideoCapturer * cameraVideoCapturer; + webrtc::TimestampAligner timestamp_aligner; + // Frames arrive on the capturer's queue, the sink is replaced on the caller's thread. + webrtc::Mutex sinkMutex; + VideoCaptureCallback * callback; + RTCCameraVideoCapturer * cameraVideoCapturer; }; } diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp index 55c44f2db..4d7e3f343 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp @@ -82,7 +82,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoS jni::VideoCaptureBase * videoSource = GetHandle(env, caller); CHECK_HANDLE(videoSource); - videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink))); + try { + videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink))); + } + catch (...) { + ThrowCxxJavaException(env); + } } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start @@ -91,6 +96,11 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start jni::VideoCaptureBase * videoSource = GetHandle(env, caller); CHECK_HANDLE(videoSource); + if (!videoSource->hasDevice()) { + ThrowJavaException(env, "java/lang/IllegalStateException", "No video capture device set"); + return; + } + try { videoSource->start(); } @@ -121,7 +131,9 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_dispose SetHandle(env, caller, nullptr); - videoSource = nullptr; + // The destructor stops a running capture and detaches the sink before + // both are destroyed. + delete videoSource; } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_initialize diff --git a/webrtc-jni/src/main/cpp/src/media/video/VideoCapture.cpp b/webrtc-jni/src/main/cpp/src/media/video/VideoCapture.cpp index 851209ea2..19c7e8978 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/VideoCapture.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/VideoCapture.cpp @@ -28,26 +28,48 @@ namespace jni } VideoCapture::~VideoCapture() - { - destroy(); - } + { + destroy(); + } + + void VideoCapture::setVideoSink(std::unique_ptr> newSink) + { + if (captureModule) { + // Deregistering takes the lock the module delivers frames under, so + // no callback into the old sink is running once this returns. + captureModule->DeRegisterCaptureDataCallback(); + } + + sink = std::move(newSink); + + if (captureModule && sink) { + captureModule->RegisterCaptureDataCallback(sink.get()); + } + } void VideoCapture::start() { if (!device) { - throw new Exception("Video device must be set"); + throw Exception("Video device must be set"); } + if (captureModule && captureModule->CaptureStarted()) { + return; + } + + // Release a module whose capture is no longer running. + destroy(); + std::unique_ptr info(webrtc::VideoCaptureFactory::CreateDeviceInfo()); if (!info) { - throw new Exception("Create video DeviceInfo failed"); + throw Exception("Create video DeviceInfo failed"); } uint32_t num = info->NumberOfDevices(); if (num < 1) { - throw new Exception("No video capture devices available"); + throw Exception("No video capture devices available"); } std::string devUid; @@ -71,27 +93,26 @@ namespace jni } if (devUid.empty()) { - throw new Exception("Device %s not found", device->getName().c_str()); + throw Exception("Device %s not found", device->getName().c_str()); } captureModule = webrtc::VideoCaptureFactory::Create(devUid.c_str()); if (!captureModule) { - throw new Exception("Create VideoCaptureModule for UID %s failed", devUid.c_str()); + throw Exception("Create VideoCaptureModule for UID %s failed", devUid.c_str()); } - captureModule->RegisterCaptureDataCallback(std::move(sink).release()); + // The module only borrows the sink, which stays owned by this capture. + if (sink) { + captureModule->RegisterCaptureDataCallback(sink.get()); + } capability.videoType = webrtc::VideoType::kI420; - if (captureModule->StartCapture(capability) != 0) { + if (captureModule->StartCapture(capability) != 0 || !captureModule->CaptureStarted()) { destroy(); - throw new Exception("Start video capture for UID %s failed", devUid.c_str()); - } - - if (!captureModule || !captureModule->CaptureStarted()) { - throw new Exception("Start video capture failed"); + throw Exception("Start video capture for UID %s failed", devUid.c_str()); } } diff --git a/webrtc-jni/src/main/cpp/src/media/video/VideoCaptureBase.cpp b/webrtc-jni/src/main/cpp/src/media/video/VideoCaptureBase.cpp index 57d32a1b5..6f5201ef9 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/VideoCaptureBase.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/VideoCaptureBase.cpp @@ -34,6 +34,11 @@ namespace jni this->device = device; } + bool VideoCaptureBase::hasDevice() const + { + return device != nullptr; + } + void VideoCaptureBase::setVideoCaptureCapability(const webrtc::VideoCaptureCapability & capability) { this->capability = capability; diff --git a/webrtc-jni/src/main/cpp/src/media/video/macos/VideoCaptureMac.cpp b/webrtc-jni/src/main/cpp/src/media/video/macos/VideoCaptureMac.cpp index 8811bd9a4..399cb4fb7 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/macos/VideoCaptureMac.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/macos/VideoCaptureMac.cpp @@ -32,7 +32,13 @@ - (void)capturer:(RTC_OBJC_TYPE(RTCVideoCapturer) *)capturer didCaptureVideoFrame:(RTC_OBJC_TYPE(RTCVideoFrame) *)frame { - _videoCapturer->OnCapturedFrame(frame); + // Stopping the capturer is asynchronous, so frames may still arrive after + // the capture detached itself (and may already be deleted). + @synchronized (self) { + if (_videoCapturer) { + _videoCapturer->OnCapturedFrame(frame); + } + } } @end @@ -41,19 +47,39 @@ namespace jni { VideoCaptureMac::VideoCaptureMac() : VideoCaptureBase(), + callback(nullptr), cameraVideoCapturer(nullptr) { } VideoCaptureMac::~VideoCaptureMac() - { - destroy(); - } + { + destroy(); + } + + void VideoCaptureMac::setVideoSink(std::unique_ptr> newSink) + { + std::unique_ptr> oldSink; + + { + webrtc::MutexLock lock(&sinkMutex); + + oldSink = std::move(sink); + sink = std::move(newSink); + } + + // Destroyed outside the lock; no frame is delivered to it any more. + oldSink.reset(); + } void VideoCaptureMac::start() { if (!device) { - throw new Exception("Video device must be set"); + throw Exception("Video device must be set"); + } + + if (cameraVideoCapturer) { + return; } AVCaptureDevice * captureDevice = nullptr; @@ -77,14 +103,22 @@ namespace jni } if (!captureDevice) { - throw new Exception("No video capture devices available"); + throw Exception("No video capture devices available"); } - VideoCaptureCallback * callback = [[VideoCaptureCallback alloc] init]; + callback = [[VideoCaptureCallback alloc] init]; callback.videoCapturer = this; cameraVideoCapturer = [[RTCCameraVideoCapturer alloc] initWithDelegate:callback]; + if (!cameraVideoCapturer) { + std::string deviceName = captureDevice.localizedName.UTF8String; + + destroy(); + + throw Exception("Create video capturer for device %s failed", deviceName.c_str()); + } + AVCaptureDeviceFormat * selectedFormat = nullptr; int currentDiff = INT_MAX; int targetWidth = capability.width; @@ -108,11 +142,6 @@ namespace jni selectedFormat = captureDevice.activeFormat; } - if (!cameraVideoCapturer) { - std::string deviceName = captureDevice.localizedName.UTF8String; - throw new Exception("Create VideoCaptureModule for UID %s failed", deviceName.c_str()); - } - void (^CaptureCompletionHandler)(NSError * _Nullable error) = ^(NSError * _Nullable error) { if (error) { RTCLogError(@"Failed to start capture: %@", error.localizedDescription); @@ -135,15 +164,31 @@ namespace jni void VideoCaptureMac::destroy() { - if (!cameraVideoCapturer) { - return; - } + if (cameraVideoCapturer) { + [cameraVideoCapturer stopCapture]; + } + + if (callback) { + // Waits for a frame being delivered; none reaches this capture afterwards. + @synchronized (callback) { + callback.videoCapturer = nullptr; + } + } - [cameraVideoCapturer stopCapture]; - cameraVideoCapturer = nullptr; +#if !__has_feature(objc_arc) + // The capturer keeps itself alive until its asynchronous stop has run, + // and holds its delegate only weakly. + [cameraVideoCapturer release]; + [callback release]; +#endif + + cameraVideoCapturer = nullptr; + callback = nullptr; } void VideoCaptureMac::OnCapturedFrame(RTC_OBJC_TYPE(RTCVideoFrame) * frame) { + webrtc::MutexLock lock(&sinkMutex); + if (!sink) { return; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoCapture.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoCapture.java index 2552063ec..c373ebb9b 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoCapture.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoCapture.java @@ -97,8 +97,15 @@ public VideoCapture() { * Idempotency: * Calling start() while already started should be a no-op (implementation-dependent). * + *

+ * May be called again after {@link #stop()}; the sink set before stays + * registered. + * * @throws NullPointerException if the instance is disposed. - * @throws IllegalStateException if prerequisites (device/capability) are missing. + * @throws IllegalStateException if no device was set with + * {@link #setVideoCaptureDevice(VideoDevice)}. + * @throws Error if the native capture cannot be started, e.g. because the + * device is not available; the message describes the cause. */ public native void start(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoCaptureTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoCaptureTests.java new file mode 100644 index 000000000..69021eae6 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoCaptureTests.java @@ -0,0 +1,104 @@ +/* + * 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; + +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 java.lang.ref.WeakReference; +import java.util.List; + +import dev.onvoid.webrtc.TestBase; + +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 VideoCaptureTests extends TestBase { + + @Test + void startWithoutDevice() { + VideoCapture capture = new VideoCapture(); + + try { + IllegalStateException e = assertThrows(IllegalStateException.class, capture::start); + + assertEquals("No video capture device set", e.getMessage()); + } + finally { + capture.dispose(); + } + } + + @Test + void startReportsNativeError() { + VideoCapture capture = new VideoCapture(); + + try { + capture.setVideoCaptureDevice(new VideoDevice("webrtc-java missing camera", "missing")); + + // Depending on the machine there is no camera at all or not this one; + // either way the native message arrives instead of "Unhandled Exception". + Error e = assertThrows(Error.class, capture::start); + + assertTrue(List.of("No video capture devices available", + "Device webrtc-java missing camera not found").contains(e.getMessage()), + e.getMessage()); + } + finally { + capture.dispose(); + } + } + + @Test + void disposeReleasesSink() { + VideoCapture capture = new VideoCapture(); + WeakReference sinkRef = setSink(capture); + + capture.dispose(); + + // Only the native sink's global reference could keep the sink alive. + for (int i = 0; i < 50 && sinkRef.get() != null; i++) { + System.gc(); + } + + assertTrue(sinkRef.get() == null, "Sink still referenced after dispose"); + } + + @Test + void disposeTwice() { + VideoCapture capture = new VideoCapture(); + capture.dispose(); + + assertThrows(NullPointerException.class, capture::dispose); + } + + private static WeakReference setSink(VideoCapture capture) { + // Not a non-capturing lambda, which the JVM would keep alive itself. + VideoTrackSink sink = new VideoTrackSink() { + @Override + public void onVideoFrame(VideoFrame frame) { + } + }; + + capture.setVideoSink(sink); + + return new WeakReference<>(sink); + } +} From 56f973b8de7fb421cb77fcb44fc0a83f54526c43 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Mon, 2 Nov 2026 00:17:15 +0100 Subject: [PATCH 2/2] fix: throw VideoDeviceSource start errors by value Thrown as pointers, they reached Java as "Unhandled Exception" and leaked. --- .../media/video/VideoTrackDeviceSource.cpp | 12 ++--- .../video/macos/VideoTrackDeviceSourceMac.cpp | 2 +- .../media/video/VideoDeviceSourceTests.java | 52 +++++++++++++++++++ 3 files changed, 59 insertions(+), 7 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDeviceSourceTests.java diff --git a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDeviceSource.cpp b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDeviceSource.cpp index 4ca66a3e6..0cea29d05 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDeviceSource.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDeviceSource.cpp @@ -39,13 +39,13 @@ namespace jni std::unique_ptr info(webrtc::VideoCaptureFactory::CreateDeviceInfo()); if (!info) { - throw new Exception("Create video DeviceInfo failed"); + throw Exception("Create video DeviceInfo failed"); } uint32_t num = info->NumberOfDevices(); if (num < 1) { - throw new Exception("No video capture devices available"); + throw Exception("No video capture devices available"); } if (device) { @@ -70,19 +70,19 @@ namespace jni } if (devUid.empty()) { - throw new Exception("Device %s not found", device->getName().c_str()); + throw Exception("Device %s not found", device->getName().c_str()); } captureModule = webrtc::VideoCaptureFactory::Create(devUid.c_str()); if (!captureModule) { - throw new Exception("Create VideoCaptureModule for UID %s failed", devUid.c_str()); + throw Exception("Create VideoCaptureModule for UID %s failed", devUid.c_str()); } if (!startCapture()) { destroy(); - throw new Exception("Start video capture for UID %s failed", devUid.c_str()); + throw Exception("Start video capture for UID %s failed", devUid.c_str()); } } @@ -118,7 +118,7 @@ namespace jni } if (!captureModule || !captureModule->CaptureStarted()) { - throw new Exception("Start video capture failed"); + throw Exception("Start video capture failed"); } } diff --git a/webrtc-jni/src/main/cpp/src/media/video/macos/VideoTrackDeviceSourceMac.cpp b/webrtc-jni/src/main/cpp/src/media/video/macos/VideoTrackDeviceSourceMac.cpp index 72b513ca1..2f53a29db 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/macos/VideoTrackDeviceSourceMac.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/macos/VideoTrackDeviceSourceMac.cpp @@ -82,7 +82,7 @@ namespace jni } if (!captureDevice) { - throw new Exception("No video capture devices available"); + throw Exception("No video capture devices available"); } VideoTrackDeviceSourceCallback * callback = [[VideoTrackDeviceSourceCallback alloc] init]; diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDeviceSourceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDeviceSourceTests.java new file mode 100644 index 000000000..c27dff533 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDeviceSourceTests.java @@ -0,0 +1,52 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import dev.onvoid.webrtc.TestBase; + +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 VideoDeviceSourceTests extends TestBase { + + @Test + void startReportsNativeError() { + VideoDeviceSource source = new VideoDeviceSource(); + + try { + source.setVideoCaptureDevice(new VideoDevice("webrtc-java missing camera", "missing")); + + // Depending on the machine there is no camera at all or not this one; + // either way the native message arrives instead of "Unhandled Exception". + Error e = assertThrows(Error.class, source::start); + + assertTrue(List.of("No video capture devices available", + "Device webrtc-java missing camera not found").contains(e.getMessage()), + e.getMessage()); + } + finally { + source.dispose(); + } + } +}