Skip to content

Commit 9701913

Browse files
authored
fix: make track sinks safe to change from any thread and callback (#517)
* fix: register track sinks atomically across threads AudioTrack and VideoTrack kept their sinks in unguarded maps, so two threads adding the same sink made two native registrations, and an add could overlap dispose(). A shared SinkRegistry now guards the map with a lock that is never held across a native call, and dispose() waits for the native calls still running. * fix: let sinks add and remove sinks from their callbacks A sink that removed itself in onVideoFrame() blocked for good: WebRTC holds the broadcaster's lock while it delivers a frame, and RemoveSink() takes it again on the worker thread the caller waits for. The same held for adding a sink, for audio sinks of a remote track or a CustomAudioSource, and for voice activity listeners. A change made within a callback now takes effect for the Java side at once and is made natively on another thread after the callback returned; dispose() there fails with an IllegalStateException. * feat: let video sinks share read-only frames VideoTrackSink copied every frame for each sink, so four sinks of a 1080p30 track copied about 356 MiB a second. addSink(sink, VideoFrameAccess.SHARED) hands a sink the pixels the source handed out, without a copy, in read-only byte buffers; frame.copy() gives a writable one. COPY stays the default and keeps sinks from seeing each other's writes.
1 parent 41cd3ea commit 9701913

16 files changed

Lines changed: 1319 additions & 81 deletions

File tree

‎docs/guide/audio/custom-audio-source.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,8 @@ audioTrack.addSink(monitorSink);
204204
audioTrack.removeSink(monitorSink);
205205
```
206206

207+
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.
208+
207209
## Cleanup
208210

209211
When you're done with the custom audio source, make sure to clean up resources:

‎docs/guide/video/camera-capture.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,37 @@ videoTrack.addSink(localVideoSink);
162162
videoTrack.removeSink(localVideoSink);
163163
```
164164

165+
### Threads and Sink Changes
166+
167+
`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:
168+
169+
```java
170+
videoTrack.addSink(new VideoTrackSink() {
171+
@Override
172+
public void onVideoFrame(VideoFrame frame) {
173+
saveSnapshot(frame);
174+
frame.release();
175+
176+
// Gets no further frames.
177+
videoTrack.removeSink(this);
178+
}
179+
});
180+
```
181+
182+
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.
183+
184+
### Sharing Frames Between Sinks
185+
186+
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:
187+
188+
```java
189+
import dev.onvoid.webrtc.media.video.VideoFrameAccess;
190+
191+
videoTrack.addSink(previewSink, VideoFrameAccess.SHARED);
192+
```
193+
194+
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.
195+
165196
### Receiving Remote Video Frames
166197

167198
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`:

‎webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webrtc-jni/src/main/cpp/include/api/VideoFrame.h‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ namespace jni
4848

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

5458
class JavaVideoFrameClass : public JavaClass
@@ -96,6 +100,7 @@ namespace jni
96100
jfieldID strideV;
97101
jfieldID width;
98102
jfieldID height;
103+
jmethodID asReadOnlyBuffer;
99104
};
100105
}
101106

‎webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ namespace jni
3131
class VideoTrackSink : public webrtc::VideoSinkInterface<webrtc::VideoFrame>
3232
{
3333
public:
34-
VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink);
34+
// A shared sink gets the pixels of the frames themselves, read-only,
35+
// and any other a copy of its own.
36+
VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool shared);
3537
~VideoTrackSink() = default;
3638

3739
// VideoSinkInterface implementation.
@@ -49,6 +51,8 @@ namespace jni
4951
private:
5052
JavaGlobalRef<jobject> sink;
5153

54+
const bool shared;
55+
5256
const std::shared_ptr<JavaVideoTrackSinkClass> javaClass;
5357
const std::shared_ptr<JavaVideoFrameClass> javaFrameClass;
5458
const std::shared_ptr<JavaNativeI420BufferClass> javaBufferClass;

‎webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoS
8282
jni::VideoCaptureBase * videoSource = GetHandle<jni::VideoCaptureBase>(env, caller);
8383
CHECK_HANDLE(videoSource);
8484

85-
videoSource->setVideoSink(std::make_unique<jni::VideoTrackSink>(env, jni::JavaGlobalRef<jobject>(env, jsink)));
85+
videoSource->setVideoSink(std::make_unique<jni::VideoTrackSink>(env, jni::JavaGlobalRef<jobject>(env, jsink), false));
8686
}
8787

8888
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start

‎webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
#include "api/media_stream_interface.h"
2323

2424
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInternal
25-
(JNIEnv * env, jobject caller, jobject jsink)
25+
(JNIEnv * env, jobject caller, jobject jsink, jboolean shared)
2626
{
2727
try {
2828
if (jsink == nullptr) {
@@ -33,7 +33,7 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInt
3333
webrtc::VideoTrackInterface * track = GetHandle<webrtc::VideoTrackInterface>(env, caller);
3434
CHECK_HANDLEV(track, 0);
3535

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

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

‎webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,15 @@ namespace jni
4646
return plane;
4747
}
4848

49+
// A read-only view of a plane, or throws.
50+
JavaLocalRef<jobject> ReadOnlyPlane(JNIEnv * env, jmethodID asReadOnlyBuffer, const JavaLocalRef<jobject> & plane)
51+
{
52+
JavaLocalRef<jobject> view(env, env->CallObjectMethod(plane, asReadOnlyBuffer));
53+
ExceptionCheck(env);
54+
55+
return view;
56+
}
57+
4958
// Throws unless the plane holds every byte a copy reads: the last row ends at the width.
5059
void CheckPlane(JNIEnv * env, const char * name, const JavaRef<jobject> & data, jint stride, jint width, jint height)
5160
{
@@ -193,7 +202,8 @@ namespace jni
193202

194203
namespace I420Buffer
195204
{
196-
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer)
205+
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::scoped_refptr<webrtc::I420BufferInterface> & buffer,
206+
bool readOnly)
197207
{
198208
const auto javaClass = JavaClasses::get<JavaNativeI420BufferClass>(env);
199209

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

219+
if (readOnly) {
220+
yBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, yBuffer);
221+
uBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, uBuffer);
222+
vBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, vBuffer);
223+
}
224+
209225
JavaLocalRef<jobject> jBuffer(env, env->NewObject(javaClass->cls, javaClass->ctor, buffer->width(), buffer->height(),
210226
yBuffer.get(), buffer->StrideY(), uBuffer.get(), buffer->StrideU(), vBuffer.get(), buffer->StrideV()));
211227

@@ -269,5 +285,9 @@ namespace jni
269285
strideV = GetFieldID(env, cls, "strideV", "I");
270286
width = GetFieldID(env, cls, "width", "I");
271287
height = GetFieldID(env, cls, "height", "I");
288+
289+
jclass byteBufferClass = FindClass(env, "java/nio/ByteBuffer");
290+
291+
asReadOnlyBuffer = GetMethod(env, byteBufferClass, "asReadOnlyBuffer", "()" BYTE_BUFFER_SIG);
272292
}
273293
}

‎webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@
2525

2626
namespace jni
2727
{
28-
VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink) :
28+
VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool shared) :
2929
sink(sink),
30+
shared(shared),
3031
javaClass(JavaClasses::get<JavaVideoTrackSinkClass>(env)),
3132
javaFrameClass(JavaClasses::get<JavaVideoFrameClass>(env)),
3233
javaBufferClass(JavaClasses::get<JavaNativeI420BufferClass>(env))
@@ -48,22 +49,30 @@ namespace jni
4849
return;
4950
}
5051

51-
webrtc::scoped_refptr<webrtc::I420Buffer> i420BufferCopy = webrtc::I420Buffer::Copy(*i420Buffer);
52+
// The copy keeps sinks from seeing what another one writes into its
53+
// pixels, at the cost of a full copy of each frame for each sink. A
54+
// shared sink gets the pixels the source handed out instead, which it
55+
// can only read, so that sinks and the encoder share one buffer.
56+
webrtc::scoped_refptr<webrtc::I420BufferInterface> javaBuffer = i420Buffer;
57+
58+
if (!shared) {
59+
javaBuffer = webrtc::I420Buffer::Copy(*i420Buffer);
60+
}
5261

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

5665
try {
57-
JavaLocalRef<jobject> jBuffer = I420Buffer::toJava(env, i420BufferCopy);
66+
JavaLocalRef<jobject> jBuffer = I420Buffer::toJava(env, javaBuffer, shared);
5867

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

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

6473
if (jFrame.get() == nullptr) {
6574
// No frame got the buffer that would release it.
66-
i420BufferCopy->Release();
75+
javaBuffer->Release();
6776
ExceptionCheck(env);
6877
}
6978
else {

0 commit comments

Comments
 (0)