Skip to content

Commit b2aabab

Browse files
committed
feat: reject the unwanted media of a WHEP counter-offer
The answer to a counter-offer rejects, with port 0, the audio or video m-lines of kinds the player does not receive, and fails if none is left. RTCRtpTransceiver.stopImmediately() stops a transceiver at once, through StopInternal, since an answer only rejects the m-lines of stopped ones; stop() leaves them inactive.
1 parent d013e71 commit b2aabab

7 files changed

Lines changed: 217 additions & 13 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
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 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. Every m-line of the counter-offer is 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 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.
602602

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

‎webrtc-jni/src/main/cpp/include/JNI_RTCRtpTransceiver.h‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webrtc-jni/src/main/cpp/src/JNI_RTCRtpTransceiver.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,17 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stop
152152
}
153153
}
154154

155+
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stopImmediately
156+
(JNIEnv * env, jobject caller)
157+
{
158+
webrtc::RtpTransceiverInterface * transceiver = GetHandle<webrtc::RtpTransceiverInterface>(env, caller);
159+
CHECK_HANDLE(transceiver);
160+
161+
// Unlike StopStandard, stopped() is true at once, so that an answer
162+
// created next rejects the m-line rather than making it inactive.
163+
transceiver->StopInternal();
164+
}
165+
155166
JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stopped
156167
(JNIEnv * env, jobject caller)
157168
{

‎webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpTransceiver.java‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,22 @@ private RTCRtpTransceiver() {
9696
* will no longer send, the receiver will no longer receive. Calling stop()
9797
* updates the negotiation-needed flag for the RTCRtpTransceiver's
9898
* associated RTCPeerConnection. Stopping a transceiver will cause future
99-
* calls to createOffer or createAnswer to generate a zero port in the media
100-
* description for the corresponding transceiver.
99+
* calls to createOffer to generate a zero port in the media description
100+
* for the corresponding transceiver. An answer created before the stop
101+
* has been negotiated keeps the media description, as inactive; {@link
102+
* #stopImmediately()} rejects it instead.
101103
*/
102104
public native void stop();
103105

106+
/**
107+
* Irreversibly stops the RTCRtpTransceiver at once, without waiting for
108+
* the stop to be negotiated, as {@link #stop()} does. An answer created
109+
* after it rejects the media description of the transceiver, with a zero
110+
* port, which lets an answerer decline a media description of a remote
111+
* offer. This goes beyond the W3C API.
112+
*/
113+
public native void stopImmediately();
114+
104115
/**
105116
* Indicates that the sender of this transceiver will no longer send, and
106117
* that the receiver will no longer receive. It is true if either stop has

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

Lines changed: 110 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@
2323
import java.util.ArrayList;
2424
import java.util.Collections;
2525
import java.util.HashMap;
26+
import java.util.EnumSet;
27+
import java.util.HashSet;
2628
import java.util.List;
2729
import java.util.Map;
30+
import java.util.Set;
2831
import java.util.UUID;
2932
import java.util.concurrent.CompletableFuture;
3033
import java.util.concurrent.CompletionException;
@@ -167,6 +170,13 @@ final class PeerImpl implements Peer {
167170

168171
private final NegotiatorImpl negotiator = new NegotiatorImpl();
169172

173+
/**
174+
* The kinds of media whose tracks this peer drops, those it declined when
175+
* it answered an offer that replaced its own. Only on the control
176+
* executor.
177+
*/
178+
private final Set<MediaKind> declinedKinds = EnumSet.noneOf(MediaKind.class);
179+
170180

171181
PeerImpl(WebRtc rtc, PeerOptions options, String name) {
172182
this.rtc = rtc;
@@ -423,21 +433,106 @@ public Negotiator negotiator() {
423433
* Takes this peer's own offer back and answers the given one instead, as
424434
* a WHEP player does when the server counters its offer. Unlike {@link
425435
* Negotiator#answer}, which fails while an offer of this peer is out.
436+
* <p>
437+
* The answer receives only the kinds of media the peer was built to
438+
* receive: the audio or video m-lines of other kinds are rejected, with
439+
* port 0. An offer without any m-line of those kinds fails.
426440
*
427441
* @param offer the offer that replaces this peer's own.
428442
* @param gathering when the answer is handed over.
429443
*
430444
* @return a future with the answer, applied as the local description.
431445
*/
432446
CompletableFuture<RTCSessionDescription> answerInstead(RTCSessionDescription offer, Gathering gathering) {
433-
return negotiator.run(() -> setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, ""))
434-
.thenCompose(ignored -> setRemote(offer))
435-
.thenCompose(ignored -> {
436-
releaseHeldCandidates();
437-
return createAnswer();
438-
})
439-
.thenCompose(this::setLocal)
440-
.thenCompose(ignored -> negotiator.gathered(gathering)));
447+
Set<String> rejected;
448+
449+
try {
450+
rejected = midsNotReceived(offer.sdp);
451+
}
452+
catch (NegotiationException e) {
453+
return toPublic(CompletableFuture.failedFuture(e));
454+
}
455+
456+
return negotiator.run(() -> {
457+
// Before the offer is applied, which reports the tracks of the
458+
// m-lines that are then rejected.
459+
for (MediaKind kind : MediaKind.values()) {
460+
if (!options.receive.contains(kind)) {
461+
declinedKinds.add(kind);
462+
}
463+
}
464+
465+
return setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, ""))
466+
.thenCompose(ignored -> setRemote(offer))
467+
.thenCompose(ignored -> {
468+
stopTransceivers(rejected);
469+
releaseHeldCandidates();
470+
return createAnswer();
471+
})
472+
.thenCompose(this::setLocal)
473+
.thenCompose(ignored -> negotiator.gathered(gathering));
474+
});
475+
}
476+
477+
/**
478+
* Finds the audio and video m-lines of an offer whose kind this peer does
479+
* not receive.
480+
*
481+
* @return their mids.
482+
*
483+
* @throws NegotiationException if the offer has no open m-line of a kind
484+
* this peer receives.
485+
*/
486+
private Set<String> midsNotReceived(String sdp) {
487+
Set<String> rejected = new HashSet<>();
488+
boolean received = false;
489+
MediaKind kind = null;
490+
491+
for (String line : sdp.split("\r?\n")) {
492+
if (line.startsWith("m=")) {
493+
String[] fields = line.substring(2).split(" ");
494+
boolean open = fields.length > 1 && !fields[1].equals("0");
495+
496+
kind = !open ? null
497+
: fields[0].equals("audio") ? MediaKind.AUDIO
498+
: fields[0].equals("video") ? MediaKind.VIDEO
499+
: null;
500+
received |= kind != null && options.receive.contains(kind);
501+
}
502+
else if (line.startsWith("a=mid:") && kind != null && !options.receive.contains(kind)) {
503+
rejected.add(line.substring("a=mid:".length()).trim());
504+
}
505+
}
506+
507+
if (!received) {
508+
throw new NegotiationException("The offer of the remote peer of " + name
509+
+ " holds none of the media it receives, " + options.receive);
510+
}
511+
512+
return rejected;
513+
}
514+
515+
/**
516+
* Stops the transceivers of the given mids, whose m-lines the next
517+
* answer then rejects.
518+
*/
519+
private void stopTransceivers(Set<String> mids) {
520+
if (mids.isEmpty()) {
521+
return;
522+
}
523+
524+
for (RTCRtpTransceiver transceiver : connection.getTransceivers()) {
525+
try {
526+
if (mids.contains(transceiver.getMid()) && !transceiver.stopped()) {
527+
// At once: an answer rejects only the m-lines of stopped
528+
// transceivers, and keeps those still stopping, inactive.
529+
transceiver.stopImmediately();
530+
}
531+
}
532+
finally {
533+
transceiver.dispose();
534+
}
535+
}
441536
}
442537

443538
@Override
@@ -1132,6 +1227,13 @@ private void trackAdded(RTCRtpReceiver receiver, MediaStream[] streams) {
11321227
MediaStreamTrack track = receiver.getTrack();
11331228
String id = track.getId();
11341229

1230+
if (declinedKinds.contains(track instanceof VideoTrack ? MediaKind.VIDEO : MediaKind.AUDIO)) {
1231+
// Of an m-line this peer rejected, when it answered an offer that
1232+
// replaced its own.
1233+
track.dispose();
1234+
receiver.dispose();
1235+
return;
1236+
}
11351237
if (remoteTrackById.containsKey(id)) {
11361238
// Renegotiation reported a track that is already known.
11371239
track.dispose();

‎webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpTransceiverTests.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
44
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertFalse;
56
import static org.junit.jupiter.api.Assertions.assertNotNull;
7+
import static org.junit.jupiter.api.Assertions.assertTrue;
68

79
import dev.onvoid.webrtc.media.MediaType;
810
import dev.onvoid.webrtc.media.audio.AudioOptions;
@@ -94,4 +96,34 @@ void senderAndReceiverAreIndependentlyDisposable() {
9496
assertDoesNotThrow(transceiver::dispose);
9597
}
9698

99+
@Test
100+
void stopImmediatelyRejectsInAnswer() throws Exception {
101+
// The answerer declines the audio of an offer of audio and video. With
102+
// stop(), the answer would keep the audio, as inactive.
103+
TestPeerConnection offerer = new TestPeerConnection(factory);
104+
105+
try {
106+
offerer.getPeerConnection().addTransceiver(MediaType.AUDIO, new RTCRtpTransceiverInit()).dispose();
107+
offerer.getPeerConnection().addTransceiver(MediaType.VIDEO, new RTCRtpTransceiverInit()).dispose();
108+
connection.setRemoteDescription(offerer.createOffer());
109+
110+
for (RTCRtpTransceiver transceiver : connection.getPeerConnection().getTransceivers()) {
111+
if ("0".equals(transceiver.getMid())) {
112+
transceiver.stopImmediately();
113+
assertTrue(transceiver.stopped());
114+
}
115+
116+
transceiver.dispose();
117+
}
118+
119+
String answer = connection.createAnswer().sdp;
120+
121+
assertTrue(answer.contains("m=audio 0 "), answer);
122+
assertFalse(answer.contains("m=video 0 "), answer);
123+
}
124+
finally {
125+
offerer.close();
126+
}
127+
}
128+
97129
}

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

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,41 @@ void counterOfferAnswered() throws Exception {
366366
}
367367
}
368368

369+
@Test
370+
void counterOfferMediaRejected() throws Exception {
371+
// The endpoint offers audio and video; the player wants only video, and
372+
// rejects the audio m-line, with port 0, as WHEP allows.
373+
List<String> answers = new CopyOnWriteArrayList<>();
374+
CustomAudio audio = rtc.media().customAudio("audio");
375+
376+
try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", answers, video, audio)) {
377+
Whep.Session session = await(Whep.from(endpoint.uri()).receive(MediaKind.VIDEO).play(rtc));
378+
379+
CompletableFuture<Integer> width = new CompletableFuture<>();
380+
session.peer().onTrack(track -> track.asVideo().onFrame(frame -> width.complete(frame.buffer.getWidth())));
381+
382+
assertEquals(160, (int) await(width));
383+
assertTrue(answers.get(0).contains("\nm=audio 0 "), answers.get(0));
384+
assertFalse(answers.get(0).contains("\nm=video 0 "), answers.get(0));
385+
// The handler, which takes every track as video, saw no audio.
386+
assertTrue(errors.isEmpty(), () -> "Errors: " + errors);
387+
388+
await(session.closeAsync());
389+
}
390+
}
391+
392+
@Test
393+
void counterOfferWithoutWantedMediaFails() throws Exception {
394+
// At least one audio or video m-line has to be accepted.
395+
try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", new ArrayList<>())) {
396+
ExecutionException failed = assertThrows(ExecutionException.class,
397+
() -> await(Whep.from(endpoint.uri()).receive(MediaKind.AUDIO).play(rtc)));
398+
399+
assertTrue(failed.getCause().getMessage().contains("none of the media"), failed.getCause().getMessage());
400+
assertEquals(0, endpoint.count("PATCH /live/session/1"));
401+
}
402+
}
403+
369404
@Test
370405
void counterOfferNeedsSdp() throws Exception {
371406
// Any other 406 is an error, as WHEP says.
@@ -807,14 +842,19 @@ void resourceKeepsTls() {
807842
*
808843
* @param contentType the Content-Type of the counter-offer.
809844
* @param answers gets the answers.
845+
* @param tracks what the endpoint sends; the video if none.
810846
*/
811-
private TestHttpEndpoint counteringEndpoint(String contentType, List<String> answers) throws Exception {
847+
private TestHttpEndpoint counteringEndpoint(String contentType, List<String> answers, LocalTrack... tracks)
848+
throws Exception {
812849
TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "", 201);
813850
Peer[] server = new Peer[1];
814851

815852
endpoint.counterOffers(() -> {
816853
server[0] = rtc.createPeer(PeerOptions.builder().negotiation(Negotiation.MANUAL).build());
817-
server[0].addTrack(video);
854+
855+
for (LocalTrack track : tracks.length > 0 ? tracks : new LocalTrack[] { video }) {
856+
server[0].addTrack(track);
857+
}
818858

819859
try {
820860
return server[0].negotiator().createOffer(Gathering.COMPLETE)

0 commit comments

Comments
 (0)