Skip to content

Commit 05dc8a7

Browse files
authored
refactor: split PeerImpl along its responsibilities (#531)
* fix: run onStats handlers on the event executor A sample attached its callback to the public future from the timer's thread, so a report read by then ran the handler on that thread. * test: pin where peer handlers run and what late handlers get * refactor: move peer statistics into StatsSampler * refactor: move data channel bookkeeping into DataChannels * refactor: move remote track bookkeeping into RemoteTracks * refactor: move codec selection into CodecPreferences * refactor: move the signaling transport into SignalingLink * refactor: move manual negotiation and WHIP/WHEP steps into ManualNegotiation
1 parent 9e450ec commit 05dc8a7

14 files changed

Lines changed: 1476 additions & 879 deletions

File tree

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import java.util.ArrayList;
20+
import java.util.Arrays;
21+
import java.util.EnumMap;
22+
import java.util.LinkedHashMap;
23+
import java.util.LinkedHashSet;
24+
import java.util.List;
25+
import java.util.Locale;
26+
import java.util.Map;
27+
import java.util.Set;
28+
29+
import dev.onvoid.webrtc.RTCRtpCapabilities;
30+
import dev.onvoid.webrtc.RTCRtpCodecCapability;
31+
import dev.onvoid.webrtc.RTCRtpReceiver;
32+
import dev.onvoid.webrtc.RTCRtpTransceiver;
33+
import dev.onvoid.webrtc.media.MediaStreamTrack;
34+
import dev.onvoid.webrtc.media.MediaType;
35+
36+
/**
37+
* The codecs a peer negotiates, for the kinds of media a session named codecs
38+
* of. Confined to the control executor.
39+
*/
40+
final class CodecPreferences {
41+
42+
/**
43+
* The codecs that go along with those a session names: retransmission,
44+
* redundancy, FEC, comfort noise and DTMF, which serve the media codecs.
45+
*/
46+
private static final Set<String> COMPANION_CODECS = Set.of("rtx", "red", "ulpfec", "flexfec-03", "cn",
47+
"telephone-event");
48+
49+
private final PeerImpl peer;
50+
51+
/** The codecs each kind of media is negotiated with, in order. */
52+
private final Map<MediaKind, List<RTCRtpCodecCapability>> codecs = new EnumMap<>(MediaKind.class);
53+
54+
55+
CodecPreferences(PeerImpl peer) {
56+
this.peer = peer;
57+
}
58+
59+
/**
60+
* Negotiates only the codecs of the given names, in that order, for each
61+
* kind of media given, together with the companion codecs WebRTC pairs
62+
* with them, and sets them on the transceivers there are.
63+
*
64+
* @param names the codec names of each kind, such as H264 or opus.
65+
*
66+
* @throws ConfigurationException if WebRTC has no codec of a name.
67+
*/
68+
void prefer(Map<MediaKind, List<String>> names) {
69+
for (Map.Entry<MediaKind, List<String>> entry : names.entrySet()) {
70+
codecs.put(entry.getKey(), named(entry.getKey(), entry.getValue()));
71+
}
72+
73+
apply();
74+
}
75+
76+
/**
77+
* Sets the preferred codecs on every transceiver that has not stopped.
78+
*/
79+
void apply() {
80+
if (codecs.isEmpty()) {
81+
return;
82+
}
83+
84+
for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) {
85+
try {
86+
if (transceiver.stopped()) {
87+
continue;
88+
}
89+
90+
RTCRtpReceiver receiver = transceiver.getReceiver();
91+
MediaStreamTrack track = receiver.getTrack();
92+
MediaKind kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind())
93+
? MediaKind.AUDIO
94+
: MediaKind.VIDEO;
95+
96+
track.dispose();
97+
receiver.dispose();
98+
99+
List<RTCRtpCodecCapability> preferred = codecs.get(kind);
100+
101+
if (preferred != null) {
102+
transceiver.setCodecPreferences(preferred);
103+
}
104+
}
105+
finally {
106+
transceiver.dispose();
107+
}
108+
}
109+
}
110+
111+
/**
112+
* Finds the codecs of the given names that WebRTC sends or receives,
113+
* followed by the companion codecs.
114+
*
115+
* @throws ConfigurationException if WebRTC has no codec of a name.
116+
*/
117+
private List<RTCRtpCodecCapability> named(MediaKind kind, List<String> names) {
118+
MediaType type = kind == MediaKind.AUDIO ? MediaType.AUDIO : MediaType.VIDEO;
119+
// Those WebRTC sends and receives, each once. WebRTC tells codecs
120+
// apart as this key does, not by their scalability modes, in which
121+
// the two lists differ; one codec twice would be offered twice.
122+
Map<List<Object>, RTCRtpCodecCapability> available = new LinkedHashMap<>();
123+
124+
for (RTCRtpCapabilities capabilities : List.of(peer.rtc.factory.getRtpSenderCapabilities(type),
125+
peer.rtc.factory.getRtpReceiverCapabilities(type))) {
126+
for (RTCRtpCodecCapability codec : capabilities.getCodecs()) {
127+
available.putIfAbsent(Arrays.asList(codec.getMimeType().toLowerCase(Locale.ROOT),
128+
codec.getClockRate(), codec.getSDPFmtp()), codec);
129+
}
130+
}
131+
132+
List<RTCRtpCodecCapability> named = new ArrayList<>();
133+
134+
for (String name : names) {
135+
boolean found = false;
136+
137+
for (RTCRtpCodecCapability codec : available.values()) {
138+
if ((codec.getName().equalsIgnoreCase(name) || codec.getMimeType().equalsIgnoreCase(name))
139+
&& !named.contains(codec)) {
140+
named.add(codec);
141+
found = true;
142+
}
143+
}
144+
145+
if (!found) {
146+
Set<String> known = new LinkedHashSet<>();
147+
available.values().forEach(codec -> known.add(codec.getName()));
148+
149+
throw new ConfigurationException("WebRTC has no " + kind.name().toLowerCase(Locale.ROOT)
150+
+ " codec " + name + " for " + peer.name + ", only " + known);
151+
}
152+
}
153+
154+
for (RTCRtpCodecCapability codec : available.values()) {
155+
if (COMPANION_CODECS.contains(codec.getName().toLowerCase(Locale.ROOT)) && !named.contains(codec)) {
156+
named.add(codec);
157+
}
158+
}
159+
160+
return named;
161+
}
162+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ void closeFromPeer(WebRtcException error) {
289289

290290
nativeBuffered = 0;
291291
state = ChannelState.CLOSED;
292-
peer.channelClosed(this);
292+
peer.channels.closed(this);
293293

294294
peer.events.execute(() -> deliverState(ChannelState.CLOSED, error),
295295
() -> settleOpened(ChannelState.CLOSED, error));
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import static java.util.Objects.requireNonNull;
20+
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
import java.util.function.Consumer;
24+
25+
import dev.onvoid.webrtc.RTCDataChannel;
26+
27+
/**
28+
* The data channels of a peer, those it created and those the remote peer
29+
* opened.
30+
* <p>
31+
* What is open is confined to the control executor, and what the handlers have
32+
* been told so far to the event executor, as the methods say. A handler added
33+
* late hears of every channel the remote peer opened that is still open.
34+
*/
35+
final class DataChannels {
36+
37+
private final PeerImpl peer;
38+
39+
// Confined to the control executor.
40+
41+
private final List<DataChannelImpl> channels = new ArrayList<>();
42+
43+
// Confined to the event executor.
44+
45+
private final List<DataChannel> delivered = new ArrayList<>();
46+
47+
private final Handlers<DataChannel> handlers;
48+
49+
50+
DataChannels(PeerImpl peer) {
51+
this.peer = peer;
52+
this.handlers = new Handlers<>(peer.rtc::reportError);
53+
}
54+
55+
/**
56+
* Creates a channel of this side. The native channel follows on the
57+
* control executor.
58+
*/
59+
DataChannel create(String label, ChannelOptions options) {
60+
requireNonNull(label, "label");
61+
requireNonNull(options, "options");
62+
63+
DataChannelImpl channel = new DataChannelImpl(peer, label);
64+
65+
peer.control.execute(() -> {
66+
if (peer.isClosed()) {
67+
channel.closeFromPeer(peer.closedError());
68+
return;
69+
}
70+
71+
try {
72+
RTCDataChannel nativeChannel = peer.connection().createDataChannel(label, options.toInit());
73+
74+
if (nativeChannel == null) {
75+
throw new ConfigurationException("WebRTC refused the data channel " + label);
76+
}
77+
78+
channels.add(channel);
79+
channel.bind(nativeChannel);
80+
}
81+
catch (Throwable e) {
82+
WebRtcException error = PeerImpl.asWebRtcException(e, "Creating the data channel " + label + " failed");
83+
channel.closeFromPeer(error);
84+
peer.deliverError(error);
85+
}
86+
});
87+
88+
return channel;
89+
}
90+
91+
Subscription onChannel(Consumer<DataChannel> handler) {
92+
requireNonNull(handler, "handler");
93+
94+
return peer.subscribe(() -> {
95+
for (DataChannel channel : new ArrayList<>(delivered)) {
96+
peer.call(handler, channel);
97+
}
98+
return handlers.add(handler);
99+
});
100+
}
101+
102+
/**
103+
* Takes a channel the remote peer opened. On the control executor.
104+
*/
105+
void opened(DataChannelImpl channel) {
106+
if (peer.isClosed()) {
107+
channel.closeFromPeer(peer.closedError());
108+
return;
109+
}
110+
111+
channels.add(channel);
112+
113+
peer.events.execute(() -> {
114+
delivered.add(channel);
115+
handlers.accept(channel);
116+
});
117+
}
118+
119+
/**
120+
* Forgets a channel that closed. On the control executor.
121+
*/
122+
void closed(DataChannelImpl channel) {
123+
channels.remove(channel);
124+
125+
peer.events.execute(() -> delivered.remove(channel));
126+
}
127+
128+
/**
129+
* Closes every channel, as the peer does when it closes. On the control
130+
* executor.
131+
*/
132+
void closeAll(PeerClosedException error) {
133+
for (DataChannelImpl channel : new ArrayList<>(channels)) {
134+
channel.closeFromPeer(error);
135+
}
136+
channels.clear();
137+
}
138+
139+
/**
140+
* Forgets the channels the handlers heard of. On the event executor.
141+
*/
142+
void clearDelivered() {
143+
delivered.clear();
144+
}
145+
146+
/**
147+
* Lets go of the handlers. On the event executor.
148+
*/
149+
void clearHandlers() {
150+
handlers.clear();
151+
}
152+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ CompletableFuture<Void> restart() {
177177

178178
Restart restart = new Restart();
179179

180-
return peer.restartIce(offer -> {
180+
return peer.manual.restartIce(offer -> {
181181
HttpCall request;
182182
Fragment fragment = Fragment.of(offer.sdp);
183183

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
307307
});
308308

309309
CompletableFuture<RTCSessionDescription> initial = prepared.thenCompose(ready -> gathering == Gathering.COMPLETE
310-
? peer.negotiator().createOffer(Gathering.COMPLETE) : peer.offer());
310+
? peer.negotiator().createOffer(Gathering.COMPLETE) : peer.manual.offer());
311311
initial
312312
.thenCompose(offer -> post(offerRequest, endpoint, withRtcpMuxOnly(offer.sdp), protocol, resource)
313313
.whenComplete((reply, error) -> {
@@ -324,7 +324,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
324324
})
325325
.thenCompose(reply -> (gathering == Gathering.COMPLETE
326326
? CompletableFuture.<Void>completedFuture(null)
327-
: peer.useIceServers(reply.iceServers)).handle((used, error) -> {
327+
: peer.manual.useIceServers(reply.iceServers)).handle((used, error) -> {
328328
if (error != null) {
329329
// Gathered without them, as if the endpoint had
330330
// named none.
@@ -340,7 +340,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
340340
ice.attach(resource.get(), reply.etag, offer.sdp);
341341

342342
return (gathering == Gathering.COMPLETE
343-
? CompletableFuture.<Void>completedFuture(null) : peer.applyLocal(offer))
343+
? CompletableFuture.<Void>completedFuture(null) : peer.manual.applyLocal(offer))
344344
.thenCompose(applied -> peer.negotiator()
345345
.applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp)));
346346
}
@@ -423,7 +423,7 @@ private static CompletableFuture<Reply> post(HttpCall request, URI endpoint, Str
423423
private static CompletableFuture<Void> answerCounterOffer(WebRtc rtc, HttpClient client, PeerImpl peer,
424424
Reply reply, String authorization, Duration timeout, AtomicReference<URI> resource, HttpIce ice,
425425
AtomicReference<HttpCall> request, AtomicBoolean finished) {
426-
return peer.answerInstead(new RTCSessionDescription(RTCSdpType.OFFER, reply.sdp), Gathering.COMPLETE)
426+
return peer.manual.answerInstead(new RTCSessionDescription(RTCSdpType.OFFER, reply.sdp), Gathering.COMPLETE)
427427
.thenCompose(answer -> {
428428
if (System.currentTimeMillis() > reply.validUntil) {
429429
throw new WebRtcException("The counter-offer for " + reply.session

0 commit comments

Comments
 (0)