diff --git a/docs/guide/get-started.md b/docs/guide/get-started.md index 39a7be43..d39e0080 100644 --- a/docs/guide/get-started.md +++ b/docs/guide/get-started.md @@ -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 diff --git a/webrtc-jni/src/main/cpp/include/NativeHandle.h b/webrtc-jni/src/main/cpp/include/NativeHandle.h index 15b093c6..32c33759 100644 --- a/webrtc-jni/src/main/cpp/include/NativeHandle.h +++ b/webrtc-jni/src/main/cpp/include/NativeHandle.h @@ -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); diff --git a/webrtc-jni/src/main/cpp/include/api/ObserverSlot.h b/webrtc-jni/src/main/cpp/include/api/ObserverSlot.h new file mode 100644 index 00000000..3f9c938b --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/api/ObserverSlot.h @@ -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 + +#include +#include +#include +#include + +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 + 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; + + ~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 owned(observer); + ObserverSlot * slot = Get(env, object, field); + + if (slot == nullptr) { + // Disposed meanwhile. + return; + } + + std::vector unused; + std::unique_lock 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 Take(JNIEnv * env, jobject object, const char * field) + { + std::lock_guard lock(ObserverSlotMutex()); + + ObserverSlot * slot = GetHandle(env, object, field); + + if (slot != nullptr) { + SetHandle(env, object, field, nullptr); + } + + return std::shared_ptr(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 lock(ObserverSlotMutex()); + + ObserverSlot * slot = GetHandle(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(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 retired; + // Whether a thread is telling WebRTC. + bool busy = false; + }; +} + +#endif diff --git a/webrtc-jni/src/main/cpp/include/api/RegisteredObservers.h b/webrtc-jni/src/main/cpp/include/api/RegisteredObservers.h index 5e6356a2..e62524d6 100644 --- a/webrtc-jni/src/main/cpp/include/api/RegisteredObservers.h +++ b/webrtc-jni/src/main/cpp/include/api/RegisteredObservers.h @@ -17,6 +17,8 @@ #ifndef JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_ #define JNI_WEBRTC_API_REGISTERED_OBSERVERS_H_ +#include + namespace jni { // Which native observer is registered on a WebRTC object that has room for @@ -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 + std::function Apply(const void * owner, std::function registerObserver, + std::function unregisterObserver) + { + return [owner, registerObserver, unregisterObserver](T * previous, T * target) { + if (target != nullptr) { + Set(owner, target); + registerObserver(target); + } + else if (Remove(owner, previous)) { + unregisterObserver(); + } + }; + } } } diff --git a/webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h b/webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h index 041fde28..143d2bd8 100644 --- a/webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h +++ b/webrtc-jni/src/main/cpp/include/media/MediaStreamTrackObserver.h @@ -23,6 +23,8 @@ #include "api/media_stream_interface.h" #include +#include +#include #include namespace jni @@ -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 work); + private: class JavaMediaStreamTrackListenerClass : public JavaClass { @@ -60,6 +78,7 @@ namespace jni const std::shared_ptr javaClass; webrtc::MediaStreamTrackInterface::TrackState trackState; bool trackEnabled; + std::atomic detached { false }; }; } diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp index 3a0c1833..063763b6 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp @@ -29,6 +29,10 @@ #include "api/media_stream_interface.h" #include "rtc_base/logging.h" +#include "rtc_base/thread.h" + +#include +#include JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose (JNIEnv * env, jobject caller) @@ -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(track)) { + auto observers = javaContext->removeNativeRefs(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(); } }); } @@ -152,7 +181,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeEnded auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(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 (...) { @@ -189,7 +223,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeMuteE auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(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 (...) { diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp index 48b38051..7aa3e751 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp @@ -24,6 +24,7 @@ #include "JavaRuntimeException.h" #include "JavaString.h" #include "JavaUtils.h" +#include "api/ObserverSlot.h" #include "api/data_channel_interface.h" #include "rtc_base/logging.h" @@ -31,6 +32,24 @@ #include #include +namespace +{ + using DataChannelObserverSlot = jni::ObserverSlot; + + // A channel has room for one observer, which must be unregistered before + // another one is registered. + DataChannelObserverSlot::Apply ApplyTo(webrtc::DataChannelInterface * channel) + { + return [channel](jni::RTCDataChannelObserver *, jni::RTCDataChannelObserver * target) { + channel->UnregisterObserver(); + + if (target != nullptr) { + channel->RegisterObserver(target); + } + }; + } +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerObserver (JNIEnv * env, jobject caller, jobject jObserver) { @@ -38,14 +57,9 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerObserver jni::NativeLease channel(env, caller); CHECK_HANDLE(channel); - // Unregister and free a previously registered observer before replacing - // it, otherwise it would leak along with its JNI global reference. - channel->UnregisterObserver(); - auto observer = new jni::RTCDataChannelObserver(env, jni::JavaGlobalRef(env, jObserver)); - ReplaceNativeObserver(env, caller, "observerHandle", observer); - channel->RegisterObserver(observer); + DataChannelObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(channel)); } catch (...) { ThrowCxxJavaException(env); @@ -55,12 +69,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerObserver JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_unregisterObserver (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLE(channel); - - channel->UnregisterObserver(); + try { + jni::NativeLease channel(env, caller); + CHECK_HANDLE(channel); - ClearNativeObserver(env, caller, "observerHandle"); + DataChannelObserverSlot::Set(env, caller, "observerHandle", nullptr, ApplyTo(channel)); + } + catch (...) { + ThrowCxxJavaException(env); + } } JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getLabel @@ -216,11 +233,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_dispose return; } - channel->UnregisterObserver(); + auto slot = DataChannelObserverSlot::Take(env, caller, "observerHandle"); - ClearNativeObserver(env, caller, "observerHandle"); + // Runs once no other thread registers through this object any more, so + // the observer it frees is the one the channel has, if any. + jni::ReleaseHandle(env, channel, [channel, slot](bool deferred) { + if (slot) { + channel->UnregisterObserver(); + } - jni::ReleaseHandle(env, channel, [channel](bool deferred) { if (channel->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { jni::NativeHandle::ReportNotDeleted(deferred); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp index 0478dc0e..43bad091 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp @@ -16,6 +16,7 @@ #include "JNI_RTCDtlsTransport.h" #include "NativeHandle.h" +#include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" #include "api/RTCDtlsTransportObserver.h" #include "rtc/RTCCertificatePEM.h" @@ -90,19 +91,18 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_getRemoteCerti namespace { - // Unregisters and frees the observer registered through the Java object. - // WebRTC is told only while that observer is still the registered one: - // another Java object for the same transport may have registered its own - // since, which stays. - void UnregisterOwnObserver(JNIEnv * env, jobject caller, webrtc::DtlsTransportInterface * transport) + using DtlsTransportObserverSlot = jni::ObserverSlot; + + // Registering replaces whatever observer the transport had, also one + // registered through another Java object. WebRTC is told of a removal only + // while the observer removed is still the registered one: another Java + // object for the same transport may have registered its own since, which + // stays. + DtlsTransportObserverSlot::Apply ApplyTo(webrtc::DtlsTransportInterface * transport) { - auto observer = GetHandle(env, caller, "observerHandle"); - - if (jni::RegisteredObservers::Remove(transport, observer)) { - transport->UnregisterObserver(); - } - - ClearNativeObserver(env, caller, "observerHandle"); + return jni::RegisteredObservers::Apply(transport, + [transport](jni::RTCDtlsTransportObserver * observer) { transport->RegisterObserver(observer); }, + [transport]() { transport->UnregisterObserver(); }); } } @@ -115,14 +115,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_registerObserver auto newObserver = new jni::RTCDtlsTransportObserver(env, jni::JavaGlobalRef(env, observer)); - // Registering replaces whatever observer the transport had, also one - // registered through another Java object, so the one registered - // through this object before is out of use and can be freed. - jni::RegisteredObservers::Set(transport, newObserver); - - transport->RegisterObserver(newObserver); - - ReplaceNativeObserver(env, caller, "observerHandle", newObserver); + DtlsTransportObserverSlot::Set(env, caller, "observerHandle", newObserver, ApplyTo(transport)); } catch (...) { ThrowCxxJavaException(env); @@ -132,10 +125,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_registerObserver JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_unregisterObserver (JNIEnv * env, jobject caller) { - jni::NativeLease transport(env, caller); - CHECK_HANDLE(transport); + try { + jni::NativeLease transport(env, caller); + CHECK_HANDLE(transport); - UnregisterOwnObserver(env, caller, transport); + DtlsTransportObserverSlot::Set(env, caller, "observerHandle", nullptr, ApplyTo(transport)); + } + catch (...) { + ThrowCxxJavaException(env); + } } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_dispose @@ -147,13 +145,18 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_dispose return; } - // WebRTC must let go of an observer registered through this object before - // it is deleted. - UnregisterOwnObserver(env, caller, transport); + auto slot = DtlsTransportObserverSlot::Take(env, caller, "observerHandle"); + + // Runs once no other thread registers through this object any more. WebRTC + // must let go of an observer registered through this object before it is + // deleted with the slot. The connection, its senders and receivers, and + // other Java objects keep their own references, so this one need not be + // the last. + jni::ReleaseHandle(env, transport, [transport, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(transport, slot->applied())) { + transport->UnregisterObserver(); + } - // The connection, its senders and receivers, and other Java objects keep - // their own references, so this one need not be the last. - jni::ReleaseHandle(env, transport, [transport](bool) { transport->Release(); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp index 70a716a2..3707522b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp @@ -16,6 +16,7 @@ #include "JNI_RTCDtmfSender.h" #include "NativeHandle.h" +#include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" #include "api/RTCDtmfSenderObserver.h" #include "JavaString.h" @@ -25,19 +26,19 @@ namespace { - // Unregisters and frees the observer registered through the Java object. - // WebRTC is told only while that observer is still the registered one: - // another Java object for the same DTMF sender may have registered its - // own since, which stays. - void UnregisterOwnObserver(JNIEnv * env, jobject caller, webrtc::DtmfSenderInterface * sender) + using DtmfSenderObserverSlot = jni::ObserverSlot; + + // Registering replaces whatever observer the DTMF sender had, also one + // registered through another Java object. It runs on the signaling thread, + // which is also the thread that calls the observer, so the ones replaced + // are out of use once it returns. WebRTC is told of a removal only while + // the observer removed is still the registered one: another Java object + // for the same DTMF sender may have registered its own since, which stays. + DtmfSenderObserverSlot::Apply ApplyTo(webrtc::DtmfSenderInterface * sender) { - auto observer = GetHandle(env, caller, "observerHandle"); - - if (jni::RegisteredObservers::Remove(sender, observer)) { - sender->UnregisterObserver(); - } - - ClearNativeObserver(env, caller, "observerHandle"); + return jni::RegisteredObservers::Apply(sender, + [sender](jni::RTCDtmfSenderObserver * observer) { sender->RegisterObserver(observer); }, + [sender]() { sender->UnregisterObserver(); }); } } @@ -109,15 +110,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_registerObserver auto observer = new jni::RTCDtmfSenderObserver(env, jni::JavaGlobalRef(env, jObserver)); - // Registering replaces whatever observer the DTMF sender had, also one - // registered through another Java object. It runs on the signaling - // thread, which is also the thread that calls the observer, so the one - // registered through this object before is out of use once it returns. - jni::RegisteredObservers::Set(sender, observer); - - sender->RegisterObserver(observer); - - ReplaceNativeObserver(env, caller, "observerHandle", observer); + DtmfSenderObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(sender)); } catch (...) { ThrowCxxJavaException(env); @@ -127,10 +120,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_registerObserver JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_unregisterObserver (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLE(sender); + try { + jni::NativeLease sender(env, caller); + CHECK_HANDLE(sender); - UnregisterOwnObserver(env, caller, sender); + DtmfSenderObserverSlot::Set(env, caller, "observerHandle", nullptr, ApplyTo(sender)); + } + catch (...) { + ThrowCxxJavaException(env); + } } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_dispose @@ -142,13 +140,17 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_dispose return; } - // WebRTC must let go of an observer registered through this object before - // it is deleted. - UnregisterOwnObserver(env, caller, sender); + auto slot = DtmfSenderObserverSlot::Take(env, caller, "observerHandle"); + + // Runs once no other thread registers through this object any more. WebRTC + // must let go of an observer registered through this object before it is + // deleted with the slot. The RTCRtpSender and other Java objects keep their + // own references, so this one need not be the last. + jni::ReleaseHandle(env, sender, [sender, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { + sender->UnregisterObserver(); + } - // The RTCRtpSender and other Java objects keep their own references, so - // this one need not be the last. - jni::ReleaseHandle(env, sender, [sender](bool) { sender->Release(); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp index 7f9391fb..ab6016f5 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp @@ -870,6 +870,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close { webrtc::PeerConnectionInterface * pc; webrtc::PeerConnectionObserver * observer; + jlong factoryHandle = 0; std::atomic pending { 2 }; }; @@ -877,6 +878,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close closing->pc = pc; closing->observer = observer; + // Until the connection is freed, a dispose of the factory waits for it: + // the close and the freeing run on the factory's signaling thread, and + // freeing the connection needs that thread. + if (factoryLease) { + closing->factoryHandle = reinterpret_cast(factoryLease.get()); + + jni::NativeHandle::Pin(closing->factoryHandle); + } + auto free = [closing]() { if (--closing->pending == 0) { // The connection lets go of its observer once closed. @@ -885,6 +895,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close // Drop the owning reference taken when the PeerConnection was // handed to Java in PeerConnectionFactory::createPeerConnection. closing->pc->Release(); + + // May release a factory disposed meanwhile, which then stops its + // threads on a thread of its own when this is one of them. + if (closing->factoryHandle != 0) { + jni::NativeHandle::Unuse(AttachCurrentThread(), closing->factoryHandle); + } } }; diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp index 01904ce2..151db902 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp @@ -16,6 +16,7 @@ #include "JNI_RTCRtpReceiver.h" #include "NativeHandle.h" +#include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" #include "api/RTCRtpParameters.h" #include "api/RTCRtpReceiverObserver.h" @@ -193,6 +194,23 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getId } } +namespace +{ + using RTCRtpReceiverObserverSlot = jni::ObserverSlot; + + // Setting replaces whatever observer the receiver had, also one set through + // another Java object. It runs on the signaling thread, which is also the + // thread that calls the observer, so the ones replaced are out of use once + // it returns. Removing removes only the one set through this object, + // unless another has replaced it since. + RTCRtpReceiverObserverSlot::Apply ApplyTo(webrtc::RtpReceiverInterface * receiver) + { + return jni::RegisteredObservers::Apply(receiver, + [receiver](jni::RTCRtpReceiverObserver * observer) { receiver->SetObserver(observer); }, + [receiver]() { receiver->SetObserver(nullptr); }); + } +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_setObserver (JNIEnv * env, jobject caller, jobject jObserver) { @@ -206,21 +224,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_setObserver observer = new jni::RTCRtpReceiverObserver(env, jni::JavaGlobalRef(env, jObserver)); } - // Setting replaces whatever observer the receiver had, also one set - // through another Java object. Removing removes only the one set - // through this object, unless another has replaced it since. - if (observer != nullptr) { - jni::RegisteredObservers::Set(receiver, observer); - - receiver->SetObserver(observer); - } - else if (jni::RegisteredObservers::Remove(receiver, GetHandle(env, caller, "observerHandle"))) { - receiver->SetObserver(nullptr); - } - - // Runs on the signaling thread, which is also the thread that calls - // the observer, so the previous one is out of use once this returns. - ReplaceNativeObserver(env, caller, "observerHandle", observer); + RTCRtpReceiverObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(receiver)); } catch (...) { ThrowCxxJavaException(env); @@ -236,20 +240,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_dispose return; } - // WebRTC must let go of an observer set through this object before it is - // deleted. One that another Java object has set since stays. - if (jni::RegisteredObservers::Remove(receiver, GetHandle(env, caller, "observerHandle"))) { - receiver->SetObserver(nullptr); - } - - ClearNativeObserver(env, caller, "observerHandle"); + auto slot = RTCRtpReceiverObserverSlot::Take(env, caller, "observerHandle"); // Unlike e.g. MediaStreamTrack, an RTCRtpReceiver is not exclusively // owned by one Java wrapper: the owning RtpTransceiver keeps its own // reference, and other Java wrappers may have been obtained via separate // getReceivers()/getReceiver() calls. Dropping our reference here is // expected to leave others around, so it is not reported as an error. - jni::ReleaseHandle(env, receiver, [receiver](bool) { + // + // Runs once no other thread sets an observer through this object any more. + // WebRTC must let go of an observer set through this object before it is + // deleted with the slot. One that another Java object has set since stays. + jni::ReleaseHandle(env, receiver, [receiver, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(receiver, slot->applied())) { + receiver->SetObserver(nullptr); + } + receiver->Release(); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp index 7c530bb3..9e54e620 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp @@ -17,6 +17,7 @@ #include "JNI_RTCRtpSender.h" #include "NativeHandle.h" #include "api/EncodedFrameInjectorObserver.h" +#include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" #include "api/RTCRtpSenderObserver.h" #include "api/RTCRtpSendParameters.h" @@ -325,6 +326,23 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getStreams } } +namespace +{ + using RTCRtpSenderObserverSlot = jni::ObserverSlot; + + // Setting replaces whatever observer the sender had, also one set through + // another Java object. It runs on the signaling thread, which is also the + // thread that calls the observer, so the ones replaced are out of use once + // it returns. Removing removes only the one set through this object, + // unless another has replaced it since. + RTCRtpSenderObserverSlot::Apply ApplyTo(webrtc::RtpSenderInterface * sender) + { + return jni::RegisteredObservers::Apply(sender, + [sender](jni::RTCRtpSenderObserver * observer) { sender->SetObserver(observer); }, + [sender]() { sender->SetObserver(nullptr); }); + } +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_setObserver (JNIEnv * env, jobject caller, jobject jObserver) { @@ -338,21 +356,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_setObserver observer = new jni::RTCRtpSenderObserver(env, jni::JavaGlobalRef(env, jObserver)); } - // Setting replaces whatever observer the sender had, also one set - // through another Java object. Removing removes only the one set - // through this object, unless another has replaced it since. - if (observer != nullptr) { - jni::RegisteredObservers::Set(sender, observer); - - sender->SetObserver(observer); - } - else if (jni::RegisteredObservers::Remove(sender, GetHandle(env, caller, "observerHandle"))) { - sender->SetObserver(nullptr); - } - - // Runs on the signaling thread, which is also the thread that calls - // the observer, so the previous one is out of use once this returns. - ReplaceNativeObserver(env, caller, "observerHandle", observer); + RTCRtpSenderObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(sender)); } catch (...) { ThrowCxxJavaException(env); @@ -368,20 +372,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_dispose return; } - // WebRTC must let go of an observer set through this object before it is - // deleted. One that another Java object has set since stays. - if (jni::RegisteredObservers::Remove(sender, GetHandle(env, caller, "observerHandle"))) { - sender->SetObserver(nullptr); - } - - ClearNativeObserver(env, caller, "observerHandle"); + auto slot = RTCRtpSenderObserverSlot::Take(env, caller, "observerHandle"); // Unlike e.g. MediaStreamTrack, an RTCRtpSender is not exclusively owned // by one Java wrapper: the owning RtpTransceiver keeps its own reference, // and other Java wrappers may have been obtained via separate // getSenders()/getSender() calls. Dropping our reference here is // expected to leave others around, so it is not reported as an error. - jni::ReleaseHandle(env, sender, [sender](bool) { + // + // Runs once no other thread sets an observer through this object any more. + // WebRTC must let go of an observer set through this object before it is + // deleted with the slot. One that another Java object has set since stays. + jni::ReleaseHandle(env, sender, [sender, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { + sender->SetObserver(nullptr); + } + sender->Release(); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp index b06ee966..1c650713 100644 --- a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp +++ b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp @@ -198,6 +198,15 @@ namespace jni } } + void Pin(jlong handle) + { + Stripe & stripe = StripeOf(handle); + std::lock_guard lock(stripe.mutex); + + // The caller's own use keeps the entry. + stripe.entries[handle].uses++; + } + jlong Take(JNIEnv * env, jobject object) { if (object == nullptr) { diff --git a/webrtc-jni/src/main/cpp/src/api/ObserverSlot.cpp b/webrtc-jni/src/main/cpp/src/api/ObserverSlot.cpp new file mode 100644 index 00000000..8b0d5fab --- /dev/null +++ b/webrtc-jni/src/main/cpp/src/api/ObserverSlot.cpp @@ -0,0 +1,28 @@ +/* + * 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. + */ + +#include "api/ObserverSlot.h" + +namespace jni +{ + std::mutex & ObserverSlotMutex() + { + // Never destroyed: a Java object may be disposed while the process + // shuts down, after static destructors have run. + static std::mutex * mutex = new std::mutex(); + return *mutex; + } +} diff --git a/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackObserver.cpp b/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackObserver.cpp index 7cd27529..bc10daea 100644 --- a/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackObserver.cpp +++ b/webrtc-jni/src/main/cpp/src/media/MediaStreamTrackObserver.cpp @@ -21,8 +21,23 @@ #include "JavaUtils.h" #include "JNI_WebRTC.h" +#include "rtc_base/thread.h" + +#include +#include + namespace jni { + namespace + { + // The callbacks this thread is in. + thread_local int callbackDepth = 0; + + // Work that waits for the end of the outermost callback, on a thread + // that is no WebRTC thread, which could run it after its task. + thread_local std::vector> afterCallbacks; + } + MediaStreamTrackObserver::MediaStreamTrackObserver(JNIEnv * env, const JavaGlobalRef & javaTrack, const webrtc::MediaStreamTrackInterface * track, const MediaStreamTrackEvent & eventType) : javaTrack(javaTrack), track(track), @@ -35,12 +50,43 @@ namespace jni void MediaStreamTrackObserver::OnChanged() { + // Removed, or its track disposed, in an earlier callback of the + // notification under way, which WebRTC goes on with from a copy of its + // list of observers. + if (detached) { + return; + } + JNIEnv * env = AttachCurrentThread(); if (env == nullptr) { return; } + struct CallbackScope + { + CallbackScope() + { + callbackDepth++; + } + + ~CallbackScope() + { + if (--callbackDepth > 0) { + return; + } + + std::vector> work; + work.swap(afterCallbacks); + + for (auto & run : work) { + run(); + } + } + }; + + CallbackScope scope; + // Check state changes. try { @@ -69,6 +115,31 @@ namespace jni trackState = track->state(); } + void MediaStreamTrackObserver::detach() + { + detached = true; + } + + bool MediaStreamTrackObserver::InCallback() + { + return callbackDepth > 0; + } + + void MediaStreamTrackObserver::AfterNotification(std::function work) + { + if (callbackDepth == 0) { + work(); + return; + } + + if (webrtc::Thread * thread = webrtc::Thread::Current()) { + thread->PostTask(std::move(work)); + } + else { + afterCallbacks.push_back(std::move(work)); + } + } + JavaLocalRef MediaStreamTrackObserver::createJavaTrack(JNIEnv * env) { return MediaStreamTrackView::create(env, track); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/PeerConnectionFactory.java b/webrtc/src/main/java/dev/onvoid/webrtc/PeerConnectionFactory.java index 7a46158c..c546377a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/PeerConnectionFactory.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/PeerConnectionFactory.java @@ -476,6 +476,17 @@ public void removeVoiceActivityListener(VoiceActivityListener listener) { } } + /** + * Releases the factory and stops its threads. Connections, tracks and the + * other objects it created are to be closed and disposed before. + *

+ * A connection closed with {@link RTCPeerConnection#close()} is freed on + * the factory's threads, possibly after close() has returned: when it was + * closed from a callback, or while another thread was still in one of its + * methods. Until it is freed, the factory stays: disposing it meanwhile + * returns at once, and the factory is released once the last such + * connection is. + */ @Override public void dispose() { // An AudioProcessing of the application lives on with its listeners. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java index 23674e29..e3a39fea 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java @@ -49,6 +49,12 @@ private RTCDataChannel() { /** * Register an observer to receive events from this RTCDataChannel. The * observer will replace the previously registered observer. + *

+ * Calls from several threads through this object, also while it is + * disposed, are safe: the call made last wins, and one that meets a + * dispose has no effect. While another thread's call through this object + * is still handing an observer to WebRTC, this call may return before + * WebRTC has its observer; the other call hands it on before it returns. * * @param observer The new data channel observer. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java index 5c113595..94f3b2b6 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java @@ -84,6 +84,12 @@ public class RTCDtlsTransport extends DisposableNativeObject { * A transport has one observer, also when several RTCDtlsTransport * instances stand for it: registering through one replaces the observer * registered through another. + *

+ * Calls from several threads through this object, also while it is + * disposed, are safe: the call made last wins, and one that meets a + * dispose has no effect. While another thread's call through this object + * is still handing an observer to WebRTC, this call may return before + * WebRTC has its observer; the other call hands it on before it returns. * * @param observer The new DTLS transport observer. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java index 7c8cd3fc..39bd4939 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java @@ -144,6 +144,12 @@ public class RTCDtmfSender extends DisposableNativeObject { * when one is already registered will replace the existing observer, also * one registered through another RTCDtmfSender instance of the same * {@link RTCRtpSender}. + *

+ * Calls from several threads through this object, also while it is + * disposed, are safe: the call made last wins, and one that meets a + * dispose has no effect. While another thread's call through this object + * is still handing an observer to WebRTC, this call may return before + * WebRTC has its observer; the other call hands it on before it returns. * * @param observer The DTMF sender observer to register. */ @@ -153,8 +159,9 @@ public class RTCDtmfSender extends DisposableNativeObject { * Unregisters the DTMF sender observer last registered through this * instance. *

- * After calling this method, that observer receives no more notifications - * about DTMF-related events. An observer that another instance has + * Once this method has returned, or the call of another thread that was + * handing an observer to WebRTC through this instance at the same time, + * that observer receives no more notifications about DTMF-related events. An observer that another instance has * registered since stays registered. *

* If no observer is currently registered through this instance, this diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java index b8aaa107..2b2702dd 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java @@ -63,6 +63,12 @@ private RTCRtpReceiver() { * another. Removing it, or disposing this object, removes only the * observer set through this object, and only while no other object has * replaced it. + *

+ * Calls from several threads through this object, also while it is + * disposed, are safe: the call made last wins, and one that meets a + * dispose has no effect. While another thread's call through this object + * is still handing an observer to WebRTC, this call may return before + * WebRTC has its observer; the other call hands it on before it returns. * * @param observer The observer, or {@code null}. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java index 80fb08a5..1662c911 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java @@ -65,6 +65,12 @@ private RTCRtpSender() { * another. Removing it, or disposing this object, removes only the * observer set through this object, and only while no other object has * replaced it. + *

+ * Calls from several threads through this object, also while it is + * disposed, are safe: the call made last wins, and one that meets a + * dispose has no effect. While another thread's call through this object + * is still handing an observer to WebRTC, this call may return before + * WebRTC has its observer; the other call hands it on before it returns. * * @param observer The observer, or {@code null}. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaStreamTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaStreamTrack.java index 68a34dae..14c06eac 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaStreamTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/MediaStreamTrack.java @@ -108,6 +108,11 @@ public void removeTrackEndedListener(MediaStreamTrackEndedListener listener) { * only detaches this object; the track and the listeners registered on it * are left as they are. A view is valid for as long as its owner keeps * the track. + *

+ * It may be called from a listener of this track. The listeners that the + * notification has not reached yet are then not called, and the track and + * its listeners are freed once the notification is over. The same holds + * for removing a listener from within a listener. */ @Override public native void dispose(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java index c95bd5a2..de81d6ac 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java @@ -22,13 +22,20 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import dev.onvoid.webrtc.media.MediaStreamTrackMuteListener; import dev.onvoid.webrtc.media.audio.AudioConverter; +import dev.onvoid.webrtc.media.audio.AudioOptions; +import dev.onvoid.webrtc.media.audio.AudioTrack; +import dev.onvoid.webrtc.media.audio.AudioTrackSource; import dev.onvoid.webrtc.media.audio.AudioDeviceModule; import dev.onvoid.webrtc.media.audio.AudioLayer; import dev.onvoid.webrtc.media.video.CustomVideoSource; import dev.onvoid.webrtc.media.video.VideoTrack; import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -270,6 +277,88 @@ void concurrentCloseDuringCall() throws Exception { source.dispose(); } + @Test + void disposeTrackInListener() { + AudioTrackSource source = factory.createAudioSource(new AudioOptions()); + AudioTrack track = factory.createAudioTrack("audio", source); + List calls = Collections.synchronizedList(new ArrayList<>()); + + track.addTrackMuteListener((t, muted) -> { + calls.add("first"); + track.dispose(); + }); + track.addTrackMuteListener((t, muted) -> calls.add("second")); + + // Mute events are delivered before setEnabled() returns. WebRTC calls + // the observers from a copy of their list: before, the dispose freed + // them, its own and the second one included, while it went on. + track.setEnabled(false); + + assertEquals(List.of("first"), calls); + assertDisposed("AudioTrack is disposed", track::isEnabled); + + source.dispose(); + } + + @Test + void removeListenerInListener() { + AudioTrackSource source = factory.createAudioSource(new AudioOptions()); + AudioTrack track = factory.createAudioTrack("audio", source); + List calls = Collections.synchronizedList(new ArrayList<>()); + MediaStreamTrackMuteListener second = (t, muted) -> calls.add("second"); + + track.addTrackMuteListener((t, muted) -> { + calls.add("first"); + track.removeTrackMuteListener(second); + }); + track.addTrackMuteListener(second); + + // Before, the second observer was freed while still in the copy of the + // list WebRTC was going through. + track.setEnabled(false); + track.setEnabled(true); + + assertEquals(List.of("first", "first"), calls); + + track.dispose(); + source.dispose(); + } + + @Test + void disposeFactoryWhileCloseIsPending() throws Exception { + AudioDeviceModule audioModule = new AudioDeviceModule(AudioLayer.kDummyAudio); + PeerConnectionFactory disposable = new PeerConnectionFactory(audioModule); + RTCPeerConnection peerConnection = disposable.createPeerConnection(new RTCConfiguration(), observer); + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = disposable.createVideoTrack("video", source); + HeldList streamIds = new HeldList(); + + // addTrack reads the stream IDs while it uses the native connection. + Future added = executor.submit(() -> peerConnection.addTrack(track, streamIds)); + + streamIds.reached.await(); + + // Closed at once, but freed only once addTrack has returned. The track + // goes then too. + peerConnection.close(); + track.dispose(); + + // Before, this stopped and freed the factory's threads, which addTrack + // and the freeing of the connection then still called into. + disposable.dispose(); + + streamIds.release.countDown(); + + ExecutionException e = assertThrows(ExecutionException.class, added::get); + + assertTrue(e.getCause().getMessage().contains("INVALID_STATE"), e.getCause().getMessage()); + assertDisposed("PeerConnectionFactory is disposed", + () -> disposable.createPeerConnection(new RTCConfiguration(), observer)); + + source.dispose(); + audioModule.dispose(); + } + private static void disposeTwice(Runnable dispose) { dispose.run(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/ObserverRegistrationTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/ObserverRegistrationTests.java new file mode 100644 index 00000000..ab0528a1 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/ObserverRegistrationTests.java @@ -0,0 +1,150 @@ +/* + * 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. + */ + +package dev.onvoid.webrtc; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.onvoid.webrtc.media.MediaType; + +import java.lang.ref.WeakReference; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +/** + * Registering an observer on one thread while another thread registers or + * disposes. A sender that has sent its first packet hands a new observer that + * packet's notification while it is being set, on the signaling thread, so an + * observer that blocks there holds the registration in the middle. + */ +class ObserverRegistrationTests extends TestBase { + + @Test + void setObserverDuringDispose() throws Exception { + try (TestMediaCall call = new TestMediaCall(factory, false, true)) { + RTCRtpSender sender = startCall(call); + BlockingObserver blocking = new BlockingObserver(); + WeakReference ref = setInThread(sender, blocking); + + blocking.entered.await(); + + // The registration is still under way. Before, the dispose freed + // the observer set before, and the registration then stored the + // new one where nothing would ever free it: it stayed registered + // on the sender, which lives on with its transceiver. + sender.dispose(); + + blocking.resume.countDown(); + blocking.thread.join(); + blocking = null; + + assertReleased(ref); + } + } + + @Test + void setObserverWhileAnotherIsSet() throws Exception { + try (TestMediaCall call = new TestMediaCall(factory, false, true)) { + RTCRtpSender sender = startCall(call); + BlockingObserver blocking = new BlockingObserver(); + WeakReference ref = setInThread(sender, blocking); + + blocking.entered.await(); + + // Hands its observer to the call under way, which sets it once its + // own one is set. + CountDownLatch latest = new CountDownLatch(1); + sender.setObserver(mediaType -> latest.countDown()); + + blocking.resume.countDown(); + blocking.thread.join(); + blocking = null; + + assertTrue(latest.await(10, TimeUnit.SECONDS), "Latest observer not set"); + + // Replaced, and so freed. + assertReleased(ref); + + sender.dispose(); + } + } + + private static RTCRtpSender startCall(TestMediaCall call) throws Exception { + call.negotiate(); + call.awaitConnected(); + call.startMedia(); + + // An instance of this test's own, the call disposes of its own one. + RTCRtpSender sender = call.getCallerSenders()[0]; + + CountDownLatch sent = new CountDownLatch(1); + sender.setObserver(mediaType -> sent.countDown()); + + assertTrue(sent.await(10, TimeUnit.SECONDS), "No packet sent"); + + return sender; + } + + /** + * Sets an observer, which blocks in its first notification, on a thread + * of its own. Only the native observer keeps it alive afterwards. + */ + private static WeakReference setInThread(RTCRtpSender sender, + BlockingObserver blocking) { + RTCRtpSenderObserver observer = new RTCRtpSenderObserver() { + + @Override + public void onFirstPacketSent(MediaType mediaType) { + blocking.entered.countDown(); + + try { + blocking.resume.await(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }; + + blocking.thread = new Thread(() -> sender.setObserver(observer), "set-observer"); + blocking.thread.start(); + + return new WeakReference<>(observer); + } + + private static void assertReleased(WeakReference ref) { + for (int i = 0; i < 50 && ref.get() != null; i++) { + System.gc(); + } + + assertTrue(ref.get() == null, "Observer still referenced"); + } + + + + private static class BlockingObserver { + + final CountDownLatch entered = new CountDownLatch(1); + + final CountDownLatch resume = new CountDownLatch(1); + + Thread thread; + + } + +}