From d81e156a72832968618749fd07f59b89b40a18ea Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 01:40:31 +0100 Subject: [PATCH 1/5] fix: stop a stats timer whose first sample found the peer closing The first sample is due at once and may run before its task is known, so it could not cancel it. Check again once the task is set. --- .../onvoid/webrtc/client/StatsSampler.java | 10 +++++++- .../dev/onvoid/webrtc/client/ManualTimer.java | 23 ++++++++++++++++- .../dev/onvoid/webrtc/client/PeerTests.java | 25 +++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java index 349ac341e..198e41a9d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java @@ -136,7 +136,15 @@ else if (!(PeerImpl.unwrap(error) instanceof PeerClosedException)) { })); }; - task.set(peer.rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS)); + ScheduledFuture scheduled = peer.rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS); + + task.set(scheduled); + + // The first sample is due at once, and may have found the peer closing + // before it could see the task. + if (!active.get()) { + scheduled.cancel(false); + } return () -> { active.set(false); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualTimer.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualTimer.java index 02150c81c..93a8f1190 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualTimer.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualTimer.java @@ -44,6 +44,17 @@ final class ManualTimer extends AbstractExecutorService implements ScheduledExec private boolean shutdown; + private boolean eagerPeriodic; + + + /** + * Has every periodic task scheduled from now on run once before its + * schedule call returns, as a timer thread may, when its first run is due + * at once. + */ + synchronized void eagerPeriodic() { + eagerPeriodic = true; + } /** * Fires every task scheduled with the delay that has not been cancelled. @@ -101,7 +112,17 @@ public ScheduledFuture schedule(Callable callable, long delay, TimeUni @Override public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { - return add(new Task<>(Executors.callable(command, null), unit.toMillis(period), true)); + Task task = add(new Task<>(Executors.callable(command, null), unit.toMillis(period), true)); + + synchronized (this) { + if (!eagerPeriodic) { + return task; + } + } + + task.fire(); + + return task; } @Override 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 8b3c7b892..f4cf20d81 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java @@ -771,6 +771,31 @@ void statsStopOnClose() throws Exception { } } + @Test + void statsStopBeforeTaskKnown() throws Exception { + // The first sample is due at once, so it may find the peer closed + // before the task it has to cancel is known. + 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(); + + await(peer.closeAsync()); + + timer.eagerPeriodic(); + peer.onStats(interval, stats -> calls.incrementAndGet()); + + assertEquals(0, timer.scheduled(interval)); + assertEquals(0, calls.get()); + } + } + @Test void statsOfClosedPeerFail() throws Exception { Peer peer = rtc.createPeer(manualOptions()); From 7df95901a11f436338bed612cdf872058b8dde36 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 01:40:31 +0100 Subject: [PATCH 2/5] fix: keep a slow custom audio track from delaying the others The pacer now only counts the ticks due. Pushing into the source moves to a pool of its own, with at most one hand-over per track at a time, and missed ticks are made up for as before. --- docs/guide/client-api.md | 2 +- .../onvoid/webrtc/client/CustomAudioImpl.java | 72 ++++++++++++++---- .../java/dev/onvoid/webrtc/client/WebRtc.java | 28 ++++++- .../onvoid/webrtc/client/ManualExecutor.java | 35 +++++++-- .../dev/onvoid/webrtc/client/MediaTests.java | 76 +++++++++++++++++++ 5 files changed, 188 insertions(+), 25 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index a60e5a93a..f35bdbf8a 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -438,7 +438,7 @@ CustomAudio voice = media.customAudio("voice"); voice.push(pcm, PcmFormat.of(48000, 1)); ``` -`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms from a thread of its own, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it. That thread does nothing else, so a slow push into WebRTC delays only the audio, not the timeouts of the runtime. Should it stall, as in a long garbage collection pause, it makes up for at most the last 50 ms instead of sending the whole pause at once; the queued audio then stays behind by the rest, until `clear()` drops it. +`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it. One thread keeps the time for all tracks and does nothing else, while the audio goes into WebRTC on other threads, one at a time for each track, so a slow push into WebRTC delays only the audio of its own track, neither the other tracks nor the timeouts of the runtime. Should a track stall, as in a long garbage collection pause, it makes up for at most the last 50 ms instead of sending the whole pause at once; the queued audio then stays behind by the rest, until `clear()` drops it. A producer faster than real time would otherwise fill memory and push the delay up without end, so the queue holds at most 10 seconds, and a `push` beyond that fails with an `AudioQueueFullException`, keeping none of its audio. `queueLimit(max, overflow)` sets another limit and what happens beyond it: diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java index fc9426bd8..10afebf8e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java @@ -29,21 +29,23 @@ /** * An audio track fed with audio the application pushes. Pushed audio is cut - * into 10 ms chunks, which the runtime's audio pacer hands to the source one - * every 10 ms. Its thread is the only one that pushes into the source, as - * {@link CustomAudioSource} requires, and it runs no timeouts, which a slow - * push would hold up. + * into 10 ms chunks, of which one is due every 10 ms. The runtime's audio + * pacer only counts what is due, for all tracks, and a thread of the audio + * sender hands it to the source. At most one does so at a time for each track, + * as {@link CustomAudioSource} requires, so that a slow push holds up this + * track alone. */ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private static final long TICK_NANOS = TimeUnit.MILLISECONDS.toNanos(10); /** - * How late a tick may run and still send. The pacer runs at a fixed rate, - * so after a stall it runs the missed ticks back to back: those up to this - * late are made up for, so that a short stall keeps the pace, and the - * earlier ones are skipped, so that a long one does not burst out all the - * audio of the pause at once. Skipped ticks leave the queue as it is. + * How late a tick may run and still send. Ticks keep coming at a fixed + * rate, so after a stall of the pacer or of this track's sending the + * missed ones run back to back: those up to this late are made up for, so + * that a short stall keeps the pace, and the earlier ones are skipped, so + * that a long one does not burst out all the audio of the pause at once. + * Skipped ticks leave the queue as it is. */ private static final long MAX_LATE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); @@ -54,7 +56,7 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private final CustomAudioSource source; - // Confined to the pacer, once the ticker is scheduled. + // Confined to the sending turn, once the ticker is scheduled. /** When the first tick was due. */ private long start; @@ -80,6 +82,12 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private boolean stopped; + /** The ticks the pacer counted that no sending turn has taken yet. */ + private long dueTicks; + + /** True while a sending turn runs or waits for its thread. */ + private boolean sending; + CustomAudioImpl(LocalMediaImpl media, AudioTrack track, CustomAudioSource source) { super(media, track, source::dispose, false); @@ -225,13 +233,51 @@ private void dropOverflow() { } } + /** + * Counts a tick, on the pacer, which never waits for the source: a turn + * that is busy takes the tick along, however long it takes. + */ private void tick() { - long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS); + synchronized (queue) { + dueTicks++; - if (late > MAX_LATE_NANOS) { - return; + if (sending) { + return; + } + + sending = true; + } + + rtc.audioSender.execute(this::send); + } + + /** A sending turn: runs the ticks due, until none is left. */ + private void send() { + while (takeTick()) { + long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS); + + if (late <= MAX_LATE_NANOS) { + sendChunk(); + } + } + } + + /** + * @return true when a tick was due, false when the turn is over. + */ + private boolean takeTick() { + synchronized (queue) { + if (dueTicks == 0) { + sending = false; + return false; + } + + dueTicks--; + return true; } + } + private void sendChunk() { Chunk chunk; synchronized (queue) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java index 3d9aaa42f..fb6fa4c50 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java @@ -106,11 +106,18 @@ public final class WebRtc implements AutoCloseable { final ScheduledExecutorService timer; /** - * The one thread that sends pushed audio, apart from the timer: a slow - * push must not delay the timeouts. + * The one thread that keeps the time of pushed audio for all tracks. It + * only counts the chunks due, and hands them to the {@link #audioSender}. */ final ScheduledExecutorService audioPacer; + /** + * The threads that hand pushed audio to WebRTC, at most one for each track + * at a time: a slow hand-over delays its own track, not the pacer, the + * other tracks or the timeouts. + */ + final ExecutorService audioSender; + /** The time in nanoseconds, as {@link System#nanoTime()}. */ final LongSupplier clock; @@ -193,6 +200,8 @@ private WebRtc(Builder builder) { : scheduler("webrtc-client-timer-" + runtime + "-"); this.audioPacer = builder.audioPacer != null ? builder.audioPacer : scheduler("webrtc-client-audio-" + runtime + "-"); + this.audioSender = builder.audioSender != null ? builder.audioSender + : Executors.newCachedThreadPool(threads("webrtc-client-audio-send-" + runtime + "-")); this.clock = builder.clock; if (builder.eventExecutor != null) { @@ -599,6 +608,7 @@ private void shutdownPools() { framePool.shutdown(); timer.shutdownNow(); audioPacer.shutdownNow(); + audioSender.shutdown(); stopHttp(); if (ownsEventExecutor) { @@ -741,6 +751,8 @@ public static final class Builder { private ScheduledExecutorService audioPacer; + private ExecutorService audioSender; + private LongSupplier clock = System::nanoTime; @@ -943,7 +955,7 @@ Builder timer(ScheduledExecutorService timer) { } /** - * Replaces the thread that sends pushed audio, so that tests decide + * Replaces the thread that paces pushed audio, so that tests decide * when each chunk is due. The runtime shuts it down when it closes. */ Builder audioPacer(ScheduledExecutorService pacer) { @@ -951,6 +963,16 @@ Builder audioPacer(ScheduledExecutorService pacer) { return this; } + /** + * Replaces the threads that hand pushed audio to WebRTC, so that tests + * decide when each hand-over runs. The runtime shuts them down when + * it closes. + */ + Builder audioSender(ExecutorService sender) { + this.audioSender = requireNonNull(sender, "sender"); + return this; + } + /** * Replaces the clock of the load statistics, of the turns of the * executors and of the audio pacing, so that tests decide how much diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java index baecbcb2b..ce988292b 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java @@ -40,18 +40,37 @@ final class ManualExecutor extends AbstractExecutorService { private int running; + private boolean inline; + + + /** + * @return an executor that runs each task at once, on the thread that + * hands it over. + */ + static ManualExecutor inline() { + ManualExecutor executor = new ManualExecutor(); + executor.inline = true; + + return executor; + } @Override - public synchronized void execute(Runnable task) { - if (shutdown) { - throw new RejectedExecutionException("Shut down"); - } - if (rejecting) { - throw new RejectedExecutionException("Rejecting"); + public void execute(Runnable task) { + synchronized (this) { + if (shutdown) { + throw new RejectedExecutionException("Shut down"); + } + if (rejecting) { + throw new RejectedExecutionException("Rejecting"); + } + if (!inline) { + queue.add(task); + notifyAll(); + return; + } } - queue.add(task); - notifyAll(); + task.run(); } /** diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java index 7bf302f03..4cfb15b5f 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java @@ -97,6 +97,7 @@ void clearedAudioNotResent() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) + .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -139,6 +140,7 @@ void stalledAudioNotBurst() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) + .audioSender(ManualExecutor.inline()) .clock(now::get) .build(); List sent = new ArrayList<>(); @@ -182,6 +184,7 @@ void defaultQueueLimit() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) + .audioSender(ManualExecutor.inline()) .build(); try { @@ -207,6 +210,7 @@ void fullQueueRejectsPush() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) + .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -259,6 +263,7 @@ void fullQueueDropsOldest() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) + .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -311,6 +316,77 @@ void queueLimitBelowChunkRejected() { () -> voice.queueLimit(Duration.ofMillis(9), AudioOverflow.REJECT)); } + @Test + void slowPushLeavesOtherTracksFree() throws Exception { + // One track hangs in WebRTC. The pacer keeps its time, the other track + // goes on sending, and the hung one gets no second hand-over: it + // catches up on what is still due once it is back. + ManualTimer pacer = new ManualTimer(); + ManualExecutor sender = new ManualExecutor(); + AtomicLong now = new AtomicLong(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .audioPacer(pacer) + .audioSender(sender) + .clock(now::get) + .build(); + CountDownLatch pushing = new CountDownLatch(1); + CountDownLatch unblock = new CountDownLatch(1); + AtomicInteger slowSent = new AtomicInteger(); + List sent = new ArrayList<>(); + + try { + CustomAudioImpl slow = recordingAudio(runtime, data -> { + slowSent.incrementAndGet(); + pushing.countDown(); + + try { + // Bounded, so that a push on the pacer fails the test. + unblock.await(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + CustomAudioImpl other = recordingAudio(runtime, sent::add); + Duration tick = Duration.ofMillis(10); + PcmFormat format = PcmFormat.of(8000, 1); + + slow.push(new byte[480], format); + other.push(new byte[480], format); + + pacer.fire(tick); + assertEquals(2, sender.queued()); + + // The slow track ticked first, so its hand-over is the oldest. + Thread hung = new Thread(sender::runNext); + hung.start(); + assertTrue(pushing.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + sender.runAll(); + assertEquals(1, sent.size()); + + now.addAndGet(tick.toNanos()); + pacer.fire(tick); + + assertEquals(1, sender.queued()); + sender.runAll(); + assertEquals(2, sent.size()); + assertEquals(1, slowSent.get()); + + unblock.countDown(); + hung.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + + assertEquals(2, slowSent.get()); + assertEquals(10, slow.queuedMillis()); + } + finally { + unblock.countDown(); + runtime.close(); + } + } + @Test void slowPushLeavesTimerFree() throws Exception { // Pushed audio is sent on a thread of its own: a push that hangs in From 1e4a62b3d536427e2dd4c9b9f63f28e5bc512b7a Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 01:40:31 +0100 Subject: [PATCH 3/5] fix: drop frames in conversion when the JavaFX view is cleared A conversion runs outside the lock of clear() and could put the old picture back. A generation counter now tells the frames that came before the clear. --- .../webrtc/client/javafx/VideoView.java | 19 ++++- .../webrtc/client/javafx/VideoViewTest.java | 69 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java index d3fe63c6e..1de71a375 100644 --- a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java +++ b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java @@ -68,6 +68,9 @@ public class VideoView extends Region implements Consumer { private boolean scheduled; + /** Counts the calls of clear(), to tell the frames that came before one. */ + private long generation; + // Confined to the JavaFX Application Thread. private Pixels shown; @@ -99,6 +102,13 @@ public void accept(VideoFrame frame) { VideoFrameBuffer buffer = frame.buffer; int width = buffer.getWidth(); int height = buffer.getHeight(); + long started; + + // Before the wait for convertLock, as the frame came before any clear() + // that happens during it. + synchronized (lock) { + started = generation; + } synchronized (convertLock) { Pixels target = back; @@ -120,6 +130,10 @@ public void accept(VideoFrame frame) { target.rotation = frame.rotation; synchronized (lock) { + if (started != generation) { + return; + } + back = ready; ready = target; @@ -135,11 +149,12 @@ public void accept(VideoFrame frame) { } /** - * Removes the picture, leaving the background. Called on the JavaFX - * Application Thread. + * Removes the picture, leaving the background, and drops the frames still + * being converted. Called on the JavaFX Application Thread. */ public void clear() { synchronized (lock) { + generation++; ready = null; back = null; } diff --git a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java index 3e1a17f0f..41831bbdb 100644 --- a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java +++ b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java @@ -25,6 +25,7 @@ import java.nio.ByteBuffer; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -41,8 +42,10 @@ import dev.onvoid.webrtc.client.Signaling; import dev.onvoid.webrtc.client.SignalingPair; import dev.onvoid.webrtc.client.WebRtc; +import dev.onvoid.webrtc.media.video.I420Buffer; import dev.onvoid.webrtc.media.video.NativeI420Buffer; import dev.onvoid.webrtc.media.video.VideoFrame; +import dev.onvoid.webrtc.media.video.VideoFrameBuffer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -114,6 +117,72 @@ void showsFrame() throws Exception { assertNull(onFx(view::snapshot)); } + @Test + void clearDropsFrameInConversion() throws Exception { + VideoView view = onFx(VideoView::new); + CountDownLatch converting = new CountDownLatch(1); + CountDownLatch cleared = new CountDownLatch(1); + VideoFrame held = frame(64, 48, 128, 128); + VideoFrameBuffer buffer = new VideoFrameBuffer() { + + @Override + public int getWidth() { + return held.buffer.getWidth(); + } + + @Override + public int getHeight() { + return held.buffer.getHeight(); + } + + @Override + public I420Buffer toI420() { + converting.countDown(); + + try { + cleared.await(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + return held.buffer.toI420(); + } + + @Override + public VideoFrameBuffer cropAndScale(int cropX, int cropY, int cropWidth, int cropHeight, + int scaleWidth, int scaleHeight) { + throw new UnsupportedOperationException(); + } + + @Override + public void retain() { + } + + @Override + public void release() { + } + }; + Thread delivery = new Thread(() -> view.accept(new VideoFrame(buffer, 0))); + + delivery.start(); + assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + onFx(() -> { + view.clear(); + return null; + }); + cleared.countDown(); + delivery.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + + // Runs after whatever the conversion handed to the JavaFX thread. + assertNull(onFx(view::snapshot)); + + // The next frame shows as usual. + view.accept(frame(32, 24, 128, 128)); + assertEquals(32, (int) presented(view).getWidth()); + } + @Test void keepsAspectRatio() throws Exception { VideoView view = sized(200, 100); From 2bc65a06943dd9d06065296a687c1b5a2d5b7664 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 01:48:34 +0100 Subject: [PATCH 4/5] fix: end the voice activity of a custom audio track on close CustomAudioImpl.beforeRelease() skipped the one of LocalAudioImpl, so a change still queued reached its handler after the track closed. --- .../onvoid/webrtc/client/CustomAudioImpl.java | 2 ++ .../onvoid/webrtc/client/LocalAudioTests.java | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java index 10afebf8e..7f01a2222 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java @@ -200,6 +200,8 @@ void beforeRelease() { ticker = null; } } + + super.beforeRelease(); } /** Queues what is left of the previous format, filled with silence. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/LocalAudioTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/LocalAudioTests.java index 266861fbe..817c0f265 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/LocalAudioTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/LocalAudioTests.java @@ -138,6 +138,38 @@ void closingTrackEndsSubscriptions() throws Exception { assertTrue(changes.isEmpty()); } + @Test + void closingTrackDropsQueuedChange() throws Exception { + // A change still waiting for its event thread when the track closes + // stays unheard, as after closing the subscription. + ManualExecutor control = new ManualExecutor(); + ManualExecutor events = new ManualExecutor(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .controlPool(control) + .eventExecutor(events) + .build(); + BlockingQueue changes = new LinkedBlockingQueue<>(); + + try { + CustomAudio audio = runtime.media().customAudio("audio"); + + audio.onVoiceActivity(ONE_SEGMENT, changes::add); + audio.push(speech(48000, 1), PcmFormat.of(48000, 1)); + events.awaitQueued(10); + + audio.close(); + control.runAll(); + events.runAll(); + + assertTrue(changes.isEmpty()); + } + finally { + HttpSessionTests.closeStepping(runtime, control); + } + } + @Test void rejectsNull() { CustomAudio audio = rtc.media().customAudio("audio"); From 12e621c9486b0c7ce9d887305fa74c904032406c Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 02:01:12 +0100 Subject: [PATCH 5/5] revert: keep the custom audio pacing out of this change This reverts commit 7df95901. --- docs/guide/client-api.md | 2 +- .../onvoid/webrtc/client/CustomAudioImpl.java | 72 ++++-------------- .../java/dev/onvoid/webrtc/client/WebRtc.java | 28 +------ .../onvoid/webrtc/client/ManualExecutor.java | 35 ++------- .../dev/onvoid/webrtc/client/MediaTests.java | 76 ------------------- 5 files changed, 25 insertions(+), 188 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index f35bdbf8a..a60e5a93a 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -438,7 +438,7 @@ CustomAudio voice = media.customAudio("voice"); voice.push(pcm, PcmFormat.of(48000, 1)); ``` -`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it. One thread keeps the time for all tracks and does nothing else, while the audio goes into WebRTC on other threads, one at a time for each track, so a slow push into WebRTC delays only the audio of its own track, neither the other tracks nor the timeouts of the runtime. Should a track stall, as in a long garbage collection pause, it makes up for at most the last 50 ms instead of sending the whole pause at once; the queued audio then stays behind by the rest, until `clear()` drops it. +`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms from a thread of its own, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it. That thread does nothing else, so a slow push into WebRTC delays only the audio, not the timeouts of the runtime. Should it stall, as in a long garbage collection pause, it makes up for at most the last 50 ms instead of sending the whole pause at once; the queued audio then stays behind by the rest, until `clear()` drops it. A producer faster than real time would otherwise fill memory and push the delay up without end, so the queue holds at most 10 seconds, and a `push` beyond that fails with an `AudioQueueFullException`, keeping none of its audio. `queueLimit(max, overflow)` sets another limit and what happens beyond it: diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java index 7f01a2222..fe581c536 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java @@ -29,23 +29,21 @@ /** * An audio track fed with audio the application pushes. Pushed audio is cut - * into 10 ms chunks, of which one is due every 10 ms. The runtime's audio - * pacer only counts what is due, for all tracks, and a thread of the audio - * sender hands it to the source. At most one does so at a time for each track, - * as {@link CustomAudioSource} requires, so that a slow push holds up this - * track alone. + * into 10 ms chunks, which the runtime's audio pacer hands to the source one + * every 10 ms. Its thread is the only one that pushes into the source, as + * {@link CustomAudioSource} requires, and it runs no timeouts, which a slow + * push would hold up. */ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private static final long TICK_NANOS = TimeUnit.MILLISECONDS.toNanos(10); /** - * How late a tick may run and still send. Ticks keep coming at a fixed - * rate, so after a stall of the pacer or of this track's sending the - * missed ones run back to back: those up to this late are made up for, so - * that a short stall keeps the pace, and the earlier ones are skipped, so - * that a long one does not burst out all the audio of the pause at once. - * Skipped ticks leave the queue as it is. + * How late a tick may run and still send. The pacer runs at a fixed rate, + * so after a stall it runs the missed ticks back to back: those up to this + * late are made up for, so that a short stall keeps the pace, and the + * earlier ones are skipped, so that a long one does not burst out all the + * audio of the pause at once. Skipped ticks leave the queue as it is. */ private static final long MAX_LATE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); @@ -56,7 +54,7 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private final CustomAudioSource source; - // Confined to the sending turn, once the ticker is scheduled. + // Confined to the pacer, once the ticker is scheduled. /** When the first tick was due. */ private long start; @@ -82,12 +80,6 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private boolean stopped; - /** The ticks the pacer counted that no sending turn has taken yet. */ - private long dueTicks; - - /** True while a sending turn runs or waits for its thread. */ - private boolean sending; - CustomAudioImpl(LocalMediaImpl media, AudioTrack track, CustomAudioSource source) { super(media, track, source::dispose, false); @@ -235,51 +227,13 @@ private void dropOverflow() { } } - /** - * Counts a tick, on the pacer, which never waits for the source: a turn - * that is busy takes the tick along, however long it takes. - */ private void tick() { - synchronized (queue) { - dueTicks++; - - if (sending) { - return; - } - - sending = true; - } - - rtc.audioSender.execute(this::send); - } + long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS); - /** A sending turn: runs the ticks due, until none is left. */ - private void send() { - while (takeTick()) { - long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS); - - if (late <= MAX_LATE_NANOS) { - sendChunk(); - } - } - } - - /** - * @return true when a tick was due, false when the turn is over. - */ - private boolean takeTick() { - synchronized (queue) { - if (dueTicks == 0) { - sending = false; - return false; - } - - dueTicks--; - return true; + if (late > MAX_LATE_NANOS) { + return; } - } - private void sendChunk() { Chunk chunk; synchronized (queue) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java index fb6fa4c50..3d9aaa42f 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java @@ -106,18 +106,11 @@ public final class WebRtc implements AutoCloseable { final ScheduledExecutorService timer; /** - * The one thread that keeps the time of pushed audio for all tracks. It - * only counts the chunks due, and hands them to the {@link #audioSender}. + * The one thread that sends pushed audio, apart from the timer: a slow + * push must not delay the timeouts. */ final ScheduledExecutorService audioPacer; - /** - * The threads that hand pushed audio to WebRTC, at most one for each track - * at a time: a slow hand-over delays its own track, not the pacer, the - * other tracks or the timeouts. - */ - final ExecutorService audioSender; - /** The time in nanoseconds, as {@link System#nanoTime()}. */ final LongSupplier clock; @@ -200,8 +193,6 @@ private WebRtc(Builder builder) { : scheduler("webrtc-client-timer-" + runtime + "-"); this.audioPacer = builder.audioPacer != null ? builder.audioPacer : scheduler("webrtc-client-audio-" + runtime + "-"); - this.audioSender = builder.audioSender != null ? builder.audioSender - : Executors.newCachedThreadPool(threads("webrtc-client-audio-send-" + runtime + "-")); this.clock = builder.clock; if (builder.eventExecutor != null) { @@ -608,7 +599,6 @@ private void shutdownPools() { framePool.shutdown(); timer.shutdownNow(); audioPacer.shutdownNow(); - audioSender.shutdown(); stopHttp(); if (ownsEventExecutor) { @@ -751,8 +741,6 @@ public static final class Builder { private ScheduledExecutorService audioPacer; - private ExecutorService audioSender; - private LongSupplier clock = System::nanoTime; @@ -955,7 +943,7 @@ Builder timer(ScheduledExecutorService timer) { } /** - * Replaces the thread that paces pushed audio, so that tests decide + * Replaces the thread that sends pushed audio, so that tests decide * when each chunk is due. The runtime shuts it down when it closes. */ Builder audioPacer(ScheduledExecutorService pacer) { @@ -963,16 +951,6 @@ Builder audioPacer(ScheduledExecutorService pacer) { return this; } - /** - * Replaces the threads that hand pushed audio to WebRTC, so that tests - * decide when each hand-over runs. The runtime shuts them down when - * it closes. - */ - Builder audioSender(ExecutorService sender) { - this.audioSender = requireNonNull(sender, "sender"); - return this; - } - /** * Replaces the clock of the load statistics, of the turns of the * executors and of the audio pacing, so that tests decide how much diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java index ce988292b..baecbcb2b 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/ManualExecutor.java @@ -40,37 +40,18 @@ final class ManualExecutor extends AbstractExecutorService { private int running; - private boolean inline; - - - /** - * @return an executor that runs each task at once, on the thread that - * hands it over. - */ - static ManualExecutor inline() { - ManualExecutor executor = new ManualExecutor(); - executor.inline = true; - - return executor; - } @Override - public void execute(Runnable task) { - synchronized (this) { - if (shutdown) { - throw new RejectedExecutionException("Shut down"); - } - if (rejecting) { - throw new RejectedExecutionException("Rejecting"); - } - if (!inline) { - queue.add(task); - notifyAll(); - return; - } + public synchronized void execute(Runnable task) { + if (shutdown) { + throw new RejectedExecutionException("Shut down"); + } + if (rejecting) { + throw new RejectedExecutionException("Rejecting"); } - task.run(); + queue.add(task); + notifyAll(); } /** diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java index 4cfb15b5f..7bf302f03 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java @@ -97,7 +97,6 @@ void clearedAudioNotResent() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) - .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -140,7 +139,6 @@ void stalledAudioNotBurst() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) - .audioSender(ManualExecutor.inline()) .clock(now::get) .build(); List sent = new ArrayList<>(); @@ -184,7 +182,6 @@ void defaultQueueLimit() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) - .audioSender(ManualExecutor.inline()) .build(); try { @@ -210,7 +207,6 @@ void fullQueueRejectsPush() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) - .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -263,7 +259,6 @@ void fullQueueDropsOldest() throws Exception { .audio(AudioMode.HEADLESS) .errorHandler(errors::add) .audioPacer(pacer) - .audioSender(ManualExecutor.inline()) .build(); List sent = new ArrayList<>(); @@ -316,77 +311,6 @@ void queueLimitBelowChunkRejected() { () -> voice.queueLimit(Duration.ofMillis(9), AudioOverflow.REJECT)); } - @Test - void slowPushLeavesOtherTracksFree() throws Exception { - // One track hangs in WebRTC. The pacer keeps its time, the other track - // goes on sending, and the hung one gets no second hand-over: it - // catches up on what is still due once it is back. - ManualTimer pacer = new ManualTimer(); - ManualExecutor sender = new ManualExecutor(); - AtomicLong now = new AtomicLong(); - WebRtc runtime = WebRtc.builder() - .audio(AudioMode.HEADLESS) - .errorHandler(errors::add) - .audioPacer(pacer) - .audioSender(sender) - .clock(now::get) - .build(); - CountDownLatch pushing = new CountDownLatch(1); - CountDownLatch unblock = new CountDownLatch(1); - AtomicInteger slowSent = new AtomicInteger(); - List sent = new ArrayList<>(); - - try { - CustomAudioImpl slow = recordingAudio(runtime, data -> { - slowSent.incrementAndGet(); - pushing.countDown(); - - try { - // Bounded, so that a push on the pacer fails the test. - unblock.await(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - }); - CustomAudioImpl other = recordingAudio(runtime, sent::add); - Duration tick = Duration.ofMillis(10); - PcmFormat format = PcmFormat.of(8000, 1); - - slow.push(new byte[480], format); - other.push(new byte[480], format); - - pacer.fire(tick); - assertEquals(2, sender.queued()); - - // The slow track ticked first, so its hand-over is the oldest. - Thread hung = new Thread(sender::runNext); - hung.start(); - assertTrue(pushing.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); - - sender.runAll(); - assertEquals(1, sent.size()); - - now.addAndGet(tick.toNanos()); - pacer.fire(tick); - - assertEquals(1, sender.queued()); - sender.runAll(); - assertEquals(2, sent.size()); - assertEquals(1, slowSent.get()); - - unblock.countDown(); - hung.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); - - assertEquals(2, slowSent.get()); - assertEquals(10, slow.queuedMillis()); - } - finally { - unblock.countDown(); - runtime.close(); - } - } - @Test void slowPushLeavesTimerFree() throws Exception { // Pushed audio is sent on a thread of its own: a push that hangs in