diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 396cd0b1..a60e5a93 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -807,7 +807,7 @@ viewer.negotiator().createOffer(Gathering.COMPLETE) | `createOffer()`, `createOffer(Gathering)` | Creates the local offer and applies it. | | `answer(offer)`, `answer(offer, Gathering)` | Applies the remote offer, then creates the answer and applies it. | | `applyAnswer(answer)` | Applies the remote answer to the local offer. | -| `addCandidate(candidate)` | Adds a remote candidate, or holds it until there is a remote description to add it to. | +| `addCandidate(candidate)` | Adds a remote candidate, or holds it until there is a remote description to add it to. The future completes once the candidate is added or held; a held candidate that WebRTC rejects later reaches the error handler. | A manual peer with a `Signaling` still sends its local candidates through it. `peer.negotiator()` throws an `IllegalStateException` on a peer that negotiates automatically. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java index 4df2817b..229d1d9a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java @@ -24,6 +24,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; +import java.util.function.Consumer; import java.util.function.Supplier; import dev.onvoid.webrtc.AddIceCandidateObserver; @@ -59,8 +60,10 @@ final class NegotiationSteps { private final BooleanSupplier ignoringOffer; + private final Consumer candidateRejected; + /** The remote candidates that came before a remote description. */ - private final List heldCandidates = new ArrayList<>(); + private final List heldCandidates = new ArrayList<>(); private final List> gatheringWaiters = new ArrayList<>(); @@ -73,15 +76,19 @@ final class NegotiationSteps { * @param gatheringTimeout how long to wait for gathering to complete. * @param ignoringOffer whether the peer ignored a remote offer, whose * candidates then fail to be added, harmlessly. + * @param candidateRejected told of a held candidate WebRTC rejected, whose + * operation is over by then. */ NegotiationSteps(SerialExecutor control, ScheduledExecutorService timer, OperationChain chain, - Supplier connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer) { + Supplier connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer, + Consumer candidateRejected) { this.control = control; this.timer = timer; this.chain = chain; this.connection = connection; this.gatheringTimeout = gatheringTimeout; this.ignoringOffer = ignoringOffer; + this.candidateRejected = candidateRejected; } /** @@ -140,18 +147,17 @@ CompletableFuture rollback() { /** * Adds a remote candidate, or holds it while there is no remote - * description to add it to. + * description to add it to. Holding it finishes the operation at once, + * since the description may be queued right behind it. */ CompletableFuture addRemoteCandidate(RTCIceCandidate candidate) { - CompletableFuture future = chain.step(); - if (connection.get().getRemoteDescription() == null) { - heldCandidates.add(new HeldCandidate(candidate, future)); - } - else { - addCandidate(candidate, future); + heldCandidates.add(candidate); + return CompletableFuture.completedFuture(null); } + CompletableFuture future = chain.step(); + addCandidate(candidate, future); return future; } @@ -160,11 +166,19 @@ CompletableFuture addRemoteCandidate(RTCIceCandidate candidate) { * description. */ void releaseHeldCandidates() { - List held = new ArrayList<>(heldCandidates); + List held = new ArrayList<>(heldCandidates); heldCandidates.clear(); - for (HeldCandidate candidate : held) { - addCandidate(candidate.candidate, candidate.future); + for (RTCIceCandidate candidate : held) { + CompletableFuture added = new CompletableFuture<>(); + + added.whenComplete((value, error) -> { + if (error != null) { + candidateRejected.accept(PeerImpl.asWebRtcException(error, "Adding a remote candidate failed")); + } + }); + + addCandidate(candidate, added); } } @@ -208,8 +222,8 @@ void gatheringComplete() { } /** - * Fails the waiting for gathering and the candidates held, once the peer - * is closing. + * Fails the waiting for gathering and drops the candidates held, once the + * peer is closing. */ void close(PeerClosedException error) { for (CompletableFuture waiter : gatheringWaiters) { @@ -217,9 +231,6 @@ void close(PeerClosedException error) { } gatheringWaiters.clear(); - for (HeldCandidate candidate : heldCandidates) { - candidate.future.completeExceptionally(error); - } heldCandidates.clear(); } @@ -277,19 +288,4 @@ public void onFailure(String error) { } }; } - - - - private static final class HeldCandidate { - - final RTCIceCandidate candidate; - - final CompletableFuture future; - - - HeldCandidate(RTCIceCandidate candidate, CompletableFuture future) { - this.candidate = candidate; - this.future = future; - } - } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Negotiator.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Negotiator.java index ec97e162..60dd677e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Negotiator.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Negotiator.java @@ -74,11 +74,12 @@ public interface Negotiator { /** * Adds a remote candidate. One that arrives before the remote description - * is held until the description is applied. + * is held until the description is applied, and the steps behind it go + * on. If WebRTC then rejects it, the error handlers of the peer hear of it. * * @param candidate the remote candidate. * - * @return a future that completes once the candidate is added. + * @return a future that completes once the candidate is added or held. */ CompletableFuture addCandidate(RTCIceCandidate candidate); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index ebd030f2..7ec72d36 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -213,7 +213,11 @@ final class PeerImpl implements Peer { this.errorHandlers = new Handlers<>(rtc::reportError); this.chain = new OperationChain(control, rtc.timer, rtc.operationTimeout, name, new ChainHost()); this.steps = new NegotiationSteps(control, rtc.timer, chain, () -> connection, options.gatheringTimeout, - this::ignoresOffer); + this::ignoresOffer, error -> { + if (!closed) { + deliverError(error); + } + }); this.automatic = new PerfectNegotiation(this, options, chain, steps); rtc.track(connected, events); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java index c8bb75c4..3d721039 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java @@ -24,15 +24,19 @@ import java.net.http.HttpClient; import java.time.Duration; +import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import java.util.function.UnaryOperator; +import dev.onvoid.webrtc.RTCIceCandidate; import dev.onvoid.webrtc.RTCSessionDescription; import dev.onvoid.webrtc.RTCSignalingState; @@ -42,6 +46,10 @@ class NegotiationTimeoutTests extends ClientTestBase { private static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(37); + private static final String CANDIDATE_ADDRESS = "203.0.113.7"; + + private static final String CANDIDATE = "candidate:1 1 udp 2122260223 " + CANDIDATE_ADDRESS + " 49203 typ host"; + @Test void lateRestartAnswerDiscarded() throws Exception { lateRestartAnswer(false); @@ -162,6 +170,94 @@ void restartCleanupPrecedesEvents() throws Exception { } } + @Test + void candidateBeforeOffer() throws Exception { + ManualExecutor control = new ManualExecutor(); + ManualExecutor events = new ManualExecutor(); + ManualTimer timer = new ManualTimer(); + WebRtc client = runtime(control, events, timer); + try { + RemoteSignaling signaling = new RemoteSignaling(); + // Nothing to receive, so that it makes no offer of its own to collide. + PeerImpl peer = (PeerImpl) drive(CompletableFuture.supplyAsync(() -> client.createPeer( + PeerOptions.builder().signaling(signaling).build())), control, events); + + // The timeout never fires here, so only the candidate letting the + // chain go on can bring the offer to its answer. + signaling.inbound.accept(SignalMessage.of(new RTCIceCandidate("0", 0, CANDIDATE))); + signaling.inbound.accept(SignalMessage.of(remoteOffer())); + control.runUntil(() -> { + events.runAll(); + return signaling.sent.stream().anyMatch(message -> message.type() == SignalMessage.Type.ANSWER); + }, TIMEOUT_SECONDS); + + assertTrue(remoteSdp(peer, control, events).contains(CANDIDATE_ADDRESS)); + assertEquals(0, timer.scheduled(OPERATION_TIMEOUT)); + } + finally { + close(client, control, events); + } + } + + @Test + void manualCandidateBeforeOffer() throws Exception { + ManualExecutor control = new ManualExecutor(); + ManualExecutor events = new ManualExecutor(); + ManualTimer timer = new ManualTimer(); + WebRtc client = runtime(control, events, timer); + try { + PeerImpl peer = manualPeer(client, control, events); + + // Done once held, so a caller may wait for it before it answers. + drive(peer.negotiator().addCandidate(new RTCIceCandidate("0", 0, CANDIDATE)), control, events); + drive(peer.negotiator().answer(remoteOffer()), control, events); + + assertTrue(remoteSdp(peer, control, events).contains(CANDIDATE_ADDRESS)); + assertEquals(0, timer.scheduled(OPERATION_TIMEOUT)); + } + finally { + close(client, control, events); + } + } + + @Test + void rejectedHeldCandidateReported() throws Exception { + ManualExecutor control = new ManualExecutor(); + ManualExecutor events = new ManualExecutor(); + WebRtc client = runtime(control, events, new ManualTimer()); + try { + PeerImpl peer = manualPeer(client, control, events); + + // The offer has no m-line of this mid. + drive(peer.negotiator().addCandidate(new RTCIceCandidate("9", 9, CANDIDATE)), control, events); + drive(peer.negotiator().answer(remoteOffer()), control, events); + + control.runUntil(() -> { + events.runAll(); + return !errors.isEmpty(); + }, TIMEOUT_SECONDS); + + assertInstanceOf(NegotiationException.class, errors.remove(0)); + } + finally { + close(client, control, events); + } + } + + private PeerImpl manualPeer(WebRtc client, ManualExecutor control, ManualExecutor events) throws Exception { + return (PeerImpl) drive(CompletableFuture.supplyAsync(() -> client.createPeer(PeerOptions.builder() + .negotiation(Negotiation.MANUAL).receive(MediaKind.AUDIO).build())), control, events); + } + + private RTCSessionDescription remoteOffer() throws Exception { + return await(rtc.createPeer(PeerOptions.builder().negotiation(Negotiation.MANUAL) + .receive(MediaKind.AUDIO).build()).negotiator().createOffer()); + } + + private static String remoteSdp(PeerImpl peer, ManualExecutor control, ManualExecutor events) throws Exception { + return drive(peer.withNative(connection -> connection.getRemoteDescription().sdp), control, events); + } + private WebRtc runtime(ManualExecutor control, ManualExecutor events, ManualTimer timer) { return WebRtc.builder().audio(AudioMode.HEADLESS).controlPool(control).eventExecutor(events) .timer(timer).operationTimeout(OPERATION_TIMEOUT).errorHandler(errors::add).build(); @@ -199,4 +295,26 @@ private static T drive(CompletableFuture future, ManualExecutor control, private static void close(WebRtc client, ManualExecutor control, ManualExecutor events) throws Exception { drive(client.closeAsync(), control, events); } + + + + /** The signaling of a peer, with the test as the remote side. */ + private static final class RemoteSignaling implements Signaling { + + final List sent = new CopyOnWriteArrayList<>(); + + volatile Consumer inbound; + + + @Override + public void send(SignalMessage message) { + sent.add(message); + } + + @Override + public Subscription attach(Consumer inbound) { + this.inbound = inbound; + return () -> { }; + } + } }