From 2e1205ed7790f1093eb8bd1b096c0b3867454bac Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 09:30:46 +0100 Subject: [PATCH 1/2] fix: close a peer connection at once while another call still uses it Since the handle leases, close() put off closing the connection until no other thread was in one of its methods, so the connection kept running, and took new tracks, after close() had returned. It is now closed right away (right after the callback when called from one); only freeing the observer and the connection waits for those methods. --- .../main/cpp/src/JNI_RTCPeerConnection.cpp | 58 +++++++++---- .../dev/onvoid/webrtc/RTCPeerConnection.java | 8 +- .../dev/onvoid/webrtc/NativeDisposeTests.java | 81 ++++++++++++++++--- 3 files changed, 119 insertions(+), 28 deletions(-) diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp index 889da03a..7f9391fb 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp @@ -48,6 +48,7 @@ #include "api/rtp_sender_interface.h" #include "rtc_base/thread.h" +#include #include #include #include @@ -861,29 +862,58 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close SetHandle(env, caller, "observerHandle", nullptr); - auto close = [pc, observer]() { - pc->Close(); + // Closing takes effect at once, also while another thread is still in + // a method of the connection: that method finds it closed. Only freeing + // the observer and the connection waits, both for the close and for the + // last such method, whichever comes later. + struct Closing + { + webrtc::PeerConnectionInterface * pc; + webrtc::PeerConnectionObserver * observer; + std::atomic pending { 2 }; + }; + + auto closing = std::make_shared(); + closing->pc = pc; + closing->observer = observer; + + auto free = [closing]() { + if (--closing->pending == 0) { + // The connection lets go of its observer once closed. + delete closing->observer; - // The connection lets go of its observer once closed. - delete observer; + // Drop the owning reference taken when the PeerConnection was + // handed to Java in PeerConnectionFactory::createPeerConnection. + closing->pc->Release(); + } + }; - // Drop the owning reference taken when the PeerConnection was handed - // to Java in PeerConnectionFactory::createPeerConnection. - pc->Release(); + auto close = [closing, free]() { + closing->pc->Close(); + free(); }; + // Called from a callback of this or another connection of the same + // factory. WebRTC goes on with the connection once the callback has + // returned, so it must not be closed and freed under its feet. + bool inCallback = signalingThread != nullptr && signalingThread->IsCurrent(); + + if (inCallback) { + // Runs right after the callback, before what WebRTC posts in turn. + signalingThread->PostTask(close); + } + else { + close(); + } + // Runs once no other thread is in a method of this connection any // more, which may be later, on the thread of the last such method. - jni::ReleaseHandle(env, pc, [close, signalingThread](bool) { + jni::ReleaseHandle(env, pc, [free, signalingThread](bool) { if (signalingThread != nullptr && signalingThread->IsCurrent()) { - // Called from a callback of this or another connection of the - // same factory. WebRTC goes on with the connection once the - // callback has returned, so it must not be closed and freed under - // its feet. - signalingThread->PostTask(close); + signalingThread->PostTask(free); } else { - close(); + free(); } }); } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java index 2562d8ac..7719c87a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java @@ -518,9 +518,11 @@ public native void getStats(RTCRtpSender sender, * closes the connection, later and concurrent ones return without doing * anything. Methods called after it throw an {@link * IllegalStateException}, except the state getters, which report a closed - * connection. A method that another thread is running when - * the connection is closed goes on with the native connection, which is - * then closed and freed once that method has returned. + * connection. A method that another thread is running when the connection + * is closed finds it closed from then on; the native connection is freed + * once that method has returned. Until then, observers may still hear of + * operations that WebRTC completed before the close; once it is freed, + * those still unreported fail. */ public native void close(); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java index 719865d7..c95bd5a2 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import dev.onvoid.webrtc.media.audio.AudioConverter; import dev.onvoid.webrtc.media.audio.AudioDeviceModule; @@ -28,10 +29,13 @@ import dev.onvoid.webrtc.media.video.VideoTrack; import java.util.AbstractList; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -135,18 +139,75 @@ void closeDuringCall() throws Exception { streamIds.reached.await(); - // Returns although addTrack still uses the connection, which must - // not be freed under it. + // Closes at once, although addTrack still uses the connection, which + // must not be freed under it. peerConnection.close(); + assertEquals(RTCPeerConnectionState.CLOSED, peerConnection.getConnectionState()); + streamIds.release.countDown(); - RTCRtpSender sender = added.get(); + // addTrack goes on with a closed connection. + ExecutionException e = assertThrows(ExecutionException.class, added::get); - assertNotNull(sender); + assertTrue(e.getCause().getMessage().contains("INVALID_STATE"), e.getCause().getMessage()); assertDisposed("RTCPeerConnection is closed", peerConnection::getSenders); - sender.dispose(); + track.dispose(); + source.dispose(); + } + + + @Test + void closeInCallbackDuringCall() throws Exception { + RTCPeerConnection peerConnection = factory.createPeerConnection(new RTCConfiguration(), observer); + RTCPeerConnection other = factory.createPeerConnection(new RTCConfiguration(), observer); + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("video", source); + HeldList streamIds = new HeldList(); + TestCreateDescObserver afterClose = new TestCreateDescObserver(); + CompletableFuture closed = new CompletableFuture<>(); + + Future added = executor.submit(() -> peerConnection.addTrack(track, streamIds)); + + streamIds.reached.await(); + + peerConnection.createOffer(new RTCOfferOptions(), new CreateSessionDescriptionObserver() { + @Override + public void onSuccess(RTCSessionDescription description) { + // On the signaling thread: the close runs once this returns, + // although addTrack still uses the connection. The offer of the + // other connection is posted to this thread after it. + try { + peerConnection.close(); + other.createOffer(new RTCOfferOptions(), afterClose); + closed.complete(null); + } + catch (Throwable e) { + closed.completeExceptionally(e); + } + } + + @Override + public void onFailure(String error) { + closed.completeExceptionally(new IllegalStateException(error)); + } + }); + + try { + closed.get(5, TimeUnit.SECONDS); + afterClose.get(5, TimeUnit.SECONDS); + } + finally { + streamIds.release.countDown(); + } + + // addTrack goes on with a connection closed meanwhile. + ExecutionException e = assertThrows(ExecutionException.class, added::get); + + assertTrue(e.getCause().getMessage().contains("INVALID_STATE"), e.getCause().getMessage()); + + other.close(); track.dispose(); source.dispose(); } @@ -189,8 +250,8 @@ void concurrentCloseDuringCall() throws Exception { streamIds.reached.await(); - // Two threads close at once; only one may get the connection, whose - // close then waits for addTrack. + // Two threads close at once; only one may get the connection, which + // is freed only once addTrack has returned. CountDownLatch start = new CountDownLatch(1); Future first = executor.submit(() -> awaitAndRun(start, peerConnection::close)); Future second = executor.submit(() -> awaitAndRun(start, peerConnection::close)); @@ -201,12 +262,10 @@ void concurrentCloseDuringCall() throws Exception { streamIds.release.countDown(); - RTCRtpSender sender = added.get(); - - assertNotNull(sender); + // addTrack goes on with a closed connection. + assertThrows(ExecutionException.class, added::get); assertDisposed("RTCPeerConnection is closed", peerConnection::getSenders); - sender.dispose(); track.dispose(); source.dispose(); } From 71ffa300b441574bf93a0ea91aced52d5f17ee0d Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 09:30:46 +0100 Subject: [PATCH 2/2] test: close in the description callback only once createOffer has returned The result of setting the description is dropped only when the connection is freed right after the callback, which waits for methods running on other threads: the createOffer of the test thread had not always returned. --- .../webrtc/RTCPeerConnectionSignalingTests.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionSignalingTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionSignalingTests.java index 6097c2f6..c94d45bf 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionSignalingTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionSignalingTests.java @@ -209,6 +209,7 @@ void closeBeforeDescriptionResultFailsObserver() throws Exception { connection.createDataChannel("data", new RTCDataChannelInit()); TestSetDescObserver applied = new TestSetDescObserver(); + CountDownLatch issued = new CountDownLatch(1); CountDownLatch closed = new CountDownLatch(1); AtomicReference failure = new AtomicReference<>(); @@ -219,8 +220,15 @@ public void onSuccess(RTCSessionDescription description) { // waits for the offer, whose result is posted to that thread. // Closing from here takes effect once this returns, before the // result of setting the description is posted in turn, and - // WebRTC drops that result with the connection. + // WebRTC drops that result with the connection. It does so + // only when the connection is freed right away, which waits + // for every method still running on another thread: here the + // createOffer below, which may not have returned yet. try { + if (!issued.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("createOffer did not return"); + } + connection.createOffer(new RTCOfferOptions(), new TestCreateDescObserver()); connection.setLocalDescription(applied); connection.close(); @@ -238,6 +246,8 @@ public void onFailure(String error) { } }); + issued.countDown(); + assertTrue(closed.await(5, TimeUnit.SECONDS), "Offer was not created"); assertNull(failure.get());