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
58 changes: 44 additions & 14 deletions webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
#include "api/rtp_sender_interface.h"
#include "rtc_base/thread.h"

#include <atomic>
#include <memory>
#include <optional>
#include <string>
Expand Down Expand Up @@ -861,29 +862,58 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close

SetHandle<std::nullptr_t>(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<int> pending { 2 };
};

auto closing = std::make_shared<Closing>();
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();
}
});
}
Expand Down
8 changes: 5 additions & 3 deletions webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
81 changes: 70 additions & 11 deletions webrtc/src/test/java/dev/onvoid/webrtc/NativeDisposeTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<Void> closed = new CompletableFuture<>();

Future<RTCRtpSender> 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();
}
Expand Down Expand Up @@ -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));
Expand All @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Throwable> failure = new AtomicReference<>();

Expand All @@ -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();
Expand All @@ -238,6 +246,8 @@ public void onFailure(String error) {
}
});

issued.countDown();

assertTrue(closed.await(5, TimeUnit.SECONDS), "Offer was not created");
assertNull(failure.get());

Expand Down
Loading