Skip to content

Commit 2ff7d29

Browse files
committed
fix: let WHIP and WHEP pick codecs, offer video for audio-only WHIP
videoCodecs() and audioCodecs() negotiate only the codecs named, in order, also in the answer to a WHEP counter-offer; endpoints that pass the stream on often take only H.264 and Opus. Whip.alwaysOfferVideo() adds send-only video without a track for endpoints that refuse an offer without video, such as Amazon IVS. The docs note that MediaMTX takes user:password as the bearer token.
1 parent fd8eb0e commit 2ff7d29

6 files changed

Lines changed: 460 additions & 13 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -614,6 +614,21 @@ Whep.Session viewer = Whep.from(endpoint)
614614

615615
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.
616616

617+
By default, the offer holds every codec WebRTC has, in WebRTC's order, and the endpoint picks; one that follows the offer's order picks VP8 for video. Endpoints that pass the stream on unchanged, to HLS or a recording, often take only H.264 and Opus. `videoCodecs(...)` and `audioCodecs(...)` offer only the codecs named, in that order of preference, by name (`H264`, `VP8`, `VP9`, `AV1`, `opus`, `G722`, ...) or MIME type (`video/H264`), whatever the case. Retransmission, redundancy, FEC, comfort noise and DTMF go along. For WHEP, they decide what the endpoint sends, also in the answer to a counter-offer. A name WebRTC has no codec of fails the session with a `ConfigurationException` before the offer goes out.
618+
619+
Some endpoints, Amazon IVS among them, refuse a WHIP offer without video, even for audio alone. `alwaysOfferVideo()` then adds video that only sends, in the stream of the tracks, without a track, so that nothing is sent on it; with a video track, it changes nothing:
620+
621+
```java
622+
Whip.Session live = Whip.to(URI.create("https://example.com/live/whip"))
623+
.bearerToken(token)
624+
.videoCodecs("H264")
625+
.audioCodecs("opus")
626+
.track(rtc.media().microphone())
627+
.alwaysOfferVideo()
628+
.publish(rtc)
629+
.get(15, TimeUnit.SECONDS);
630+
```
631+
617632
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.
618633

619634
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.
@@ -626,16 +641,20 @@ Endpoints have to be `https` URLs, as WHIP and WHEP ask, except on the machine t
626641

627642
The bearer token goes to the endpoint, and along with the deletion to the session the endpoint names in its `Location` header. That session may be on another host, but an `https` endpoint cannot name a plain `http` one. The offer follows redirects with status 307 and 308, as WHIP and WHEP ask of clients, such as those of a load balancer: up to five of them, all within the timeout, and the token goes along. A redirect from `https` to plain `http` fails the session, and so does one with status 301, 302 or 303, which would turn the offer into a `GET`. The deletion follows no redirect; one fails it with its status.
628643

644+
Servers that ask for a user and password rather than a token, such as MediaMTX, take them as the token, the way OBS Studio sends them: `bearerToken("user:password")` sends `Authorization: Bearer user:password`.
645+
629646
Requests go through Java's `HttpClient`, with the default `SSLContext` and the HTTP proxy Java is configured with, the first the default `ProxySelector` names: `-Dhttps.proxyHost` and `-Dhttps.proxyPort`, `-Dhttp.proxyHost`, or `-Djava.net.useSystemProxies=true`. `HttpClient` takes no SOCKS proxies. A proxy that asks for credentials gets Basic ones from the default `Authenticator`, but only for sessions without a bearer token: `HttpClient` drops the token of a request once it answers for credentials itself. As in Java, Basic is not used for the tunnel of an `https` request unless `jdk.http.auth.tunneling.disabledSchemes` allows it. Other schemes, such as Digest, NTLM and Negotiate, are not supported.
630647

631648
| Builder method | What it sets |
632649
|---|---|
633-
| `bearerToken(String)` | The token sent as `Authorization: Bearer`; for many services, the stream key. |
650+
| `bearerToken(String)` | The token sent as `Authorization: Bearer`; for many services, the stream key, for MediaMTX `user:password`. |
634651
| `iceServer(String...)` | A STUN or TURN server without credentials, overriding endpoint-provided servers. |
635652
| `turnServer(String, String, String)` | A TURN URL, username and password, overriding endpoint-provided servers. |
636653
| `gathering(Gathering)` | When the initial offer is sent: `TRICKLE` by default, or `COMPLETE` to gather first. |
637654
| `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream, which holds one audio and one video track at most. |
638655
| `receive(MediaKind...)` | What to receive, WHEP only; video and audio by default. |
656+
| `videoCodecs(String...)`, `audioCodecs(String...)` | The only codecs to negotiate, in order of preference; every codec WebRTC has by default. |
657+
| `alwaysOfferVideo()` | Video in the offer even without a video track, WHIP only, for endpoints that refuse an offer without video. |
639658
| `timeout(Duration)` | How long the session may take to be connected, and its deletion to be answered. |
640659

641660
## Manual Negotiation

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

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.time.ZonedDateTime;
2626
import java.time.format.DateTimeFormatter;
2727
import java.time.format.DateTimeParseException;
28+
import java.util.ArrayList;
2829
import java.util.Collections;
2930
import java.util.List;
3031
import java.util.Set;
@@ -194,18 +195,22 @@ public void close() {
194195
* a server that does not answer holds no connection; what it creates for
195196
* an offer it had yet to answer is left for it to time out.
196197
*
198+
* @param prepared the steps that set the peer up for the offer, which
199+
* fail the session if they fail.
197200
* @param gathering when the initial offer is sent.
198201
* @param protocol what WHIP or WHEP asks beyond the offer and its answer.
199202
* @param factory makes the session of the connected peer.
200203
*
201204
* @return the future handed to the application.
202205
*/
203206
static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl peer, URI endpoint,
204-
String bearerToken, Duration timeout, Gathering gathering, Protocol protocol, Factory<S> factory) {
207+
String bearerToken, Duration timeout, CompletableFuture<?> prepared, Gathering gathering,
208+
Protocol protocol, Factory<S> factory) {
205209
CompletableFuture<Void> abandoned = new CompletableFuture<>();
206210
HttpIce ice = new HttpIce(rtc, rtc.httpClient(bearerToken != null), peer, bearerToken, timeout);
207-
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, gathering, protocol,
208-
ice, abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout, ice)),
211+
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, prepared,
212+
gathering, protocol, ice, abandoned)
213+
.thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout, ice)),
209214
HttpSession::close);
210215

211216
// Once the session was handed out, this finds the negotiation finished.
@@ -225,14 +230,16 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
225230
* the initial offer is applied and gathered before POST; endpoint-provided
226231
* ICE servers then arrive too late for this gathering and are ignored.
227232
*
233+
* @param prepared completes once the peer is set up for the offer.
228234
* @param ice the ICE of the session once the offer is answered.
229235
* @param abandoned completes when no one waits for the session anymore,
230236
* which then ends as if it had failed.
231237
*
232238
* @return a future with the resource the server named, or null.
233239
*/
234240
private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI endpoint, String bearerToken,
235-
Duration timeout, Gathering gathering, Protocol protocol, HttpIce ice, CompletableFuture<?> abandoned) {
241+
Duration timeout, CompletableFuture<?> prepared, Gathering gathering, Protocol protocol, HttpIce ice,
242+
CompletableFuture<?> abandoned) {
236243
CompletableFuture<URI> result = new CompletableFuture<>();
237244
long started = System.nanoTime();
238245
// The resource the server created. Whoever takes it out owns it: the
@@ -277,8 +284,8 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
277284
fail.accept(new CancellationException("The session with " + endpoint + " was abandoned"));
278285
});
279286

280-
CompletableFuture<RTCSessionDescription> initial = gathering == Gathering.COMPLETE
281-
? peer.negotiator().createOffer(Gathering.COMPLETE) : peer.offer();
287+
CompletableFuture<RTCSessionDescription> initial = prepared.thenCompose(ready -> gathering == Gathering.COMPLETE
288+
? peer.negotiator().createOffer(Gathering.COMPLETE) : peer.offer());
282289
initial
283290
.thenCompose(offer -> post(offerRequest, endpoint, withRtcpMuxOnly(offer.sdp), protocol, resource)
284291
.whenComplete((reply, error) -> {
@@ -708,6 +715,31 @@ static void requireContentType(HttpCall.Response response, String expected) {
708715
}
709716
}
710717

718+
/**
719+
* Checks the codec names given to a builder.
720+
*
721+
* @return the names, trimmed, in their order.
722+
*
723+
* @throws IllegalArgumentException if there are none, or one is blank.
724+
*/
725+
static List<String> codecNames(String... names) {
726+
if (names.length == 0) {
727+
throw new IllegalArgumentException("Name at least one codec");
728+
}
729+
730+
List<String> checked = new ArrayList<>();
731+
732+
for (String name : names) {
733+
if (requireNonNull(name, "name").trim().isEmpty()) {
734+
throw new IllegalArgumentException("A codec name is blank");
735+
}
736+
737+
checked.add(name.trim());
738+
}
739+
740+
return Collections.unmodifiableList(checked);
741+
}
742+
711743
static URI checkEndpoint(URI endpoint) {
712744
requireNonNull(endpoint, "endpoint");
713745

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

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,16 @@
2121
import java.time.Duration;
2222
import java.util.ArrayDeque;
2323
import java.util.ArrayList;
24+
import java.util.Arrays;
2425
import java.util.Collections;
2526
import java.util.HashMap;
27+
import java.util.EnumMap;
2628
import java.util.EnumSet;
2729
import java.util.HashSet;
30+
import java.util.LinkedHashMap;
31+
import java.util.LinkedHashSet;
2832
import java.util.List;
33+
import java.util.Locale;
2934
import java.util.Map;
3035
import java.util.Set;
3136
import java.util.UUID;
@@ -56,6 +61,8 @@
5661
import dev.onvoid.webrtc.RTCOfferOptions;
5762
import dev.onvoid.webrtc.RTCPeerConnection;
5863
import dev.onvoid.webrtc.RTCPeerConnectionState;
64+
import dev.onvoid.webrtc.RTCRtpCapabilities;
65+
import dev.onvoid.webrtc.RTCRtpCodecCapability;
5966
import dev.onvoid.webrtc.RTCRtpReceiver;
6067
import dev.onvoid.webrtc.RTCRtpTransceiver;
6168
import dev.onvoid.webrtc.RTCRtpTransceiverDirection;
@@ -96,6 +103,13 @@ final class PeerImpl implements Peer {
96103
/** How long an impolite peer waits for an answer after it ignored an offer. */
97104
private static final long COLLISION_TIMEOUT_MS = 5000;
98105

106+
/**
107+
* The codecs that go along with those a session names: retransmission,
108+
* redundancy, FEC, comfort noise and DTMF, which serve the media codecs.
109+
*/
110+
private static final Set<String> COMPANION_CODECS = Set.of("rtx", "red", "ulpfec", "flexfec-03", "cn",
111+
"telephone-event");
112+
99113
final WebRtc rtc;
100114

101115
final String name;
@@ -180,6 +194,12 @@ final class PeerImpl implements Peer {
180194
*/
181195
private final Set<MediaKind> declinedKinds = EnumSet.noneOf(MediaKind.class);
182196

197+
/**
198+
* The codecs each kind of media is negotiated with, in order, for the
199+
* kinds a session named codecs of. Only on the control executor.
200+
*/
201+
private final Map<MediaKind, List<RTCRtpCodecCapability>> codecs = new EnumMap<>(MediaKind.class);
202+
183203
/** Gets the local candidates as well, or null. Called on the control executor. */
184204
private volatile Consumer<RTCIceCandidate> candidateListener;
185205

@@ -479,6 +499,135 @@ CompletableFuture<Void> sendOnly() {
479499
});
480500
}
481501

502+
/**
503+
* Adds video that only sends, without a track, to the stream of the
504+
* tracks added without stream ids, for endpoints that take no offer
505+
* without video. Ordered with the negotiation steps.
506+
*/
507+
CompletableFuture<Void> addVideoWithoutTrack() {
508+
return negotiator.run(() -> {
509+
RTCRtpTransceiverInit init = new RTCRtpTransceiverInit();
510+
init.direction = RTCRtpTransceiverDirection.SEND_ONLY;
511+
init.streamIds.add(defaultStreamId);
512+
513+
connection.addTransceiver(MediaType.VIDEO, init).dispose();
514+
515+
return CompletableFuture.completedFuture(null);
516+
});
517+
}
518+
519+
/**
520+
* Negotiates only the codecs of the given names, in that order, for each
521+
* kind of media given, together with the companion codecs WebRTC pairs
522+
* with them. This holds for the transceivers there are, and for those an
523+
* offer adds later, as a counter-offer this peer answers instead of its
524+
* own. Ordered with the negotiation steps, so it takes effect on the next
525+
* offer or answer.
526+
*
527+
* @param names the codec names of each kind, such as H264 or opus.
528+
*
529+
* @return a future that fails if WebRTC has no codec of a name.
530+
*/
531+
CompletableFuture<Void> preferCodecs(Map<MediaKind, List<String>> names) {
532+
return negotiator.run(() -> {
533+
for (Map.Entry<MediaKind, List<String>> entry : names.entrySet()) {
534+
codecs.put(entry.getKey(), codecsNamed(entry.getKey(), entry.getValue()));
535+
}
536+
537+
applyCodecs();
538+
539+
return CompletableFuture.completedFuture(null);
540+
});
541+
}
542+
543+
/**
544+
* Finds the codecs of the given names that WebRTC sends or receives,
545+
* followed by the companion codecs.
546+
*
547+
* @throws ConfigurationException if WebRTC has no codec of a name.
548+
*/
549+
private List<RTCRtpCodecCapability> codecsNamed(MediaKind kind, List<String> names) {
550+
MediaType type = kind == MediaKind.AUDIO ? MediaType.AUDIO : MediaType.VIDEO;
551+
// Those WebRTC sends and receives, each once. WebRTC tells codecs
552+
// apart as this key does, not by their scalability modes, in which
553+
// the two lists differ; one codec twice would be offered twice.
554+
Map<List<Object>, RTCRtpCodecCapability> available = new LinkedHashMap<>();
555+
556+
for (RTCRtpCapabilities capabilities : List.of(rtc.factory.getRtpSenderCapabilities(type),
557+
rtc.factory.getRtpReceiverCapabilities(type))) {
558+
for (RTCRtpCodecCapability codec : capabilities.getCodecs()) {
559+
available.putIfAbsent(Arrays.asList(codec.getMimeType().toLowerCase(Locale.ROOT),
560+
codec.getClockRate(), codec.getSDPFmtp()), codec);
561+
}
562+
}
563+
564+
List<RTCRtpCodecCapability> named = new ArrayList<>();
565+
566+
for (String name : names) {
567+
boolean found = false;
568+
569+
for (RTCRtpCodecCapability codec : available.values()) {
570+
if ((codec.getName().equalsIgnoreCase(name) || codec.getMimeType().equalsIgnoreCase(name))
571+
&& !named.contains(codec)) {
572+
named.add(codec);
573+
found = true;
574+
}
575+
}
576+
577+
if (!found) {
578+
Set<String> known = new LinkedHashSet<>();
579+
available.values().forEach(codec -> known.add(codec.getName()));
580+
581+
throw new ConfigurationException("WebRTC has no " + kind.name().toLowerCase(Locale.ROOT)
582+
+ " codec " + name + " for " + this.name + ", only " + known);
583+
}
584+
}
585+
586+
for (RTCRtpCodecCapability codec : available.values()) {
587+
if (COMPANION_CODECS.contains(codec.getName().toLowerCase(Locale.ROOT)) && !named.contains(codec)) {
588+
named.add(codec);
589+
}
590+
}
591+
592+
return named;
593+
}
594+
595+
/**
596+
* Sets the codecs of {@link #preferCodecs} on every transceiver that has
597+
* not stopped.
598+
*/
599+
private void applyCodecs() {
600+
if (codecs.isEmpty()) {
601+
return;
602+
}
603+
604+
for (RTCRtpTransceiver transceiver : connection.getTransceivers()) {
605+
try {
606+
if (transceiver.stopped()) {
607+
continue;
608+
}
609+
610+
RTCRtpReceiver receiver = transceiver.getReceiver();
611+
MediaStreamTrack track = receiver.getTrack();
612+
MediaKind kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind())
613+
? MediaKind.AUDIO
614+
: MediaKind.VIDEO;
615+
616+
track.dispose();
617+
receiver.dispose();
618+
619+
List<RTCRtpCodecCapability> preferred = codecs.get(kind);
620+
621+
if (preferred != null) {
622+
transceiver.setCodecPreferences(preferred);
623+
}
624+
}
625+
finally {
626+
transceiver.dispose();
627+
}
628+
}
629+
}
630+
482631
/**
483632
* Gathers candidates from now on with the given ICE servers, unless the
484633
* peer was built with servers of its own, which take precedence.
@@ -658,6 +807,8 @@ CompletableFuture<RTCSessionDescription> answerInstead(RTCSessionDescription off
658807
.thenCompose(ignored -> setRemote(offer))
659808
.thenCompose(ignored -> {
660809
stopTransceivers(rejected);
810+
// The offer made transceivers of its own.
811+
applyCodecs();
661812
releaseHeldCandidates();
662813
return createAnswer();
663814
})

0 commit comments

Comments
 (0)