From c988613d23cd309b34e74bbbfb0786ed2e4aa837 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 14:07:21 +0100 Subject: [PATCH 1/2] fix: keep quoted Link parameter values intact --- .../dev/onvoid/webrtc/client/HttpIce.java | 7 ++++--- .../onvoid/webrtc/client/HttpIceTests.java | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) 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 5899cf3dd..54412814a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -596,7 +596,7 @@ private static int parameters(String field, int start, Map param if (i < field.length() && field.charAt(i) == '=') { i++; - while (i < field.length() && field.charAt(i) == ' ') { + while (i < field.length() && " \t".indexOf(field.charAt(i)) >= 0) { i++; } @@ -614,14 +614,15 @@ private static int parameters(String field, int start, Map param } i++; + value = text.toString(); } else { while (i < field.length() && ";,".indexOf(field.charAt(i)) < 0) { text.append(field.charAt(i++)); } - } - value = text.toString().trim(); + value = text.toString().trim(); + } } parameters.putIfAbsent(name, value); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java index d44691960..52fd94418 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java @@ -81,6 +81,26 @@ void linksRead() { assertEquals("pw", servers.get(2).password); } + @Test + void quotedSpacesKept() { + List servers = HttpIce.iceServers(Arrays.asList( + "; rel=\"ice-server\"; username=\"\\ alice\\\t\"; credential=\" secret \"")); + + assertEquals(1, servers.size(), () -> "Servers: " + servers); + assertEquals(" alice\t", servers.get(0).username); + assertEquals(" secret ", servers.get(0).password); + } + + @Test + void tabsAroundValuesSkipped() { + List servers = HttpIce.iceServers(Arrays.asList( + ";\trel=\t\"ice-server\"\t;\tusername=\t\"alice\"\t;\tcredential \t= \tpw\t ; x=y")); + + assertEquals(1, servers.size(), () -> "Servers: " + servers); + assertEquals("alice", servers.get(0).username); + assertEquals("pw", servers.get(0).password); + } + @Test void fragmentOfOffer() { // The m-line that tags the BUNDLE group stands for all, as RFC 9725 From 8a0906ea84f679358b7f35d56c8601d040092218 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 14:20:53 +0100 Subject: [PATCH 2/2] fix: tie DTMF events to their tones and bound their end --- docs/guide/client-api.md | 2 +- .../java/dev/onvoid/webrtc/client/Sender.java | 4 +- .../dev/onvoid/webrtc/client/SenderImpl.java | 122 +++++++++++--- .../webrtc/client/SenderTonesTests.java | 153 ++++++++++++++++++ 4 files changed, 257 insertions(+), 24 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/SenderTonesTests.java diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 049e3d5f5..8859fec78 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -478,7 +478,7 @@ audioSender.sendTones("1234#"); // 100 ms audioSender.sendTones("*99,1", Duration.ofMillis(200), Duration.ofMillis(100)); ``` -The characters 0 to 9, A to D, `#` and `*` are tones, and a comma is a pause of 2 seconds. Tones still queued from an earlier call are replaced, and that call's future is cancelled. A video sender, or one whose remote peer accepts no telephone events, fails the future with an `IllegalStateException`. The [DTMF Sender](/guide/audio/dtmf-sender) guide has the details. +The characters 0 to 9, A to D, `#` and `*` are tones, and a comma is a pause of 2 seconds. Tones still queued from an earlier call are replaced, and that call's future is cancelled. A video sender, or one whose remote peer accepts no telephone events, fails the future with an `IllegalStateException`. So do tones WebRTC stops sending midway, for example because the sender was paused with `configure`, a few seconds after their planned end. The [DTMF Sender](/guide/audio/dtmf-sender) guide has the details. ### Switching Cameras diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Sender.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Sender.java index 1c62fd92c..bef0e55d5 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Sender.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Sender.java @@ -102,7 +102,9 @@ public interface Sender { * * @return a future that completes once the tones have been sent. It fails * with an {@link IllegalStateException} if the sender cannot send tones, - * because it sends video or the remote peer does not accept them. + * because it sends video or the remote peer does not accept them, and a + * few seconds after their planned end if WebRTC stopped sending them + * midway. */ CompletableFuture sendTones(String tones, Duration duration, Duration gap); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/SenderImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/SenderImpl.java index 1bf43efb5..3ab922a81 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/SenderImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/SenderImpl.java @@ -22,6 +22,8 @@ import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import dev.onvoid.webrtc.RTCDtmfSender; @@ -41,12 +43,25 @@ */ final class SenderImpl implements Sender { + /** How much later than planned the end of tones may come. */ + static final Duration TONE_GRACE = Duration.ofSeconds(5); + + /** The pause of a comma, WebRTC's default. */ + private static final long COMMA_MILLIS = 2000; + private final PeerImpl peer; private final MediaKind kind; private volatile LocalTrackImpl track; + /** + * Identifies the tones WebRTC plays, written on the control executor. A + * tone event takes it on WebRTC's thread, when it happens, so that it + * still names its tones after later ones started. + */ + private volatile long toneRun; + // Confined to the peer's control executor. private RTCPeerConnection connection; @@ -62,6 +77,9 @@ final class SenderImpl implements Sender { /** Completes once the tones sent last have been played. */ private CompletableFuture pendingTones; + /** Ends the pending tones should WebRTC never report their end. */ + private ScheduledFuture tonesDeadline; + // Confined to the peer's event executor. private final Handlers toneHandlers; @@ -268,16 +286,22 @@ public CompletableFuture sendTones(String tones, Duration duration, Durati throw new IllegalStateException("WebRTC refused the tones \"" + tones + "\""); } - if (pendingTones != null) { - pendingTones.completeExceptionally(new CancellationException("Replaced by later tones")); - } + // Set only now: the tones before play until this call stops + // them, and the first of these takes at least a millisecond. + long run = toneRun + 1; + toneRun = run; + + finishTones(new CancellationException("Replaced by later tones")); - if (hasTone(tones)) { + long playMillis = playMillis(tones, durationMs, gapMs); + + if (playMillis > 0) { + tonesDeadline = peer.rtc.timer.schedule(() -> peer.control.execute(() -> tonesOverdue(run)), + playMillis + TONE_GRACE.toMillis(), TimeUnit.MILLISECONDS); pendingTones = sent; } else { // Nothing to play, so no event would complete the future. - pendingTones = null; sent.complete(null); } } @@ -408,11 +432,7 @@ private void release() { dtmf.dispose(); dtmf = null; } - if (pendingTones != null) { - pendingTones.completeExceptionally(peer.isClosed() - ? peer.closedError() : new IllegalStateException("The sender was removed")); - pendingTones = null; - } + finishTones(peer.isClosed() ? peer.closedError() : new IllegalStateException("The sender was removed")); if (sender != null) { sender.dispose(); @@ -439,21 +459,69 @@ private LocalTrackImpl checkTrack(LocalTrack replacement) { } /** Called on a WebRTC thread, so it only posts. */ - private void toneChanged(String tone) { + void toneChanged(String tone) { String current = tone == null ? "" : tone; + long run = toneRun; peer.control.execute(() -> { - // The handlers hear of the tone before the future of the tones - // completes, which also goes through the event executor. - peer.events.execute(() -> toneHandlers.accept(current)); - - if (current.isEmpty() && pendingTones != null) { - pendingTones.complete(null); - pendingTones = null; + if (!current.isEmpty()) { + peer.events.execute(() -> toneHandlers.accept(current)); + } + else if (run == toneRun) { + tonesEnded(); } + // The end of tones replaced meanwhile says nothing of the new + // ones. Replaced a moment earlier, they would have had no end. }); } + private void tonesEnded() { + // The handlers hear of the end before the future of the tones + // completes, which also goes through the event executor. + peer.events.execute(() -> toneHandlers.accept("")); + finishTones(null); + } + + /** + * WebRTC gives up without an event when it can no longer send a tone, + * which it then keeps in its queue. With an empty queue only the event is + * missing. + */ + private void tonesOverdue(long run) { + if (run != toneRun || pendingTones == null) { + return; + } + + if (dtmf.tones().isEmpty()) { + tonesEnded(); + } + else { + finishTones(new IllegalStateException("WebRTC could no longer send the tones")); + } + } + + /** + * Settles the pending tones, if any. + * + * @param error why they failed, or null if they have been sent. + */ + private void finishTones(Throwable error) { + if (pendingTones == null) { + return; + } + + tonesDeadline.cancel(false); + + if (error != null) { + pendingTones.completeExceptionally(error); + } + else { + pendingTones.complete(null); + } + + pendingTones = null; + } + private void checkUsable() { if (peer.isClosed()) { throw peer.closedError(); @@ -466,14 +534,24 @@ private void checkUsable() { } } - private static boolean hasTone(String tones) { + /** + * @return how long WebRTC takes for the tones, 0 if they hold none. + */ + private static long playMillis(String tones, long durationMs, long gapMs) { + long millis = 0; + for (int i = 0; i < tones.length(); i++) { - if ("0123456789ABCDabcd#*,".indexOf(tones.charAt(i)) >= 0) { - return true; + char tone = tones.charAt(i); + + if (tone == ',') { + millis += COMMA_MILLIS; + } + else if ("0123456789ABCDabcd#*".indexOf(tone) >= 0) { + millis += durationMs + gapMs; } } - return false; + return millis; } private CompletableFuture run(Runnable operation) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/SenderTonesTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/SenderTonesTests.java new file mode 100644 index 000000000..be32566b8 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/SenderTonesTests.java @@ -0,0 +1,153 @@ +/* + * 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 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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * How the future of tones ends, on a connected sender whose control executor + * and timer the tests drive. A tone this long leaves WebRTC's own end event + * out of the way; the tests send the events they need. + */ +class SenderTonesTests extends ClientTestBase { + + private static final Duration LONG_TONE = Duration.ofSeconds(6); + + private static final Duration GAP = Duration.ofMillis(30); + + /** When one long tone is overdue. */ + private static final Duration DEADLINE = LONG_TONE.plus(GAP).plus(SenderImpl.TONE_GRACE); + + private final ManualExecutor control = new ManualExecutor(); + + private final ManualTimer timer = new ManualTimer(); + + /** Written on the test's thread, which runs the handlers. */ + private final List heard = new ArrayList<>(); + + private WebRtc runtime; + + private SenderImpl sender; + + + @BeforeEach + void connect() throws Exception { + runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .controlPool(control) + .eventExecutor(Runnable::run) + .timer(timer) + .build(); + + Peer caller = drive(CompletableFuture.supplyAsync(() -> { + SignalingPair link = Signaling.loopback(); + Peer peer = runtime.createPeer(PeerOptions.builder().name("caller").signaling(link.first()).build()); + + runtime.createPeer(PeerOptions.builder().name("callee").signaling(link.second()).polite(true).build()); + sender = (SenderImpl) peer.addTrack(runtime.media().customAudio("voice")); + + return peer; + })); + + sender.onTone(heard::add); + drive(caller.whenConnected()); + } + + @AfterEach + void closeManualRuntime() throws Exception { + drive(runtime.closeAsync()); + } + + @Test + void lateEndKeepsNewTones() throws Exception { + CompletableFuture first = sender.sendTones("1", LONG_TONE, GAP); + control.runAll(); + + CompletableFuture second = sender.sendTones("2", LONG_TONE, GAP); + + // WebRTC ends the first tones while the second wait on the control + // executor, so that the event runs after them. + sender.toneChanged(""); + control.runAll(); + + assertTrue(first.isCompletedExceptionally()); + assertFalse(second.isDone()); + assertFalse(heard.contains(""), () -> "Heard: " + heard); + assertEquals(1, timer.scheduled(DEADLINE)); + + sender.toneChanged(""); + control.runAll(); + + await(second); + assertEquals("", heard.get(heard.size() - 1)); + assertEquals(0, timer.scheduled(DEADLINE)); + } + + @Test + void stoppedTonesFail() throws Exception { + CompletableFuture sent = sender.sendTones("123", Duration.ofMillis(40), GAP); + + // A paused stream refuses the next tone, and WebRTC gives up without + // an event. A sender without a track would go on sending tones. + drive(sender.configure(Encoding.builder().active(false).build())); + + assertEquals(1, timer.fire(Duration.ofMillis(3 * 70).plus(SenderImpl.TONE_GRACE))); + control.runAll(); + + ExecutionException failed = assertThrows(ExecutionException.class, () -> await(sent)); + + assertInstanceOf(IllegalStateException.class, failed.getCause()); + assertFalse(heard.contains(""), () -> "Heard: " + heard); + } + + @Test + void playedTonesComplete() throws Exception { + CompletableFuture sent = sender.sendTones("1", LONG_TONE, GAP); + + control.runUntil(() -> heard.contains("1"), TIMEOUT_SECONDS); + + // The last tone left WebRTC's queue, and only its end event is missing. + assertEquals(1, timer.fire(DEADLINE)); + control.runAll(); + + await(sent); + assertEquals(Arrays.asList("1", ""), heard); + } + + private T drive(CompletableFuture future) throws Exception { + control.runUntil(future::isDone, TIMEOUT_SECONDS); + + return await(future); + } + +}