Skip to content

Commit 004ad36

Browse files
committed
fix: follow the WebRTC constraints of WHIP and WHEP
RFC 9725 4.4: peers of WHIP and WHEP sessions use max-bundle, so that only the tagged m-line gathers the candidates that trickle to the session; the descriptions they send mark each m-line rtcp-mux-only, which WebRTC never writes; and WHIP refuses a second track of a kind before the peer exists.
1 parent 8f509ca commit 004ad36

5 files changed

Lines changed: 132 additions & 8 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 2 additions & 2 deletions
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 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.
601+
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.
602602

603603
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.
604604

@@ -618,7 +618,7 @@ Requests go through Java's `HttpClient`, with the default `SSLContext` and the H
618618
|---|---|
619619
| `bearerToken(String)` | The token sent as `Authorization: Bearer`; for many services, the stream key. |
620620
| `iceServer(String...)` | A STUN or TURN server, which replaces those the endpoint names in its answer. |
621-
| `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream. |
621+
| `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream, which holds one audio and one video track at most. |
622622
| `receive(MediaKind...)` | What to receive, WHEP only; video and audio by default. |
623623
| `timeout(Duration)` | How long the session may take to be connected, and its deletion to be answered. |
624624

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

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
import java.util.regex.Matcher;
4040
import java.util.regex.Pattern;
4141

42+
import dev.onvoid.webrtc.RTCBundlePolicy;
43+
import dev.onvoid.webrtc.RTCConfiguration;
4244
import dev.onvoid.webrtc.RTCIceServer;
4345
import dev.onvoid.webrtc.RTCSdpType;
4446
import dev.onvoid.webrtc.RTCSessionDescription;
@@ -273,7 +275,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
273275
});
274276

275277
peer.offer()
276-
.thenCompose(offer -> post(offerRequest, endpoint, offer.sdp, protocol, resource)
278+
.thenCompose(offer -> post(offerRequest, endpoint, withRtcpMuxOnly(offer.sdp), protocol, resource)
277279
.whenComplete((reply, error) -> {
278280
if (finished.get()) {
279281
// The session ended while the offer was out,
@@ -400,7 +402,8 @@ private static CompletableFuture<Void> answerCounterOffer(WebRtc rtc, HttpClient
400402
resource.set(reply.session);
401403
}
402404

403-
return answerRequest.send("application/sdp", answer.sdp.getBytes(StandardCharsets.UTF_8), 0,
405+
return answerRequest.send("application/sdp",
406+
withRtcpMuxOnly(answer.sdp).getBytes(StandardCharsets.UTF_8), 0,
404407
head -> { }).handle((response, error) -> {
405408
if (error != null) {
406409
throw new WebRtcException("Sending the answer to " + reply.session + " failed: "
@@ -632,6 +635,56 @@ static URI resourceOf(URI endpoint, String location) {
632635
return resource;
633636
}
634637

638+
/**
639+
* Bundles all media on one transport, as RFC 9725 asks (4.4.1), so that
640+
* only the m-line that tags the BUNDLE group gathers candidates, the ones
641+
* that go to the session.
642+
*/
643+
static void requireBundle(RTCConfiguration config) {
644+
config.bundlePolicy = RTCBundlePolicy.MAX_BUNDLE;
645+
}
646+
647+
/**
648+
* Marks each m-line that multiplexes RTP and RTCP as rtcp-mux-only, as RFC
649+
* 9725 asks of what a client sends (4.4.1). WebRTC multiplexes them anyway,
650+
* by {@code RTCRtcpMuxPolicy.REQUIRE}, but does not say so; only the
651+
* description that goes out says it, the one applied stays as WebRTC made
652+
* it.
653+
*
654+
* @param sdp a description WebRTC made.
655+
*
656+
* @return the description with the attribute, where it was missing.
657+
*/
658+
static String withRtcpMuxOnly(String sdp) {
659+
String[] lines = sdp.split("\r?\n", -1);
660+
StringBuilder marked = new StringBuilder(sdp.length() + 64);
661+
boolean present = false;
662+
663+
for (int i = 0; i < lines.length; i++) {
664+
String line = lines[i];
665+
666+
if (line.startsWith("m=")) {
667+
present = false;
668+
669+
for (int j = i + 1; j < lines.length && !lines[j].startsWith("m="); j++) {
670+
present |= lines[j].equals("a=rtcp-mux-only");
671+
}
672+
}
673+
674+
marked.append(line);
675+
676+
if (i < lines.length - 1) {
677+
marked.append("\r\n");
678+
}
679+
if (line.equals("a=rtcp-mux") && !present) {
680+
marked.append("a=rtcp-mux-only\r\n");
681+
present = true;
682+
}
683+
}
684+
685+
return marked.toString();
686+
}
687+
635688
static URI checkEndpoint(URI endpoint) {
636689
requireNonNull(endpoint, "endpoint");
637690

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@ public CompletableFuture<Session> play(WebRtc rtc) {
172172
PeerOptions.Builder options = PeerOptions.builder()
173173
.name("whep-" + endpoint.getHost())
174174
.negotiation(Negotiation.MANUAL)
175-
.receive(receive.toArray(new MediaKind[0]));
175+
.receive(receive.toArray(new MediaKind[0]))
176+
.configure(HttpSession::requireBundle);
176177

177178
for (String[] urls : iceServers) {
178179
options.iceServer(urls);

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
import java.time.Duration;
2323
import java.util.ArrayList;
2424
import java.util.List;
25+
import java.util.EnumSet;
26+
import java.util.Locale;
2527
import java.util.Set;
2628
import java.util.concurrent.CompletableFuture;
2729

@@ -104,7 +106,8 @@ private Builder(URI endpoint) {
104106

105107
/**
106108
* @param track a track of the runtime to publish. Tracks share one
107-
* stream, so the server keeps audio and video in sync.
109+
* stream, so the server keeps audio and video in sync,
110+
* which holds one audio and one video track at most.
108111
*
109112
* @return this builder.
110113
*/
@@ -160,7 +163,8 @@ public Builder timeout(Duration timeout) {
160163
*
161164
* @throws IllegalStateException if no track was given.
162165
* @throws IllegalArgumentException if a track was not created by the
163-
* runtime.
166+
* runtime, or two tracks are of the
167+
* same kind.
164168
*/
165169
public CompletableFuture<Session> publish(WebRtc rtc) {
166170
requireNonNull(rtc, "rtc");
@@ -170,15 +174,23 @@ public CompletableFuture<Session> publish(WebRtc rtc) {
170174
}
171175

172176
// Before the peer exists, so that a wrong track leaves nothing behind.
177+
Set<MediaKind> kinds = EnumSet.noneOf(MediaKind.class);
178+
173179
for (LocalTrack track : tracks) {
174180
if (!(track instanceof LocalTrackImpl) || ((LocalTrackImpl) track).rtc != rtc) {
175181
throw new IllegalArgumentException("The track " + track + " was not created by the runtime");
176182
}
183+
if (!kinds.add(track.kind())) {
184+
// RFC 9725, 4.4.2: one stream, with one track of each kind.
185+
throw new IllegalArgumentException("WHIP publishes at most one "
186+
+ track.kind().name().toLowerCase(Locale.ROOT) + " track, got another: " + track);
187+
}
177188
}
178189

179190
PeerOptions.Builder options = PeerOptions.builder()
180191
.name("whip-" + endpoint.getHost())
181-
.negotiation(Negotiation.MANUAL);
192+
.negotiation(Negotiation.MANUAL)
193+
.configure(HttpSession::requireBundle);
182194

183195
for (String[] urls : iceServers) {
184196
options.iceServer(urls);

‎webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
import java.util.function.Function;
4747
import java.util.function.UnaryOperator;
4848

49+
import dev.onvoid.webrtc.RTCBundlePolicy;
4950
import dev.onvoid.webrtc.RTCIceServer;
5051
import dev.onvoid.webrtc.RTCSdpType;
5152
import dev.onvoid.webrtc.RTCSessionDescription;
@@ -167,6 +168,62 @@ void foreignTrackLeavesNothing() throws Exception {
167168
}
168169
}
169170

171+
@Test
172+
void secondTrackOfKindRefused() throws Exception {
173+
// RFC 9725, 4.4.2: one stream, with one track of each kind at most.
174+
try (TestHttpEndpoint endpoint = receivingEndpoint()) {
175+
Whip.Builder whip = Whip.to(endpoint.uri()).track(video).track(rtc.media().customVideo("other"));
176+
177+
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> whip.publish(rtc));
178+
179+
assertTrue(refused.getMessage().contains("at most one video track"), refused.getMessage());
180+
assertTrue(rtc.peers().isEmpty(), () -> "Peers left: " + rtc.peers());
181+
assertTrue(endpoint.requests.isEmpty());
182+
}
183+
}
184+
185+
@Test
186+
void offerBundledAndMuxed() throws Exception {
187+
// RFC 9725, 4.4.1: max-bundle, and rtcp-mux-only in each m-line.
188+
try (TestHttpEndpoint endpoint = receivingEndpoint()) {
189+
Whip.Session session = await(Whip.to(endpoint.uri())
190+
.track(video)
191+
.track(rtc.media().customAudio("audio"))
192+
.publish(rtc));
193+
String offer = endpoint.request("POST /live/endpoint").body;
194+
RTCBundlePolicy policy = await(session.peer().withNative(connection ->
195+
connection.getConfiguration().bundlePolicy));
196+
197+
assertEquals(RTCBundlePolicy.MAX_BUNDLE, policy);
198+
assertEquals(2, offer.split("\r\na=rtcp-mux-only\r\n", -1).length - 1, offer);
199+
assertEquals(2, offer.split("\r\nm=", -1).length - 1, offer);
200+
201+
await(session.closeAsync());
202+
}
203+
}
204+
205+
@Test
206+
void rtcpMuxOnlyMarked() {
207+
String sdp = String.join("\r\n",
208+
"v=0",
209+
"a=group:BUNDLE 0 1 2",
210+
"m=audio 9 UDP/TLS/RTP/SAVPF 111",
211+
"a=mid:0",
212+
"a=rtcp-mux",
213+
"m=video 9 UDP/TLS/RTP/SAVPF 96",
214+
"a=mid:1",
215+
"a=rtcp-mux",
216+
"a=rtcp-mux-only",
217+
"m=application 9 UDP/DTLS/SCTP webrtc-datachannel",
218+
"a=mid:2",
219+
"");
220+
String marked = HttpSession.withRtcpMuxOnly(sdp);
221+
222+
assertEquals(sdp.replace("a=mid:0\r\na=rtcp-mux\r\n", "a=mid:0\r\na=rtcp-mux\r\na=rtcp-mux-only\r\n"), marked);
223+
// Once is enough.
224+
assertEquals(marked, HttpSession.withRtcpMuxOnly(marked));
225+
}
226+
170227
@Test
171228
void failedStartClosesPeer() throws Exception {
172229
// The session's deadline cannot be scheduled, after the peer was created.
@@ -544,6 +601,7 @@ void counterOfferAnswered() throws Exception {
544601
assertEquals("Bearer secret", endpoint.requests.get(1).authorization);
545602
// WHEP asks the player's answer to receive only.
546603
assertTrue(answers.get(0).contains("a=recvonly"), answers.get(0));
604+
assertTrue(answers.get(0).contains("\r\na=rtcp-mux-only\r\n"), answers.get(0));
547605
assertFalse(answers.get(0).contains("a=sendrecv"), answers.get(0));
548606
// With its candidates, gathered anew after the player's offer was
549607
// taken back.

0 commit comments

Comments
 (0)