Skip to content

Commit 9aaea48

Browse files
committed
refactor: split operation chain and perfect negotiation out of PeerImpl
1 parent 2dd25d2 commit 9aaea48

5 files changed

Lines changed: 1158 additions & 499 deletions

File tree

Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import java.time.Duration;
20+
import java.util.ArrayList;
21+
import java.util.List;
22+
import java.util.concurrent.CompletableFuture;
23+
import java.util.concurrent.RejectedExecutionException;
24+
import java.util.concurrent.ScheduledExecutorService;
25+
import java.util.concurrent.TimeUnit;
26+
import java.util.function.BooleanSupplier;
27+
import java.util.function.Supplier;
28+
29+
import dev.onvoid.webrtc.AddIceCandidateObserver;
30+
import dev.onvoid.webrtc.CreateSessionDescriptionObserver;
31+
import dev.onvoid.webrtc.RTCAnswerOptions;
32+
import dev.onvoid.webrtc.RTCIceCandidate;
33+
import dev.onvoid.webrtc.RTCIceGatheringState;
34+
import dev.onvoid.webrtc.RTCOfferOptions;
35+
import dev.onvoid.webrtc.RTCPeerConnection;
36+
import dev.onvoid.webrtc.RTCSdpType;
37+
import dev.onvoid.webrtc.RTCSessionDescription;
38+
import dev.onvoid.webrtc.RTCSignalingState;
39+
import dev.onvoid.webrtc.SetSessionDescriptionObserver;
40+
import dev.onvoid.webrtc.internal.Timeouts;
41+
42+
/**
43+
* The calls into the connection that negotiation is made of, each as a step
44+
* of the running operation of the {@link OperationChain}, so that its timeout
45+
* fails them. WebRTC answers them on its own threads; the answers are posted
46+
* to the control executor, where everything here is confined to.
47+
*/
48+
final class NegotiationSteps {
49+
50+
private final SerialExecutor control;
51+
52+
private final ScheduledExecutorService timer;
53+
54+
private final OperationChain chain;
55+
56+
private final Supplier<RTCPeerConnection> connection;
57+
58+
private final Duration gatheringTimeout;
59+
60+
private final BooleanSupplier ignoringOffer;
61+
62+
/** The remote candidates that came before a remote description. */
63+
private final List<HeldCandidate> heldCandidates = new ArrayList<>();
64+
65+
private final List<CompletableFuture<Void>> gatheringWaiters = new ArrayList<>();
66+
67+
68+
/**
69+
* @param control the control executor of the peer.
70+
* @param timer schedules the end of waiting for gathering.
71+
* @param chain the operations chain the steps belong to.
72+
* @param connection the connection, once there is one.
73+
* @param gatheringTimeout how long to wait for gathering to complete.
74+
* @param ignoringOffer whether the peer ignored a remote offer, whose
75+
* candidates then fail to be added, harmlessly.
76+
*/
77+
NegotiationSteps(SerialExecutor control, ScheduledExecutorService timer, OperationChain chain,
78+
Supplier<RTCPeerConnection> connection, Duration gatheringTimeout, BooleanSupplier ignoringOffer) {
79+
this.control = control;
80+
this.timer = timer;
81+
this.chain = chain;
82+
this.connection = connection;
83+
this.gatheringTimeout = gatheringTimeout;
84+
this.ignoringOffer = ignoringOffer;
85+
}
86+
87+
/**
88+
* Applies the description WebRTC finds for the signaling state, an offer
89+
* or an answer.
90+
*/
91+
CompletableFuture<Void> setLocal() {
92+
CompletableFuture<Void> future = chain.step();
93+
connection.get().setLocalDescription(descriptionObserver(future, "Applying the local description failed"));
94+
return future;
95+
}
96+
97+
CompletableFuture<Void> setLocal(RTCSessionDescription description) {
98+
CompletableFuture<Void> future = chain.step();
99+
connection.get().setLocalDescription(description,
100+
descriptionObserver(future, "Applying the local description failed"));
101+
return future;
102+
}
103+
104+
CompletableFuture<Void> setRemote(RTCSessionDescription description) {
105+
CompletableFuture<Void> future = chain.step();
106+
connection.get().setRemoteDescription(description, descriptionObserver(future,
107+
"Applying the remote " + description.sdpType.name().toLowerCase() + " failed"));
108+
return future;
109+
}
110+
111+
CompletableFuture<RTCSessionDescription> createOffer() {
112+
CompletableFuture<RTCSessionDescription> future = chain.step();
113+
connection.get().createOffer(new RTCOfferOptions(), createObserver(future, "Creating the offer failed"));
114+
return future;
115+
}
116+
117+
CompletableFuture<RTCSessionDescription> createAnswer() {
118+
CompletableFuture<RTCSessionDescription> future = chain.step();
119+
connection.get().createAnswer(new RTCAnswerOptions(), createObserver(future, "Creating the answer failed"));
120+
return future;
121+
}
122+
123+
/**
124+
* Takes back what is pending of an offer/answer exchange, whichever side
125+
* made the offer, so that signaling is stable again.
126+
*/
127+
CompletableFuture<Void> rollback() {
128+
RTCSignalingState state = connection.get().getSignalingState();
129+
130+
if (state == RTCSignalingState.STABLE) {
131+
return CompletableFuture.completedFuture(null);
132+
}
133+
134+
RTCSessionDescription description = new RTCSessionDescription(RTCSdpType.ROLLBACK, "");
135+
136+
return state == RTCSignalingState.HAVE_REMOTE_OFFER || state == RTCSignalingState.HAVE_LOCAL_PR_ANSWER
137+
? setRemote(description)
138+
: setLocal(description);
139+
}
140+
141+
/**
142+
* Adds a remote candidate, or holds it while there is no remote
143+
* description to add it to.
144+
*/
145+
CompletableFuture<Void> addRemoteCandidate(RTCIceCandidate candidate) {
146+
CompletableFuture<Void> future = chain.step();
147+
148+
if (connection.get().getRemoteDescription() == null) {
149+
heldCandidates.add(new HeldCandidate(candidate, future));
150+
}
151+
else {
152+
addCandidate(candidate, future);
153+
}
154+
155+
return future;
156+
}
157+
158+
/**
159+
* Adds the remote candidates held so far, once there is a remote
160+
* description.
161+
*/
162+
void releaseHeldCandidates() {
163+
List<HeldCandidate> held = new ArrayList<>(heldCandidates);
164+
heldCandidates.clear();
165+
166+
for (HeldCandidate candidate : held) {
167+
addCandidate(candidate.candidate, candidate.future);
168+
}
169+
}
170+
171+
/**
172+
* Waits until gathering is complete, or the gathering timeout passed.
173+
*/
174+
CompletableFuture<Void> waitForGathering() {
175+
if (connection.get().getIceGatheringState() == RTCIceGatheringState.COMPLETE) {
176+
return CompletableFuture.completedFuture(null);
177+
}
178+
179+
CompletableFuture<Void> future = chain.step();
180+
gatheringWaiters.add(future);
181+
182+
// A STUN or TURN server that cannot be reached holds up the end of
183+
// gathering for long; the description then goes with what there is.
184+
try {
185+
timer.schedule(() -> control.execute(() -> {
186+
if (gatheringWaiters.remove(future)) {
187+
future.complete(null);
188+
}
189+
}), Timeouts.toMillis(gatheringTimeout), TimeUnit.MILLISECONDS);
190+
}
191+
catch (RejectedExecutionException e) {
192+
// The runtime is closing and has no timer left to wait with.
193+
gatheringWaiters.remove(future);
194+
future.complete(null);
195+
}
196+
197+
return future;
198+
}
199+
200+
/**
201+
* Ends the waiting for gathering, which WebRTC reports complete.
202+
*/
203+
void gatheringComplete() {
204+
List<CompletableFuture<Void>> waiters = new ArrayList<>(gatheringWaiters);
205+
gatheringWaiters.clear();
206+
207+
waiters.forEach(waiter -> waiter.complete(null));
208+
}
209+
210+
/**
211+
* Fails the waiting for gathering and the candidates held, once the peer
212+
* is closing.
213+
*/
214+
void close(PeerClosedException error) {
215+
for (CompletableFuture<Void> waiter : gatheringWaiters) {
216+
waiter.completeExceptionally(error);
217+
}
218+
gatheringWaiters.clear();
219+
220+
for (HeldCandidate candidate : heldCandidates) {
221+
candidate.future.completeExceptionally(error);
222+
}
223+
heldCandidates.clear();
224+
}
225+
226+
private void addCandidate(RTCIceCandidate candidate, CompletableFuture<Void> future) {
227+
connection.get().addIceCandidate(candidate, new AddIceCandidateObserver() {
228+
229+
@Override
230+
public void onSuccess() {
231+
control.execute(() -> future.complete(null));
232+
}
233+
234+
@Override
235+
public void onFailure(String error) {
236+
control.execute(() -> {
237+
if (ignoringOffer.getAsBoolean()) {
238+
// A candidate of an offer this peer ignored.
239+
future.complete(null);
240+
}
241+
else {
242+
future.completeExceptionally(new NegotiationException("Adding a remote candidate failed: "
243+
+ error));
244+
}
245+
});
246+
}
247+
});
248+
}
249+
250+
private SetSessionDescriptionObserver descriptionObserver(CompletableFuture<Void> future, String message) {
251+
return new SetSessionDescriptionObserver() {
252+
253+
@Override
254+
public void onSuccess() {
255+
control.execute(() -> future.complete(null));
256+
}
257+
258+
@Override
259+
public void onFailure(String error) {
260+
control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error)));
261+
}
262+
};
263+
}
264+
265+
private CreateSessionDescriptionObserver createObserver(
266+
CompletableFuture<RTCSessionDescription> future, String message) {
267+
return new CreateSessionDescriptionObserver() {
268+
269+
@Override
270+
public void onSuccess(RTCSessionDescription description) {
271+
control.execute(() -> future.complete(description));
272+
}
273+
274+
@Override
275+
public void onFailure(String error) {
276+
control.execute(() -> future.completeExceptionally(new NegotiationException(message + ": " + error)));
277+
}
278+
};
279+
}
280+
281+
282+
283+
private static final class HeldCandidate {
284+
285+
final RTCIceCandidate candidate;
286+
287+
final CompletableFuture<Void> future;
288+
289+
290+
HeldCandidate(RTCIceCandidate candidate, CompletableFuture<Void> future) {
291+
this.candidate = candidate;
292+
this.future = future;
293+
}
294+
}
295+
}

0 commit comments

Comments
 (0)