Skip to content

Commit 5ac2157

Browse files
committed
Merge remote-tracking branch 'origin/main' into fix/video-capture-lifecycle
# Conflicts: # webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp
2 parents 56f973b + 9701913 commit 5ac2157

33 files changed

Lines changed: 1610 additions & 141 deletions

‎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/dependencies/jni-voithos/include/JavaFactories.h‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@
1515

1616
#include <jni.h>
1717
#include <memory>
18+
#include <type_traits>
1819
#include <typeindex>
20+
#include <typeinfo>
1921
#include <unordered_map>
22+
#include <utility>
2023

2124
#ifdef __cpp_lib_any
2225
#include <any>
@@ -30,6 +33,47 @@ namespace jni
3033
JavaFactories() = default;
3134
~JavaFactories() = default;
3235

36+
// Creates the Java object for what `owner` points to and moves the
37+
// reference `owner` holds into it, for a Java object that owns and
38+
// disposes its native object. The reference is handed over only once
39+
// the Java object exists and holds the handle: if creating it fails,
40+
// `owner` keeps the reference and frees it as usual, and the Java
41+
// object, which nothing can reach yet, is left to the garbage
42+
// collector. `owner` is a smart pointer with get() and release(), such
43+
// as webrtc::scoped_refptr or std::unique_ptr, passed with std::move.
44+
template <class Ptr>
45+
static JavaLocalRef<jobject> createOwning(JNIEnv * env, Ptr && owner)
46+
{
47+
return createOwning(env, std::forward<Ptr>(owner), [](jobject) {});
48+
}
49+
50+
// Same as above, and calls `bind` with the new Java object before the
51+
// reference is handed over, so that whatever else has to be bound to
52+
// the Java object (e.g. the handle of an observer) is bound before the
53+
// Java object owns anything. If `bind` throws, `owner` keeps the
54+
// reference.
55+
template <class Ptr, class Bind>
56+
static JavaLocalRef<jobject> createOwning(JNIEnv * env, Ptr && owner, Bind && bind)
57+
{
58+
static_assert(!std::is_lvalue_reference<Ptr>::value,
59+
"Pass the owner with std::move, the call takes its reference");
60+
61+
using T = typename std::remove_cv<typename std::remove_pointer<decltype(owner.get())>::type>::type;
62+
63+
JavaLocalRef<jobject> object = create<T>(env, owner.get());
64+
65+
if (object.get() == nullptr) {
66+
throw Exception("Create Java object for [%s] failed", typeid(T).name());
67+
}
68+
69+
bind(object.get());
70+
71+
// The Java object holds the reference now.
72+
static_cast<void>(owner.release());
73+
74+
return object;
75+
}
76+
3377
#ifdef __cpp_lib_any
3478
template <class T>
3579
static void add(JNIEnv * env, const char * className)

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaFactory.h‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ namespace jni
3131

3232
virtual JavaLocalRef<jobject> create(JNIEnv * env, const T * nativeObject) const
3333
{
34-
jobject object = env->NewObject(javaClass, javaCtor);
34+
JavaLocalRef<jobject> object(env, env->NewObject(javaClass, javaCtor));
3535
ExceptionCheck(env);
3636

37-
SetHandle(env, object, nativeObject);
37+
SetHandle(env, object.get(), nativeObject);
3838

39-
return JavaLocalRef<jobject>(env, object);
39+
return object;
4040
}
4141

4242
virtual JavaLocalRef<jobjectArray> createArray(JNIEnv * env, const jsize & length) const

‎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/include/api/WebRTCUtils.h‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ namespace jni
5656
// and nothing else already guarantees the pointer outlives the call --
5757
// callers of the returned array elements are then responsible for
5858
// disposing them.
59+
//
60+
// The references are handed over only once the whole array is filled, as
61+
// JavaFactories::createOwning does for a single object: if a wrapper
62+
// cannot be created, `vector` frees all of them, and the wrappers made so
63+
// far, which only the dropped array refers to, are left to the garbage
64+
// collector.
5965
template <class T>
6066
JavaLocalRef<jobjectArray> createOwningObjectArray(JNIEnv * env, std::vector<webrtc::scoped_refptr<T>> vector)
6167
{
@@ -68,9 +74,15 @@ namespace jni
6874
}
6975

7076
for (jsize i = 0; i < vectorSize; i++) {
71-
JavaLocalRef<jobject> obj = JavaFactories::create(env, vector[i].release());
77+
JavaLocalRef<jobject> obj = JavaFactories::create(env, vector[i].get());
7278

7379
env->SetObjectArrayElement(objectArray, i, obj.get());
80+
ExceptionCheck(env);
81+
}
82+
83+
// The Java objects hold the references now.
84+
for (auto & item : vector) {
85+
static_cast<void>(item.release());
7486
}
7587

7688
return objectArray;

‎webrtc-jni/src/main/cpp/include/media/video/codec/JavaLocalFrame.h‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,27 @@ namespace jni
2525
// thread stays attached to the JVM for as long as it runs, so without a
2626
// frame of their own the references made for one call would pile up
2727
// behind those of the next.
28+
//
29+
// A frame that cannot be pushed reports the JVM's exception as a codec
30+
// exception, and the call it was meant for gives up rather than make
31+
// references that nothing would free soon: see pushed().
2832
class JavaLocalFrame
2933
{
3034
public:
31-
JavaLocalFrame(JNIEnv * env, jint capacity);
35+
// The context names the call in the log.
36+
JavaLocalFrame(JNIEnv * env, jint capacity, const char * context);
3237
~JavaLocalFrame();
3338

3439
JavaLocalFrame(const JavaLocalFrame &) = delete;
3540
JavaLocalFrame & operator=(const JavaLocalFrame &) = delete;
3641

42+
// Whether the frame is in place, which a call checks before it
43+
// makes any local reference.
44+
bool pushed() const;
45+
3746
private:
3847
JNIEnv * env;
39-
bool pushed;
48+
const bool isPushed;
4049
};
4150
}
4251

‎webrtc-jni/src/main/cpp/include/media/video/codec/VideoDecoderWrapper.h‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,10 @@ namespace jni
117117
Settings settings;
118118
bool initialized;
119119

120-
// Parsing stops while the decoder provides the QP itself.
121-
bool qpParsingEnabled;
120+
// Parsing stops while the decoder provides the QP itself. Read on
121+
// the decoder thread and written on the Java decoder's, which
122+
// may deliver its frames from a thread of its own.
123+
std::atomic<bool> qpParsingEnabled;
122124
webrtc::H264BitstreamParser h264BitstreamParser;
123125
};
124126
}

0 commit comments

Comments
 (0)