Skip to content
162 changes: 162 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dev.onvoid.webrtc.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import dev.onvoid.webrtc.RTCRtpCapabilities;
import dev.onvoid.webrtc.RTCRtpCodecCapability;
import dev.onvoid.webrtc.RTCRtpReceiver;
import dev.onvoid.webrtc.RTCRtpTransceiver;
import dev.onvoid.webrtc.media.MediaStreamTrack;
import dev.onvoid.webrtc.media.MediaType;

/**
* The codecs a peer negotiates, for the kinds of media a session named codecs
* of. Confined to the control executor.
*/
final class CodecPreferences {

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

private final PeerImpl peer;

/** The codecs each kind of media is negotiated with, in order. */
private final Map<MediaKind, List<RTCRtpCodecCapability>> codecs = new EnumMap<>(MediaKind.class);


CodecPreferences(PeerImpl peer) {
this.peer = peer;
}

/**
* Negotiates only the codecs of the given names, in that order, for each
* kind of media given, together with the companion codecs WebRTC pairs
* with them, and sets them on the transceivers there are.
*
* @param names the codec names of each kind, such as H264 or opus.
*
* @throws ConfigurationException if WebRTC has no codec of a name.
*/
void prefer(Map<MediaKind, List<String>> names) {
for (Map.Entry<MediaKind, List<String>> entry : names.entrySet()) {
codecs.put(entry.getKey(), named(entry.getKey(), entry.getValue()));
}

apply();
}

/**
* Sets the preferred codecs on every transceiver that has not stopped.
*/
void apply() {
if (codecs.isEmpty()) {
return;
}

for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) {
try {
if (transceiver.stopped()) {
continue;
}

RTCRtpReceiver receiver = transceiver.getReceiver();
MediaStreamTrack track = receiver.getTrack();
MediaKind kind = MediaStreamTrack.AUDIO_TRACK_KIND.equals(track.getKind())
? MediaKind.AUDIO
: MediaKind.VIDEO;

track.dispose();
receiver.dispose();

List<RTCRtpCodecCapability> preferred = codecs.get(kind);

if (preferred != null) {
transceiver.setCodecPreferences(preferred);
}
}
finally {
transceiver.dispose();
}
}
}

/**
* Finds the codecs of the given names that WebRTC sends or receives,
* followed by the companion codecs.
*
* @throws ConfigurationException if WebRTC has no codec of a name.
*/
private List<RTCRtpCodecCapability> named(MediaKind kind, List<String> names) {
MediaType type = kind == MediaKind.AUDIO ? MediaType.AUDIO : MediaType.VIDEO;
// Those WebRTC sends and receives, each once. WebRTC tells codecs
// apart as this key does, not by their scalability modes, in which
// the two lists differ; one codec twice would be offered twice.
Map<List<Object>, RTCRtpCodecCapability> available = new LinkedHashMap<>();

for (RTCRtpCapabilities capabilities : List.of(peer.rtc.factory.getRtpSenderCapabilities(type),
peer.rtc.factory.getRtpReceiverCapabilities(type))) {
for (RTCRtpCodecCapability codec : capabilities.getCodecs()) {
available.putIfAbsent(Arrays.asList(codec.getMimeType().toLowerCase(Locale.ROOT),
codec.getClockRate(), codec.getSDPFmtp()), codec);
}
}

List<RTCRtpCodecCapability> named = new ArrayList<>();

for (String name : names) {
boolean found = false;

for (RTCRtpCodecCapability codec : available.values()) {
if ((codec.getName().equalsIgnoreCase(name) || codec.getMimeType().equalsIgnoreCase(name))
&& !named.contains(codec)) {
named.add(codec);
found = true;
}
}

if (!found) {
Set<String> known = new LinkedHashSet<>();
available.values().forEach(codec -> known.add(codec.getName()));

throw new ConfigurationException("WebRTC has no " + kind.name().toLowerCase(Locale.ROOT)
+ " codec " + name + " for " + peer.name + ", only " + known);
}
}

for (RTCRtpCodecCapability codec : available.values()) {
if (COMPANION_CODECS.contains(codec.getName().toLowerCase(Locale.ROOT)) && !named.contains(codec)) {
named.add(codec);
}
}

return named;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ void closeFromPeer(WebRtcException error) {

nativeBuffered = 0;
state = ChannelState.CLOSED;
peer.channelClosed(this);
peer.channels.closed(this);

peer.events.execute(() -> deliverState(ChannelState.CLOSED, error),
() -> settleOpened(ChannelState.CLOSED, error));
Expand Down
152 changes: 152 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannels.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dev.onvoid.webrtc.client;

import static java.util.Objects.requireNonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import dev.onvoid.webrtc.RTCDataChannel;

/**
* The data channels of a peer, those it created and those the remote peer
* opened.
* <p>
* What is open is confined to the control executor, and what the handlers have
* been told so far to the event executor, as the methods say. A handler added
* late hears of every channel the remote peer opened that is still open.
*/
final class DataChannels {

private final PeerImpl peer;

// Confined to the control executor.

private final List<DataChannelImpl> channels = new ArrayList<>();

// Confined to the event executor.

private final List<DataChannel> delivered = new ArrayList<>();

private final Handlers<DataChannel> handlers;


DataChannels(PeerImpl peer) {
this.peer = peer;
this.handlers = new Handlers<>(peer.rtc::reportError);
}

/**
* Creates a channel of this side. The native channel follows on the
* control executor.
*/
DataChannel create(String label, ChannelOptions options) {
requireNonNull(label, "label");
requireNonNull(options, "options");

DataChannelImpl channel = new DataChannelImpl(peer, label);

peer.control.execute(() -> {
if (peer.isClosed()) {
channel.closeFromPeer(peer.closedError());
return;
}

try {
RTCDataChannel nativeChannel = peer.connection().createDataChannel(label, options.toInit());

if (nativeChannel == null) {
throw new ConfigurationException("WebRTC refused the data channel " + label);
}

channels.add(channel);
channel.bind(nativeChannel);
}
catch (Throwable e) {
WebRtcException error = PeerImpl.asWebRtcException(e, "Creating the data channel " + label + " failed");
channel.closeFromPeer(error);
peer.deliverError(error);
}
});

return channel;
}

Subscription onChannel(Consumer<DataChannel> handler) {
requireNonNull(handler, "handler");

return peer.subscribe(() -> {
for (DataChannel channel : new ArrayList<>(delivered)) {
peer.call(handler, channel);
}
return handlers.add(handler);
});
}

/**
* Takes a channel the remote peer opened. On the control executor.
*/
void opened(DataChannelImpl channel) {
if (peer.isClosed()) {
channel.closeFromPeer(peer.closedError());
return;
}

channels.add(channel);

peer.events.execute(() -> {
delivered.add(channel);
handlers.accept(channel);
});
}

/**
* Forgets a channel that closed. On the control executor.
*/
void closed(DataChannelImpl channel) {
channels.remove(channel);

peer.events.execute(() -> delivered.remove(channel));
}

/**
* Closes every channel, as the peer does when it closes. On the control
* executor.
*/
void closeAll(PeerClosedException error) {
for (DataChannelImpl channel : new ArrayList<>(channels)) {
channel.closeFromPeer(error);
}
channels.clear();
}

/**
* Forgets the channels the handlers heard of. On the event executor.
*/
void clearDelivered() {
delivered.clear();
}

/**
* Lets go of the handlers. On the event executor.
*/
void clearHandlers() {
handlers.clear();
}
}
2 changes: 1 addition & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ CompletableFuture<Void> restart() {

Restart restart = new Restart();

return peer.restartIce(offer -> {
return peer.manual.restartIce(offer -> {
HttpCall request;
Fragment fragment = Fragment.of(offer.sdp);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
});

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

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