Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/tools/video/video-capturer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 3 additions & 1 deletion webrtc-jni/src/main/cpp/include/media/video/VideoCapture.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ namespace jni
VideoCapture();
~VideoCapture();

void start() override;
void setVideoSink(std::unique_ptr<webrtc::VideoSinkInterface<webrtc::VideoFrame>> sink) override;

void start() override;
void stop() override;
void destroy() override;

Expand Down
10 changes: 8 additions & 2 deletions webrtc-jni/src/main/cpp/include/media/video/VideoCaptureBase.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<webrtc::VideoSinkInterface<webrtc::VideoFrame>> 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<webrtc::VideoSinkInterface<webrtc::VideoFrame>> sink);

virtual void start() = 0;
virtual void stop() = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -39,15 +40,20 @@ namespace jni
VideoCaptureMac();
~VideoCaptureMac();

void start() override;
void setVideoSink(std::unique_ptr<webrtc::VideoSinkInterface<webrtc::VideoFrame>> 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;
};
}

Expand Down
16 changes: 14 additions & 2 deletions webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoS
jni::VideoCaptureBase * videoSource = GetHandle<jni::VideoCaptureBase>(env, caller);
CHECK_HANDLE(videoSource);

videoSource->setVideoSink(std::make_unique<jni::VideoTrackSink>(env, jni::JavaGlobalRef<jobject>(env, jsink), false));
try {
videoSource->setVideoSink(std::make_unique<jni::VideoTrackSink>(env, jni::JavaGlobalRef<jobject>(env, jsink), false));
}
catch (...) {
ThrowCxxJavaException(env);
}
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start
Expand All @@ -91,6 +96,11 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start
jni::VideoCaptureBase * videoSource = GetHandle<jni::VideoCaptureBase>(env, caller);
CHECK_HANDLE(videoSource);

if (!videoSource->hasDevice()) {
ThrowJavaException(env, "java/lang/IllegalStateException", "No video capture device set");
return;
}

try {
videoSource->start();
}
Expand Down Expand Up @@ -121,7 +131,9 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_dispose

SetHandle<std::nullptr_t>(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
Expand Down
51 changes: 36 additions & 15 deletions webrtc-jni/src/main/cpp/src/media/video/VideoCapture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,48 @@ namespace jni
}

VideoCapture::~VideoCapture()
{
destroy();
}
{
destroy();
}

void VideoCapture::setVideoSink(std::unique_ptr<webrtc::VideoSinkInterface<webrtc::VideoFrame>> 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<webrtc::VideoCaptureModule::DeviceInfo> 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;
Expand All @@ -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());
}
}

Expand Down
5 changes: 5 additions & 0 deletions webrtc-jni/src/main/cpp/src/media/video/VideoCaptureBase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@ namespace jni
std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> 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) {
Expand All @@ -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());
}
}

Expand Down Expand Up @@ -118,7 +118,7 @@ namespace jni
}

if (!captureModule || !captureModule->CaptureStarted()) {
throw new Exception("Start video capture failed");
throw Exception("Start video capture failed");
}
}

Expand Down
79 changes: 62 additions & 17 deletions webrtc-jni/src/main/cpp/src/media/video/macos/VideoCaptureMac.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -41,19 +47,39 @@
namespace jni
{
VideoCaptureMac::VideoCaptureMac() : VideoCaptureBase(),
callback(nullptr),
cameraVideoCapturer(nullptr)
{
}

VideoCaptureMac::~VideoCaptureMac()
{
destroy();
}
{
destroy();
}

void VideoCaptureMac::setVideoSink(std::unique_ptr<webrtc::VideoSinkInterface<webrtc::VideoFrame>> newSink)
{
std::unique_ptr<webrtc::VideoSinkInterface<webrtc::VideoFrame>> 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;
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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;
}
Expand Down
Loading
Loading