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
2 changes: 2 additions & 0 deletions docs/guide/audio/custom-audio-source.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ audioTrack.addSink(monitorSink);
audioTrack.removeSink(monitorSink);
```

As with video tracks, sinks may be added and removed from any thread, and also from within `onData`, the sink's own included. Only `dispose()` must not be called from within a callback.

## Cleanup

When you're done with the custom audio source, make sure to clean up resources:
Expand Down
31 changes: 31 additions & 0 deletions docs/guide/video/camera-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,37 @@ videoTrack.addSink(localVideoSink);
videoTrack.removeSink(localVideoSink);
```

### Threads and Sink Changes

`addSink` and `removeSink` may be called from any thread, also at the same time, and from within `onVideoFrame`, so a sink can remove itself once it has seen what it wanted:

```java
videoTrack.addSink(new VideoTrackSink() {
@Override
public void onVideoFrame(VideoFrame frame) {
saveSnapshot(frame);
frame.release();

// Gets no further frames.
videoTrack.removeSink(this);
}
});
```

WebRTC holds a lock while it hands a frame to the sinks, and adding or removing a sink takes the same lock. A change made from within a callback therefore takes effect for the sinks at once, while the native sink is added or removed on another thread right after the callback returned. Disposing the track is the one thing a callback cannot do: `dispose()` throws an `IllegalStateException` there, and belongs on another thread.

### Sharing Frames Between Sinks

By default each sink gets an I420 copy of each frame of its own, which it may write into without the other sinks or the encoder seeing it. That costs a full copy of the pixels per frame and sink: at 1080p and 30 frames a second about 89 MiB a second, for each sink. A sink that only reads the frames can share them instead:

```java
import dev.onvoid.webrtc.media.video.VideoFrameAccess;

videoTrack.addSink(previewSink, VideoFrameAccess.SHARED);
```

A shared sink gets the pixels the source handed out, without a copy, which the other shared sinks and the encoder use as well. The planes of its `NativeI420Buffer` are read-only, so a write throws a `ReadOnlyBufferException`; a sink that wants to change a frame takes a writable copy with `frame.copy()`. The frames may come from a pool of the decoder or capturer, so a shared sink should not hold on to them for long: keep a copy instead, and release the frame.

### Receiving Remote Video Frames

To receive frames from a remote peer, you need to add a sink to the remote video track when it's received. This is typically done in the `onTrack` method of your `PeerConnectionObserver`:
Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion webrtc-jni/src/main/cpp/include/api/VideoFrame.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ namespace jni

namespace I420Buffer
{
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer);
// Wraps the pixels of the buffer in a NativeI420Buffer without
// copying them. With readOnly its planes are read-only byte buffers,
// for pixels that others share.
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer,
bool readOnly = false);
}

class JavaVideoFrameClass : public JavaClass
Expand Down Expand Up @@ -96,6 +100,7 @@ namespace jni
jfieldID strideV;
jfieldID width;
jfieldID height;
jmethodID asReadOnlyBuffer;
};
}

Expand Down
6 changes: 5 additions & 1 deletion webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ namespace jni
class VideoTrackSink : public webrtc::VideoSinkInterface<webrtc::VideoFrame>
{
public:
VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink);
// A shared sink gets the pixels of the frames themselves, read-only,
// and any other a copy of its own.
VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool shared);
~VideoTrackSink() = default;

// VideoSinkInterface implementation.
Expand All @@ -49,6 +51,8 @@ namespace jni
private:
JavaGlobalRef<jobject> sink;

const bool shared;

const std::shared_ptr<JavaVideoTrackSinkClass> javaClass;
const std::shared_ptr<JavaVideoFrameClass> javaFrameClass;
const std::shared_ptr<JavaNativeI420BufferClass> javaBufferClass;
Expand Down
2 changes: 1 addition & 1 deletion webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ 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)));
videoSource->setVideoSink(std::make_unique<jni::VideoTrackSink>(env, jni::JavaGlobalRef<jobject>(env, jsink), false));
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start
Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
#include "api/media_stream_interface.h"

JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInternal
(JNIEnv * env, jobject caller, jobject jsink)
(JNIEnv * env, jobject caller, jobject jsink, jboolean shared)
{
try {
if (jsink == nullptr) {
Expand All @@ -33,7 +33,7 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInt
webrtc::VideoTrackInterface * track = GetHandle<webrtc::VideoTrackInterface>(env, caller);
CHECK_HANDLEV(track, 0);

auto sink = new jni::VideoTrackSink(env, jni::JavaGlobalRef<jobject>(env, jsink));
auto sink = new jni::VideoTrackSink(env, jni::JavaGlobalRef<jobject>(env, jsink), shared == JNI_TRUE);

track->AddOrUpdateSink(sink, webrtc::VideoSinkWants());

Expand Down
22 changes: 21 additions & 1 deletion webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ namespace jni
return plane;
}

// A read-only view of a plane, or throws.
JavaLocalRef<jobject> ReadOnlyPlane(JNIEnv * env, jmethodID asReadOnlyBuffer, const JavaLocalRef<jobject> & plane)
{
JavaLocalRef<jobject> view(env, env->CallObjectMethod(plane, asReadOnlyBuffer));
ExceptionCheck(env);

return view;
}

// Throws unless the plane holds every byte a copy reads: the last row ends at the width.
void CheckPlane(JNIEnv * env, const char * name, const JavaRef<jobject> & data, jint stride, jint width, jint height)
{
Expand Down Expand Up @@ -193,7 +202,8 @@ namespace jni

namespace I420Buffer
{
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer)
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer,
bool readOnly)
{
const auto javaClass = JavaClasses::get<JavaNativeI420BufferClass>(env);

Expand All @@ -206,6 +216,12 @@ namespace jni
JavaLocalRef<jobject> uBuffer = NewPlane(env, "U", buffer->DataU(), planeSize(buffer->StrideU(), buffer->ChromaWidth(), buffer->ChromaHeight()));
JavaLocalRef<jobject> vBuffer = NewPlane(env, "V", buffer->DataV(), planeSize(buffer->StrideV(), buffer->ChromaWidth(), buffer->ChromaHeight()));

if (readOnly) {
yBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, yBuffer);
uBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, uBuffer);
vBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, vBuffer);
}

JavaLocalRef<jobject> jBuffer(env, env->NewObject(javaClass->cls, javaClass->ctor, buffer->width(), buffer->height(),
yBuffer.get(), buffer->StrideY(), uBuffer.get(), buffer->StrideU(), vBuffer.get(), buffer->StrideV()));

Expand Down Expand Up @@ -269,5 +285,9 @@ namespace jni
strideV = GetFieldID(env, cls, "strideV", "I");
width = GetFieldID(env, cls, "width", "I");
height = GetFieldID(env, cls, "height", "I");

jclass byteBufferClass = FindClass(env, "java/nio/ByteBuffer");

asReadOnlyBuffer = GetMethod(env, byteBufferClass, "asReadOnlyBuffer", "()" BYTE_BUFFER_SIG);
}
}
19 changes: 14 additions & 5 deletions webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@

namespace jni
{
VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink) :
VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool shared) :
sink(sink),
shared(shared),
javaClass(JavaClasses::get<JavaVideoTrackSinkClass>(env)),
javaFrameClass(JavaClasses::get<JavaVideoFrameClass>(env)),
javaBufferClass(JavaClasses::get<JavaNativeI420BufferClass>(env))
Expand All @@ -48,22 +49,30 @@ namespace jni
return;
}

webrtc::scoped_refptr<webrtc::I420Buffer> i420BufferCopy = webrtc::I420Buffer::Copy(*i420Buffer);
// The copy keeps sinks from seeing what another one writes into its
// pixels, at the cost of a full copy of each frame for each sink. A
// shared sink gets the pixels the source handed out instead, which it
// can only read, so that sinks and the encoder share one buffer.
webrtc::scoped_refptr<webrtc::I420BufferInterface> javaBuffer = i420Buffer;

if (!shared) {
javaBuffer = webrtc::I420Buffer::Copy(*i420Buffer);
}

jint rotation = static_cast<jint>(frame.rotation());
jlong timestamp = frame.timestamp_us() * webrtc::kNumNanosecsPerMicrosec;

try {
JavaLocalRef<jobject> jBuffer = I420Buffer::toJava(env, i420BufferCopy);
JavaLocalRef<jobject> jBuffer = I420Buffer::toJava(env, javaBuffer, shared);

// The reference the Java frame gives up when it is released.
i420BufferCopy->AddRef();
javaBuffer->AddRef();

JavaLocalRef<jobject> jFrame(env, env->NewObject(javaFrameClass->cls, javaFrameClass->ctor, jBuffer.get(), rotation, timestamp));

if (jFrame.get() == nullptr) {
// No frame got the buffer that would release it.
i420BufferCopy->Release();
javaBuffer->Release();
ExceptionCheck(env);
}
else {
Expand Down
Loading
Loading