Skip to content

Commit 5367e7e

Browse files
authored
fix: close a peer connection at once while another call still uses it (#524)
* 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. * 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.
1 parent 1fb9805 commit 5367e7e

4 files changed

Lines changed: 130 additions & 29 deletions

File tree

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

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
#include "api/rtp_sender_interface.h"
4949
#include "rtc_base/thread.h"
5050

51+
#include <atomic>
5152
#include <memory>
5253
#include <optional>
5354
#include <string>
@@ -861,29 +862,58 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close
861862

862863
SetHandle<std::nullptr_t>(env, caller, "observerHandle", nullptr);
863864

864-
auto close = [pc, observer]() {
865-
pc->Close();
865+
// Closing takes effect at once, also while another thread is still in
866+
// a method of the connection: that method finds it closed. Only freeing
867+
// the observer and the connection waits, both for the close and for the
868+
// last such method, whichever comes later.
869+
struct Closing
870+
{
871+
webrtc::PeerConnectionInterface * pc;
872+
webrtc::PeerConnectionObserver * observer;
873+
std::atomic<int> pending { 2 };
874+
};
875+
876+
auto closing = std::make_shared<Closing>();
877+
closing->pc = pc;
878+
closing->observer = observer;
879+
880+
auto free = [closing]() {
881+
if (--closing->pending == 0) {
882+
// The connection lets go of its observer once closed.
883+
delete closing->observer;
866884

867-
// The connection lets go of its observer once closed.
868-
delete observer;
885+
// Drop the owning reference taken when the PeerConnection was
886+
// handed to Java in PeerConnectionFactory::createPeerConnection.
887+
closing->pc->Release();
888+
}
889+
};
869890

870-
// Drop the owning reference taken when the PeerConnection was handed
871-
// to Java in PeerConnectionFactory::createPeerConnection.
872-
pc->Release();
891+
auto close = [closing, free]() {
892+
closing->pc->Close();
893+
free();
873894
};
874895

896+
// Called from a callback of this or another connection of the same
897+
// factory. WebRTC goes on with the connection once the callback has
898+
// returned, so it must not be closed and freed under its feet.
899+
bool inCallback = signalingThread != nullptr && signalingThread->IsCurrent();
900+
901+
if (inCallback) {
902+
// Runs right after the callback, before what WebRTC posts in turn.
903+
signalingThread->PostTask(close);
904+
}
905+
else {
906+
close();
907+
}
908+
875909
// Runs once no other thread is in a method of this connection any
876910
// more, which may be later, on the thread of the last such method.
877-
jni::ReleaseHandle(env, pc, [close, signalingThread](bool) {
911+
jni::ReleaseHandle(env, pc, [free, signalingThread](bool) {
878912
if (signalingThread != nullptr && signalingThread->IsCurrent()) {
879-
// Called from a callback of this or another connection of the
880-
// same factory. WebRTC goes on with the connection once the
881-
// callback has returned, so it must not be closed and freed under
882-
// its feet.
883-
signalingThread->PostTask(close);
913+
signalingThread->PostTask(free);
884914
}
885915
else {
886-
close();
916+
free();
887917
}
888918
});
889919
}

‎webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -518,9 +518,11 @@ public native void getStats(RTCRtpSender sender,
518518
* closes the connection, later and concurrent ones return without doing
519519
* anything. Methods called after it throw an {@link
520520
* IllegalStateException}, except the state getters, which report a closed
521-
* connection. A method that another thread is running when
522-
* the connection is closed goes on with the native connection, which is
523-
* then closed and freed once that method has returned.
521+
* connection. A method that another thread is running when the connection
522+
* is closed finds it closed from then on; the native connection is freed
523+
* once that method has returned. Until then, observers may still hear of
524+
* operations that WebRTC completed before the close; once it is freed,
525+
* those still unreported fail.
524526
*/
525527
public native void close();
526528

‎webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java‎

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import static org.junit.jupiter.api.Assertions.assertEquals;
2121
import static org.junit.jupiter.api.Assertions.assertNotNull;
2222
import static org.junit.jupiter.api.Assertions.assertThrows;
23+
import static org.junit.jupiter.api.Assertions.assertTrue;
2324

2425
import dev.onvoid.webrtc.media.audio.AudioConverter;
2526
import dev.onvoid.webrtc.media.audio.AudioDeviceModule;
@@ -28,10 +29,13 @@
2829
import dev.onvoid.webrtc.media.video.VideoTrack;
2930

3031
import java.util.AbstractList;
32+
import java.util.concurrent.CompletableFuture;
3133
import java.util.concurrent.CountDownLatch;
34+
import java.util.concurrent.ExecutionException;
3235
import java.util.concurrent.ExecutorService;
3336
import java.util.concurrent.Executors;
3437
import java.util.concurrent.Future;
38+
import java.util.concurrent.TimeUnit;
3539

3640
import org.junit.jupiter.api.AfterEach;
3741
import org.junit.jupiter.api.BeforeEach;
@@ -135,18 +139,75 @@ void closeDuringCall() throws Exception {
135139

136140
streamIds.reached.await();
137141

138-
// Returns although addTrack still uses the connection, which must
139-
// not be freed under it.
142+
// Closes at once, although addTrack still uses the connection, which
143+
// must not be freed under it.
140144
peerConnection.close();
141145

146+
assertEquals(RTCPeerConnectionState.CLOSED, peerConnection.getConnectionState());
147+
142148
streamIds.release.countDown();
143149

144-
RTCRtpSender sender = added.get();
150+
// addTrack goes on with a closed connection.
151+
ExecutionException e = assertThrows(ExecutionException.class, added::get);
145152

146-
assertNotNull(sender);
153+
assertTrue(e.getCause().getMessage().contains("INVALID_STATE"), e.getCause().getMessage());
147154
assertDisposed("RTCPeerConnection is closed", peerConnection::getSenders);
148155

149-
sender.dispose();
156+
track.dispose();
157+
source.dispose();
158+
}
159+
160+
161+
@Test
162+
void closeInCallbackDuringCall() throws Exception {
163+
RTCPeerConnection peerConnection = factory.createPeerConnection(new RTCConfiguration(), observer);
164+
RTCPeerConnection other = factory.createPeerConnection(new RTCConfiguration(), observer);
165+
CustomVideoSource source = new CustomVideoSource();
166+
VideoTrack track = factory.createVideoTrack("video", source);
167+
HeldList streamIds = new HeldList();
168+
TestCreateDescObserver afterClose = new TestCreateDescObserver();
169+
CompletableFuture<Void> closed = new CompletableFuture<>();
170+
171+
Future<RTCRtpSender> added = executor.submit(() -> peerConnection.addTrack(track, streamIds));
172+
173+
streamIds.reached.await();
174+
175+
peerConnection.createOffer(new RTCOfferOptions(), new CreateSessionDescriptionObserver() {
176+
@Override
177+
public void onSuccess(RTCSessionDescription description) {
178+
// On the signaling thread: the close runs once this returns,
179+
// although addTrack still uses the connection. The offer of the
180+
// other connection is posted to this thread after it.
181+
try {
182+
peerConnection.close();
183+
other.createOffer(new RTCOfferOptions(), afterClose);
184+
closed.complete(null);
185+
}
186+
catch (Throwable e) {
187+
closed.completeExceptionally(e);
188+
}
189+
}
190+
191+
@Override
192+
public void onFailure(String error) {
193+
closed.completeExceptionally(new IllegalStateException(error));
194+
}
195+
});
196+
197+
try {
198+
closed.get(5, TimeUnit.SECONDS);
199+
afterClose.get(5, TimeUnit.SECONDS);
200+
}
201+
finally {
202+
streamIds.release.countDown();
203+
}
204+
205+
// addTrack goes on with a connection closed meanwhile.
206+
ExecutionException e = assertThrows(ExecutionException.class, added::get);
207+
208+
assertTrue(e.getCause().getMessage().contains("INVALID_STATE"), e.getCause().getMessage());
209+
210+
other.close();
150211
track.dispose();
151212
source.dispose();
152213
}
@@ -189,8 +250,8 @@ void concurrentCloseDuringCall() throws Exception {
189250

190251
streamIds.reached.await();
191252

192-
// Two threads close at once; only one may get the connection, whose
193-
// close then waits for addTrack.
253+
// Two threads close at once; only one may get the connection, which
254+
// is freed only once addTrack has returned.
194255
CountDownLatch start = new CountDownLatch(1);
195256
Future<?> first = executor.submit(() -> awaitAndRun(start, peerConnection::close));
196257
Future<?> second = executor.submit(() -> awaitAndRun(start, peerConnection::close));
@@ -201,12 +262,10 @@ void concurrentCloseDuringCall() throws Exception {
201262

202263
streamIds.release.countDown();
203264

204-
RTCRtpSender sender = added.get();
205-
206-
assertNotNull(sender);
265+
// addTrack goes on with a closed connection.
266+
assertThrows(ExecutionException.class, added::get);
207267
assertDisposed("RTCPeerConnection is closed", peerConnection::getSenders);
208268

209-
sender.dispose();
210269
track.dispose();
211270
source.dispose();
212271
}

‎webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionSignalingTests.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ void closeBeforeDescriptionResultFailsObserver() throws Exception {
209209
connection.createDataChannel("data", new RTCDataChannelInit());
210210

211211
TestSetDescObserver applied = new TestSetDescObserver();
212+
CountDownLatch issued = new CountDownLatch(1);
212213
CountDownLatch closed = new CountDownLatch(1);
213214
AtomicReference<Throwable> failure = new AtomicReference<>();
214215

@@ -219,8 +220,15 @@ public void onSuccess(RTCSessionDescription description) {
219220
// waits for the offer, whose result is posted to that thread.
220221
// Closing from here takes effect once this returns, before the
221222
// result of setting the description is posted in turn, and
222-
// WebRTC drops that result with the connection.
223+
// WebRTC drops that result with the connection. It does so
224+
// only when the connection is freed right away, which waits
225+
// for every method still running on another thread: here the
226+
// createOffer below, which may not have returned yet.
223227
try {
228+
if (!issued.await(5, TimeUnit.SECONDS)) {
229+
throw new IllegalStateException("createOffer did not return");
230+
}
231+
224232
connection.createOffer(new RTCOfferOptions(), new TestCreateDescObserver());
225233
connection.setLocalDescription(applied);
226234
connection.close();
@@ -238,6 +246,8 @@ public void onFailure(String error) {
238246
}
239247
});
240248

249+
issued.countDown();
250+
241251
assertTrue(closed.await(5, TimeUnit.SECONDS), "Offer was not created");
242252
assertNull(failure.get());
243253

0 commit comments

Comments
 (0)