Skip to content

Commit 0deb274

Browse files
authored
fix: free observers and factories safely while they are still in use (#528)
* fix: free each observer once when it is registered while being disposed Registering, removing and disposing through one Java object may now run on several threads at once. WebRTC is told by one of them at a time, without anyone waiting, and an observer is freed once WebRTC has a newer one. A dispose frees the observer only once no registration through the object is running any more, so none is left registered. * fix: free track listeners only once the notification under way is over WebRTC calls the observers of a track from a copy of their list, so a listener that disposed the track, or removed a listener, freed observers that were still to be called, its own included. They are now detached at once and freed, with the track, after the notification; detached ones are no longer called. * fix: keep the factory until a closed connection is freed A connection closed from a callback, or while another thread was still in one of its methods, is freed later on the factory's signaling thread. A factory disposed meanwhile stopped and freed that thread first. The close now holds the factory's handle until the connection is freed, so the factory is released after it. * docs: dispose from listeners, concurrent observer registration and pending closes
1 parent 4e2447e commit 0deb274

24 files changed

Lines changed: 856 additions & 127 deletions

‎docs/guide/get-started.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,8 @@ peerConnection.close();
479479
factory.dispose();
480480
```
481481

482+
A track may be disposed, and a listener removed, from within one of its listeners: the listeners the notification has not reached yet are then not called, and what goes is freed once the notification is over. An observer registered on one thread while the object is disposed on another is freed once and never left registered. A factory disposed while a closed connection is still being freed is released once that connection is.
483+
482484
`dispose()` and `close()` may be called from any thread and more than once: only the first call frees anything, later ones do nothing. Once an object is disposed, its methods throw an `IllegalStateException` (a closed connection still reports its state). A method that another thread is running at that moment keeps the native object until it returns, and what the dispose frees is freed then.
483485

484486
## Next Steps

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,15 @@ namespace jni
4242
// given back with Unuse().
4343
jlong Use(JNIEnv * env, jobject object);
4444

45-
// Ends a use begun with Use(), and runs the releases that waited for it
46-
// if it was the last.
45+
// Ends a use begun with Use() or Pin(), and runs the releases that
46+
// waited for it if it was the last.
4747
void Unuse(JNIEnv * env, jlong handle) noexcept;
4848

49+
// Marks a handle in use once more, for work that outlives the call
50+
// using it, which is to end that use with Unuse() when it is done. Only
51+
// for a handle the calling thread uses, e.g. through a NativeLease.
52+
void Pin(jlong handle);
53+
4954
// Unbinds the handle of a NativeObject and returns it. Returns 0 when
5055
// the object is null or another thread has taken the handle before.
5156
jlong Take(JNIEnv * env, jobject object);
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#ifndef JNI_WEBRTC_API_OBSERVER_SLOT_H_
18+
#define JNI_WEBRTC_API_OBSERVER_SLOT_H_
19+
20+
#include "JavaUtils.h"
21+
22+
#include <jni.h>
23+
24+
#include <functional>
25+
#include <memory>
26+
#include <mutex>
27+
#include <vector>
28+
29+
namespace jni
30+
{
31+
// Guards the creation and the taking of observer slots, never held while
32+
// WebRTC is called.
33+
std::mutex & ObserverSlotMutex();
34+
35+
// The native observer a Java object registers on its WebRTC object, which
36+
// has room for one, kept in a long field of that Java object.
37+
//
38+
// Registering and removing may happen on several threads at once, and
39+
// while the object is disposed. WebRTC is told by one thread at a time:
40+
// a thread that finds another one telling WebRTC leaves its observer to
41+
// that thread and returns, so no thread waits for another, which may be
42+
// waiting for a WebRTC thread that runs a callback of the observer. An
43+
// observer is freed once WebRTC has been given a newer one, and never
44+
// twice.
45+
//
46+
// dispose() takes the slot right after the object's handle, and frees it
47+
// in the handle's release. That release runs once no native method of the
48+
// object is running any more, the ones that register included, and none
49+
// can start, so it is the last to tell WebRTC and finds the observer that
50+
// WebRTC has. A registration that comes too late to get a slot frees its
51+
// observer without telling WebRTC.
52+
template <typename T>
53+
class ObserverSlot
54+
{
55+
public:
56+
// Tells WebRTC about the observer that is to be registered now, or
57+
// to be removed when target is null. previous is the one it was
58+
// told about last through this slot, or null.
59+
using Apply = std::function<void(T * previous, T * target)>;
60+
61+
~ObserverSlot()
62+
{
63+
delete desired;
64+
65+
for (T * observer : retired) {
66+
delete observer;
67+
}
68+
}
69+
70+
// Registers the observer through the Java object, or removes the
71+
// one registered through it when observer is null, and takes
72+
// ownership of it.
73+
static void Set(JNIEnv * env, jobject object, const char * field, T * observer, const Apply & apply)
74+
{
75+
std::unique_ptr<T> owned(observer);
76+
ObserverSlot * slot = Get(env, object, field);
77+
78+
if (slot == nullptr) {
79+
// Disposed meanwhile.
80+
return;
81+
}
82+
83+
std::vector<T *> unused;
84+
std::unique_lock<std::mutex> lock(slot->mutex);
85+
86+
if (slot->desired != nullptr) {
87+
slot->retired.push_back(slot->desired);
88+
}
89+
90+
slot->desired = owned.release();
91+
92+
if (slot->busy) {
93+
// The thread telling WebRTC goes on with this observer.
94+
return;
95+
}
96+
97+
slot->busy = true;
98+
99+
while (true) {
100+
T * target = slot->desired;
101+
T * previous = slot->applied_;
102+
103+
lock.unlock();
104+
105+
try {
106+
apply(previous, target);
107+
}
108+
catch (...) {
109+
lock.lock();
110+
slot->busy = false;
111+
throw;
112+
}
113+
114+
lock.lock();
115+
116+
slot->applied_ = target;
117+
118+
if (slot->desired == target) {
119+
// WebRTC has the latest; it has let go of all the others.
120+
slot->busy = false;
121+
unused.swap(slot->retired);
122+
break;
123+
}
124+
}
125+
126+
lock.unlock();
127+
128+
for (T * unusedObserver : unused) {
129+
delete unusedObserver;
130+
}
131+
}
132+
133+
// Takes the slot of a Java object whose handle has been taken, for
134+
// the handle's release to free. No slot is made for it afterwards.
135+
static std::shared_ptr<ObserverSlot> Take(JNIEnv * env, jobject object, const char * field)
136+
{
137+
std::lock_guard<std::mutex> lock(ObserverSlotMutex());
138+
139+
ObserverSlot * slot = GetHandle<ObserverSlot>(env, object, field);
140+
141+
if (slot != nullptr) {
142+
SetHandle<std::nullptr_t>(env, object, field, nullptr);
143+
}
144+
145+
return std::shared_ptr<ObserverSlot>(slot);
146+
}
147+
148+
// The observer WebRTC was told about last, or null. Only for the
149+
// release of a disposed object, when nothing registers any more.
150+
T * applied() const
151+
{
152+
return applied_;
153+
}
154+
155+
private:
156+
ObserverSlot() = default;
157+
158+
// The slot of the Java object, made on first use, or null once its
159+
// handle has been taken.
160+
static ObserverSlot * Get(JNIEnv * env, jobject object, const char * field)
161+
{
162+
std::lock_guard<std::mutex> lock(ObserverSlotMutex());
163+
164+
ObserverSlot * slot = GetHandle<ObserverSlot>(env, object, field);
165+
166+
if (slot != nullptr) {
167+
return slot;
168+
}
169+
170+
// Read under the lock that Take() holds: a dispose that took
171+
// the handle before takes this slot too, or finds none.
172+
if (GetHandle<void>(env, object) == nullptr) {
173+
return nullptr;
174+
}
175+
176+
slot = new ObserverSlot();
177+
178+
SetHandle(env, object, field, slot);
179+
180+
return slot;
181+
}
182+
183+
private:
184+
std::mutex mutex;
185+
// The observer to be registered last, owned.
186+
T * desired = nullptr;
187+
// What WebRTC was told about last, desired or one of retired.
188+
T * applied_ = nullptr;
189+
// Replaced observers WebRTC may still have, owned.
190+
std::vector<T *> retired;
191+
// Whether a thread is telling WebRTC.
192+
bool busy = false;
193+
};
194+
}
195+
196+
#endif

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
#ifndef JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_
1818
#define JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_
1919

20+
#include <functional>
21+
2022
namespace jni
2123
{
2224
// Which native observer is registered on a WebRTC object that has room for
@@ -40,6 +42,24 @@ namespace jni
4042
// Forgets the observer if it is the one registered on the owner, and
4143
// returns whether it was. Only then is it to be unregistered.
4244
bool Remove(const void * owner, const void * observer);
45+
46+
// How an ObserverSlot tells WebRTC: registering records the observer
47+
// here first, removing tells WebRTC only while the observer removed is
48+
// still the registered one.
49+
template <typename T>
50+
std::function<void(T *, T *)> Apply(const void * owner, std::function<void(T *)> registerObserver,
51+
std::function<void()> unregisterObserver)
52+
{
53+
return [owner, registerObserver, unregisterObserver](T * previous, T * target) {
54+
if (target != nullptr) {
55+
Set(owner, target);
56+
registerObserver(target);
57+
}
58+
else if (Remove(owner, previous)) {
59+
unregisterObserver();
60+
}
61+
};
62+
}
4363
}
4464
}
4565

‎webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#include "api/media_stream_interface.h"
2424

2525
#include <jni.h>
26+
#include <atomic>
27+
#include <functional>
2628
#include <memory>
2729

2830
namespace jni
@@ -41,6 +43,22 @@ namespace jni
4143
// ObserverInterface implementation.
4244
void OnChanged() override;
4345

46+
// Keeps this observer from calling its listener from now on, also
47+
// when WebRTC still calls it in the notification under way.
48+
void detach();
49+
50+
// Whether this thread is in a listener's callback. WebRTC goes on
51+
// calling the other observers of the track afterwards, from a copy
52+
// of its list, so none of them, nor the track, may be freed before
53+
// the notification is over.
54+
static bool InCallback();
55+
56+
// Runs the work right away, or, in a listener's callback, once the
57+
// notification under way on this thread is over: after the task the
58+
// WebRTC thread runs, or, on a thread that is none, after the
59+
// outermost callback.
60+
static void AfterNotification(std::function<void()> work);
61+
4462
private:
4563
class JavaMediaStreamTrackListenerClass : public JavaClass
4664
{
@@ -60,6 +78,7 @@ namespace jni
6078
const std::shared_ptr<JavaMediaStreamTrackListenerClass> javaClass;
6179
webrtc::MediaStreamTrackInterface::TrackState trackState;
6280
bool trackEnabled;
81+
std::atomic<bool> detached { false };
6382
};
6483
}
6584

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

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@
2929

3030
#include "api/media_stream_interface.h"
3131
#include "rtc_base/logging.h"
32+
#include "rtc_base/thread.h"
33+
34+
#include <memory>
35+
#include <vector>
3236

3337
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose
3438
(JNIEnv * env, jobject caller)
@@ -45,17 +49,42 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose
4549
return;
4650
}
4751

52+
// Disposed from a listener of this track, or of another track the same
53+
// notification reaches: WebRTC goes on calling the observers of the track
54+
// from a copy of their list, and they use the track. Both are freed once
55+
// the notification is over.
56+
bool inCallback = jni::MediaStreamTrackObserver::InCallback();
57+
webrtc::Thread * callbackThread = inCallback ? webrtc::Thread::Current() : nullptr;
58+
4859
// Listeners still registered are taken off the track before it goes. Their
4960
// entries are keyed by this track's address, which a later track can be
5061
// given, and an observer left registered would be freed with its entry
5162
// while the track (if something else still holds it) can still call it.
52-
for (const auto & observer : javaContext->removeNativeRefs<jni::MediaStreamTrackObserver>(track)) {
63+
auto observers = javaContext->removeNativeRefs<jni::MediaStreamTrackObserver>(track);
64+
65+
for (const auto & observer : observers) {
66+
observer->detach();
5367
track->UnregisterObserver(observer.get());
5468
}
5569

56-
jni::ReleaseHandle(env, track, [track](bool deferred) {
57-
if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
58-
jni::NativeHandle::ReportNotDeleted(deferred);
70+
jni::ReleaseHandle(env, track, [track, observers, inCallback, callbackThread](bool deferred) {
71+
// The observers go with the last copy of this.
72+
auto release = [track, observers, report = deferred || inCallback]() {
73+
if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
74+
jni::NativeHandle::ReportNotDeleted(report);
75+
}
76+
};
77+
78+
if (callbackThread != nullptr) {
79+
// Also when a method of another thread held the track until now:
80+
// the notification may still be under way on the callback's thread.
81+
callbackThread->PostTask(std::move(release));
82+
}
83+
else if (inCallback && !deferred) {
84+
jni::MediaStreamTrackObserver::AfterNotification(std::move(release));
85+
}
86+
else {
87+
release();
5988
}
6089
});
6190
}
@@ -152,7 +181,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeEnded
152181
auto observerPtr = javaContext->removeNativeRef<jni::MediaStreamTrackObserver>(env, jni::JavaLocalRef<jobject>(env, jListener), track, static_cast<int>(jni::MediaStreamTrackEvent::ended));
153182

154183
if (observerPtr) {
184+
observerPtr->detach();
155185
track->UnregisterObserver(observerPtr.get());
186+
187+
// Removed in a callback, maybe its own: freed once the notification
188+
// is over.
189+
jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {});
156190
}
157191
}
158192
catch (...) {
@@ -189,7 +223,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeMuteE
189223
auto observerPtr = javaContext->removeNativeRef<jni::MediaStreamTrackObserver>(env, jni::JavaLocalRef<jobject>(env, jListener), track, static_cast<int>(jni::MediaStreamTrackEvent::mute));
190224

191225
if (observerPtr) {
226+
observerPtr->detach();
192227
track->UnregisterObserver(observerPtr.get());
228+
229+
// Removed in a callback, maybe its own: freed once the notification
230+
// is over.
231+
jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {});
193232
}
194233
}
195234
catch (...) {

0 commit comments

Comments
 (0)