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/get-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,8 @@ peerConnection.close();
factory.dispose();
```

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.

`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.

## Next Steps
Expand Down
9 changes: 7 additions & 2 deletions webrtc-jni/src/main/cpp/include/NativeHandle.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ namespace jni
// given back with Unuse().
jlong Use(JNIEnv * env, jobject object);

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

// Marks a handle in use once more, for work that outlives the call
// using it, which is to end that use with Unuse() when it is done. Only
// for a handle the calling thread uses, e.g. through a NativeLease.
void Pin(jlong handle);

// Unbinds the handle of a NativeObject and returns it. Returns 0 when
// the object is null or another thread has taken the handle before.
jlong Take(JNIEnv * env, jobject object);
Expand Down
196 changes: 196 additions & 0 deletions webrtc-jni/src/main/cpp/include/api/ObserverSlot.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef JNI_WEBRTC_API_OBSERVER_SLOT_H_
#define JNI_WEBRTC_API_OBSERVER_SLOT_H_

#include "JavaUtils.h"

#include <jni.h>

#include <functional>
#include <memory>
#include <mutex>
#include <vector>

namespace jni
{
// Guards the creation and the taking of observer slots, never held while
// WebRTC is called.
std::mutex & ObserverSlotMutex();

// The native observer a Java object registers on its WebRTC object, which
// has room for one, kept in a long field of that Java object.
//
// Registering and removing may happen on several threads at once, and
// while the object is disposed. WebRTC is told by one thread at a time:
// a thread that finds another one telling WebRTC leaves its observer to
// that thread and returns, so no thread waits for another, which may be
// waiting for a WebRTC thread that runs a callback of the observer. An
// observer is freed once WebRTC has been given a newer one, and never
// twice.
//
// dispose() takes the slot right after the object's handle, and frees it
// in the handle's release. That release runs once no native method of the
// object is running any more, the ones that register included, and none
// can start, so it is the last to tell WebRTC and finds the observer that
// WebRTC has. A registration that comes too late to get a slot frees its
// observer without telling WebRTC.
template <typename T>
class ObserverSlot
{
public:
// Tells WebRTC about the observer that is to be registered now, or
// to be removed when target is null. previous is the one it was
// told about last through this slot, or null.
using Apply = std::function<void(T * previous, T * target)>;

~ObserverSlot()
{
delete desired;

for (T * observer : retired) {
delete observer;
}
}

// Registers the observer through the Java object, or removes the
// one registered through it when observer is null, and takes
// ownership of it.
static void Set(JNIEnv * env, jobject object, const char * field, T * observer, const Apply & apply)
{
std::unique_ptr<T> owned(observer);
ObserverSlot * slot = Get(env, object, field);

if (slot == nullptr) {
// Disposed meanwhile.
return;
}

std::vector<T *> unused;
std::unique_lock<std::mutex> lock(slot->mutex);

if (slot->desired != nullptr) {
slot->retired.push_back(slot->desired);
}

slot->desired = owned.release();

if (slot->busy) {
// The thread telling WebRTC goes on with this observer.
return;
}

slot->busy = true;

while (true) {
T * target = slot->desired;
T * previous = slot->applied_;

lock.unlock();

try {
apply(previous, target);
}
catch (...) {
lock.lock();
slot->busy = false;
throw;
}

lock.lock();

slot->applied_ = target;

if (slot->desired == target) {
// WebRTC has the latest; it has let go of all the others.
slot->busy = false;
unused.swap(slot->retired);
break;
}
}

lock.unlock();

for (T * unusedObserver : unused) {
delete unusedObserver;
}
}

// Takes the slot of a Java object whose handle has been taken, for
// the handle's release to free. No slot is made for it afterwards.
static std::shared_ptr<ObserverSlot> Take(JNIEnv * env, jobject object, const char * field)
{
std::lock_guard<std::mutex> lock(ObserverSlotMutex());

ObserverSlot * slot = GetHandle<ObserverSlot>(env, object, field);

if (slot != nullptr) {
SetHandle<std::nullptr_t>(env, object, field, nullptr);
}

return std::shared_ptr<ObserverSlot>(slot);
}

// The observer WebRTC was told about last, or null. Only for the
// release of a disposed object, when nothing registers any more.
T * applied() const
{
return applied_;
}

private:
ObserverSlot() = default;

// The slot of the Java object, made on first use, or null once its
// handle has been taken.
static ObserverSlot * Get(JNIEnv * env, jobject object, const char * field)
{
std::lock_guard<std::mutex> lock(ObserverSlotMutex());

ObserverSlot * slot = GetHandle<ObserverSlot>(env, object, field);

if (slot != nullptr) {
return slot;
}

// Read under the lock that Take() holds: a dispose that took
// the handle before takes this slot too, or finds none.
if (GetHandle<void>(env, object) == nullptr) {
return nullptr;
}

slot = new ObserverSlot();

SetHandle(env, object, field, slot);

return slot;
}

private:
std::mutex mutex;
// The observer to be registered last, owned.
T * desired = nullptr;
// What WebRTC was told about last, desired or one of retired.
T * applied_ = nullptr;
// Replaced observers WebRTC may still have, owned.
std::vector<T *> retired;
// Whether a thread is telling WebRTC.
bool busy = false;
};
}

#endif
20 changes: 20 additions & 0 deletions webrtc-jni/src/main/cpp/include/api/RegisteredObservers.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
#ifndef JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_
#define JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_

#include <functional>

namespace jni
{
// Which native observer is registered on a WebRTC object that has room for
Expand All @@ -40,6 +42,24 @@ namespace jni
// Forgets the observer if it is the one registered on the owner, and
// returns whether it was. Only then is it to be unregistered.
bool Remove(const void * owner, const void * observer);

// How an ObserverSlot tells WebRTC: registering records the observer
// here first, removing tells WebRTC only while the observer removed is
// still the registered one.
template <typename T>
std::function<void(T *, T *)> Apply(const void * owner, std::function<void(T *)> registerObserver,
std::function<void()> unregisterObserver)
{
return [owner, registerObserver, unregisterObserver](T * previous, T * target) {
if (target != nullptr) {
Set(owner, target);
registerObserver(target);
}
else if (Remove(owner, previous)) {
unregisterObserver();
}
};
}
}
}

Expand Down
19 changes: 19 additions & 0 deletions webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
#include "api/media_stream_interface.h"

#include <jni.h>
#include <atomic>
#include <functional>
#include <memory>

namespace jni
Expand All @@ -41,6 +43,22 @@ namespace jni
// ObserverInterface implementation.
void OnChanged() override;

// Keeps this observer from calling its listener from now on, also
// when WebRTC still calls it in the notification under way.
void detach();

// Whether this thread is in a listener's callback. WebRTC goes on
// calling the other observers of the track afterwards, from a copy
// of its list, so none of them, nor the track, may be freed before
// the notification is over.
static bool InCallback();

// Runs the work right away, or, in a listener's callback, once the
// notification under way on this thread is over: after the task the
// WebRTC thread runs, or, on a thread that is none, after the
// outermost callback.
static void AfterNotification(std::function<void()> work);

private:
class JavaMediaStreamTrackListenerClass : public JavaClass
{
Expand All @@ -60,6 +78,7 @@ namespace jni
const std::shared_ptr<JavaMediaStreamTrackListenerClass> javaClass;
webrtc::MediaStreamTrackInterface::TrackState trackState;
bool trackEnabled;
std::atomic<bool> detached { false };
};
}

Expand Down
47 changes: 43 additions & 4 deletions webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@

#include "api/media_stream_interface.h"
#include "rtc_base/logging.h"
#include "rtc_base/thread.h"

#include <memory>
#include <vector>

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose
(JNIEnv * env, jobject caller)
Expand All @@ -45,17 +49,42 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose
return;
}

// Disposed from a listener of this track, or of another track the same
// notification reaches: WebRTC goes on calling the observers of the track
// from a copy of their list, and they use the track. Both are freed once
// the notification is over.
bool inCallback = jni::MediaStreamTrackObserver::InCallback();
webrtc::Thread * callbackThread = inCallback ? webrtc::Thread::Current() : nullptr;

// Listeners still registered are taken off the track before it goes. Their
// entries are keyed by this track's address, which a later track can be
// given, and an observer left registered would be freed with its entry
// while the track (if something else still holds it) can still call it.
for (const auto & observer : javaContext->removeNativeRefs<jni::MediaStreamTrackObserver>(track)) {
auto observers = javaContext->removeNativeRefs<jni::MediaStreamTrackObserver>(track);

for (const auto & observer : observers) {
observer->detach();
track->UnregisterObserver(observer.get());
}

jni::ReleaseHandle(env, track, [track](bool deferred) {
if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
jni::NativeHandle::ReportNotDeleted(deferred);
jni::ReleaseHandle(env, track, [track, observers, inCallback, callbackThread](bool deferred) {
// The observers go with the last copy of this.
auto release = [track, observers, report = deferred || inCallback]() {
if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
jni::NativeHandle::ReportNotDeleted(report);
}
};

if (callbackThread != nullptr) {
// Also when a method of another thread held the track until now:
// the notification may still be under way on the callback's thread.
callbackThread->PostTask(std::move(release));
}
else if (inCallback && !deferred) {
jni::MediaStreamTrackObserver::AfterNotification(std::move(release));
}
else {
release();
}
});
}
Expand Down Expand Up @@ -152,7 +181,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeEnded
auto observerPtr = javaContext->removeNativeRef<jni::MediaStreamTrackObserver>(env, jni::JavaLocalRef<jobject>(env, jListener), track, static_cast<int>(jni::MediaStreamTrackEvent::ended));

if (observerPtr) {
observerPtr->detach();
track->UnregisterObserver(observerPtr.get());

// Removed in a callback, maybe its own: freed once the notification
// is over.
jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {});
}
}
catch (...) {
Expand Down Expand Up @@ -189,7 +223,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeMuteE
auto observerPtr = javaContext->removeNativeRef<jni::MediaStreamTrackObserver>(env, jni::JavaLocalRef<jobject>(env, jListener), track, static_cast<int>(jni::MediaStreamTrackEvent::mute));

if (observerPtr) {
observerPtr->detach();
track->UnregisterObserver(observerPtr.get());

// Removed in a callback, maybe its own: freed once the notification
// is over.
jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {});
}
}
catch (...) {
Expand Down
Loading
Loading