diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 2f056eb2c..526a2b115 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -598,7 +598,7 @@ 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. 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. 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. @@ -618,7 +618,7 @@ Requests go through Java's `HttpClient`, with the default `SSLContext` and the H |---|---| | `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. | -| `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream. | +| `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. | 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 117a9667a..21533acd2 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -39,6 +39,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import dev.onvoid.webrtc.RTCBundlePolicy; +import dev.onvoid.webrtc.RTCConfiguration; import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCSdpType; import dev.onvoid.webrtc.RTCSessionDescription; @@ -273,7 +275,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e }); peer.offer() - .thenCompose(offer -> post(offerRequest, endpoint, offer.sdp, protocol, resource) + .thenCompose(offer -> post(offerRequest, endpoint, withRtcpMuxOnly(offer.sdp), protocol, resource) .whenComplete((reply, error) -> { if (finished.get()) { // The session ended while the offer was out, @@ -400,7 +402,8 @@ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient resource.set(reply.session); } - return answerRequest.send("application/sdp", answer.sdp.getBytes(StandardCharsets.UTF_8), 0, + return answerRequest.send("application/sdp", + withRtcpMuxOnly(answer.sdp).getBytes(StandardCharsets.UTF_8), 0, head -> { }).handle((response, error) -> { if (error != null) { throw new WebRtcException("Sending the answer to " + reply.session + " failed: " @@ -632,6 +635,56 @@ static URI resourceOf(URI endpoint, String location) { return resource; } + /** + * Bundles all media on one transport, as RFC 9725 asks (4.4.1), so that + * only the m-line that tags the BUNDLE group gathers candidates, the ones + * that go to the session. + */ + static void requireBundle(RTCConfiguration config) { + config.bundlePolicy = RTCBundlePolicy.MAX_BUNDLE; + } + + /** + * Marks each m-line that multiplexes RTP and RTCP as rtcp-mux-only, as RFC + * 9725 asks of what a client sends (4.4.1). WebRTC multiplexes them anyway, + * by {@code RTCRtcpMuxPolicy.REQUIRE}, but does not say so; only the + * description that goes out says it, the one applied stays as WebRTC made + * it. + * + * @param sdp a description WebRTC made. + * + * @return the description with the attribute, where it was missing. + */ + static String withRtcpMuxOnly(String sdp) { + String[] lines = sdp.split("\r?\n", -1); + StringBuilder marked = new StringBuilder(sdp.length() + 64); + boolean present = false; + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + + if (line.startsWith("m=")) { + present = false; + + for (int j = i + 1; j < lines.length && !lines[j].startsWith("m="); j++) { + present |= lines[j].equals("a=rtcp-mux-only"); + } + } + + marked.append(line); + + if (i < lines.length - 1) { + marked.append("\r\n"); + } + if (line.equals("a=rtcp-mux") && !present) { + marked.append("a=rtcp-mux-only\r\n"); + present = true; + } + } + + return marked.toString(); + } + static URI checkEndpoint(URI endpoint) { requireNonNull(endpoint, "endpoint"); 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 9d187b962..2add060a5 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java @@ -172,7 +172,8 @@ public CompletableFuture play(WebRtc rtc) { PeerOptions.Builder options = PeerOptions.builder() .name("whep-" + endpoint.getHost()) .negotiation(Negotiation.MANUAL) - .receive(receive.toArray(new MediaKind[0])); + .receive(receive.toArray(new MediaKind[0])) + .configure(HttpSession::requireBundle); for (String[] urls : iceServers) { options.iceServer(urls); 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 a3520f6ef..0e2e8230e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java @@ -22,6 +22,8 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.EnumSet; +import java.util.Locale; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -104,7 +106,8 @@ private Builder(URI endpoint) { /** * @param track a track of the runtime to publish. Tracks share one - * stream, so the server keeps audio and video in sync. + * stream, so the server keeps audio and video in sync, + * which holds one audio and one video track at most. * * @return this builder. */ @@ -160,7 +163,8 @@ public Builder timeout(Duration timeout) { * * @throws IllegalStateException if no track was given. * @throws IllegalArgumentException if a track was not created by the - * runtime. + * runtime, or two tracks are of the + * same kind. */ public CompletableFuture publish(WebRtc rtc) { requireNonNull(rtc, "rtc"); @@ -170,15 +174,23 @@ public CompletableFuture publish(WebRtc rtc) { } // Before the peer exists, so that a wrong track leaves nothing behind. + Set kinds = EnumSet.noneOf(MediaKind.class); + for (LocalTrack track : tracks) { if (!(track instanceof LocalTrackImpl) || ((LocalTrackImpl) track).rtc != rtc) { throw new IllegalArgumentException("The track " + track + " was not created by the runtime"); } + if (!kinds.add(track.kind())) { + // RFC 9725, 4.4.2: one stream, with one track of each kind. + throw new IllegalArgumentException("WHIP publishes at most one " + + track.kind().name().toLowerCase(Locale.ROOT) + " track, got another: " + track); + } } PeerOptions.Builder options = PeerOptions.builder() .name("whip-" + endpoint.getHost()) - .negotiation(Negotiation.MANUAL); + .negotiation(Negotiation.MANUAL) + .configure(HttpSession::requireBundle); for (String[] urls : iceServers) { options.iceServer(urls); 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 0b24805db..ef9caac60 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -46,6 +46,7 @@ import java.util.function.Function; import java.util.function.UnaryOperator; +import dev.onvoid.webrtc.RTCBundlePolicy; import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCSdpType; import dev.onvoid.webrtc.RTCSessionDescription; @@ -167,6 +168,62 @@ void foreignTrackLeavesNothing() throws Exception { } } + @Test + void secondTrackOfKindRefused() throws Exception { + // RFC 9725, 4.4.2: one stream, with one track of each kind at most. + try (TestHttpEndpoint endpoint = receivingEndpoint()) { + Whip.Builder whip = Whip.to(endpoint.uri()).track(video).track(rtc.media().customVideo("other")); + + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> whip.publish(rtc)); + + assertTrue(refused.getMessage().contains("at most one video track"), refused.getMessage()); + assertTrue(rtc.peers().isEmpty(), () -> "Peers left: " + rtc.peers()); + assertTrue(endpoint.requests.isEmpty()); + } + } + + @Test + void offerBundledAndMuxed() throws Exception { + // RFC 9725, 4.4.1: max-bundle, and rtcp-mux-only in each m-line. + try (TestHttpEndpoint endpoint = receivingEndpoint()) { + Whip.Session session = await(Whip.to(endpoint.uri()) + .track(video) + .track(rtc.media().customAudio("audio")) + .publish(rtc)); + String offer = endpoint.request("POST /live/endpoint").body; + RTCBundlePolicy policy = await(session.peer().withNative(connection -> + connection.getConfiguration().bundlePolicy)); + + assertEquals(RTCBundlePolicy.MAX_BUNDLE, policy); + assertEquals(2, offer.split("\r\na=rtcp-mux-only\r\n", -1).length - 1, offer); + assertEquals(2, offer.split("\r\nm=", -1).length - 1, offer); + + await(session.closeAsync()); + } + } + + @Test + void rtcpMuxOnlyMarked() { + String sdp = String.join("\r\n", + "v=0", + "a=group:BUNDLE 0 1 2", + "m=audio 9 UDP/TLS/RTP/SAVPF 111", + "a=mid:0", + "a=rtcp-mux", + "m=video 9 UDP/TLS/RTP/SAVPF 96", + "a=mid:1", + "a=rtcp-mux", + "a=rtcp-mux-only", + "m=application 9 UDP/DTLS/SCTP webrtc-datachannel", + "a=mid:2", + ""); + String marked = HttpSession.withRtcpMuxOnly(sdp); + + 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); + // Once is enough. + assertEquals(marked, HttpSession.withRtcpMuxOnly(marked)); + } + @Test void failedStartClosesPeer() throws Exception { // The session's deadline cannot be scheduled, after the peer was created. @@ -544,6 +601,7 @@ void counterOfferAnswered() throws Exception { assertEquals("Bearer secret", endpoint.requests.get(1).authorization); // WHEP asks the player's answer to receive only. assertTrue(answers.get(0).contains("a=recvonly"), answers.get(0)); + assertTrue(answers.get(0).contains("\r\na=rtcp-mux-only\r\n"), answers.get(0)); assertFalse(answers.get(0).contains("a=sendrecv"), answers.get(0)); // With its candidates, gathered anew after the player's offer was // taken back.