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
2 changes: 1 addition & 1 deletion docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
60 changes: 28 additions & 32 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/NegotiationSteps.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -59,8 +60,10 @@ final class NegotiationSteps {

private final BooleanSupplier ignoringOffer;

private final Consumer<WebRtcException> candidateRejected;

/** The remote candidates that came before a remote description. */
private final List<HeldCandidate> heldCandidates = new ArrayList<>();
private final List<RTCIceCandidate> heldCandidates = new ArrayList<>();

private final List<CompletableFuture<Void>> gatheringWaiters = new ArrayList<>();

Expand All @@ -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<RTCPeerConnection> connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer) {
Supplier<RTCPeerConnection> connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer,
Consumer<WebRtcException> candidateRejected) {
this.control = control;
this.timer = timer;
this.chain = chain;
this.connection = connection;
this.gatheringTimeout = gatheringTimeout;
this.ignoringOffer = ignoringOffer;
this.candidateRejected = candidateRejected;
}

/**
Expand Down Expand Up @@ -140,18 +147,17 @@ CompletableFuture<Void> 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<Void> addRemoteCandidate(RTCIceCandidate candidate) {
CompletableFuture<Void> 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<Void> future = chain.step();
addCandidate(candidate, future);
return future;
}

Expand All @@ -160,11 +166,19 @@ CompletableFuture<Void> addRemoteCandidate(RTCIceCandidate candidate) {
* description.
*/
void releaseHeldCandidates() {
List<HeldCandidate> held = new ArrayList<>(heldCandidates);
List<RTCIceCandidate> held = new ArrayList<>(heldCandidates);
heldCandidates.clear();

for (HeldCandidate candidate : held) {
addCandidate(candidate.candidate, candidate.future);
for (RTCIceCandidate candidate : held) {
CompletableFuture<Void> added = new CompletableFuture<>();

added.whenComplete((value, error) -> {
if (error != null) {
candidateRejected.accept(PeerImpl.asWebRtcException(error, "Adding a remote candidate failed"));
}
});

addCandidate(candidate, added);
}
}

Expand Down Expand Up @@ -208,18 +222,15 @@ 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<Void> waiter : gatheringWaiters) {
waiter.completeExceptionally(error);
}
gatheringWaiters.clear();

for (HeldCandidate candidate : heldCandidates) {
candidate.future.completeExceptionally(error);
}
heldCandidates.clear();
}

Expand Down Expand Up @@ -277,19 +288,4 @@ public void onFailure(String error) {
}
};
}



private static final class HeldCandidate {

final RTCIceCandidate candidate;

final CompletableFuture<Void> future;


HeldCandidate(RTCIceCandidate candidate, CompletableFuture<Void> future) {
this.candidate = candidate;
this.future = future;
}
}
}
5 changes: 3 additions & 2 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/Negotiator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> addCandidate(RTCIceCandidate candidate);

Expand Down
6 changes: 5 additions & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -199,4 +295,26 @@ private static <T> T drive(CompletableFuture<T> 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<SignalMessage> sent = new CopyOnWriteArrayList<>();

volatile Consumer<SignalMessage> inbound;


@Override
public void send(SignalMessage message) {
sent.add(message);
}

@Override
public Subscription attach(Consumer<SignalMessage> inbound) {
this.inbound = inbound;
return () -> { };
}
}
}
Loading