diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 348c3b8a3..2f056eb2c 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -598,7 +598,11 @@ Whep.Session viewer = Whep.from(URI.create("https://example.com/live/whep")) viewer.peer().onTrack(track -> System.out.println("Receiving " + track.kind())); ``` -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. The answer rejects the audio or video of the counter-offer that `receive(...)` leaves out, and the session fails if the counter-offer holds none of what it asks for. Data channels of a counter-offer are 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. +The offer goes to the endpoint at once, before any candidate is gathered, 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. The answer rejects the audio or video of the counter-offer that `receive(...)` leaves out, and the session fails if the counter-offer holds none of what it asks for. Data channels of a counter-offer are 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. + +Only once the endpoint answered does the peer gather its candidates, with the STUN and TURN servers the endpoint names in `Link` headers with `rel="ice-server"`, unless `iceServer(...)` names servers of its own, which take precedence. The candidates follow the offer by `PATCH` to the session, as `application/trickle-ice-sdpfrag`, a few at a time and with the session's `ETag` as `If-Match`, as RFC 9725 describes. An endpoint that takes no such `PATCH`, with status 405, 415, 422 or 501, gets no more; it finds the peer all the same, from the checks the peer sends to its candidates. + +When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200, brings its own ICE information and a new `ETag`. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. A session that answered a WHEP counter-offer takes no restarts. 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. @@ -613,7 +617,7 @@ Requests go through Java's `HttpClient`, with the default `SSLContext` and the H | Builder method | What it sets | |---|---| | `bearerToken(String)` | The token sent as `Authorization: Bearer`; for many services, the stream key. | -| `iceServer(String...)` | A STUN or TURN server; endpoints usually name their own in the answer. | +| `iceServer(String...)` | A STUN or TURN server, which replaces those the endpoint names in its answer. | | `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream. | | `receive(MediaKind...)` | What to receive, WHEP only; video and audio by default. | | `timeout(Duration)` | How long the session may take to be connected, and its deletion to be answered. | diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java index 18f729f6a..785b8b0b7 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java @@ -35,8 +35,8 @@ *
  • Ending the session, which deletes it on the server
  • * *

    - * {@link Whep} sends an offer with all local candidates, applies the answer and waits until - * the peer is connected. The Client API guide shows the same steps by hand, through the + * {@link Whep} sends an offer, trickles the local candidates after it, applies the answer and + * waits until the peer is connected. The Client API guide shows the same steps by hand, through the * peer's negotiator, for servers that speak a protocol of their own. *

    * Run it against a WHEP endpoint, such as one of MediaMTX, for a number of seconds: diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java index 5921e33a4..1b70bd78a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java @@ -37,6 +37,7 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -108,6 +109,9 @@ final class HttpCall { /** Statuses other than 2xx whose body is read as that of a 2xx one. */ private Set answerStatuses = Collections.emptySet(); + /** Header fields the request carries beyond those it sets itself. */ + private final Map headers = new LinkedHashMap<>(); + /** The exchange under way, which an abort cancels. */ private CompletableFuture exchange; @@ -189,6 +193,16 @@ HttpCall retry(ScheduledExecutorService timer, Set statuses) { return this; } + /** + * Adds a header field to the request, such as If-Match. + * + * @return this request. + */ + HttpCall header(String name, String value) { + headers.put(name, value); + return this; + } + /** * Reads the body of a response with one of the given statuses as that of * a 2xx one, up to the size {@link #send} is given, rather than only as @@ -290,6 +304,8 @@ private void exchange(URI target, String contentType, byte[] content, int maxBod if (bearerToken != null) { builder.header("Authorization", "Bearer " + bearerToken); } + + headers.forEach(builder::header); if (content != null) { builder.header("Content-Type", contentType) .header("Accept", contentType) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java new file mode 100644 index 000000000..1731788f5 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -0,0 +1,802 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import java.net.URI; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.UnaryOperator; + +import dev.onvoid.webrtc.RTCIceCandidate; +import dev.onvoid.webrtc.RTCIceServer; +import dev.onvoid.webrtc.internal.Timeouts; + +/** + * The ICE of a WHIP or WHEP session once its offer is answered, carried by + * PATCH requests to the session (RFC 9725, 4.3; draft-ietf-wish-whep-05, 4.5). + * The candidates the peer gathers trickle to the session, a few at a time, + * and an ICE restart exchanges only the ICE information of a new offer, as + * an SDP fragment of RFC 8840. + *

    + * A session that takes no PATCH of a kind, which it says with 405, 415, 422 + * or 501, gets none of that kind any more. It finds the peer all the same, + * from the checks the peer sends to its candidates. + */ +final class HttpIce { + + /** The media type of the SDP fragments. */ + static final String FRAGMENT_TYPE = "application/trickle-ice-sdpfrag"; + + /** How long the connection may stay disconnected before ICE restarts. */ + static final Duration DISCONNECTED_GRACE = Duration.ofSeconds(2); + + /** The most restarts in a row that ICE makes by itself without success. */ + static final int MAX_AUTOMATIC_RESTARTS = 3; + + /** The largest fragment read; one holds a few candidates. */ + private static final int MAX_FRAGMENT = 64 * 1024; + + /** The statuses with which a session says it takes no PATCH of a kind. */ + private static final Set UNSUPPORTED = Set.of(405, 415, 422, 501); + + private final WebRtc rtc; + + private final HttpClient client; + + private final PeerImpl peer; + + private final String bearerToken; + + private final Duration timeout; + + /** Where the PATCH requests go, once the endpoint named it. */ + private URI session; + + /** The entity-tag of the ICE session, or null if the session sent none. */ + private String etag; + + /** The ICE information of the local description, as a fragment. */ + private Fragment local; + + /** Whether candidates go to the session. */ + private boolean trickle; + + /** The candidates gathered and not sent yet. */ + private final List pending = new ArrayList<>(); + + /** Whether gathering completed since the last candidates were sent. */ + private boolean gathered; + + private HttpCall candidatesRequest; + + private HttpCall restartRequest; + + /** Whether an ICE restart waits for its answer, which candidates wait for too. */ + private boolean restarting; + + private boolean restartsRefused; + + private int automaticRestarts; + + private ScheduledFuture disconnected; + + private Subscription stateSubscription; + + private boolean closed; + + + HttpIce(WebRtc rtc, HttpClient client, PeerImpl peer, String bearerToken, Duration timeout) { + this.rtc = rtc; + this.client = client; + this.peer = peer; + this.bearerToken = bearerToken; + this.timeout = timeout; + + peer.onLocalCandidates(this::candidate, this::gathered); + } + + /** + * Tells the session the endpoint named, before the offer is applied and + * its candidates are gathered, which then go there. + * + * @param session where the PATCH requests go, or null for none. + * @param etag the entity-tag of the ICE session, or null. + * @param offer the local offer. + */ + synchronized void attach(URI session, String etag, String offer) { + if (closed || session == null) { + return; + } + + this.session = session; + this.etag = etag; + this.local = Fragment.of(offer); + this.trickle = true; + } + + /** + * Restarts ICE by itself from now on, when the connection fails, or stays + * disconnected for {@link #DISCONNECTED_GRACE}. + */ + void watch() { + Subscription subscription = peer.onStateChange(this::stateChanged); + + synchronized (this) { + if (closed) { + subscription.close(); + return; + } + + stateSubscription = subscription; + } + } + + /** + * Restarts ICE: the peer gathers new candidates for a new offer, whose ICE + * information alone goes to the session, and the session's comes back. + * + * @return a future that completes once both sides' ICE information is + * applied, or fails, the ICE session before going on. + */ + CompletableFuture restart() { + synchronized (this) { + if (closed) { + return CompletableFuture.failedFuture(new PeerClosedException("The session is closed")); + } + if (session == null) { + return CompletableFuture.failedFuture(new WebRtcException("ICE cannot restart: the endpoint named " + + "no session, or answered with an offer of its own")); + } + } + + Fragment[] before = new Fragment[1]; + + return peer.restartIce(offer -> { + HttpCall request; + Fragment fragment = Fragment.of(offer.sdp); + + synchronized (this) { + if (closed) { + return CompletableFuture.failedFuture(new PeerClosedException("The session is closed")); + } + + before[0] = local; + local = fragment; + restarting = true; + pending.clear(); + gathered = false; + + request = new HttpCall(client, session, "PATCH", bearerToken, timeout).header("If-Match", "*"); + restartRequest = request; + } + + return request.send(FRAGMENT_TYPE, fragment.text.getBytes(StandardCharsets.UTF_8), MAX_FRAGMENT, + head -> { }).handle((response, error) -> answered(request, response, error)); + }).whenComplete((restarted, error) -> { + synchronized (this) { + restarting = false; + restartRequest = null; + + if (error != null && before[0] != null) { + // Taken back: the candidates of the new offer go nowhere. + local = before[0]; + pending.clear(); + gathered = false; + } + } + + flush(); + }); + } + + /** + * Stops sending: cuts off the requests under way, and makes no more. + */ + void close() { + HttpCall candidates; + HttpCall restart; + Subscription subscription; + ScheduledFuture wait; + + synchronized (this) { + if (closed) { + return; + } + + closed = true; + candidates = candidatesRequest; + restart = restartRequest; + subscription = stateSubscription; + wait = disconnected; + } + + if (candidates != null) { + candidates.abort(); + } + if (restart != null) { + restart.abort(); + } + if (subscription != null) { + subscription.close(); + } + if (wait != null) { + wait.cancel(false); + } + } + + /** + * Reads the answer to an ICE restart. + * + * @return how to change the remote answer. + */ + private UnaryOperator answered(HttpCall request, HttpCall.Response response, Throwable error) { + URI target; + + synchronized (this) { + target = session; + } + + if (error != null) { + throw new WebRtcException("Restarting ICE of the session " + target + " failed: " + error.getMessage(), + error); + } + if (UNSUPPORTED.contains(response.status)) { + synchronized (this) { + restartsRefused = true; + } + + throw new WebRtcException("The session " + target + " takes no ICE restarts: status " + + response.status); + } + if (response.status / 100 != 2) { + throw new WebRtcException("The session " + target + " answered the ICE restart with status " + + response.status + ": " + response.body); + } + + Fragment remote = Fragment.parse(response.body); + + if (remote.ufrag == null || remote.pwd == null) { + throw new WebRtcException("The session " + target + " answered the ICE restart without " + + "its new ICE credentials"); + } + + synchronized (this) { + etag = response.header("ETag"); + } + + return remote::applyTo; + } + + // On the control executor. + + private void candidate(RTCIceCandidate candidate) { + synchronized (this) { + if (closed || !trickle || !local.owns(candidate.sdp)) { + return; + } + + pending.add("a=" + candidate.sdp); + } + + flush(); + } + + private void gathered() { + synchronized (this) { + if (closed || !trickle) { + return; + } + + gathered = true; + } + + flush(); + } + + /** + * Sends the candidates gathered since the last request, unless one is + * under way, or an ICE restart waits for the session's new entity-tag. + */ + private void flush() { + HttpCall request; + String body; + URI target; + + synchronized (this) { + if (closed || !trickle || restarting || candidatesRequest != null || (pending.isEmpty() && !gathered)) { + return; + } + + StringBuilder fragment = new StringBuilder(local.text); + pending.forEach(line -> fragment.append(line).append("\r\n")); + + if (gathered) { + fragment.append("a=end-of-candidates\r\n"); + } + + pending.clear(); + gathered = false; + + request = new HttpCall(client, session, "PATCH", bearerToken, timeout); + + if (etag != null) { + request.header("If-Match", etag); + } + + candidatesRequest = request; + body = fragment.toString(); + target = session; + } + + request.send(FRAGMENT_TYPE, body.getBytes(StandardCharsets.UTF_8), 0, head -> { }) + .whenComplete((response, error) -> { + boolean report; + + synchronized (this) { + candidatesRequest = null; + + if (error == null && UNSUPPORTED.contains(response.status)) { + // The session finds the peer from its checks. + trickle = false; + } + + // A precondition that fails belongs to an ICE session + // a restart replaced. + report = !closed && (error != null || (response.status / 100 != 2 + && !UNSUPPORTED.contains(response.status) && response.status != 412 + && response.status != 428)); + + if (report) { + trickle = false; + } + } + + if (report) { + rtc.reportError(new WebRtcException("Sending ICE candidates to the session " + target + + " failed, and no more are sent: " + (error != null + ? error.getMessage() + : "status " + response.status), error)); + } + + flush(); + }); + } + + /** + * Follows the state of the connection, on the event executor; tests call + * it as well. + */ + void stateChanged(PeerState state) { + switch (state) { + case CONNECTED: + synchronized (this) { + automaticRestarts = 0; + } + cancelWait(); + break; + + case DISCONNECTED: + waitForReconnect(); + break; + + case FAILED: + cancelWait(); + restartByItself(); + break; + + case CLOSED: + close(); + break; + + default: + break; + } + } + + private void waitForReconnect() { + synchronized (this) { + if (closed || disconnected != null) { + return; + } + + try { + disconnected = rtc.timer.schedule(() -> { + synchronized (this) { + disconnected = null; + } + + if (peer.state() == PeerState.DISCONNECTED) { + restartByItself(); + } + }, Timeouts.toMillis(DISCONNECTED_GRACE), TimeUnit.MILLISECONDS); + } + catch (RejectedExecutionException e) { + // The runtime is closing, and the peer with it. + } + } + } + + private void cancelWait() { + ScheduledFuture wait; + + synchronized (this) { + wait = disconnected; + disconnected = null; + } + + if (wait != null) { + wait.cancel(false); + } + } + + private void restartByItself() { + URI target; + + synchronized (this) { + if (closed || session == null || restartsRefused || automaticRestarts >= MAX_AUTOMATIC_RESTARTS) { + return; + } + + automaticRestarts++; + target = session; + } + + restart().whenComplete((restarted, error) -> { + boolean report; + + synchronized (this) { + report = error != null && !closed; + } + + if (report) { + rtc.reportError(new WebRtcException("Restarting ICE of the session " + target + + " after the connection broke failed", PeerImpl.unwrap(error))); + } + }); + } + + /** + * Reads the STUN and TURN servers an endpoint names in Link header fields + * with the relation "ice-server" (RFC 9725, 4.6). + * + * @param fields the values of the Link header fields. + * + * @return the servers, in order. + */ + static List iceServers(List fields) { + List servers = new ArrayList<>(); + + for (String field : fields) { + int i = 0; + + while (true) { + int open = field.indexOf('<', i); + int close = open < 0 ? -1 : field.indexOf('>', open); + + if (close < 0) { + break; + } + + String target = field.substring(open + 1, close).trim(); + Map parameters = new HashMap<>(); + i = parameters(field, close + 1, parameters); + + String rel = parameters.getOrDefault("rel", ""); + boolean iceServer = false; + + for (String relation : rel.trim().split("\\s+")) { + iceServer |= relation.equalsIgnoreCase("ice-server"); + } + + if (iceServer && !target.isEmpty()) { + RTCIceServer server = new RTCIceServer(); + server.urls.add(target); + server.username = parameters.get("username"); + server.password = parameters.get("credential"); + servers.add(server); + } + } + } + + return servers; + } + + /** + * Reads the parameters of a link, up to the comma that ends it. + * + * @return where the next link starts. + */ + private static int parameters(String field, int start, Map parameters) { + int i = start; + + while (i < field.length() && field.charAt(i) != ',') { + if (field.charAt(i) != ';') { + i++; + continue; + } + + int nameStart = ++i; + + while (i < field.length() && "=;,".indexOf(field.charAt(i)) < 0) { + i++; + } + + String name = field.substring(nameStart, i).trim().toLowerCase(Locale.ROOT); + String value = ""; + + if (i < field.length() && field.charAt(i) == '=') { + i++; + + while (i < field.length() && field.charAt(i) == ' ') { + i++; + } + + StringBuilder text = new StringBuilder(); + + if (i < field.length() && field.charAt(i) == '"') { + i++; + + while (i < field.length() && field.charAt(i) != '"') { + if (field.charAt(i) == '\\' && i + 1 < field.length()) { + i++; + } + + text.append(field.charAt(i++)); + } + + i++; + } + else { + while (i < field.length() && ";,".indexOf(field.charAt(i)) < 0) { + text.append(field.charAt(i++)); + } + } + + value = text.toString().trim(); + } + + parameters.putIfAbsent(name, value); + } + + return i + 1; + } + + + + /** + * The ICE information of a description as an SDP fragment of RFC 8840: + * the ICE options, the BUNDLE group, and of the m-line that tags the group + * its line, mid, username fragment and password. Candidates follow it. + */ + static final class Fragment { + + /** The fragment, each line ended by CRLF. */ + final String text; + + final String ufrag; + + final String pwd; + + /** The candidate lines of a fragment that was read. */ + final List candidates; + + /** Whether a fragment that was read ends the candidates. */ + final boolean endOfCandidates; + + + private Fragment(String text, String ufrag, String pwd, List candidates, boolean endOfCandidates) { + this.text = text; + this.ufrag = ufrag; + this.pwd = pwd; + this.candidates = candidates; + this.endOfCandidates = endOfCandidates; + } + + /** + * Takes the ICE information out of a description. + */ + static Fragment of(String sdp) { + List> sections = sections(sdp); + List session = sections.get(0); + String group = first(session, "a=group:BUNDLE"); + String tag = group != null && group.trim().split("\\s+").length > 1 + ? group.trim().split("\\s+")[1] + : null; + List media = sections.size() > 1 ? sections.get(1) : null; + + for (List section : sections.subList(1, sections.size())) { + if (tag != null && tag.equals(value(section, "a=mid:"))) { + media = section; + break; + } + } + + String options = first(session, "a=ice-options:"); + String ufrag = media != null && value(media, "a=ice-ufrag:") != null + ? value(media, "a=ice-ufrag:") + : value(session, "a=ice-ufrag:"); + String pwd = media != null && value(media, "a=ice-pwd:") != null + ? value(media, "a=ice-pwd:") + : value(session, "a=ice-pwd:"); + + StringBuilder text = new StringBuilder(); + append(text, options != null ? options : media != null ? first(media, "a=ice-options:") : null); + append(text, group); + + if (media != null) { + append(text, media.get(0)); + append(text, first(media, "a=mid:")); + } + + append(text, ufrag != null ? "a=ice-ufrag:" + ufrag : null); + append(text, pwd != null ? "a=ice-pwd:" + pwd : null); + + return new Fragment(text.toString(), ufrag, pwd, new ArrayList<>(), false); + } + + /** + * Reads a fragment a session sent. + */ + static Fragment parse(String body) { + String ufrag = null; + String pwd = null; + List candidates = new ArrayList<>(); + boolean end = false; + + for (String line : body.split("\r?\n")) { + String trimmed = line.trim(); + + if (trimmed.startsWith("a=ice-ufrag:") && ufrag == null) { + ufrag = trimmed.substring("a=ice-ufrag:".length()).trim(); + } + else if (trimmed.startsWith("a=ice-pwd:") && pwd == null) { + pwd = trimmed.substring("a=ice-pwd:".length()).trim(); + } + else if (trimmed.startsWith("a=candidate:")) { + candidates.add(trimmed); + } + else if (trimmed.equals("a=end-of-candidates")) { + end = true; + } + } + + return new Fragment(body, ufrag, pwd, candidates, end); + } + + /** + * @return whether a local candidate belongs to the ICE session of + * this fragment, by the username fragment it names; one that names + * none does. + */ + boolean owns(String candidate) { + String[] fields = candidate.trim().split("\\s+"); + + for (int i = 0; i + 1 < fields.length; i++) { + if (fields[i].equals("ufrag")) { + return ufrag == null || ufrag.equals(fields[i + 1]); + } + } + + return true; + } + + /** + * Puts the ICE information of this fragment, which a session sent, + * into the remote answer applied before. Its candidates replace those + * of the answer; with none, the answer keeps its own, since a session + * that names none has kept them. + */ + String applyTo(String answer) { + List> sections = sections(answer); + String group = first(sections.get(0), "a=group:BUNDLE"); + String tag = group != null && group.trim().split("\\s+").length > 1 + ? group.trim().split("\\s+")[1] + : null; + boolean replace = !candidates.isEmpty(); + boolean placed = false; + StringBuilder sdp = new StringBuilder(); + + for (int s = 0; s < sections.size(); s++) { + List section = sections.get(s); + boolean target = s > 0 && !placed && (tag == null || tag.equals(value(section, "a=mid:"))); + + for (String line : section) { + if (line.startsWith("a=ice-ufrag:")) { + line = "a=ice-ufrag:" + ufrag; + } + else if (line.startsWith("a=ice-pwd:")) { + line = "a=ice-pwd:" + pwd; + } + else if (replace && (line.startsWith("a=candidate:") || line.equals("a=end-of-candidates"))) { + continue; + } + + append(sdp, line); + } + + if (target && replace) { + candidates.forEach(candidate -> append(sdp, candidate)); + + if (endOfCandidates) { + append(sdp, "a=end-of-candidates"); + } + + placed = true; + } + } + + return sdp.toString(); + } + + /** + * Splits a description into its session part and its media sections, + * each a list of lines without their ends. + */ + private static List> sections(String sdp) { + List> sections = new ArrayList<>(); + List section = new ArrayList<>(); + sections.add(section); + + for (String line : sdp.split("\r?\n")) { + if (line.isEmpty()) { + continue; + } + if (line.startsWith("m=")) { + section = new ArrayList<>(); + sections.add(section); + } + + section.add(line); + } + + return sections; + } + + private static String first(List lines, String prefix) { + for (String line : lines) { + if (line.startsWith(prefix)) { + return line; + } + } + + return null; + } + + private static String value(List lines, String prefix) { + String line = first(lines, prefix); + + return line != null ? line.substring(prefix.length()).trim() : null; + } + + private static void append(StringBuilder text, String line) { + if (line != null) { + text.append(line).append("\r\n"); + } + } + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index 9b301cf1d..117a9667a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -26,6 +26,7 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Collections; +import java.util.List; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -38,6 +39,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCSdpType; import dev.onvoid.webrtc.RTCSessionDescription; import dev.onvoid.webrtc.internal.Timeouts; @@ -72,17 +74,25 @@ abstract class HttpSession implements AutoCloseable { private final WebRtc rtc; + /** The ICE of the session, or null for a session made without. */ + private final HttpIce ice; + private final AtomicBoolean closing = new AtomicBoolean(); private final CompletableFuture closed = new CompletableFuture<>(); - HttpSession(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout) { + HttpSession(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout, HttpIce ice) { this.rtc = rtc; this.peer = peer; this.resource = resource; this.bearerToken = bearerToken; this.timeout = timeout; + this.ice = ice; + + if (ice != null) { + ice.watch(); + } } /** @@ -100,6 +110,13 @@ public URI resource() { return resource; } + /** + * @return the ICE of the session, or null. + */ + HttpIce ice() { + return ice; + } + /** * Deletes the session's resource on the server, which frees what the * server holds for it, and closes the peer. Both start at once, so that a @@ -114,6 +131,10 @@ public URI resource() { */ public CompletableFuture closeAsync() { if (closing.compareAndSet(false, true)) { + if (ice != null) { + ice.close(); + } + CompletableFuture peerClosed = peer.closeAsync().handle((ignored, error) -> error); CompletableFuture deleted = discard(rtc, resource, bearerToken, timeout); @@ -134,6 +155,26 @@ public CompletableFuture closeAsync() { return ClientFuture.copyOf(closed); } + /** + * Restarts ICE, as after the network changed: the peer gathers new + * candidates, and only the ICE information goes to the session, by PATCH, + * as WHIP and WHEP do; the media go on as negotiated. The session restarts + * ICE by itself too, when the connection fails or stays disconnected for + * two seconds, up to three times in a row without success. + * + * @return a future that completes once the new ICE information of both + * sides is applied, or fails, among others when the session takes no ICE + * restarts or answered the offer with one of its own. The ICE session + * before then goes on. + */ + public CompletableFuture restartIce() { + CompletableFuture restarted = ice != null + ? ice.restart() + : CompletableFuture.failedFuture(new WebRtcException("The session has no ICE to restart")); + + return ClientFuture.copyOf(restarted); + } + /** * Ends the session, as {@link #closeAsync()} does, without waiting. */ @@ -159,8 +200,9 @@ public void close() { static CompletableFuture start(WebRtc rtc, PeerImpl peer, URI endpoint, String bearerToken, Duration timeout, Protocol protocol, Factory factory) { CompletableFuture abandoned = new CompletableFuture<>(); + HttpIce ice = new HttpIce(rtc, rtc.httpClient(bearerToken != null), peer, bearerToken, timeout); CompletableFuture session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, protocol, - abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout)), + ice, abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout, ice)), HttpSession::close); // Once the session was handed out, this finds the negotiation finished. @@ -170,18 +212,22 @@ static CompletableFuture start(WebRtc rtc, PeerImpl p } /** - * Negotiates a manual peer over HTTP: creates the offer with all candidates, - * posts it, applies the answer and waits until the peer is connected. An - * endpoint that counters the offer, as WHEP allows, gets the answer to its - * own offer instead. + * Negotiates a manual peer over HTTP: creates the offer and posts it at + * once, without candidates, as RFC 9725 recommends with Trickle ICE. Only + * then is the offer applied, with the STUN and TURN servers the endpoint + * named, and the candidates it gathers go to the session by PATCH. The + * answer is applied, and the future completes once the peer is connected. + * An endpoint that counters the offer, as WHEP allows, gets the answer to + * its own offer instead, with all candidates. * + * @param ice the ICE of the session once the offer is answered. * @param abandoned completes when no one waits for the session anymore, * which then ends as if it had failed. * * @return a future with the resource the server named, or null. */ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI endpoint, String bearerToken, - Duration timeout, Protocol protocol, CompletableFuture abandoned) { + Duration timeout, Protocol protocol, HttpIce ice, CompletableFuture abandoned) { CompletableFuture result = new CompletableFuture<>(); long started = System.nanoTime(); // The resource the server created. Whoever takes it out owns it: the @@ -207,6 +253,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e // Ends a request still out, whose answer would only meet a closed // peer. request.get().abort(); + ice.close(); // Reported before the resource is deleted, which may take as long // as the timeout again. peer.close(); @@ -225,7 +272,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e fail.accept(new CancellationException("The session with " + endpoint + " was abandoned")); }); - peer.negotiator().createOffer(Gathering.COMPLETE) + peer.offer() .thenCompose(offer -> post(offerRequest, endpoint, offer.sdp, protocol, resource) .whenComplete((reply, error) -> { if (finished.get()) { @@ -234,19 +281,33 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e // then has no one else to delete it. discard(rtc, resource.getAndSet(null), bearerToken, timeout); } + }) + .thenCompose(reply -> peer.useIceServers(reply.iceServers).handle((used, error) -> { + if (error != null) { + // Gathered without them, as if the endpoint had + // named none. + rtc.reportError(PeerImpl.unwrap(error)); + } + + return reply; })) - .thenCompose(reply -> { - if (!reply.counterOffer) { - return peer.negotiator().applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp)); - } + .thenCompose(reply -> { + if (!reply.counterOffer) { + // Before the offer is applied, which starts the + // gathering of the candidates that go there. + ice.attach(resource.get(), reply.etag, offer.sdp); + + return peer.applyLocal(offer).thenCompose(applied -> peer.negotiator() + .applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp))); + } - // The rest of the session's time, which the answer has. - Duration left = timeout.minusNanos(System.nanoTime() - started); + // The rest of the session's time, which the answer has. + Duration left = timeout.minusNanos(System.nanoTime() - started); - return answerCounterOffer(rtc, client, peer, reply, bearerToken, - left.isNegative() || left.isZero() ? Duration.ofNanos(1) : left, resource, request, - finished); - }) + return answerCounterOffer(rtc, client, peer, reply, bearerToken, + left.isNegative() || left.isZero() ? Duration.ofNanos(1) : left, resource, + request, finished); + })) .thenCompose(applied -> peer.whenConnected()) .whenComplete((connected, error) -> { deadline.cancel(false); @@ -284,7 +345,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str error); } if (response.status == 201 || response.status == 200) { - return new Reply(response.body, false, null, 0); + return new Reply(response.body, false, null, 0, response); } if (protocol.counterOffers && isCounterOffer(response)) { URI session = resourceOf(response.uri, response.header("Location")); @@ -295,7 +356,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str } return new Reply(response.body, true, session, - counterOfferExpiry(response.header("Content-Type"), System.currentTimeMillis())); + counterOfferExpiry(response.header("Content-Type"), System.currentTimeMillis()), response); } String body = response.body; @@ -440,12 +501,20 @@ private static final class Reply { /** Until when a counter-offer can be answered. */ final long validUntil; + /** The entity-tag of the ICE session, or null. */ + final String etag; + + /** The STUN and TURN servers the endpoint named. */ + final List iceServers; + - Reply(String sdp, boolean counterOffer, URI session, long validUntil) { + Reply(String sdp, boolean counterOffer, URI session, long validUntil, HttpCall.Response response) { this.sdp = sdp; this.counterOffer = counterOffer; this.session = session; this.validUntil = validUntil; + this.etag = response.header("ETag"); + this.iceServers = HttpIce.iceServers(response.headers.allValues("Link")); } } @@ -458,7 +527,7 @@ private static final class Reply { */ interface Factory { - S create(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout); + S create(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout, HttpIce ice); } /** 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 09e60bded..4c7d8819f 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -42,14 +42,17 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import java.util.function.UnaryOperator; import dev.onvoid.webrtc.AddIceCandidateObserver; import dev.onvoid.webrtc.CreateSessionDescriptionObserver; import dev.onvoid.webrtc.PeerConnectionObserver; import dev.onvoid.webrtc.RTCAnswerOptions; +import dev.onvoid.webrtc.RTCConfiguration; import dev.onvoid.webrtc.RTCDataChannel; import dev.onvoid.webrtc.RTCIceCandidate; import dev.onvoid.webrtc.RTCIceGatheringState; +import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCOfferOptions; import dev.onvoid.webrtc.RTCPeerConnection; import dev.onvoid.webrtc.RTCPeerConnectionState; @@ -177,6 +180,12 @@ final class PeerImpl implements Peer { */ private final Set declinedKinds = EnumSet.noneOf(MediaKind.class); + /** Gets the local candidates as well, or null. Called on the control executor. */ + private volatile Consumer candidateListener; + + /** Runs once gathering is complete, or null. Called on the control executor. */ + private volatile Runnable gatheredListener; + PeerImpl(WebRtc rtc, PeerOptions options, String name) { this.rtc = rtc; @@ -429,6 +438,131 @@ public Negotiator negotiator() { return negotiator; } + /** + * Creates an offer without applying it, so that the configuration can + * still change before candidates are gathered for it, as WHIP and WHEP do + * with the ICE servers the endpoint names in its answer. + * + * @return a future with the offer, which {@link #applyLocal} applies. + */ + CompletableFuture offer() { + return negotiator.run(this::createOffer); + } + + /** + * Applies a description this peer created, which starts the gathering of + * candidates for it. + */ + CompletableFuture applyLocal(RTCSessionDescription description) { + return negotiator.run(() -> setLocal(description)); + } + + /** + * Gathers candidates from now on with the given ICE servers, unless the + * peer was built with servers of its own, which take precedence. + * + * @param servers the ICE servers; none leaves the configuration as it is. + * + * @return a future that fails if WebRTC refuses the servers. + */ + CompletableFuture useIceServers(List servers) { + if (servers.isEmpty() || !options.iceServers.isEmpty()) { + return CompletableFuture.completedFuture(null); + } + + return negotiator.run(() -> { + try { + RTCConfiguration config = connection.getConfiguration(); + config.iceServers = new ArrayList<>(servers); + connection.setConfiguration(config); + + return CompletableFuture.completedFuture(null); + } + catch (RuntimeException e) { + return CompletableFuture.failedFuture(new ConfigurationException("WebRTC refused the ICE servers " + + servers + " for " + name + ": " + e.getMessage(), e)); + } + }); + } + + /** + * Hands the candidates this peer gathers to the given listener as well, + * on the control executor, and tells it when gathering is complete. + * + * @param candidates gets each local candidate. + * @param gathered runs once gathering is complete, each time. + */ + void onLocalCandidates(Consumer candidates, Runnable gathered) { + this.candidateListener = candidates; + this.gatheredListener = gathered; + } + + /** + * Restarts ICE as WHIP and WHEP do, without a renegotiation: only the ICE + * information of a new offer goes to the remote peer, and the remote + * answer applied before stays, with the ICE information that comes back. + * An exchange that fails takes the new offer back, and the ICE session + * before goes on. + * + * @param exchange sends the ICE information of the new offer, and returns + * how to change the remote answer. + * + * @return a future that completes once the new ICE information is applied. + */ + CompletableFuture restartIce( + Function>> exchange) { + return negotiator.run(() -> { + RTCSessionDescription remote = connection.getRemoteDescription(); + + if (connection.getSignalingState() != RTCSignalingState.STABLE || remote == null + || remote.sdpType != RTCSdpType.ANSWER) { + return CompletableFuture.failedFuture(new NegotiationException("The peer " + name + + " has no answer to its own offer to restart ICE with")); + } + + connection.restartIce(); + + return createOffer() + .thenCompose(offer -> setLocal(offer).thenApply(ignored -> offer)) + .thenCompose(offer -> onControl(exchange.apply(offer))) + .thenCompose(change -> { + RTCSessionDescription answer = connection.getRemoteDescription(); + + return setRemote(new RTCSessionDescription(RTCSdpType.ANSWER, change.apply(answer.sdp))); + }) + .handle((applied, error) -> { + if (error == null) { + return CompletableFuture.completedFuture(null); + } + + CompletableFuture failed = CompletableFuture.failedFuture(unwrap(error)); + + if (closed || connection.getSignalingState() == RTCSignalingState.STABLE) { + return failed; + } + + // Back to the ICE session before, which the server keeps. + return setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + .handle((ignored, rollbackError) -> null) + .thenCompose(ignored -> failed); + }) + .thenCompose(result -> result); + }); + } + + /** + * @return a future that completes as the given one, but on the control + * executor, or fails once the peer is closed. + */ + private CompletableFuture onControl(CompletableFuture future) { + CompletableFuture result = new CompletableFuture<>(); + + future.whenComplete((value, error) -> control.execute(() -> complete(result, value, error), + () -> result.completeExceptionally(closedError()))); + + return result; + } + /** * Takes this peer's own offer back and answers the given one instead, as * a WHEP player does when the server counters its offer. Unlike {@link @@ -462,7 +596,12 @@ CompletableFuture answerInstead(RTCSessionDescription off } } - return setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + // An offer created but not applied yet needs no taking back. + CompletableFuture stable = connection.getSignalingState() == RTCSignalingState.STABLE + ? CompletableFuture.completedFuture(null) + : setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")); + + return stable .thenCompose(ignored -> setRemote(offer)) .thenCompose(ignored -> { stopTransceivers(rejected); @@ -1214,6 +1353,12 @@ private void gatheringChanged(RTCIceGatheringState gatheringState) { gatheringWaiters.clear(); waiters.forEach(waiter -> waiter.complete(null)); + + Runnable listener = gatheredListener; + + if (listener != null && !closed) { + listener.run(); + } } } @@ -1415,6 +1560,12 @@ private final class Observer implements PeerConnectionObserver { public void onIceCandidate(RTCIceCandidate candidate) { control.execute(() -> { if (!closed) { + Consumer listener = candidateListener; + + if (listener != null) { + listener.accept(candidate); + } + send(SignalMessage.of(candidate)); } }); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java index b92206a2e..9d187b962 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java @@ -40,8 +40,10 @@ * ... * session.close(); * } - * The offer goes to the endpoint with all local candidates, as WHEP servers - * expect, and the session's future completes once the peer is connected. + * The offer goes to the endpoint at once, and the candidates follow it by + * PATCH, gathered with the STUN and TURN servers the endpoint names. The + * session's future completes once the peer is connected. The session + * restarts ICE when the connection breaks, or by {@link Session#restartIce()}. * {@link Peer#onTrack} hands over tracks that arrived before a handler was * added, so registering it after the future completed misses none. * @@ -77,8 +79,8 @@ public static Builder from(URI endpoint) { /** A stream received over WHEP. Closing it ends the session on the server. */ public static final class Session extends HttpSession { - Session(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout) { - super(rtc, peer, resource, bearerToken, timeout); + Session(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout, HttpIce ice) { + super(rtc, peer, resource, bearerToken, timeout, ice); } } @@ -114,8 +116,8 @@ public Builder bearerToken(String token) { } /** - * @param urls a STUN or TURN server without credentials. The endpoint - * usually names its own in its answer. + * @param urls a STUN or TURN server without credentials. Servers given + * here replace those the endpoint names in its answer. * * @return this builder. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java index 71c01a2a4..a3520f6ef 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java @@ -40,8 +40,10 @@ * ... * session.close(); * } - * The offer goes to the endpoint with all local candidates, as WHIP servers - * expect, and the session's future completes once the peer is connected. + * The offer goes to the endpoint at once, and the candidates follow it by + * PATCH, gathered with the STUN and TURN servers the endpoint names. The + * session's future completes once the peer is connected. The session + * restarts ICE when the connection breaks, or by {@link Session#restartIce()}. * Closing the session ends it on the server; the tracks stay open. * * @see RFC 9725: WHIP @@ -75,8 +77,8 @@ public static Builder to(URI endpoint) { /** Tracks published over WHIP. Closing it ends the session on the server. */ public static final class Session extends HttpSession { - Session(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout) { - super(rtc, peer, resource, bearerToken, timeout); + Session(WebRtc rtc, Peer peer, URI resource, String bearerToken, Duration timeout, HttpIce ice) { + super(rtc, peer, resource, bearerToken, timeout, ice); } } @@ -124,7 +126,8 @@ public Builder bearerToken(String token) { } /** - * @param urls a STUN or TURN server without credentials. + * @param urls a STUN or TURN server without credentials. Servers given + * here replace those the endpoint names in its answer. * * @return this builder. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java new file mode 100644 index 000000000..16a0b3af5 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java @@ -0,0 +1,142 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import dev.onvoid.webrtc.RTCIceServer; + +import org.junit.jupiter.api.Test; + +/** + * What a WHIP or WHEP session reads and writes about ICE, without WebRTC. + */ +class HttpIceTests { + + private static final String OFFER = String.join("\r\n", + "v=0", + "o=- 1 2 IN IP4 127.0.0.1", + "s=-", + "t=0 0", + "a=group:BUNDLE 0 1", + "a=msid-semantic: WMS", + "m=audio 9 UDP/TLS/RTP/SAVPF 111", + "c=IN IP4 0.0.0.0", + "a=ice-ufrag:aaaa", + "a=ice-pwd:aaaaaaaaaaaaaaaaaaaaaaaa", + "a=ice-options:trickle", + "a=mid:0", + "a=recvonly", + "m=video 9 UDP/TLS/RTP/SAVPF 96", + "c=IN IP4 0.0.0.0", + "a=ice-ufrag:aaaa", + "a=ice-pwd:aaaaaaaaaaaaaaaaaaaaaaaa", + "a=ice-options:trickle", + "a=mid:1", + "a=recvonly", + ""); + + private static final String ANSWER = OFFER + .replace("aaaa", "bbbb") + .replace("a=mid:0\r\n", "a=mid:0\r\na=candidate:1 1 udp 2122260223 192.0.2.1 5000 typ host\r\n" + + "a=end-of-candidates\r\n"); + + + @Test + void linksRead() { + List servers = HttpIce.iceServers(Arrays.asList( + "; rel=\"ice-server\"", + "; rel=\"ice-server\"; username=\"user\"; " + + "credential=\"my, \\\"password\\\"\", ; rel=\"terms-of-service\"", + "; rel=\"ice-server other\"; username=user; credential=pw")); + + assertEquals(3, servers.size(), () -> "Servers: " + servers); + assertEquals(Arrays.asList("stun:stun.example.net"), servers.get(0).urls); + assertNull(servers.get(0).username); + assertEquals(Arrays.asList("turn:turn.example.net?transport=udp"), servers.get(1).urls); + assertEquals("user", servers.get(1).username); + // A comma and escaped quotes within the quoted value end nothing. + assertEquals("my, \"password\"", servers.get(1).password); + assertEquals(Arrays.asList("turns:turn.example.net?transport=tcp"), servers.get(2).urls); + assertEquals("pw", servers.get(2).password); + } + + @Test + void fragmentOfOffer() { + // The m-line that tags the BUNDLE group stands for all, as RFC 9725 + // asks with max-bundle. + HttpIce.Fragment fragment = HttpIce.Fragment.of(OFFER); + + assertEquals(String.join("\r\n", + "a=ice-options:trickle", + "a=group:BUNDLE 0 1", + "m=audio 9 UDP/TLS/RTP/SAVPF 111", + "a=mid:0", + "a=ice-ufrag:aaaa", + "a=ice-pwd:aaaaaaaaaaaaaaaaaaaaaaaa", + ""), fragment.text); + assertEquals("aaaa", fragment.ufrag); + } + + @Test + void fragmentOwnsItsCandidates() { + HttpIce.Fragment fragment = HttpIce.Fragment.of(OFFER); + + assertTrue(fragment.owns("candidate:1 1 udp 2122260223 192.0.2.1 5000 typ host generation 0 ufrag aaaa")); + assertFalse(fragment.owns("candidate:1 1 udp 2122260223 192.0.2.1 5000 typ host generation 0 ufrag zzzz")); + assertTrue(fragment.owns("candidate:1 1 udp 2122260223 192.0.2.1 5000 typ host")); + } + + @Test + void restartAppliedToAnswer() { + // The session's new ICE information replaces the old in every m-line, + // and its candidates replace the answer's, in the tagged m-line. + HttpIce.Fragment restart = HttpIce.Fragment.parse(String.join("\r\n", + "a=ice-lite", + "a=group:BUNDLE 0 1", + "m=audio 9 UDP/TLS/RTP/SAVPF 111", + "a=mid:0", + "a=ice-ufrag:cccc", + "a=ice-pwd:cccccccccccccccccccccccc", + "a=candidate:2 1 udp 2122260223 192.0.2.2 6000 typ host", + "a=end-of-candidates", + "")); + String answer = restart.applyTo(ANSWER); + + assertFalse(answer.contains("bbbb"), answer); + assertEquals(2, answer.split("a=ice-ufrag:cccc", -1).length - 1, answer); + assertFalse(answer.contains("192.0.2.1"), answer); + assertTrue(answer.contains("a=mid:0\r\n"), answer); + assertTrue(answer.indexOf("192.0.2.2") < answer.indexOf("m=video"), answer); + assertTrue(answer.contains("a=end-of-candidates"), answer); + } + + @Test + void restartWithoutCandidatesKeepsThem() { + HttpIce.Fragment restart = HttpIce.Fragment.parse("a=ice-ufrag:cccc\r\na=ice-pwd:cccccccccccccccccccccccc\r\n"); + String answer = restart.applyTo(ANSWER); + + assertTrue(answer.contains("192.0.2.1"), answer); + assertTrue(answer.contains("a=ice-ufrag:cccc"), answer); + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index 777445de9..0b24805db 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -45,6 +46,7 @@ import java.util.function.Function; import java.util.function.UnaryOperator; +import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCSdpType; import dev.onvoid.webrtc.RTCSessionDescription; import dev.onvoid.webrtc.media.video.NativeI420Buffer; @@ -107,7 +109,7 @@ void whepPlays() throws Exception { await(session.closeAsync()); - assertEquals("DELETE /live/session/1", endpoint.requests.get(1).toString()); + assertEquals(1, endpoint.count("DELETE /live/session/1")); assertEquals(PeerState.CLOSED, session.peer().state()); } } @@ -128,7 +130,7 @@ void whipPublishes() throws Exception { // Before the endpoint goes, which would fail the DELETE. await(session.closeAsync()); - assertEquals("DELETE /live/session/1", endpoint.requests.get(1).toString()); + assertEquals(1, endpoint.count("DELETE /live/session/1")); } } @@ -338,6 +340,192 @@ void cancelEndsRetryWait() throws Exception { } } + @Test + void candidatesTrickled() throws Exception { + // The offer goes out at once, without candidates. They follow by + // PATCH, with the entity-tag of the ICE session, as RFC 9725 asks. + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerHeaders = "ETag: \"ice-1\"\r\n"; + + Whep.Session session = await(Whep.from(endpoint.uri()).bearerToken("secret").play(rtc)); + TestHttpEndpoint.Request offer = endpoint.request("POST /live/endpoint"); + TestHttpEndpoint.Request last = endpoint.awaitRequest(request -> request.method.equals("PATCH") + && request.body.contains("a=end-of-candidates"), "PATCH that ends the candidates", TIMEOUT_SECONDS); + + assertFalse(offer.body.contains("a=candidate:"), offer.body); + assertEquals(HttpIce.FRAGMENT_TYPE, last.contentType); + assertEquals("\"ice-1\"", last.ifMatch); + assertEquals("Bearer secret", last.authorization); + // The ICE information of the offer, then the candidates. + assertTrue(last.body.startsWith(HttpIce.Fragment.of(offer.body).text), last.body); + assertTrue(endpoint.requests.stream().anyMatch(request -> request.method.equals("PATCH") + && request.body.contains("a=candidate:")), () -> "Requests: " + endpoint.requests); + + await(session.closeAsync()); + } + } + + @Test + void iceServersFromLink() throws Exception { + // The STUN and TURN servers the endpoint names, which the peer gathers + // its candidates with. + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerHeaders = "Link: ; rel=\"ice-server\"\r\n" + + "Link: ; rel=\"ice-server\"; username=\"user\"; " + + "credential=\"secret\"\r\n"; + + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + List servers = await(session.peer().withNative(connection -> + connection.getConfiguration().iceServers)); + + assertEquals(2, servers.size(), () -> "Servers: " + servers); + assertEquals(Arrays.asList("stun:127.0.0.1:3478"), servers.get(0).urls); + assertEquals(Arrays.asList("turn:127.0.0.1:3478?transport=udp"), servers.get(1).urls); + assertEquals("user", servers.get(1).username); + assertEquals("secret", servers.get(1).password); + + await(session.closeAsync()); + } + } + + @Test + void ownIceServersWin() throws Exception { + // Servers the application names override the endpoint's, as RFC 9725 + // allows. + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerHeaders = "Link: ; rel=\"ice-server\"\r\n"; + + Whep.Session session = await(Whep.from(endpoint.uri()).iceServer("stun:127.0.0.2:3478").play(rtc)); + List servers = await(session.peer().withNative(connection -> + connection.getConfiguration().iceServers)); + + assertEquals(1, servers.size(), () -> "Servers: " + servers); + assertEquals(Arrays.asList("stun:127.0.0.2:3478"), servers.get(0).urls); + + await(session.closeAsync()); + } + } + + @Test + void iceRestarted() throws Exception { + // Only the ICE information goes to the session, which answers with its + // own; the media go on, and later candidates carry the new entity-tag. + List fragments = new CopyOnWriteArrayList<>(); + + try (TestHttpEndpoint endpoint = restartingEndpoint(fragments)) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + String offered = HttpIce.Fragment.of(endpoint.request("POST /live/endpoint").body).ufrag; + + await(session.restartIce()); + + TestHttpEndpoint.Request restart = endpoint.awaitRequest(request -> "*".equals(request.ifMatch), + "ICE restart", TIMEOUT_SECONDS); + String remote = await(session.peer().withNative(connection -> connection.getRemoteDescription().sdp)); + + assertEquals(HttpIce.FRAGMENT_TYPE, restart.contentType); + assertNotEquals(offered, HttpIce.Fragment.parse(restart.body).ufrag); + assertTrue(remote.contains("a=ice-ufrag:" + HttpIce.Fragment.parse(fragments.get(0)).ufrag), remote); + + endpoint.awaitRequest(request -> "\"restart-1\"".equals(request.ifMatch), + "candidates after the restart", TIMEOUT_SECONDS); + + CompletableFuture width = new CompletableFuture<>(); + session.peer().onTrack(track -> track.asVideo().onFrame(frame -> width.complete(frame.buffer.getWidth()))); + assertEquals(160, (int) await(width)); + + await(session.closeAsync()); + } + } + + @Test + void refusedIceRestartKeepsSession() throws Exception { + // The endpoint takes no ICE restarts: the new offer is taken back, and + // the ICE session before goes on. + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + String offered = HttpIce.Fragment.of(endpoint.request("POST /live/endpoint").body).ufrag; + + ExecutionException failed = assertThrows(ExecutionException.class, () -> await(session.restartIce())); + String local = await(session.peer().withNative(connection -> connection.getLocalDescription().sdp)); + + assertTrue(failed.getCause().getMessage().contains("takes no ICE restarts"), + failed.getCause().getMessage()); + assertEquals(offered, HttpIce.Fragment.of(local).ufrag); + assertEquals(PeerState.CONNECTED, session.peer().state()); + + await(session.closeAsync()); + } + } + + @Test + void failedConnectionRestartsIce() throws Exception { + List fragments = new CopyOnWriteArrayList<>(); + + try (TestHttpEndpoint endpoint = restartingEndpoint(fragments)) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + + session.ice().stateChanged(PeerState.FAILED); + + endpoint.awaitRequest(request -> "*".equals(request.ifMatch), "ICE restart", TIMEOUT_SECONDS); + await(session.closeAsync()); + } + } + + @Test + void disconnectedWaitsBeforeRestart() throws Exception { + // A connection that comes back by itself needs no restart. + ManualTimer timer = new ManualTimer(); + WebRtc client = clientRuntime(builder -> builder.timer(timer)); + + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + Whep.Session session = await(Whep.from(endpoint.uri()).timeout(SESSION_TIMEOUT).play(client)); + + session.ice().stateChanged(PeerState.DISCONNECTED); + assertEquals(1, timer.scheduled(HttpIce.DISCONNECTED_GRACE)); + + session.ice().stateChanged(PeerState.CONNECTED); + assertEquals(0, timer.scheduled(HttpIce.DISCONNECTED_GRACE)); + + // Still connected when the wait is over: no restart either. + session.ice().stateChanged(PeerState.DISCONNECTED); + assertEquals(1, timer.fire(HttpIce.DISCONNECTED_GRACE)); + assertEquals(0, endpoint.requests.stream().filter(request -> "*".equals(request.ifMatch)).count()); + + await(session.closeAsync()); + } + finally { + client.close(); + } + } + + @Test + void automaticRestartsLimited() throws Exception { + // Restarts that fail are not made forever: three in a row at most. + List fragments = new CopyOnWriteArrayList<>(); + + try (TestHttpEndpoint endpoint = restartingEndpoint(fragments)) { + endpoint.iceRestartStatus = 500; + + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + + for (int i = 0; i <= HttpIce.MAX_AUTOMATIC_RESTARTS; i++) { + session.ice().stateChanged(PeerState.FAILED); + } + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + while (errors.size() < HttpIce.MAX_AUTOMATIC_RESTARTS && System.nanoTime() < deadline) { + Thread.sleep(10); + } + + assertEquals(HttpIce.MAX_AUTOMATIC_RESTARTS, errors.size(), () -> "Errors: " + errors); + assertEquals(HttpIce.MAX_AUTOMATIC_RESTARTS, + endpoint.requests.stream().filter(request -> "*".equals(request.ifMatch)).count()); + errors.clear(); + + await(session.closeAsync()); + } + } + @Test void counterOfferAnswered() throws Exception { // The endpoint rejects the player's offer and makes its own, which the @@ -527,7 +715,7 @@ void tricklingDeleteTimesOut() throws Exception { try (TestHttpEndpoint endpoint = receivingEndpoint()) { Peer peer = rtc.createPeer(PeerOptions.builder().negotiation(Negotiation.MANUAL).build()); HttpSession session = new Whep.Session(rtc, peer, endpoint.uri().resolve("/live/session/1"), null, - Duration.ofSeconds(1)); + Duration.ofSeconds(1), null); endpoint.trickleDeletes(); @@ -754,7 +942,7 @@ void failedPeerCloseFails() throws Exception { IllegalStateException peerError = new IllegalStateException("The peer did not close"); // Nothing to delete: the session fails as the peer did. - HttpSession session = new Whep.Session(rtc, failingToClose(peerError), null, null, SESSION_TIMEOUT); + HttpSession session = new Whep.Session(rtc, failingToClose(peerError), null, null, SESSION_TIMEOUT, null); ExecutionException failed = assertThrows(ExecutionException.class, () -> await(session.closeAsync())); assertSame(peerError, failed.getCause()); @@ -763,7 +951,7 @@ void failedPeerCloseFails() throws Exception { endpoint.deleteStatus = 500; HttpSession both = new Whep.Session(rtc, failingToClose(peerError), - endpoint.uri().resolve("/live/session/1"), null, SESSION_TIMEOUT); + endpoint.uri().resolve("/live/session/1"), null, SESSION_TIMEOUT, null); Throwable error = assertCloseFails(both, "500"); assertEquals(Arrays.asList(peerError), Arrays.asList(error.getSuppressed())); @@ -801,8 +989,8 @@ void sessionKeepsItsToken() throws Exception { await(await(session).closeAsync()); assertEquals("Bearer first", endpoint.requests.get(0).authorization); - assertEquals("DELETE /live/session/1", endpoint.requests.get(1).toString()); - assertEquals("Bearer first", endpoint.requests.get(1).authorization); + assertEquals(1, endpoint.count("DELETE /live/session/1")); + assertEquals("Bearer first", endpoint.request("DELETE /live/session/1").authorization); } try (TestHttpEndpoint endpoint = sendingEndpoint()) { @@ -815,8 +1003,8 @@ void sessionKeepsItsToken() throws Exception { answer.countDown(); await(await(session).closeAsync()); - assertEquals("DELETE /live/session/1", endpoint.requests.get(1).toString()); - assertEquals("Bearer first", endpoint.requests.get(1).authorization); + assertEquals(1, endpoint.count("DELETE /live/session/1")); + assertEquals("Bearer first", endpoint.request("DELETE /live/session/1").authorization); } } @@ -906,6 +1094,42 @@ private TestHttpEndpoint counteringEndpoint(String contentType, List ans return endpoint; } + /** + * An endpoint whose side sends the video and takes ICE restarts, as a WHEP + * session that supports them: it restarts ICE with the player's new ICE + * information and answers with its own. + * + * @param fragments gets the fragments the endpoint answers with. + */ + private TestHttpEndpoint restartingEndpoint(List fragments) throws Exception { + Peer[] server = new Peer[1]; + TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> { + server[0] = rtc.createPeer(PeerOptions.builder().negotiation(Negotiation.MANUAL).build()); + server[0].addTrack(video); + return answer(server[0], offer); + }, 201); + + endpoint.iceRestarts = fragment -> { + try { + String offer = server[0].withNative(connection -> connection.getRemoteDescription().sdp) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + String answer = answer(server[0], HttpIce.Fragment.parse(fragment).applyTo(offer)); + StringBuilder own = new StringBuilder(HttpIce.Fragment.of(answer).text); + + HttpIce.Fragment.parse(answer).candidates.forEach(candidate -> own.append(candidate).append("\r\n")); + own.append("a=end-of-candidates\r\n"); + fragments.add(own.toString()); + + return own.toString(); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + }; + + return endpoint; + } + /** * An endpoint whose side of the session sends the video. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java index 22ee7b84c..39e0433d3 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java @@ -32,6 +32,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; import javax.net.ssl.SSLContext; @@ -40,8 +41,8 @@ /** * Just enough HTTP for WHIP and WHEP tests. A POST is answered with what the * handler returns for the offer, and creates a resource; a DELETE of that - * resource returns 200, unless the test sets another status. Requests are - * served one at a time, in the order they arrive. + * resource returns 200, unless the test sets another status. Each connection + * is served on a thread of its own, as a server does. */ final class TestHttpEndpoint implements AutoCloseable { @@ -54,11 +55,26 @@ static final class Request { final String authorization; + /** The If-Match header field, or null. */ + final String ifMatch; + + /** The Content-Type header field, or null. */ + final String contentType; + + final String body; + Request(String method, String path, String authorization) { + this(method, path, authorization, null, null, ""); + } + + Request(String method, String path, String authorization, String ifMatch, String contentType, String body) { this.method = method; this.path = path; this.authorization = authorization; + this.ifMatch = ifMatch; + this.contentType = contentType; + this.body = body; } @Override @@ -110,6 +126,21 @@ public String toString() { /** The status a PATCH is answered with. */ volatile int patchStatus = 204; + /** Header fields an answer of 201 carries beyond Location, each ended by CRLF. */ + volatile String answerHeaders = ""; + + /** + * Takes the fragment of an ICE restart, a PATCH with If-Match *, and + * returns the endpoint's own, or is null for an endpoint that refuses ICE + * restarts with 405. Answered with 200 and the ETag "restart-n". + */ + volatile Function iceRestarts; + + /** The status an ICE restart is answered with; with another than 200, the restart fails. */ + volatile int iceRestartStatus = 200; + + private int restarts; + /** Where POSTs are redirected to, or null. */ private volatile String redirectLocation; @@ -302,6 +333,43 @@ synchronized void awaitRequest(String request, long timeoutSeconds) throws Inter } } + /** + * Waits until the endpoint has received a request that matches. + * + * @return the request. + */ + synchronized Request awaitRequest(Predicate matching, String what, long timeoutSeconds) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); + + while (true) { + for (Request request : requests) { + if (matching.test(request)) { + return request; + } + } + + long left = deadline - System.nanoTime(); + + if (left <= 0) { + throw new AssertionError("No " + what + " within " + timeoutSeconds + " s. Requests: " + requests); + } + + TimeUnit.NANOSECONDS.timedWait(this, left); + } + } + + /** + * @return the first request received that is the given one, such as + * "DELETE /live/session/1". + */ + Request request(String request) { + return requests.stream() + .filter(r -> r.toString().equals(request)) + .findFirst() + .orElseThrow(() -> new AssertionError("No " + request + ". Requests: " + requests)); + } + /** * @return how many of the requests received are the given one. */ @@ -316,8 +384,11 @@ public void close() throws IOException { private void serve() { while (!server.isClosed()) { - try (Socket socket = server.accept()) { - handle(socket); + try { + Socket socket = server.accept(); + Thread thread = new Thread(() -> serve(socket), "test-http-endpoint-connection"); + thread.setDaemon(true); + thread.start(); } catch (IOException e) { // Closed. @@ -325,10 +396,25 @@ private void serve() { } } + /** + * Serves one connection, apart from the others: one that a client opened + * and gave up before it sent anything holds up no other. + */ + private void serve(Socket socket) { + try (Socket connection = socket) { + handle(connection); + } + catch (IOException e) { + // The client went away. + } + } + private void handle(Socket socket) throws IOException { InputStream in = socket.getInputStream(); String[] requestLine = readLine(in).split(" "); String authorization = null; + String ifMatch = null; + String contentType = null; int length = 0; String line; @@ -342,6 +428,12 @@ private void handle(Socket socket) throws IOException { else if (name.equals("authorization")) { authorization = value; } + else if (name.equals("if-match")) { + ifMatch = value; + } + else if (name.equals("content-type")) { + contentType = value; + } } byte[] body = new byte[length]; @@ -351,7 +443,8 @@ else if (name.equals("authorization")) { } synchronized (this) { - requests.add(new Request(requestLine[0], requestLine[1], authorization)); + requests.add(new Request(requestLine[0], requestLine[1], authorization, ifMatch, contentType, + new String(body, StandardCharsets.UTF_8))); notifyAll(); } @@ -408,7 +501,36 @@ else if (name.equals("authorization")) { answered++; } - respond(out, "201 Created", "Location: " + location + "\r\n", answer); + respond(out, "201 Created", "Location: " + location + "\r\n" + answerHeaders, answer); + return; + } + + if (requestLine[0].equals("PATCH") && "*".equals(ifMatch)) { + Function restarter = iceRestarts; + + if (restarter == null) { + respond(out, "405 Method Not Allowed", "", ""); + return; + } + if (iceRestartStatus != 200) { + respond(out, iceRestartStatus + " Status", "", ""); + return; + } + + byte[] fragment = restarter.apply(new String(body, StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8); + int restart; + + synchronized (this) { + restart = ++restarts; + } + + String head = "HTTP/1.1 200 OK\r\nContent-Type: application/trickle-ice-sdpfrag\r\nETag: \"restart-" + + restart + "\"\r\nContent-Length: " + fragment.length + "\r\nConnection: close\r\n\r\n"; + + out.write(head.getBytes(StandardCharsets.US_ASCII)); + out.write(fragment); + out.flush(); return; }