Skip to content

Commit d013e71

Browse files
committed
feat: answer WHEP counter-offers
A WHEP endpoint may reject the offer with a 406 that carries its own SDP offer. The player now rolls its offer back, answers the endpoint's, receiving only, and sends the answer by PATCH to the session named in Location before valid-until. Any other 406 stays an error, as does a 406 to WHIP.
1 parent 05951a2 commit d013e71

8 files changed

Lines changed: 466 additions & 38 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,7 @@ Whep.Session viewer = Whep.from(URI.create("https://example.com/live/whep"))
598598
viewer.peer().onTrack(track -> System.out.println("Receiving " + track.kind()));
599599
```
600600

601-
The offer goes to the endpoint with the local candidates, as WHIP and WHEP servers expect, and the future completes once the peer is connected. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. An endpoint that is busy, with status 503, or a WHEP endpoint whose stream has yet to start, with status 409, gets the offer again after the wait its `Retry-After` names, at least a second, as long as that fits within the timeout; without `Retry-After` the session fails at once. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none.
601+
The offer goes to the endpoint with the local candidates, as WHIP and WHEP servers expect, and the future completes once the peer is connected. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. An endpoint that is busy, with status 503, or a WHEP endpoint whose stream has yet to start, with status 409, gets the offer again after the wait its `Retry-After` names, at least a second, as long as that fits within the timeout; without `Retry-After` the session fails at once. A WHEP endpoint may also reject the offer and counter it with one of its own, with status 406: `Whep` then takes its offer back, answers the endpoint's, receiving only, and sends the answer by `PATCH` to the session the endpoint named, before the counter-offer's `valid-until`, 30 seconds by default. Every m-line of the counter-offer is accepted. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none.
602602

603603
The timeout bounds the requests as a whole, not each read, so a server that sends its answer a byte at a time cannot stretch it. A request still out when the session times out or is cancelled is cut off at once; one still waiting for the head of its answer only from Java 16 on, and before that at its timeout. Once the server has named the session, in the head of its answer, it is deleted all the same; a session the server created for an answer that had not come yet is left for the server to time out.
604604

‎webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ final class HttpCall {
103103

104104
private Set<Integer> retryStatuses = Collections.emptySet();
105105

106+
/** Statuses other than 2xx whose body is read as that of a 2xx one. */
107+
private Set<Integer> answerStatuses = Collections.emptySet();
108+
106109
/** The exchange under way, which an abort cancels. */
107110
private CompletableFuture<?> exchange;
108111

@@ -184,6 +187,20 @@ HttpCall retry(ScheduledExecutorService timer, Set<Integer> statuses) {
184187
return this;
185188
}
186189

190+
/**
191+
* Reads the body of a response with one of the given statuses as that of
192+
* a 2xx one, up to the size {@link #send} is given, rather than only as
193+
* much as a message takes.
194+
*
195+
* @param statuses the statuses whose bodies are read in full.
196+
*
197+
* @return this request.
198+
*/
199+
HttpCall readBodies(Set<Integer> statuses) {
200+
this.answerStatuses = statuses;
201+
return this;
202+
}
203+
187204
/**
188205
* Follows redirects with status 307 and 308, up to {@link #MAX_REDIRECTS}
189206
* of them, with the bearer token. One from https to plain http fails.
@@ -341,7 +358,7 @@ private HttpResponse.BodySubscriber<String> head(HttpResponse.ResponseInfo info,
341358
Consumer<Response> onHead) {
342359
int status = info.statusCode();
343360
boolean redirect = isRedirect(status, info.headers().firstValue("Location").orElse(null));
344-
boolean success = status / 100 == 2;
361+
boolean success = status / 100 == 2 || answerStatuses.contains(status);
345362
// A redirect's body is not read, and neither is an error's beyond what
346363
// a message takes.
347364
Body body = new Body(redirect ? 0 : success ? maxBody : MAX_ERROR_BODY, !success || redirect);

‎webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java‎

Lines changed: 222 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,13 @@
1919
import static java.util.Objects.requireNonNull;
2020

2121
import java.net.URI;
22+
import java.net.http.HttpClient;
2223
import java.nio.charset.StandardCharsets;
2324
import java.time.Duration;
25+
import java.time.ZonedDateTime;
26+
import java.time.format.DateTimeFormatter;
27+
import java.time.format.DateTimeParseException;
28+
import java.util.Collections;
2429
import java.util.Set;
2530
import java.util.concurrent.CancellationException;
2631
import java.util.concurrent.CompletableFuture;
@@ -30,6 +35,8 @@
3035
import java.util.concurrent.atomic.AtomicBoolean;
3136
import java.util.concurrent.atomic.AtomicReference;
3237
import java.util.function.Consumer;
38+
import java.util.regex.Matcher;
39+
import java.util.regex.Pattern;
3340

3441
import dev.onvoid.webrtc.RTCSdpType;
3542
import dev.onvoid.webrtc.RTCSessionDescription;
@@ -45,6 +52,16 @@ abstract class HttpSession implements AutoCloseable {
4552
/** The largest answer read; an SDP answer is a few kilobytes. */
4653
private static final int MAX_BODY = 1 << 20;
4754

55+
/** The status of a counter-offer, whose body is an offer to answer. */
56+
private static final Set<Integer> COUNTER_OFFER = Set.of(406);
57+
58+
/** How long a counter-offer can be answered if it does not say. */
59+
private static final long COUNTER_OFFER_VALIDITY_MILLIS = 30_000;
60+
61+
/** The "valid-until" parameter of a counter-offer's Content-Type. */
62+
private static final Pattern VALID_UNTIL = Pattern.compile(";\\s*valid-until\\s*=\\s*\"?([^\";]+)\"?",
63+
Pattern.CASE_INSENSITIVE);
64+
4865
private final Peer peer;
4966

5067
private final URI resource;
@@ -130,21 +147,19 @@ public void close() {
130147
* connected. A caller that stops waiting, by cancelling the future or
131148
* completing it itself, ends the negotiation, and a session made too late
132149
* for the future is closed: either way the peer is closed and what the
133-
* server named is deleted. An offer still out is cut off then, so that
134-
* a server that does not answer holds no thread; what it creates for an
135-
* offer it had yet to answer is left for it to time out.
150+
* server named is deleted. A request still out is cut off then, so that
151+
* a server that does not answer holds no connection; what it creates for
152+
* an offer it had yet to answer is left for it to time out.
136153
*
137-
* @param retried the statuses of an answer to the offer, together with a
138-
* Retry-After header field, after which the offer is sent
139-
* again, as long as the wait fits within the timeout.
140-
* @param factory makes the session of the connected peer.
154+
* @param protocol what WHIP or WHEP asks beyond the offer and its answer.
155+
* @param factory makes the session of the connected peer.
141156
*
142157
* @return the future handed to the application.
143158
*/
144159
static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl peer, URI endpoint,
145-
String bearerToken, Duration timeout, Set<Integer> retried, Factory<S> factory) {
160+
String bearerToken, Duration timeout, Protocol protocol, Factory<S> factory) {
146161
CompletableFuture<Void> abandoned = new CompletableFuture<>();
147-
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, retried,
162+
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, protocol,
148163
abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout)),
149164
HttpSession::close);
150165

@@ -156,34 +171,42 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
156171

157172
/**
158173
* Negotiates a manual peer over HTTP: creates the offer with all candidates,
159-
* posts it, applies the answer and waits until the peer is connected.
174+
* posts it, applies the answer and waits until the peer is connected. An
175+
* endpoint that counters the offer, as WHEP allows, gets the answer to its
176+
* own offer instead.
160177
*
161178
* @param abandoned completes when no one waits for the session anymore,
162179
* which then ends as if it had failed.
163180
*
164181
* @return a future with the resource the server named, or null.
165182
*/
166-
private static CompletableFuture<URI> negotiate(WebRtc rtc, Peer peer, URI endpoint, String bearerToken,
167-
Duration timeout, Set<Integer> retried, CompletableFuture<?> abandoned) {
183+
private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI endpoint, String bearerToken,
184+
Duration timeout, Protocol protocol, CompletableFuture<?> abandoned) {
168185
CompletableFuture<URI> result = new CompletableFuture<>();
186+
long started = System.nanoTime();
169187
// The resource the server created. Whoever takes it out owns it: the
170188
// session that connected, or whoever deletes it.
171189
AtomicReference<URI> resource = new AtomicReference<>();
172190
AtomicBoolean finished = new AtomicBoolean();
191+
HttpClient client = rtc.httpClient(bearerToken != null);
173192
// Made now, so that it ends with the session's deadline at the latest,
174193
// however long the offer takes.
175-
HttpCall offerRequest = new HttpCall(rtc.httpClient(bearerToken != null), endpoint, "POST", bearerToken,
176-
timeout).followRedirects().retry(rtc.timer, retried);
194+
HttpCall offerRequest = new HttpCall(client, endpoint, "POST", bearerToken, timeout)
195+
.followRedirects()
196+
.retry(rtc.timer, protocol.retried)
197+
.readBodies(protocol.counterOffers ? COUNTER_OFFER : Collections.emptySet());
198+
// The request under way, which the end of the session cuts off.
199+
AtomicReference<HttpCall> request = new AtomicReference<>(offerRequest);
177200

178201
// Either way the session ends, once: connected, failed or timed out.
179202
Consumer<Throwable> fail = error -> {
180203
if (!finished.compareAndSet(false, true)) {
181204
return;
182205
}
183206

184-
// Ends an offer still out, whose answer would only meet a closed
207+
// Ends a request still out, whose answer would only meet a closed
185208
// peer.
186-
offerRequest.abort();
209+
request.get().abort();
187210
// Reported before the resource is deleted, which may take as long
188211
// as the timeout again.
189212
peer.close();
@@ -203,17 +226,27 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, Peer peer, URI endpo
203226
});
204227

205228
peer.negotiator().createOffer(Gathering.COMPLETE)
206-
.thenCompose(offer -> post(offerRequest, endpoint, offer.sdp, resource)
207-
.whenComplete((answer, error) -> {
229+
.thenCompose(offer -> post(offerRequest, endpoint, offer.sdp, protocol, resource)
230+
.whenComplete((reply, error) -> {
208231
if (finished.get()) {
209232
// The session ended while the offer was out,
210233
// after the server named what it created, which
211234
// then has no one else to delete it.
212235
discard(rtc, resource.getAndSet(null), bearerToken, timeout);
213236
}
214237
}))
215-
.thenCompose(answer -> peer.negotiator()
216-
.applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, answer)))
238+
.thenCompose(reply -> {
239+
if (!reply.counterOffer) {
240+
return peer.negotiator().applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp));
241+
}
242+
243+
// The rest of the session's time, which the answer has.
244+
Duration left = timeout.minusNanos(System.nanoTime() - started);
245+
246+
return answerCounterOffer(rtc, client, peer, reply, bearerToken,
247+
left.isNegative() || left.isZero() ? Duration.ofNanos(1) : left, resource, request,
248+
finished);
249+
})
217250
.thenCompose(applied -> peer.whenConnected())
218251
.whenComplete((connected, error) -> {
219252
deadline.cancel(false);
@@ -230,12 +263,13 @@ else if (finished.compareAndSet(false, true)) {
230263
}
231264

232265
/**
233-
* Posts the offer and returns the answer. The resource the server names is
234-
* set as soon as it is known, so that it is deleted even if reading the
235-
* answer fails. The request follows the redirects WHIP and WHEP allow, and
236-
* the resource is resolved against the endpoint that answered.
266+
* Posts the offer and returns what the endpoint answered with. The
267+
* resource the server names with an answer is set as soon as it is known,
268+
* so that it is deleted even if reading the answer fails. The request
269+
* follows the redirects WHIP and WHEP allow, and the resource is resolved
270+
* against the endpoint that answered.
237271
*/
238-
private static CompletableFuture<String> post(HttpCall request, URI endpoint, String sdp,
272+
private static CompletableFuture<Reply> post(HttpCall request, URI endpoint, String sdp, Protocol protocol,
239273
AtomicReference<URI> resource) {
240274
return request.send("application/sdp", sdp.getBytes(StandardCharsets.UTF_8), MAX_BODY, head -> {
241275
if (head.status == 201 || head.status == 200) {
@@ -249,15 +283,174 @@ private static CompletableFuture<String> post(HttpCall request, URI endpoint, St
249283
throw new WebRtcException("Sending the offer to " + endpoint + " failed: " + error.getMessage(),
250284
error);
251285
}
252-
if (response.status != 201 && response.status != 200) {
253-
throw new WebRtcException("The endpoint " + endpoint + " answered the offer with status "
254-
+ response.status + ": " + response.body);
286+
if (response.status == 201 || response.status == 200) {
287+
return new Reply(response.body, false, null, 0);
255288
}
289+
if (protocol.counterOffers && isCounterOffer(response)) {
290+
URI session = resourceOf(response.uri, response.header("Location"));
291+
292+
if (session == null) {
293+
throw new WebRtcException("The endpoint " + endpoint
294+
+ " countered the offer without naming the session");
295+
}
256296

257-
return response.body;
297+
return new Reply(response.body, true, session,
298+
counterOfferExpiry(response.header("Content-Type"), System.currentTimeMillis()));
299+
}
300+
301+
String body = response.body;
302+
303+
if (body.length() > HttpCall.MAX_ERROR_BODY) {
304+
body = body.substring(0, HttpCall.MAX_ERROR_BODY);
305+
}
306+
307+
throw new WebRtcException("The endpoint " + endpoint + " answered the offer with status "
308+
+ response.status + ": " + body);
258309
});
259310
}
260311

312+
/**
313+
* Answers the endpoint's own offer, which replaces the peer's, and sends
314+
* the answer to the session the endpoint named. The session is the
315+
* peer's to delete from the moment the answer goes out, since the server
316+
* creates it only then.
317+
*
318+
* @param timeout what is left of the session's timeout.
319+
*/
320+
private static CompletableFuture<Void> answerCounterOffer(WebRtc rtc, HttpClient client, PeerImpl peer,
321+
Reply reply, String bearerToken, Duration timeout, AtomicReference<URI> resource,
322+
AtomicReference<HttpCall> request, AtomicBoolean finished) {
323+
return peer.answerInstead(new RTCSessionDescription(RTCSdpType.OFFER, reply.sdp), Gathering.COMPLETE)
324+
.thenCompose(answer -> {
325+
if (System.currentTimeMillis() > reply.validUntil) {
326+
throw new WebRtcException("The counter-offer for " + reply.session
327+
+ " expired before it was answered");
328+
}
329+
330+
HttpCall answerRequest = new HttpCall(client, reply.session, "PATCH", bearerToken, timeout);
331+
request.set(answerRequest);
332+
333+
if (finished.get()) {
334+
// Ended meanwhile, by what may have aborted the request
335+
// before.
336+
answerRequest.abort();
337+
}
338+
else {
339+
resource.set(reply.session);
340+
}
341+
342+
return answerRequest.send("application/sdp", answer.sdp.getBytes(StandardCharsets.UTF_8), 0,
343+
head -> { }).handle((response, error) -> {
344+
if (error != null) {
345+
throw new WebRtcException("Sending the answer to " + reply.session + " failed: "
346+
+ error.getMessage(), error);
347+
}
348+
if (response.status / 100 != 2) {
349+
throw new WebRtcException("The endpoint answered the answer for "
350+
+ reply.session + " with status " + response.status + ": "
351+
+ response.body);
352+
}
353+
354+
return null;
355+
});
356+
});
357+
}
358+
359+
/**
360+
* Tells a counter-offer from any other 406 answer, which WHEP asks to be
361+
* taken as an error: one has an SDP offer as its body.
362+
*/
363+
private static boolean isCounterOffer(HttpCall.Response response) {
364+
String type = response.header("Content-Type");
365+
366+
if (response.status != 406 || type == null) {
367+
return false;
368+
}
369+
370+
String mediaType = type.split(";", 2)[0].trim();
371+
372+
return mediaType.equalsIgnoreCase("application/sdp") && response.body.startsWith("v=0")
373+
&& response.body.contains("\nm=");
374+
}
375+
376+
/**
377+
* Reads until when a counter-offer can be answered: the "valid-until"
378+
* parameter of its Content-Type, an HTTP date, or else 30 seconds after
379+
* it came, as WHEP says.
380+
*
381+
* @param contentType the Content-Type of the counter-offer.
382+
* @param nowMillis the time it came, as {@link System#currentTimeMillis()}.
383+
*
384+
* @return the time, as {@link System#currentTimeMillis()}.
385+
*/
386+
static long counterOfferExpiry(String contentType, long nowMillis) {
387+
Matcher validUntil = VALID_UNTIL.matcher(contentType != null ? contentType : "");
388+
389+
if (validUntil.find()) {
390+
try {
391+
return ZonedDateTime.parse(validUntil.group(1).trim(), DateTimeFormatter.RFC_1123_DATE_TIME)
392+
.toInstant().toEpochMilli();
393+
}
394+
catch (DateTimeParseException e) {
395+
// Not an HTTP date; as if there were none.
396+
}
397+
}
398+
399+
return nowMillis + COUNTER_OFFER_VALIDITY_MILLIS;
400+
}
401+
402+
/**
403+
* What WHIP or WHEP asks of a session beyond the offer and its answer.
404+
*/
405+
static final class Protocol {
406+
407+
/**
408+
* The statuses of an answer to the offer, together with a Retry-After
409+
* header field, after which the offer is sent again, as long as the
410+
* wait fits within the timeout.
411+
*/
412+
final Set<Integer> retried;
413+
414+
/** Whether the endpoint may counter the offer with one of its own. */
415+
final boolean counterOffers;
416+
417+
418+
Protocol(Set<Integer> retried, boolean counterOffers) {
419+
this.retried = retried;
420+
this.counterOffers = counterOffers;
421+
}
422+
}
423+
424+
425+
426+
/**
427+
* What the endpoint answered the offer with: an answer, or an offer of its
428+
* own.
429+
*/
430+
private static final class Reply {
431+
432+
final String sdp;
433+
434+
/** Whether the SDP is the endpoint's offer, which replaces the peer's. */
435+
final boolean counterOffer;
436+
437+
/** Where the session is once a counter-offer is answered. */
438+
final URI session;
439+
440+
/** Until when a counter-offer can be answered. */
441+
final long validUntil;
442+
443+
444+
Reply(String sdp, boolean counterOffer, URI session, long validUntil) {
445+
this.sdp = sdp;
446+
this.counterOffer = counterOffer;
447+
this.session = session;
448+
this.validUntil = validUntil;
449+
}
450+
}
451+
452+
453+
261454
/**
262455
* Makes the session of a peer that connected.
263456
*

0 commit comments

Comments
 (0)