From 0e88fe31c1da854bcc76b370416a8aa8dc89e8b6 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:30:10 +0100 Subject: [PATCH 1/8] 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. --- .../dev/onvoid/webrtc/client/PeerImpl.java | 16 +++++-- .../dev/onvoid/webrtc/client/PeerTests.java | 43 +++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index ebd030f29..27ba96145 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -912,6 +912,14 @@ private void stopTransceivers(Set mids) { @Override public CompletableFuture stats() { + return toPublic(readStats()); + } + + /** + * @return a future with the statistics, which completes on the control + * executor. + */ + private CompletableFuture readStats() { CompletableFuture result = new CompletableFuture<>(); control.execute(() -> { @@ -935,7 +943,7 @@ public CompletableFuture stats() { } }); - return toPublic(result); + return result; } @Override @@ -967,7 +975,9 @@ public Subscription onStats(Duration interval, Consumer handler) { return; } - stats().whenComplete((stats, error) -> { + // Handed over here: a callback on a public future runs on this + // thread of the timer if the future is done by then. + readStats().whenComplete((stats, error) -> events.execute(() -> { if (!active.get()) { return; } @@ -977,7 +987,7 @@ public Subscription onStats(Duration interval, Consumer handler) { else if (!(unwrap(error) instanceof PeerClosedException)) { deliverError(asWebRtcException(error, "Reading the statistics failed")); } - }); + })); }; task.set(rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS)); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java index ad69f107c..a384afa5f 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java @@ -43,11 +43,14 @@ import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import dev.onvoid.webrtc.RTCSessionDescription; @@ -704,6 +707,46 @@ void statsHandlerErrorReported() throws Exception { } } + @Test + void statsHandlerKeepsEventExecutor() throws Exception { + // The report of a sample may be read before the timer's thread gets + // to wait for it. The control pool holds that thread back behind a + // second read, which must not make it the thread of the handler. + ManualTimer timer = new ManualTimer(); + Duration interval = Duration.ofSeconds(7); + Thread firing = Thread.currentThread(); + AtomicReference holding = new AtomicReference<>(); + ExecutorService control = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()) { + @Override + public void execute(Runnable task) { + super.execute(task); + + Peer held = Thread.currentThread() == firing ? holding.getAndSet(null) : null; + + if (held != null) { + held.stats().orTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS).join(); + } + } + }; + + try (WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .controlPool(control) + .eventExecutor(Runnable::run) + .timer(timer) + .build()) { + PeerImpl peer = (PeerImpl) runtime.createPeer(manualOptions()); + CompletableFuture onEvents = new CompletableFuture<>(); + + peer.onStats(interval, stats -> onEvents.complete(peer.events.inExecutor())); + holding.set(peer); + + assertEquals(1, timer.fire(interval)); + assertTrue(await(onEvents)); + } + } + @Test void subscriptionStopsHandler() throws Exception { Peer[] peers = pair(); From a8a9f5e9089589f7a6440b614fef26b33a0ca6db Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:30:10 +0100 Subject: [PATCH 2/8] test: pin where peer handlers run and what late handlers get --- .../dev/onvoid/webrtc/client/PeerTests.java | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java index a384afa5f..8b3c7b892 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -747,6 +748,107 @@ public void execute(Runnable task) { } } + @Test + void statsStopOnClose() throws Exception { + // The sample after the peer closed cancels its task, unheard. + ManualTimer timer = new ManualTimer(); + Duration interval = Duration.ofSeconds(7); + + try (WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .timer(timer) + .build()) { + Peer peer = runtime.createPeer(manualOptions()); + AtomicInteger calls = new AtomicInteger(); + + peer.onStats(interval, stats -> calls.incrementAndGet()); + await(peer.closeAsync()); + + assertEquals(1, timer.fire(interval)); + assertEquals(0, timer.scheduled(interval)); + assertEquals(0, calls.get()); + } + } + + @Test + void statsOfClosedPeerFail() throws Exception { + Peer peer = rtc.createPeer(manualOptions()); + await(peer.closeAsync()); + + assertInstanceOf(PeerClosedException.class, cause(peer.stats())); + } + + @Test + void handlersRunOnEventExecutor() throws Exception { + // Whichever thread a report comes from, the application hears of it + // on the event executor of the peer. + Peer[] peers = pair(); + PeerImpl peer = (PeerImpl) peers[1]; + CompletableFuture state = new CompletableFuture<>(); + CompletableFuture channel = new CompletableFuture<>(); + CompletableFuture track = new CompletableFuture<>(); + CompletableFuture stats = new CompletableFuture<>(); + + peer.onStateChange(value -> state.complete(peer.events.inExecutor())); + peer.onChannel(value -> channel.complete(peer.events.inExecutor())); + peer.onTrack(value -> track.complete(peer.events.inExecutor())); + + Subscription sampling = peer.onStats(Duration.ofMillis(10), value -> stats.complete(peer.events.inExecutor())); + + peers[0].createChannel("chat"); + peers[0].addTrack(rtc.media().customAudio("voice")); + + assertTrue(await(state)); + assertTrue(await(channel)); + assertTrue(await(track)); + assertTrue(await(stats)); + + sampling.close(); + } + + @Test + void lateHandlerGetsOpenChannels() throws Exception { + Peer[] peers = pair(); + CompletableFuture first = new CompletableFuture<>(); + peers[1].onChannel(first::complete); + + DataChannel channel = peers[0].createChannel("chat"); + DataChannel remote = await(first); + + CompletableFuture late = new CompletableFuture<>(); + peers[1].onChannel(late::complete); + assertSame(remote, await(late)); + + CompletableFuture closed = whenClosed(remote); + channel.close(); + await(closed); + + // The state is replayed on the same executor, behind the channels. + List afterClose = new CopyOnWriteArrayList<>(); + CompletableFuture replayed = new CompletableFuture<>(); + peers[1].onChannel(afterClose::add); + peers[1].onStateChange(replayed::complete); + await(replayed); + + assertTrue(afterClose.isEmpty(), () -> "Channels: " + afterClose); + } + + @Test + void lateHandlerGetsTracks() throws Exception { + Peer[] peers = pair(); + CompletableFuture first = new CompletableFuture<>(); + peers[1].onTrack(first::complete); + + peers[0].addTrack(rtc.media().customAudio("voice")); + RemoteTrack track = await(first); + + CompletableFuture late = new CompletableFuture<>(); + peers[1].onTrack(late::complete); + + assertSame(track, await(late)); + } + @Test void subscriptionStopsHandler() throws Exception { Peer[] peers = pair(); From 125132eb5aceffc0b7f9d335c6a63b2f0cb62686 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:31:37 +0100 Subject: [PATCH 3/8] refactor: move peer statistics into StatsSampler --- .../dev/onvoid/webrtc/client/PeerImpl.java | 89 +---------- .../onvoid/webrtc/client/StatsSampler.java | 146 ++++++++++++++++++ 2 files changed, 151 insertions(+), 84 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 27ba96145..6896cb226 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -37,8 +37,6 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; @@ -143,12 +141,12 @@ final class PeerImpl implements Peer { private final PerfectNegotiation automatic; + private final StatsSampler statistics; + private final Map remoteTrackById = new HashMap<>(); private final List channels = new ArrayList<>(); - private final StatsReader statsReader = new StatsReader(); - // Confined to the event executor. private PeerState deliveredState = PeerState.NEW; @@ -215,6 +213,7 @@ final class PeerImpl implements Peer { this.steps = new NegotiationSteps(control, rtc.timer, chain, () -> connection, options.gatheringTimeout, this::ignoresOffer); this.automatic = new PerfectNegotiation(this, options, chain, steps); + this.statistics = new StatsSampler(this); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -912,90 +911,12 @@ private void stopTransceivers(Set mids) { @Override public CompletableFuture stats() { - return toPublic(readStats()); - } - - /** - * @return a future with the statistics, which completes on the control - * executor. - */ - private CompletableFuture readStats() { - CompletableFuture result = new CompletableFuture<>(); - - control.execute(() -> { - if (closed) { - result.completeExceptionally(closedError()); - return; - } - - try { - connection.getStats(report -> control.execute(() -> { - try { - result.complete(statsReader.read(report)); - } - catch (Throwable e) { - result.completeExceptionally(e); - } - })); - } - catch (Throwable e) { - result.completeExceptionally(asWebRtcException(e, "Reading the statistics failed")); - } - }); - - return result; + return statistics.read(); } @Override public Subscription onStats(Duration interval, Consumer handler) { - requireNonNull(interval, "interval"); - requireNonNull(handler, "handler"); - - long millis = interval.toMillis(); - - if (millis <= 0) { - throw new IllegalArgumentException("The interval must be positive, got " + interval); - } - - AtomicBoolean active = new AtomicBoolean(true); - AtomicReference> task = new AtomicReference<>(); - - Runnable sample = () -> { - if (!active.get()) { - return; - } - if (closing.get()) { - active.set(false); - - ScheduledFuture scheduled = task.get(); - - if (scheduled != null) { - scheduled.cancel(false); - } - return; - } - - // Handed over here: a callback on a public future runs on this - // thread of the timer if the future is done by then. - readStats().whenComplete((stats, error) -> events.execute(() -> { - if (!active.get()) { - return; - } - if (error == null) { - call(handler, stats); - } - else if (!(unwrap(error) instanceof PeerClosedException)) { - deliverError(asWebRtcException(error, "Reading the statistics failed")); - } - })); - }; - - task.set(rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS)); - - return () -> { - active.set(false); - task.get().cancel(false); - }; + return statistics.subscribe(interval, handler); } @Override diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java new file mode 100644 index 000000000..349ac341e --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java @@ -0,0 +1,146 @@ +/* + * 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.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +/** + * The statistics of a peer, read on request or at an interval. + *

+ * The connection is asked and its report read on the control executor, which + * alone uses the {@link StatsReader}. The timer only starts a sample, whose + * result is handed to the event executor, where the handlers run. + */ +final class StatsSampler { + + private final PeerImpl peer; + + /** Confined to the control executor. */ + private final StatsReader reader = new StatsReader(); + + + StatsSampler(PeerImpl peer) { + this.peer = peer; + } + + /** + * @return a future with the statistics, which completes on the event + * executor. + */ + CompletableFuture read() { + return peer.toPublic(report()); + } + + /** + * @return a future with the statistics, which completes on the control + * executor. + */ + private CompletableFuture report() { + CompletableFuture result = new CompletableFuture<>(); + + peer.control.execute(() -> { + if (peer.isClosed()) { + result.completeExceptionally(peer.closedError()); + return; + } + + try { + peer.connection().getStats(report -> peer.control.execute(() -> { + try { + result.complete(reader.read(report)); + } + catch (Throwable e) { + result.completeExceptionally(e); + } + })); + } + catch (Throwable e) { + result.completeExceptionally(PeerImpl.asWebRtcException(e, "Reading the statistics failed")); + } + }); + + return result; + } + + /** + * Hands the handler the statistics at the given interval, until the + * subscription or the peer closes. + * + * @param interval the time between two samples. + * @param handler gets each sample, on the event executor. + * + * @return the subscription of the handler. + */ + Subscription subscribe(Duration interval, Consumer handler) { + requireNonNull(interval, "interval"); + requireNonNull(handler, "handler"); + + long millis = interval.toMillis(); + + if (millis <= 0) { + throw new IllegalArgumentException("The interval must be positive, got " + interval); + } + + AtomicBoolean active = new AtomicBoolean(true); + AtomicReference> task = new AtomicReference<>(); + + Runnable sample = () -> { + if (!active.get()) { + return; + } + if (peer.isClosing()) { + active.set(false); + + ScheduledFuture scheduled = task.get(); + + if (scheduled != null) { + scheduled.cancel(false); + } + return; + } + + // Handed over here: a callback on a public future runs on this + // thread of the timer if the future is done by then. + report().whenComplete((stats, error) -> peer.events.execute(() -> { + if (!active.get()) { + return; + } + if (error == null) { + peer.call(handler, stats); + } + else if (!(PeerImpl.unwrap(error) instanceof PeerClosedException)) { + peer.deliverError(PeerImpl.asWebRtcException(error, "Reading the statistics failed")); + } + })); + }; + + task.set(peer.rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS)); + + return () -> { + active.set(false); + task.get().cancel(false); + }; + } +} From b2f423826da61c28d003bfe6ce1106bacc9761ed Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:31:45 +0100 Subject: [PATCH 4/8] refactor: move data channel bookkeeping into DataChannels --- .../onvoid/webrtc/client/DataChannelImpl.java | 2 +- .../onvoid/webrtc/client/DataChannels.java | 152 ++++++++++++++++++ .../dev/onvoid/webrtc/client/PeerImpl.java | 84 ++-------- 3 files changed, 162 insertions(+), 76 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannels.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java index 1a5bf67e0..4b92e6dd1 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java @@ -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)); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannels.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannels.java new file mode 100644 index 000000000..dfcace482 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannels.java @@ -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. + *

+ * 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 channels = new ArrayList<>(); + + // Confined to the event executor. + + private final List delivered = new ArrayList<>(); + + private final Handlers 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 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(); + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 6896cb226..0e76183c1 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -110,6 +110,8 @@ final class PeerImpl implements Peer { final SerialExecutor events; + final DataChannels channels; + private final PeerOptions options; private final Signaling signaling; @@ -145,22 +147,16 @@ final class PeerImpl implements Peer { private final Map remoteTrackById = new HashMap<>(); - private final List channels = new ArrayList<>(); - // Confined to the event executor. private PeerState deliveredState = PeerState.NEW; private final List deliveredTracks = new ArrayList<>(); - private final List deliveredChannels = new ArrayList<>(); - private final Handlers stateHandlers; private final Handlers trackHandlers; - private final Handlers channelHandlers; - private final Handlers errorHandlers; private final ClientFuture connected = new ClientFuture<>(); @@ -207,13 +203,13 @@ final class PeerImpl implements Peer { rtc.ownsEventExecutor ? "webrtc-client-events-" + name : null); this.stateHandlers = new Handlers<>(rtc::reportError); this.trackHandlers = new Handlers<>(rtc::reportError); - this.channelHandlers = new Handlers<>(rtc::reportError); this.errorHandlers = new Handlers<>(rtc::reportError); this.chain = new OperationChain(control, rtc.timer, rtc.operationTimeout, name, new ChainHost()); this.steps = new NegotiationSteps(control, rtc.timer, chain, () -> connection, options.gatheringTimeout, this::ignoresOffer); this.automatic = new PerfectNegotiation(this, options, chain, steps); this.statistics = new StatsSampler(this); + this.channels = new DataChannels(this); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -403,47 +399,12 @@ public DataChannel createChannel(String label) { @Override public DataChannel createChannel(String label, ChannelOptions options) { - requireNonNull(label, "label"); - requireNonNull(options, "options"); - - DataChannelImpl channel = new DataChannelImpl(this, label); - - control.execute(() -> { - if (closed) { - channel.closeFromPeer(new PeerClosedException("The peer " + name + " is closed")); - return; - } - - try { - RTCDataChannel nativeChannel = 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 = asWebRtcException(e, "Creating the data channel " + label + " failed"); - channel.closeFromPeer(error); - deliverError(error); - } - }); - - return channel; + return channels.create(label, options); } @Override public Subscription onChannel(Consumer handler) { - requireNonNull(handler, "handler"); - - return subscribe(() -> { - for (DataChannel channel : new ArrayList<>(deliveredChannels)) { - call(handler, channel); - } - return channelHandlers.add(handler); - }); + return channels.onChannel(handler); } @Override @@ -1135,10 +1096,6 @@ void forgetSender(SenderImpl sender) { senders.remove(sender); } - void forgetChannel(DataChannelImpl channel) { - channels.remove(channel); - } - boolean isClosed() { return closed; } @@ -1326,26 +1283,6 @@ private void trackRemoved(RTCRtpReceiver receiver) { }); } - private void channelOpened(DataChannelImpl channel) { - if (closed) { - channel.closeFromPeer(closedError()); - return; - } - - channels.add(channel); - - events.execute(() -> { - deliveredChannels.add(channel); - channelHandlers.accept(channel); - }); - } - - void channelClosed(DataChannelImpl channel) { - channels.remove(channel); - - events.execute(() -> deliveredChannels.remove(channel)); - } - private void teardown() { if (teardownStarted) { return; @@ -1360,10 +1297,7 @@ private void teardown() { automatic.close(); steps.close(error); - for (DataChannelImpl channel : new ArrayList<>(channels)) { - channel.closeFromPeer(error); - } - channels.clear(); + channels.closeAll(error); for (SenderImpl sender : senders) { sender.closeFromPeer(); @@ -1413,7 +1347,7 @@ private void finishTeardown(List ended, PeerClosedException err remote.fireEnded(); } deliveredTracks.clear(); - deliveredChannels.clear(); + channels.clearDelivered(); deliverState(PeerState.CLOSED); @@ -1421,7 +1355,7 @@ private void finishTeardown(List ended, PeerClosedException err closedFuture.complete(null); trackHandlers.clear(); - channelHandlers.clear(); + channels.clearHandlers(); stateHandlers.clear(); errorHandlers.clear(); }, () -> { @@ -1538,7 +1472,7 @@ public void onDataChannel(RTCDataChannel dataChannel) { // itself only posts as well. DataChannelImpl channel = new DataChannelImpl(PeerImpl.this, dataChannel); - control.execute(() -> channelOpened(channel)); + control.execute(() -> channels.opened(channel)); } } From 8c25630cc33c1393cedd399a6c4244c9356e3c78 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:31:51 +0100 Subject: [PATCH 5/8] refactor: move remote track bookkeeping into RemoteTracks --- .../dev/onvoid/webrtc/client/PeerImpl.java | 133 +---------- .../onvoid/webrtc/client/RemoteTracks.java | 223 ++++++++++++++++++ 2 files changed, 234 insertions(+), 122 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTracks.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 0e76183c1..b1b85a4e0 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -22,9 +22,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.EnumMap; -import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -68,8 +66,6 @@ import dev.onvoid.webrtc.media.MediaStream; import dev.onvoid.webrtc.media.MediaStreamTrack; import dev.onvoid.webrtc.media.MediaType; -import dev.onvoid.webrtc.media.audio.AudioTrack; -import dev.onvoid.webrtc.media.video.VideoTrack; /** * The {@link Peer} of a {@link WebRtc} runtime. @@ -112,6 +108,8 @@ final class PeerImpl implements Peer { final DataChannels channels; + private final RemoteTracks tracks; + private final PeerOptions options; private final Signaling signaling; @@ -125,8 +123,6 @@ final class PeerImpl implements Peer { private final CopyOnWriteArrayList senders = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList remoteTracks = new CopyOnWriteArrayList<>(); - private volatile PeerState state = PeerState.NEW; // Confined to the control executor. @@ -145,18 +141,12 @@ final class PeerImpl implements Peer { private final StatsSampler statistics; - private final Map remoteTrackById = new HashMap<>(); - // Confined to the event executor. private PeerState deliveredState = PeerState.NEW; - private final List deliveredTracks = new ArrayList<>(); - private final Handlers stateHandlers; - private final Handlers trackHandlers; - private final Handlers errorHandlers; private final ClientFuture connected = new ClientFuture<>(); @@ -165,13 +155,6 @@ final class PeerImpl implements Peer { private final NegotiatorImpl negotiator = new NegotiatorImpl(); - /** - * The kinds of media whose tracks this peer drops, those it declined when - * it answered an offer that replaced its own. Only on the control - * executor. - */ - private final Set declinedKinds = EnumSet.noneOf(MediaKind.class); - /** * The codecs each kind of media is negotiated with, in order, for the * kinds a session named codecs of. Only on the control executor. @@ -202,7 +185,6 @@ final class PeerImpl implements Peer { this.events = new SerialExecutor(rtc.eventExecutor, rtc.eventWork, rtc::reportError, true, rtc.ownsEventExecutor ? "webrtc-client-events-" + name : null); this.stateHandlers = new Handlers<>(rtc::reportError); - this.trackHandlers = new Handlers<>(rtc::reportError); this.errorHandlers = new Handlers<>(rtc::reportError); this.chain = new OperationChain(control, rtc.timer, rtc.operationTimeout, name, new ChainHost()); this.steps = new NegotiationSteps(control, rtc.timer, chain, () -> connection, options.gatheringTimeout, @@ -210,6 +192,7 @@ final class PeerImpl implements Peer { this.automatic = new PerfectNegotiation(this, options, chain, steps); this.statistics = new StatsSampler(this); this.channels = new DataChannels(this); + this.tracks = new RemoteTracks(this, options.receiveTransform); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -377,19 +360,12 @@ public List senders() { @Override public Subscription onTrack(Consumer handler) { - requireNonNull(handler, "handler"); - - return subscribe(() -> { - for (RemoteTrack track : new ArrayList<>(deliveredTracks)) { - call(handler, track); - } - return trackHandlers.add(handler); - }); + return tracks.onTrack(handler); } @Override public List remoteTracks() { - return Collections.unmodifiableList(new ArrayList(remoteTracks)); + return tracks.current(); } @Override @@ -786,7 +762,7 @@ CompletableFuture answerInstead(RTCSessionDescription off // m-lines that are then rejected. for (MediaKind kind : MediaKind.values()) { if (!options.receive.contains(kind)) { - declinedKinds.add(kind); + tracks.decline(kind); } } @@ -1205,84 +1181,6 @@ private void gatheringChanged(RTCIceGatheringState gatheringState) { } } - private void trackAdded(RTCRtpReceiver receiver, MediaStream[] streams) { - List streamIds = new ArrayList<>(); - - for (MediaStream stream : streams) { - streamIds.add(stream.id()); - stream.dispose(); - } - - if (closed) { - receiver.dispose(); - return; - } - - MediaStreamTrack track = receiver.getTrack(); - String id = track.getId(); - - if (declinedKinds.contains(track instanceof VideoTrack ? MediaKind.VIDEO : MediaKind.AUDIO)) { - // Of an m-line this peer rejected, when it answered an offer that - // replaced its own. - track.dispose(); - receiver.dispose(); - return; - } - if (remoteTrackById.containsKey(id)) { - // Renegotiation reported a track that is already known. - track.dispose(); - receiver.dispose(); - return; - } - - if (options.receiveTransform != null) { - String owner = "the track " + id + " of " + name; - - try { - // Before the application hears of the track, and so before - // its first frame arrives. - receiver.setTransform(guard(options.receiveTransform, owner)); - } - catch (Throwable e) { - deliverError(asWebRtcException(e, "Setting the receive transform of " + owner + " failed")); - } - } - - RemoteTrackImpl remote = track instanceof VideoTrack - ? new RemoteVideoImpl(this, receiver, (VideoTrack) track, id, streamIds) - : new RemoteAudioImpl(this, receiver, (AudioTrack) track, id, streamIds); - - remoteTrackById.put(id, remote); - remoteTracks.add(remote); - - events.execute(() -> { - deliveredTracks.add(remote); - trackHandlers.accept(remote); - }); - } - - private void trackRemoved(RTCRtpReceiver receiver) { - MediaStreamTrack track = receiver.getTrack(); - String id = track.getId(); - - track.dispose(); - receiver.dispose(); - - RemoteTrackImpl remote = remoteTrackById.remove(id); - - if (remote == null || closed) { - return; - } - - remoteTracks.remove(remote); - remote.end(); - - events.execute(() -> { - deliveredTracks.remove(remote); - remote.fireEnded(); - }); - } - private void teardown() { if (teardownStarted) { return; @@ -1304,13 +1202,7 @@ private void teardown() { } senders.clear(); - List ended = new ArrayList<>(remoteTracks); - - for (RemoteTrackImpl remote : ended) { - remote.end(); - } - remoteTracks.clear(); - remoteTrackById.clear(); + List ended = tracks.endAll(); try { if (connection != null) { @@ -1343,10 +1235,7 @@ private void finishTeardown(List ended, PeerClosedException err // hears of none once it was let go of. detachSignaling(); - for (RemoteTrackImpl remote : ended) { - remote.fireEnded(); - } - deliveredTracks.clear(); + tracks.fireEnded(ended); channels.clearDelivered(); deliverState(PeerState.CLOSED); @@ -1354,7 +1243,7 @@ private void finishTeardown(List ended, PeerClosedException err connected.completeExceptionally(error); closedFuture.complete(null); - trackHandlers.clear(); + tracks.clearHandlers(); channels.clearHandlers(); stateHandlers.clear(); errorHandlers.clear(); @@ -1458,12 +1347,12 @@ public void onTrack(RTCRtpTransceiver transceiver) { @Override public void onAddTrack(RTCRtpReceiver receiver, MediaStream[] mediaStreams) { - control.execute(() -> trackAdded(receiver, mediaStreams)); + control.execute(() -> tracks.added(receiver, mediaStreams)); } @Override public void onRemoveTrack(RTCRtpReceiver receiver) { - control.execute(() -> trackRemoved(receiver)); + control.execute(() -> tracks.removed(receiver)); } @Override diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTracks.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTracks.java new file mode 100644 index 000000000..c6d77f416 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTracks.java @@ -0,0 +1,223 @@ +/* + * 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.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +import dev.onvoid.webrtc.RTCEncodedFrameTransformer; +import dev.onvoid.webrtc.RTCRtpReceiver; +import dev.onvoid.webrtc.media.MediaStream; +import dev.onvoid.webrtc.media.MediaStreamTrack; +import dev.onvoid.webrtc.media.audio.AudioTrack; +import dev.onvoid.webrtc.media.video.VideoTrack; + +/** + * The tracks a peer receives. + *

+ * WebRTC's reports of them are handled on the control executor, and what the + * handlers have been told so far is confined to the event executor, as the + * methods say. Any thread may ask for the current tracks. A handler added late + * hears of every track still there. + */ +final class RemoteTracks { + + private final PeerImpl peer; + + /** Set on each track before the application hears of it, or null. */ + private final RTCEncodedFrameTransformer transform; + + private final CopyOnWriteArrayList tracks = new CopyOnWriteArrayList<>(); + + // Confined to the control executor. + + private final Map byId = new HashMap<>(); + + /** + * The kinds of media whose tracks this peer drops, those it declined when + * it answered an offer that replaced its own. + */ + private final Set declined = EnumSet.noneOf(MediaKind.class); + + // Confined to the event executor. + + private final List delivered = new ArrayList<>(); + + private final Handlers handlers; + + + RemoteTracks(PeerImpl peer, RTCEncodedFrameTransformer transform) { + this.peer = peer; + this.transform = transform; + this.handlers = new Handlers<>(peer.rtc::reportError); + } + + /** + * @return the tracks received now. + */ + List current() { + return Collections.unmodifiableList(new ArrayList(tracks)); + } + + Subscription onTrack(Consumer handler) { + requireNonNull(handler, "handler"); + + return peer.subscribe(() -> { + for (RemoteTrack track : new ArrayList<>(delivered)) { + peer.call(handler, track); + } + return handlers.add(handler); + }); + } + + /** + * Drops the tracks of a kind from now on. On the control executor. + */ + void decline(MediaKind kind) { + declined.add(kind); + } + + /** + * Takes a track WebRTC reported. On the control executor. + */ + void added(RTCRtpReceiver receiver, MediaStream[] streams) { + List streamIds = new ArrayList<>(); + + for (MediaStream stream : streams) { + streamIds.add(stream.id()); + stream.dispose(); + } + + if (peer.isClosed()) { + receiver.dispose(); + return; + } + + MediaStreamTrack track = receiver.getTrack(); + String id = track.getId(); + + if (declined.contains(track instanceof VideoTrack ? MediaKind.VIDEO : MediaKind.AUDIO)) { + // Of an m-line this peer rejected, when it answered an offer that + // replaced its own. + track.dispose(); + receiver.dispose(); + return; + } + if (byId.containsKey(id)) { + // Renegotiation reported a track that is already known. + track.dispose(); + receiver.dispose(); + return; + } + + if (transform != null) { + String owner = "the track " + id + " of " + peer.name; + + try { + // Before the application hears of the track, and so before + // its first frame arrives. + receiver.setTransform(peer.guard(transform, owner)); + } + catch (Throwable e) { + peer.deliverError(PeerImpl.asWebRtcException(e, "Setting the receive transform of " + owner + + " failed")); + } + } + + RemoteTrackImpl remote = track instanceof VideoTrack + ? new RemoteVideoImpl(peer, receiver, (VideoTrack) track, id, streamIds) + : new RemoteAudioImpl(peer, receiver, (AudioTrack) track, id, streamIds); + + byId.put(id, remote); + tracks.add(remote); + + peer.events.execute(() -> { + delivered.add(remote); + handlers.accept(remote); + }); + } + + /** + * Ends a track WebRTC took away. On the control executor. + */ + void removed(RTCRtpReceiver receiver) { + MediaStreamTrack track = receiver.getTrack(); + String id = track.getId(); + + track.dispose(); + receiver.dispose(); + + RemoteTrackImpl remote = byId.remove(id); + + if (remote == null || peer.isClosed()) { + return; + } + + tracks.remove(remote); + remote.end(); + + peer.events.execute(() -> { + delivered.remove(remote); + remote.fireEnded(); + }); + } + + /** + * Ends every track, as the peer does when it closes. On the control + * executor. + * + * @return the tracks ended, for {@link #fireEnded}. + */ + List endAll() { + List ended = new ArrayList<>(tracks); + + for (RemoteTrackImpl remote : ended) { + remote.end(); + } + tracks.clear(); + byId.clear(); + + return ended; + } + + /** + * Tells the handlers of the given tracks they ended, and forgets what the + * handlers heard of. On the event executor. + */ + void fireEnded(List ended) { + for (RemoteTrackImpl remote : ended) { + remote.fireEnded(); + } + delivered.clear(); + } + + /** + * Lets go of the handlers. On the event executor. + */ + void clearHandlers() { + handlers.clear(); + } +} From f45ffcf98b3548e328973802b9d48a4368791e72 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:31:58 +0100 Subject: [PATCH 6/8] refactor: move codec selection into CodecPreferences --- .../webrtc/client/CodecPreferences.java | 162 ++++++++++++++++++ .../dev/onvoid/webrtc/client/PeerImpl.java | 120 +------------ 2 files changed, 167 insertions(+), 115 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java new file mode 100644 index 000000000..c44d47739 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CodecPreferences.java @@ -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 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> 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> names) { + for (Map.Entry> 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 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 named(MediaKind kind, List 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, 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 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 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; + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index b1b85a4e0..83dd41486 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -20,14 +20,9 @@ import java.time.Duration; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; -import java.util.EnumMap; import java.util.HashSet; -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 java.util.UUID; @@ -52,8 +47,6 @@ import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCPeerConnection; import dev.onvoid.webrtc.RTCPeerConnectionState; -import dev.onvoid.webrtc.RTCRtpCapabilities; -import dev.onvoid.webrtc.RTCRtpCodecCapability; import dev.onvoid.webrtc.RTCRtpEncodingParameters; import dev.onvoid.webrtc.RTCRtpReceiver; import dev.onvoid.webrtc.RTCRtpTransceiver; @@ -64,7 +57,6 @@ import dev.onvoid.webrtc.RTCSignalingState; import dev.onvoid.webrtc.client.internal.EncodedFrames; import dev.onvoid.webrtc.media.MediaStream; -import dev.onvoid.webrtc.media.MediaStreamTrack; import dev.onvoid.webrtc.media.MediaType; /** @@ -91,13 +83,6 @@ final class PeerImpl implements Peer { EncodedFrames.register(new EncodedFramesAccess()); } - /** - * 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 COMPANION_CODECS = Set.of("rtx", "red", "ulpfec", "flexfec-03", "cn", - "telephone-event"); - final WebRtc rtc; final String name; @@ -110,6 +95,8 @@ final class PeerImpl implements Peer { private final RemoteTracks tracks; + private final CodecPreferences codecs; + private final PeerOptions options; private final Signaling signaling; @@ -155,12 +142,6 @@ final class PeerImpl implements Peer { private final NegotiatorImpl negotiator = new NegotiatorImpl(); - /** - * The codecs each kind of media is negotiated with, in order, for the - * kinds a session named codecs of. Only on the control executor. - */ - private final Map> codecs = new EnumMap<>(MediaKind.class); - /** Gets the local candidates as well, or null. Called on the control executor. */ private volatile Consumer candidateListener; @@ -193,6 +174,7 @@ final class PeerImpl implements Peer { this.statistics = new StatsSampler(this); this.channels = new DataChannels(this); this.tracks = new RemoteTracks(this, options.receiveTransform); + this.codecs = new CodecPreferences(this); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -492,104 +474,12 @@ CompletableFuture addVideoWithoutTrack() { */ CompletableFuture preferCodecs(Map> names) { return negotiator.run(() -> { - for (Map.Entry> entry : names.entrySet()) { - codecs.put(entry.getKey(), codecsNamed(entry.getKey(), entry.getValue())); - } - - applyCodecs(); + codecs.prefer(names); return CompletableFuture.completedFuture(null); }); } - /** - * 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 codecsNamed(MediaKind kind, List 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, RTCRtpCodecCapability> available = new LinkedHashMap<>(); - - for (RTCRtpCapabilities capabilities : List.of(rtc.factory.getRtpSenderCapabilities(type), - rtc.factory.getRtpReceiverCapabilities(type))) { - for (RTCRtpCodecCapability codec : capabilities.getCodecs()) { - available.putIfAbsent(Arrays.asList(codec.getMimeType().toLowerCase(Locale.ROOT), - codec.getClockRate(), codec.getSDPFmtp()), codec); - } - } - - List 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 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 " + this.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; - } - - /** - * Sets the codecs of {@link #preferCodecs} on every transceiver that has - * not stopped. - */ - private void applyCodecs() { - if (codecs.isEmpty()) { - return; - } - - for (RTCRtpTransceiver transceiver : 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 preferred = codecs.get(kind); - - if (preferred != null) { - transceiver.setCodecPreferences(preferred); - } - } - finally { - transceiver.dispose(); - } - } - } - /** * Gathers candidates from now on with the given ICE servers, unless the * peer was built with servers of its own, which take precedence. @@ -776,7 +666,7 @@ CompletableFuture answerInstead(RTCSessionDescription off .thenCompose(ignored -> { stopTransceivers(rejected); // The offer made transceivers of its own. - applyCodecs(); + codecs.apply(); steps.releaseHeldCandidates(); return steps.createAnswer(); }) From fe327d3cc7215850c6c10b7503927c64c070dec4 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:32:09 +0100 Subject: [PATCH 7/8] refactor: move the signaling transport into SignalingLink --- .../dev/onvoid/webrtc/client/PeerImpl.java | 74 ++---------- .../onvoid/webrtc/client/SignalingLink.java | 112 ++++++++++++++++++ 2 files changed, 120 insertions(+), 66 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingLink.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 83dd41486..56df1f567 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -31,7 +31,6 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; @@ -97,9 +96,9 @@ final class PeerImpl implements Peer { private final CodecPreferences codecs; - private final PeerOptions options; + private final SignalingLink signaling; - private final Signaling signaling; + private final PeerOptions options; /** The stream the tracks added without stream ids share. */ private final String defaultStreamId = UUID.randomUUID().toString(); @@ -148,20 +147,11 @@ final class PeerImpl implements Peer { /** Runs once gathering is complete, or null. Called on the control executor. */ private volatile Runnable gatheredListener; - /** - * What {@link Signaling#attach} returned, or null before, and {@link - * #DETACHED} once the peer has let go of the signaling on close. - */ - private final AtomicReference signalingSubscription = new AtomicReference<>(); - - private static final Subscription DETACHED = () -> { }; - PeerImpl(WebRtc rtc, PeerOptions options, String name) { this.rtc = rtc; this.options = options; this.name = name; - this.signaling = options.signaling; this.control = new SerialExecutor(rtc.controlPool, rtc.controlWork, rtc::reportError, false, null); this.events = new SerialExecutor(rtc.eventExecutor, rtc.eventWork, rtc::reportError, true, rtc.ownsEventExecutor ? "webrtc-client-events-" + name : null); @@ -175,6 +165,7 @@ final class PeerImpl implements Peer { this.channels = new DataChannels(this); this.tracks = new RemoteTracks(this, options.receiveTransform); this.codecs = new CodecPreferences(this); + this.signaling = new SignalingLink(this, options.signaling); rtc.track(connected, events); rtc.track(closedFuture, events); @@ -247,15 +238,7 @@ void open() { throw new ConfigurationException("Creating " + name + " failed: " + cause.getMessage(), cause); } - if (signaling != null && !closing.get()) { - Subscription subscription = signaling.attach(this::signal); - - if (subscription != null && !signalingSubscription.compareAndSet(null, subscription)) { - // Closed while attaching: the close found nothing to let go of - // yet, so this lets go of what attach returned. - detach(subscription); - } - } + signaling.attach(); } @Override @@ -1023,27 +1006,7 @@ RTCPeerConnection connection() { * executor. */ void sendLocalDescription() { - send(SignalMessage.of(connection.getLocalDescription())); - } - - private void send(SignalMessage message) { - if (signaling == null) { - return; - } - - events.execute(() -> { - if (signalingSubscription.get() == DETACHED) { - // The transport may take another peer by now. - return; - } - - try { - signaling.send(message); - } - catch (Throwable e) { - deliverError(new WebRtcException("The signaling failed to send " + message.type(), e)); - } - }); + signaling.send(SignalMessage.of(connection.getLocalDescription())); } // What WebRTC reports, on the control executor. @@ -1123,7 +1086,7 @@ private void finishTeardown(List ended, PeerClosedException err events.execute(() -> { // Behind the messages queued for sending, so that the transport // hears of none once it was let go of. - detachSignaling(); + signaling.detach(); tracks.fireEnded(ended); channels.clearDelivered(); @@ -1138,34 +1101,13 @@ private void finishTeardown(List ended, PeerClosedException err stateHandlers.clear(); errorHandlers.clear(); }, () -> { - detachSignaling(); + signaling.detach(); connected.completeExceptionally(error); closedFuture.complete(null); }); } - /** - * Lets go of the signaling, once: a transport that outlives the peer must - * not keep it, and the runtime with it, reachable. - */ - private void detachSignaling() { - Subscription subscription = signalingSubscription.getAndSet(DETACHED); - - if (subscription != null && subscription != DETACHED) { - detach(subscription); - } - } - - private void detach(Subscription subscription) { - try { - subscription.close(); - } - catch (Throwable e) { - rtc.reportError(new WebRtcException("Detaching " + name + " from its signaling failed", e)); - } - } - // On the event executor. private void deliverState(PeerState newState) { @@ -1209,7 +1151,7 @@ public void onIceCandidate(RTCIceCandidate candidate) { listener.accept(candidate); } - send(SignalMessage.of(candidate)); + signaling.send(SignalMessage.of(candidate)); } }); } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingLink.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingLink.java new file mode 100644 index 000000000..52cc76255 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingLink.java @@ -0,0 +1,112 @@ +/* + * 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.concurrent.atomic.AtomicReference; + +/** + * The link of a peer to its {@link Signaling}, if it has one. + *

+ * The transport is application code, so messages go out on the event executor. + * The subscription is the only state, and atomic, since the thread that + * attaches and the event executor that lets go may race. + */ +final class SignalingLink { + + private static final Subscription DETACHED = () -> { }; + + private final PeerImpl peer; + + private final Signaling signaling; + + /** + * What {@link Signaling#attach} returned, or null before, and {@link + * #DETACHED} once the peer has let go of the signaling on close. + */ + private final AtomicReference subscription = new AtomicReference<>(); + + + /** + * @param peer the peer. + * @param signaling the transport, or null for none. + */ + SignalingLink(PeerImpl peer, Signaling signaling) { + this.peer = peer; + this.signaling = signaling; + } + + /** + * Attaches the peer to the transport, unless it began to close. + */ + void attach() { + if (signaling == null || peer.isClosing()) { + return; + } + + Subscription attached = signaling.attach(peer::signal); + + if (attached != null && !subscription.compareAndSet(null, attached)) { + // Closed while attaching: the close found nothing to let go of + // yet, so this lets go of what attach returned. + close(attached); + } + } + + /** + * Sends a message from the event executor, behind what is queued there. + */ + void send(SignalMessage message) { + if (signaling == null) { + return; + } + + peer.events.execute(() -> { + if (subscription.get() == DETACHED) { + // The transport may take another peer by now. + return; + } + + try { + signaling.send(message); + } + catch (Throwable e) { + peer.deliverError(new WebRtcException("The signaling failed to send " + message.type(), e)); + } + }); + } + + /** + * Lets go of the signaling, once: a transport that outlives the peer must + * not keep it, and the runtime with it, reachable. + */ + void detach() { + Subscription attached = subscription.getAndSet(DETACHED); + + if (attached != null && attached != DETACHED) { + close(attached); + } + } + + private void close(Subscription attached) { + try { + attached.close(); + } + catch (Throwable e) { + peer.rtc.reportError(new WebRtcException("Detaching " + peer.name + " from its signaling failed", e)); + } + } +} From ec299be68f8c0a2f095127a2196b6cf5b2fcebf3 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 4 Nov 2026 18:32:33 +0100 Subject: [PATCH 8/8] refactor: move manual negotiation and WHIP/WHEP steps into ManualNegotiation --- .../dev/onvoid/webrtc/client/HttpIce.java | 2 +- .../dev/onvoid/webrtc/client/HttpSession.java | 8 +- .../webrtc/client/ManualNegotiation.java | 477 ++++++++++++++++++ .../dev/onvoid/webrtc/client/PeerImpl.java | 438 +--------------- .../java/dev/onvoid/webrtc/client/Whep.java | 2 +- .../java/dev/onvoid/webrtc/client/Whip.java | 6 +- .../client/NegotiationTimeoutTests.java | 4 +- 7 files changed, 504 insertions(+), 433 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/ManualNegotiation.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index 5672bdbf6..23c205a2d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -177,7 +177,7 @@ CompletableFuture restart() { Restart restart = new Restart(); - return peer.restartIce(offer -> { + return peer.manual.restartIce(offer -> { HttpCall request; Fragment fragment = Fragment.of(offer.sdp); 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 ea7293a69..c61d6ca09 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -307,7 +307,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e }); CompletableFuture 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) -> { @@ -324,7 +324,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e }) .thenCompose(reply -> (gathering == Gathering.COMPLETE ? CompletableFuture.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. @@ -340,7 +340,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e ice.attach(resource.get(), reply.etag, offer.sdp); return (gathering == Gathering.COMPLETE - ? CompletableFuture.completedFuture(null) : peer.applyLocal(offer)) + ? CompletableFuture.completedFuture(null) : peer.manual.applyLocal(offer)) .thenCompose(applied -> peer.negotiator() .applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp))); } @@ -423,7 +423,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient client, PeerImpl peer, Reply reply, String authorization, Duration timeout, AtomicReference resource, HttpIce ice, AtomicReference 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 diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/ManualNegotiation.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/ManualNegotiation.java new file mode 100644 index 000000000..36822cac6 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/ManualNegotiation.java @@ -0,0 +1,477 @@ +/* + * 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.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCIceCandidate; +import dev.onvoid.webrtc.RTCIceServer; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCRtpTransceiver; +import dev.onvoid.webrtc.RTCRtpTransceiverDirection; +import dev.onvoid.webrtc.RTCRtpTransceiverInit; +import dev.onvoid.webrtc.RTCSdpType; +import dev.onvoid.webrtc.RTCSessionDescription; +import dev.onvoid.webrtc.RTCSignalingState; +import dev.onvoid.webrtc.media.MediaType; + +/** + * The negotiation of a peer driven by hand: the {@link Negotiator} of the + * application, and the finer steps WHIP and WHEP take on top of it. + *

+ * Any thread may call these methods. Each posts an operation to the peer's + * {@link OperationChain}, so that the operation runs on the control executor, + * and hands back a future that completes on the event executor. + */ +final class ManualNegotiation implements Negotiator { + + private final PeerImpl peer; + + private final PeerOptions options; + + private final OperationChain chain; + + private final NegotiationSteps steps; + + private final RemoteTracks tracks; + + private final CodecPreferences codecs; + + + ManualNegotiation(PeerImpl peer, PeerOptions options, OperationChain chain, NegotiationSteps steps, + RemoteTracks tracks, CodecPreferences codecs) { + this.peer = peer; + this.options = options; + this.chain = chain; + this.steps = steps; + this.tracks = tracks; + this.codecs = codecs; + } + + @Override + public CompletableFuture createOffer() { + return createOffer(Gathering.TRICKLE); + } + + @Override + public CompletableFuture createOffer(Gathering gathering) { + requireNonNull(gathering, "gathering"); + + return run(() -> steps.createOffer() + .thenCompose(steps::setLocal) + .thenCompose(ignored -> gathered(gathering))); + } + + @Override + public CompletableFuture answer(RTCSessionDescription offer) { + return answer(offer, Gathering.TRICKLE); + } + + @Override + public CompletableFuture answer(RTCSessionDescription offer, Gathering gathering) { + requireNonNull(offer, "offer"); + requireNonNull(gathering, "gathering"); + + if (offer.sdpType != RTCSdpType.OFFER) { + throw new IllegalArgumentException("Expected an offer, got " + offer.sdpType); + } + + return run(() -> steps.setRemote(offer) + .thenCompose(ignored -> { + steps.releaseHeldCandidates(); + return steps.createAnswer(); + }) + .thenCompose(steps::setLocal) + .thenCompose(ignored -> gathered(gathering))); + } + + @Override + public CompletableFuture applyAnswer(RTCSessionDescription answer) { + requireNonNull(answer, "answer"); + + if (answer.sdpType != RTCSdpType.ANSWER && answer.sdpType != RTCSdpType.PR_ANSWER) { + throw new IllegalArgumentException("Expected an answer, got " + answer.sdpType); + } + + return run(() -> steps.setRemote(answer).thenRun(steps::releaseHeldCandidates)); + } + + @Override + public CompletableFuture addCandidate(RTCIceCandidate candidate) { + requireNonNull(candidate, "candidate"); + + return run(() -> steps.addRemoteCandidate(candidate)); + } + + /** + * Creates an offer without applying it, so that the configuration can + * still change before candidates are gathered for it, as WHIP and WHEP do + * with the ICE servers the endpoint names in its answer. + * + * @return a future with the offer, which {@link #applyLocal} applies. + */ + CompletableFuture offer() { + return run(steps::createOffer); + } + + /** + * Applies a description this peer created, which starts the gathering of + * candidates for it. + */ + CompletableFuture applyLocal(RTCSessionDescription description) { + return run(() -> steps.setLocal(description)); + } + + /** + * Makes every transceiver send only, as a WHIP client's offer should be + * (RFC 9725, 4.2). Ordered with the negotiation steps, so it takes effect + * on the next offer. + */ + CompletableFuture sendOnly() { + return run(() -> { + for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) { + try { + if (!transceiver.stopped()) { + transceiver.setDirection(RTCRtpTransceiverDirection.SEND_ONLY); + } + } + finally { + transceiver.dispose(); + } + } + + return CompletableFuture.completedFuture(null); + }); + } + + /** + * Adds video that only sends, without a track, to the stream of the + * tracks added without stream ids, for endpoints that take no offer + * without video. Ordered with the negotiation steps. + */ + CompletableFuture addVideoWithoutTrack() { + return run(() -> { + RTCRtpTransceiverInit init = new RTCRtpTransceiverInit(); + init.direction = RTCRtpTransceiverDirection.SEND_ONLY; + init.streamIds.add(peer.defaultStreamId); + + peer.connection().addTransceiver(MediaType.VIDEO, init).dispose(); + + return CompletableFuture.completedFuture(null); + }); + } + + /** + * 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. This holds for the transceivers there are, and for those an + * offer adds later, as a counter-offer this peer answers instead of its + * own. Ordered with the negotiation steps, so it takes effect on the next + * offer or answer. + * + * @param names the codec names of each kind, such as H264 or opus. + * + * @return a future that fails if WebRTC has no codec of a name. + */ + CompletableFuture preferCodecs(Map> names) { + return run(() -> { + codecs.prefer(names); + + return CompletableFuture.completedFuture(null); + }); + } + + /** + * Gathers candidates from now on with the given ICE servers, unless the + * peer was built with servers of its own, which take precedence. + * + * @param servers the ICE servers; none leaves the configuration as it is. + * + * @return a future that fails if WebRTC refuses the servers. + */ + CompletableFuture useIceServers(List servers) { + if (servers.isEmpty() || !options.iceServers.isEmpty()) { + return CompletableFuture.completedFuture(null); + } + + return run(() -> { + try { + RTCPeerConnection connection = peer.connection(); + RTCConfiguration config = connection.getConfiguration(); + config.iceServers = new ArrayList<>(servers); + connection.setConfiguration(config); + + return CompletableFuture.completedFuture(null); + } + catch (RuntimeException e) { + return CompletableFuture.failedFuture(new ConfigurationException("WebRTC refused the ICE servers " + + servers + " for " + peer.name + ": " + e.getMessage(), e)); + } + }); + } + + /** + * Restarts ICE as WHIP and WHEP do, without a renegotiation: only the ICE + * information of a new offer goes to the remote peer, and the remote + * description keeps its offer/answer role, with the ICE information that + * comes back. After a server counter-offer, the new local credentials are + * applied in an answer to the updated remote offer. + * An exchange that fails takes the new offer back, and the ICE session + * before goes on. + * + * @param exchange sends the ICE information of the new offer, and returns + * how to change the remote answer. + * + * @return a future that completes once the new ICE information is applied. + */ + CompletableFuture restartIce( + Function>> exchange) { + return restartIce(exchange, (value, error) -> { }); + } + + CompletableFuture restartIce( + Function>> exchange, + BiConsumer finished) { + return run(() -> { + RTCPeerConnection connection = peer.connection(); + RTCSessionDescription remote = connection.getRemoteDescription(); + + if (connection.getSignalingState() != RTCSignalingState.STABLE || remote == null + || (remote.sdpType != RTCSdpType.ANSWER && remote.sdpType != RTCSdpType.OFFER)) { + return CompletableFuture.failedFuture(new NegotiationException("The peer " + peer.name + + " has no stable description to restart ICE with")); + } + + connection.restartIce(); + + if (remote.sdpType == RTCSdpType.OFFER) { + // Keep the server's offerer role (including its DTLS role and + // media sections). Create an offer only to obtain fresh local + // ICE credentials; do not apply it or change signaling roles. + return steps.createOffer().thenCompose(offer -> onControl(exchange.apply(offer)) + .thenCompose(change -> steps.setRemote(new RTCSessionDescription( + RTCSdpType.OFFER, change.apply(remote.sdp)))) + .thenCompose(ignored -> { + // Reapplying the server's offer can create transceivers + // for media the original answer rejected. + stopTransceivers(midsNotReceived(remote.sdp)); + return steps.createAnswer(); + }) + .thenCompose(answer -> steps.setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, + HttpIce.Fragment.of(offer.sdp).applyCredentialsTo(answer.sdp))))) + .handle((applied, error) -> { + if (error == null) { + return CompletableFuture.completedFuture(null); + } + CompletableFuture failed = CompletableFuture.failedFuture(PeerImpl.unwrap(error)); + if (peer.isClosed() || connection.getSignalingState() != RTCSignalingState.HAVE_REMOTE_OFFER) { + return failed; + } + return steps.setRemote(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + .handle((ignored, rollbackError) -> null) + .thenCompose(ignored -> failed); + }).thenCompose(result -> result); + } + + return steps.createOffer() + .thenCompose(offer -> steps.setLocal(offer).thenApply(ignored -> offer)) + .thenCompose(offer -> onControl(exchange.apply(offer))) + .thenCompose(change -> { + RTCSessionDescription answer = connection.getRemoteDescription(); + + return steps.setRemote(new RTCSessionDescription(RTCSdpType.ANSWER, change.apply(answer.sdp))); + }) + .handle((applied, error) -> { + if (error == null) { + return CompletableFuture.completedFuture(null); + } + + CompletableFuture failed = CompletableFuture.failedFuture(PeerImpl.unwrap(error)); + + if (peer.isClosed() || connection.getSignalingState() == RTCSignalingState.STABLE) { + return failed; + } + + // Back to the ICE session before, which the server keeps. + return steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + .handle((ignored, rollbackError) -> null) + .thenCompose(ignored -> failed); + }) + .thenCompose(result -> result); + }, finished); + } + + /** + * Takes this peer's own offer back and answers the given one instead, as + * a WHEP player does when the server counters its offer. Unlike {@link + * Negotiator#answer}, which fails while an offer of this peer is out. + *

+ * The answer receives only the kinds of media the peer was built to + * receive: the audio or video m-lines of other kinds are rejected, with + * port 0. An offer without any m-line of those kinds fails. + * + * @param offer the offer that replaces this peer's own. + * @param gathering when the answer is handed over. + * + * @return a future with the answer, applied as the local description. + */ + CompletableFuture answerInstead(RTCSessionDescription offer, Gathering gathering) { + Set rejected; + + try { + rejected = midsNotReceived(offer.sdp); + } + catch (NegotiationException e) { + return peer.toPublic(CompletableFuture.failedFuture(e)); + } + + return run(() -> { + // Before the offer is applied, which reports the tracks of the + // m-lines that are then rejected. + for (MediaKind kind : MediaKind.values()) { + if (!options.receive.contains(kind)) { + tracks.decline(kind); + } + } + + // An offer created but not applied yet needs no taking back. + CompletableFuture stable = peer.connection().getSignalingState() == RTCSignalingState.STABLE + ? CompletableFuture.completedFuture(null) + : steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")); + + return stable + .thenCompose(ignored -> steps.setRemote(offer)) + .thenCompose(ignored -> { + stopTransceivers(rejected); + // The offer made transceivers of its own. + codecs.apply(); + steps.releaseHeldCandidates(); + return steps.createAnswer(); + }) + .thenCompose(steps::setLocal) + .thenCompose(ignored -> gathered(gathering)); + }); + } + + /** + * @return a future that completes as the given one, but on the control + * executor, or fails once the peer is closed. + */ + private CompletableFuture onControl(CompletableFuture future) { + CompletableFuture result = chain.step(); + + future.whenComplete((value, error) -> peer.control.execute(() -> PeerImpl.complete(result, value, error), + () -> result.completeExceptionally(peer.closedError()))); + + return result; + } + + /** + * Finds the audio and video m-lines of an offer whose kind this peer does + * not receive. + * + * @return their mids. + * + * @throws NegotiationException if the offer has no open m-line of a kind + * this peer receives. + */ + private Set midsNotReceived(String sdp) { + Set rejected = new HashSet<>(); + boolean received = false; + MediaKind kind = null; + + for (String line : sdp.split("\r?\n")) { + if (line.startsWith("m=")) { + String[] fields = line.substring(2).split(" "); + boolean open = fields.length > 1 && !fields[1].equals("0"); + + kind = !open ? null + : fields[0].equals("audio") ? MediaKind.AUDIO + : fields[0].equals("video") ? MediaKind.VIDEO + : null; + received |= kind != null && options.receive.contains(kind); + } + else if (line.startsWith("a=mid:") && kind != null && !options.receive.contains(kind)) { + rejected.add(line.substring("a=mid:".length()).trim()); + } + } + + if (!received) { + throw new NegotiationException("The offer of the remote peer of " + peer.name + + " holds none of the media it receives, " + options.receive); + } + + return rejected; + } + + /** + * Stops the transceivers of the given mids, whose m-lines the next + * answer then rejects. + */ + private void stopTransceivers(Set mids) { + if (mids.isEmpty()) { + return; + } + + for (RTCRtpTransceiver transceiver : peer.connection().getTransceivers()) { + try { + if (mids.contains(transceiver.getMid()) && !transceiver.stopped()) { + // At once: an answer rejects only the m-lines of stopped + // transceivers, and keeps those still stopping, inactive. + transceiver.stopImmediately(); + } + } + finally { + transceiver.dispose(); + } + } + } + + private CompletableFuture gathered(Gathering gathering) { + CompletableFuture ready = gathering == Gathering.COMPLETE + ? steps.waitForGathering() + : CompletableFuture.completedFuture(null); + + return ready.thenApply(ignored -> peer.connection().getLocalDescription()); + } + + private CompletableFuture run(Supplier> operation) { + return run(operation, (value, error) -> { }); + } + + private CompletableFuture run(Supplier> operation, + BiConsumer finished) { + CompletableFuture result = new CompletableFuture<>(); + + peer.control.execute(() -> chain.enqueue(operation, finished) + .whenComplete((value, error) -> PeerImpl.complete(result, value, error))); + + return peer.toPublic(result); + } +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 56df1f567..a877aa0b3 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -21,29 +21,22 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -import java.util.function.UnaryOperator; import dev.onvoid.webrtc.PeerConnectionObserver; -import dev.onvoid.webrtc.RTCConfiguration; import dev.onvoid.webrtc.RTCDataChannel; import dev.onvoid.webrtc.RTCEncodedFrameTransformer; import dev.onvoid.webrtc.RTCIceCandidate; import dev.onvoid.webrtc.RTCIceGatheringState; -import dev.onvoid.webrtc.RTCIceServer; import dev.onvoid.webrtc.RTCPeerConnection; import dev.onvoid.webrtc.RTCPeerConnectionState; import dev.onvoid.webrtc.RTCRtpEncodingParameters; @@ -51,9 +44,6 @@ import dev.onvoid.webrtc.RTCRtpTransceiver; import dev.onvoid.webrtc.RTCRtpTransceiverDirection; import dev.onvoid.webrtc.RTCRtpTransceiverInit; -import dev.onvoid.webrtc.RTCSdpType; -import dev.onvoid.webrtc.RTCSessionDescription; -import dev.onvoid.webrtc.RTCSignalingState; import dev.onvoid.webrtc.client.internal.EncodedFrames; import dev.onvoid.webrtc.media.MediaStream; import dev.onvoid.webrtc.media.MediaType; @@ -73,6 +63,13 @@ * made of the {@link NegotiationSteps}. The automatic negotiation is the * {@link PerfectNegotiation}; all three are confined to the control executor * as well. + *

+ * This class owns the lifecycle of the connection, its senders, and the step + * from internal to public futures. The other concerns have classes of their + * own, which keep to the same two executors and say which of their state + * belongs to which: the {@link DataChannels}, the {@link RemoteTracks}, the + * {@link StatsSampler}, the {@link SignalingLink}, and the {@link + * ManualNegotiation} with its {@link CodecPreferences}. */ final class PeerImpl implements Peer { @@ -90,18 +87,23 @@ final class PeerImpl implements Peer { final SerialExecutor events; + // Called from any thread; each says which of its state is confined to + // which executor. + final DataChannels channels; + final ManualNegotiation manual; + private final RemoteTracks tracks; - private final CodecPreferences codecs; + private final StatsSampler statistics; private final SignalingLink signaling; private final PeerOptions options; /** The stream the tracks added without stream ids share. */ - private final String defaultStreamId = UUID.randomUUID().toString(); + final String defaultStreamId = UUID.randomUUID().toString(); private final AtomicBoolean closing = new AtomicBoolean(); @@ -125,8 +127,6 @@ final class PeerImpl implements Peer { private final PerfectNegotiation automatic; - private final StatsSampler statistics; - // Confined to the event executor. private PeerState deliveredState = PeerState.NEW; @@ -139,8 +139,6 @@ final class PeerImpl implements Peer { private final ClientFuture closedFuture = new ClientFuture<>(); - private final NegotiatorImpl negotiator = new NegotiatorImpl(); - /** Gets the local candidates as well, or null. Called on the control executor. */ private volatile Consumer candidateListener; @@ -164,7 +162,7 @@ final class PeerImpl implements Peer { this.statistics = new StatsSampler(this); this.channels = new DataChannels(this); this.tracks = new RemoteTracks(this, options.receiveTransform); - this.codecs = new CodecPreferences(this); + this.manual = new ManualNegotiation(this, options, chain, steps, tracks, new CodecPreferences(this)); this.signaling = new SignalingLink(this, options.signaling); rtc.track(connected, events); @@ -382,113 +380,7 @@ public Negotiator negotiator() { + "Build it with Negotiation.MANUAL to drive the exchange by hand"); } - return negotiator; - } - - /** - * Creates an offer without applying it, so that the configuration can - * still change before candidates are gathered for it, as WHIP and WHEP do - * with the ICE servers the endpoint names in its answer. - * - * @return a future with the offer, which {@link #applyLocal} applies. - */ - CompletableFuture offer() { - return negotiator.run(steps::createOffer); - } - - /** - * Applies a description this peer created, which starts the gathering of - * candidates for it. - */ - CompletableFuture applyLocal(RTCSessionDescription description) { - return negotiator.run(() -> steps.setLocal(description)); - } - - /** - * Makes every transceiver send only, as a WHIP client's offer should be - * (RFC 9725, 4.2). Ordered with the negotiation steps, so it takes effect - * on the next offer. - */ - CompletableFuture sendOnly() { - return negotiator.run(() -> { - for (RTCRtpTransceiver transceiver : connection.getTransceivers()) { - try { - if (!transceiver.stopped()) { - transceiver.setDirection(RTCRtpTransceiverDirection.SEND_ONLY); - } - } - finally { - transceiver.dispose(); - } - } - - return CompletableFuture.completedFuture(null); - }); - } - - /** - * Adds video that only sends, without a track, to the stream of the - * tracks added without stream ids, for endpoints that take no offer - * without video. Ordered with the negotiation steps. - */ - CompletableFuture addVideoWithoutTrack() { - return negotiator.run(() -> { - RTCRtpTransceiverInit init = new RTCRtpTransceiverInit(); - init.direction = RTCRtpTransceiverDirection.SEND_ONLY; - init.streamIds.add(defaultStreamId); - - connection.addTransceiver(MediaType.VIDEO, init).dispose(); - - return CompletableFuture.completedFuture(null); - }); - } - - /** - * 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. This holds for the transceivers there are, and for those an - * offer adds later, as a counter-offer this peer answers instead of its - * own. Ordered with the negotiation steps, so it takes effect on the next - * offer or answer. - * - * @param names the codec names of each kind, such as H264 or opus. - * - * @return a future that fails if WebRTC has no codec of a name. - */ - CompletableFuture preferCodecs(Map> names) { - return negotiator.run(() -> { - codecs.prefer(names); - - return CompletableFuture.completedFuture(null); - }); - } - - /** - * Gathers candidates from now on with the given ICE servers, unless the - * peer was built with servers of its own, which take precedence. - * - * @param servers the ICE servers; none leaves the configuration as it is. - * - * @return a future that fails if WebRTC refuses the servers. - */ - CompletableFuture useIceServers(List servers) { - if (servers.isEmpty() || !options.iceServers.isEmpty()) { - return CompletableFuture.completedFuture(null); - } - - return negotiator.run(() -> { - try { - RTCConfiguration config = connection.getConfiguration(); - config.iceServers = new ArrayList<>(servers); - connection.setConfiguration(config); - - return CompletableFuture.completedFuture(null); - } - catch (RuntimeException e) { - return CompletableFuture.failedFuture(new ConfigurationException("WebRTC refused the ICE servers " - + servers + " for " + name + ": " + e.getMessage(), e)); - } - }); + return manual; } /** @@ -503,222 +395,6 @@ void onLocalCandidates(Consumer candidates, Runnable gathered) this.gatheredListener = gathered; } - /** - * Restarts ICE as WHIP and WHEP do, without a renegotiation: only the ICE - * information of a new offer goes to the remote peer, and the remote - * description keeps its offer/answer role, with the ICE information that - * comes back. After a server counter-offer, the new local credentials are - * applied in an answer to the updated remote offer. - * An exchange that fails takes the new offer back, and the ICE session - * before goes on. - * - * @param exchange sends the ICE information of the new offer, and returns - * how to change the remote answer. - * - * @return a future that completes once the new ICE information is applied. - */ - CompletableFuture restartIce( - Function>> exchange) { - return restartIce(exchange, (value, error) -> { }); - } - - CompletableFuture restartIce( - Function>> exchange, - BiConsumer finished) { - return negotiator.run(() -> { - RTCSessionDescription remote = connection.getRemoteDescription(); - - if (connection.getSignalingState() != RTCSignalingState.STABLE || remote == null - || (remote.sdpType != RTCSdpType.ANSWER && remote.sdpType != RTCSdpType.OFFER)) { - return CompletableFuture.failedFuture(new NegotiationException("The peer " + name - + " has no stable description to restart ICE with")); - } - - connection.restartIce(); - - if (remote.sdpType == RTCSdpType.OFFER) { - // Keep the server's offerer role (including its DTLS role and - // media sections). Create an offer only to obtain fresh local - // ICE credentials; do not apply it or change signaling roles. - return steps.createOffer().thenCompose(offer -> onControl(exchange.apply(offer)) - .thenCompose(change -> steps.setRemote(new RTCSessionDescription( - RTCSdpType.OFFER, change.apply(remote.sdp)))) - .thenCompose(ignored -> { - // Reapplying the server's offer can create transceivers - // for media the original answer rejected. - stopTransceivers(midsNotReceived(remote.sdp)); - return steps.createAnswer(); - }) - .thenCompose(answer -> steps.setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, - HttpIce.Fragment.of(offer.sdp).applyCredentialsTo(answer.sdp))))) - .handle((applied, error) -> { - if (error == null) { - return CompletableFuture.completedFuture(null); - } - CompletableFuture failed = CompletableFuture.failedFuture(unwrap(error)); - if (closed || connection.getSignalingState() != RTCSignalingState.HAVE_REMOTE_OFFER) { - return failed; - } - return steps.setRemote(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) - .handle((ignored, rollbackError) -> null) - .thenCompose(ignored -> failed); - }).thenCompose(result -> result); - } - - return steps.createOffer() - .thenCompose(offer -> steps.setLocal(offer).thenApply(ignored -> offer)) - .thenCompose(offer -> onControl(exchange.apply(offer))) - .thenCompose(change -> { - RTCSessionDescription answer = connection.getRemoteDescription(); - - return steps.setRemote(new RTCSessionDescription(RTCSdpType.ANSWER, change.apply(answer.sdp))); - }) - .handle((applied, error) -> { - if (error == null) { - return CompletableFuture.completedFuture(null); - } - - CompletableFuture failed = CompletableFuture.failedFuture(unwrap(error)); - - if (closed || connection.getSignalingState() == RTCSignalingState.STABLE) { - return failed; - } - - // Back to the ICE session before, which the server keeps. - return steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) - .handle((ignored, rollbackError) -> null) - .thenCompose(ignored -> failed); - }) - .thenCompose(result -> result); - }, finished); - } - - /** - * @return a future that completes as the given one, but on the control - * executor, or fails once the peer is closed. - */ - private CompletableFuture onControl(CompletableFuture future) { - CompletableFuture result = chain.step(); - - future.whenComplete((value, error) -> control.execute(() -> complete(result, value, error), - () -> result.completeExceptionally(closedError()))); - - return result; - } - - /** - * Takes this peer's own offer back and answers the given one instead, as - * a WHEP player does when the server counters its offer. Unlike {@link - * Negotiator#answer}, which fails while an offer of this peer is out. - *

- * The answer receives only the kinds of media the peer was built to - * receive: the audio or video m-lines of other kinds are rejected, with - * port 0. An offer without any m-line of those kinds fails. - * - * @param offer the offer that replaces this peer's own. - * @param gathering when the answer is handed over. - * - * @return a future with the answer, applied as the local description. - */ - CompletableFuture answerInstead(RTCSessionDescription offer, Gathering gathering) { - Set rejected; - - try { - rejected = midsNotReceived(offer.sdp); - } - catch (NegotiationException e) { - return toPublic(CompletableFuture.failedFuture(e)); - } - - return negotiator.run(() -> { - // Before the offer is applied, which reports the tracks of the - // m-lines that are then rejected. - for (MediaKind kind : MediaKind.values()) { - if (!options.receive.contains(kind)) { - tracks.decline(kind); - } - } - - // An offer created but not applied yet needs no taking back. - CompletableFuture stable = connection.getSignalingState() == RTCSignalingState.STABLE - ? CompletableFuture.completedFuture(null) - : steps.setLocal(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")); - - return stable - .thenCompose(ignored -> steps.setRemote(offer)) - .thenCompose(ignored -> { - stopTransceivers(rejected); - // The offer made transceivers of its own. - codecs.apply(); - steps.releaseHeldCandidates(); - return steps.createAnswer(); - }) - .thenCompose(steps::setLocal) - .thenCompose(ignored -> negotiator.gathered(gathering)); - }); - } - - /** - * Finds the audio and video m-lines of an offer whose kind this peer does - * not receive. - * - * @return their mids. - * - * @throws NegotiationException if the offer has no open m-line of a kind - * this peer receives. - */ - private Set midsNotReceived(String sdp) { - Set rejected = new HashSet<>(); - boolean received = false; - MediaKind kind = null; - - for (String line : sdp.split("\r?\n")) { - if (line.startsWith("m=")) { - String[] fields = line.substring(2).split(" "); - boolean open = fields.length > 1 && !fields[1].equals("0"); - - kind = !open ? null - : fields[0].equals("audio") ? MediaKind.AUDIO - : fields[0].equals("video") ? MediaKind.VIDEO - : null; - received |= kind != null && options.receive.contains(kind); - } - else if (line.startsWith("a=mid:") && kind != null && !options.receive.contains(kind)) { - rejected.add(line.substring("a=mid:".length()).trim()); - } - } - - if (!received) { - throw new NegotiationException("The offer of the remote peer of " + name - + " holds none of the media it receives, " + options.receive); - } - - return rejected; - } - - /** - * Stops the transceivers of the given mids, whose m-lines the next - * answer then rejects. - */ - private void stopTransceivers(Set mids) { - if (mids.isEmpty()) { - return; - } - - for (RTCRtpTransceiver transceiver : connection.getTransceivers()) { - try { - if (mids.contains(transceiver.getMid()) && !transceiver.stopped()) { - // At once: an answer rejects only the m-lines of stopped - // transceivers, and keeps those still stopping, inactive. - transceiver.stopImmediately(); - } - } - finally { - transceiver.dispose(); - } - } - } - @Override public CompletableFuture stats() { return statistics.read(); @@ -1199,88 +875,6 @@ public void onDataChannel(RTCDataChannel dataChannel) { - private final class NegotiatorImpl implements Negotiator { - - @Override - public CompletableFuture createOffer() { - return createOffer(Gathering.TRICKLE); - } - - @Override - public CompletableFuture createOffer(Gathering gathering) { - requireNonNull(gathering, "gathering"); - - return run(() -> steps.createOffer() - .thenCompose(steps::setLocal) - .thenCompose(ignored -> gathered(gathering))); - } - - @Override - public CompletableFuture answer(RTCSessionDescription offer) { - return answer(offer, Gathering.TRICKLE); - } - - @Override - public CompletableFuture answer(RTCSessionDescription offer, Gathering gathering) { - requireNonNull(offer, "offer"); - requireNonNull(gathering, "gathering"); - - if (offer.sdpType != RTCSdpType.OFFER) { - throw new IllegalArgumentException("Expected an offer, got " + offer.sdpType); - } - - return run(() -> steps.setRemote(offer) - .thenCompose(ignored -> { - steps.releaseHeldCandidates(); - return steps.createAnswer(); - }) - .thenCompose(steps::setLocal) - .thenCompose(ignored -> gathered(gathering))); - } - - @Override - public CompletableFuture applyAnswer(RTCSessionDescription answer) { - requireNonNull(answer, "answer"); - - if (answer.sdpType != RTCSdpType.ANSWER && answer.sdpType != RTCSdpType.PR_ANSWER) { - throw new IllegalArgumentException("Expected an answer, got " + answer.sdpType); - } - - return run(() -> steps.setRemote(answer).thenRun(steps::releaseHeldCandidates)); - } - - @Override - public CompletableFuture addCandidate(RTCIceCandidate candidate) { - requireNonNull(candidate, "candidate"); - - return run(() -> steps.addRemoteCandidate(candidate)); - } - - private CompletableFuture gathered(Gathering gathering) { - CompletableFuture ready = gathering == Gathering.COMPLETE - ? steps.waitForGathering() - : CompletableFuture.completedFuture(null); - - return ready.thenApply(ignored -> connection.getLocalDescription()); - } - - private CompletableFuture run(Supplier> operation) { - return run(operation, (value, error) -> { }); - } - - private CompletableFuture run(Supplier> operation, - BiConsumer finished) { - CompletableFuture result = new CompletableFuture<>(); - - control.execute(() -> chain.enqueue(operation, finished) - .whenComplete((value, error) -> complete(result, value, error))); - - return toPublic(result); - } - } - - - /** * What the operations chain needs of this peer, on the control executor. */ 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 a6cea397d..690db9227 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java @@ -342,7 +342,7 @@ public CompletableFuture play(WebRtc rtc) { PeerImpl peer = (PeerImpl) rtc.createPeer(options.build()); try { - return HttpSession.start(rtc, peer, endpoint, credentials, limit, peer.preferCodecs(names), gathering, + return HttpSession.start(rtc, peer, endpoint, credentials, limit, peer.manual.preferCodecs(names), gathering, PROTOCOL, Session::new); } catch (RuntimeException | Error e) { 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 ade08986f..c95bced27 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java @@ -412,15 +412,15 @@ public CompletableFuture publish(WebRtc rtc) { } } if (placeholder) { - video = peer.addVideoWithoutTrack(); + video = peer.manual.addVideoWithoutTrack(); } // Before the offer, which follows in the same order: WHIP only // sends (RFC 9725, 4.2). Should WebRTC refuse, the offer stays // sendrecv, which WHIP allows as well. - peer.sendOnly(); + peer.manual.sendOnly(); - CompletableFuture prepared = CompletableFuture.allOf(video, peer.preferCodecs(names)); + CompletableFuture prepared = CompletableFuture.allOf(video, peer.manual.preferCodecs(names)); return HttpSession.start(rtc, peer, endpoint, credentials, limit, prepared, gathering, PROTOCOL, Session::new); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java index c8bb75c4e..46584316f 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/NegotiationTimeoutTests.java @@ -62,7 +62,7 @@ private void lateRestartAnswer(boolean remoteOffer) throws Exception { CompletableFuture> late = new CompletableFuture<>(); AtomicBoolean firstSent = new AtomicBoolean(); AtomicBoolean applied = new AtomicBoolean(); - CompletableFuture first = peer.restartIce(offer -> { + CompletableFuture first = peer.manual.restartIce(offer -> { firstSent.set(true); return late; }); @@ -70,7 +70,7 @@ private void lateRestartAnswer(boolean remoteOffer) throws Exception { CompletableFuture> answer = new CompletableFuture<>(); AtomicBoolean nextSent = new AtomicBoolean(); - CompletableFuture next = peer.restartIce(offer -> { + CompletableFuture next = peer.manual.restartIce(offer -> { nextSent.set(true); return answer; });