Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -598,11 +598,25 @@ 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 at once, before any candidate is gathered, and the future completes once the peer is connected. As RFC 9725 asks, the peer bundles all media on one transport (`max-bundle`), and the descriptions it sends mark each m-line `rtcp-mux-only`. 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.
By default, the offer goes to the endpoint at once, before any candidate is gathered, and the future completes once the peer is connected. As RFC 9725 asks, the peer bundles all media on one transport (`max-bundle`), and the descriptions it sends mark each m-line `rtcp-mux-only`. 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.
With the default `Gathering.TRICKLE`, 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(...)` or `turnServer(...)` 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 may still learn peer-reflexive candidates from incoming connectivity checks, but that does not cover every network topology. A 412 or 428 for the current ICE generation reaches the error handler and stops candidate PATCHes; responses to a generation replaced by a restart are ignored.

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.
For an endpoint without Trickle ICE, use `.gathering(Gathering.COMPLETE)` to include gathered candidates in the initial POST. It waits at most three seconds for gathering, within the overall session timeout, then sends the candidates available so far; any later candidates may still follow by PATCH. Configure STUN/TURN servers locally in this mode, since the endpoint's Link headers arrive after gathering. For example:

```java
Whep.Session viewer = Whep.from(endpoint)
.turnServer("turn:turn.example.com:3478", turnUsername, turnPassword)
.gathering(Gathering.COMPLETE)
.play(rtc)
.get(15, TimeUnit.SECONDS);
```

Both builders support these methods. `turnServer` is separate from `iceServer(String...)`, so passing three URLs to `iceServer` still means three URLs. The gathering setting controls the initial POST only; ICE restarts continue to use PATCH and trickled candidates.

A normal SDP answer must have status 201, a nonempty session `Location`, and Content-Type `application/sdp` (parameters are allowed). Invalid responses fail the session; a resource already named by the server is deleted even when its SDP response cannot be used.

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 and Content-Type `application/trickle-ice-sdpfrag`, brings its own ICE information and a new `ETag`. Its candidate set replaces the old one completely, including when it is empty. 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. Restarts also work after a WHEP counter-offer; the player keeps its answerer role and updates only the ICE information.

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.

Expand All @@ -617,7 +631,9 @@ 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, which replaces those the endpoint names in its answer. |
| `iceServer(String...)` | A STUN or TURN server without credentials, overriding endpoint-provided servers. |
| `turnServer(String, String, String)` | A TURN URL, username and password, overriding endpoint-provided servers. |
| `gathering(Gathering)` | When the initial offer is sent: `TRICKLE` by default, or `COMPLETE` to gather first. |
| `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream, which holds one audio and one video track at most. |
| `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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public static void main(String[] args) throws Exception {
System.out.println("Requesting the stream from " + endpoint);

// The main thread may wait for the session; a handler must not.
// For endpoints without Trickle ICE, add .gathering(Gathering.COMPLETE).
// Authenticated TURN is configured with .turnServer(url, username, password).
Whep.Session session = Whep.from(endpoint)
.iceServer("stun:stun.l.google.com:19302")
.play(rtc)
Expand Down
31 changes: 20 additions & 11 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ CompletableFuture<Void> restart() {
}
if (session == null) {
return CompletableFuture.failedFuture(new WebRtcException("ICE cannot restart: the endpoint named "
+ "no session, or answered with an offer of its own"));
+ "no session"));
}
}

Expand Down Expand Up @@ -278,6 +278,7 @@ private UnaryOperator<String> answered(HttpCall request, HttpCall.Response respo
+ response.status + ": " + response.body);
}

HttpSession.requireContentType(response, FRAGMENT_TYPE);
Fragment remote = Fragment.parse(response.body);

if (remote.ufrag == null || remote.pwd == null) {
Expand Down Expand Up @@ -326,6 +327,7 @@ private void flush() {
HttpCall request;
String body;
URI target;
Fragment generation;

synchronized (this) {
if (closed || !trickle || restarting || candidatesRequest != null || (pending.isEmpty() && !gathered)) {
Expand All @@ -351,6 +353,7 @@ private void flush() {
candidatesRequest = request;
body = fragment.toString();
target = session;
generation = local;
}

request.send(FRAGMENT_TYPE, body.getBytes(StandardCharsets.UTF_8), 0, head -> { })
Expand All @@ -360,16 +363,15 @@ private void flush() {
synchronized (this) {
candidatesRequest = null;

if (error == null && UNSUPPORTED.contains(response.status)) {
if (local == generation && 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));
// Only replies to a replaced ICE generation are obsolete.
// A 412 or 428 for the current one is a real failure.
report = !closed && local == generation && (error != null
|| (response.status / 100 != 2 && !UNSUPPORTED.contains(response.status)));

if (report) {
trickle = false;
Expand Down Expand Up @@ -707,17 +709,24 @@ boolean owns(String candidate) {

/**
* 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.
* into the remote description. The new candidate set replaces the old
* one even when empty (RFC 9725, 4.3.3).
*/
String applyTo(String answer) {
return applyTo(answer, true);
}

/** Changes local credentials without replacing locally gathered candidates. */
String applyCredentialsTo(String answer) {
return applyTo(answer, false);
}

private String applyTo(String answer, boolean replace) {
List<List<String>> 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();

Expand Down
Loading
Loading