From dcd9e66de9f92a0ca9cd3c562ed631553c55ef21 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 28 Oct 2026 23:40:01 +0100 Subject: [PATCH] feat: bound the queue of pushed audio CustomAudio holds at most 10 s by default. queueLimit sets the limit and whether a push beyond it is rejected or drops the oldest audio. --- design/client-api.md | 2 + docs/guide/client-api.md | 13 ++ .../onvoid/webrtc/client/AudioOverflow.java | 41 +++++ .../client/AudioQueueFullException.java | 40 +++++ .../dev/onvoid/webrtc/client/CustomAudio.java | 29 ++++ .../onvoid/webrtc/client/CustomAudioImpl.java | 67 +++++++- .../dev/onvoid/webrtc/client/MediaTests.java | 144 ++++++++++++++++++ 7 files changed, 333 insertions(+), 3 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/AudioOverflow.java create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/AudioQueueFullException.java diff --git a/design/client-api.md b/design/client-api.md index f47f348a2..b8c7222f8 100644 --- a/design/client-api.md +++ b/design/client-api.md @@ -463,6 +463,8 @@ public interface CustomVideo extends LocalVideo { public interface CustomAudio extends LocalAudio { void push(byte[] pcm, PcmFormat format); // any length, any thread + + void queueLimit(Duration max, AudioOverflow overflow); // 10 s, REJECT by default } ``` diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 6c2844e43..f0b7555ce 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -411,6 +411,18 @@ 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. +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: + +```java +// Live audio: stay at most 200 ms behind, dropping the oldest audio. +voice.queueLimit(Duration.ofMillis(200), AudioOverflow.DROP_OLDEST); + +// A file, which must arrive whole: refuse the push, to try it again later. +voice.queueLimit(Duration.ofSeconds(2), AudioOverflow.REJECT); +``` + +With `REJECT` a refused push can be pushed again once `queuedMillis()` has shrunk; with `DROP_OLDEST` every push is taken, and the audio sent lags at most the limit behind. + ### Controlling Senders and Tracks ```java @@ -716,6 +728,7 @@ Failures arrive as exceptions, thrown or as the cause of a failed future, all of | `NegotiationException` | A description or candidate was rejected, or two impolite peers collided. | | `PeerClosedException` | An operation was pending when its peer, channel or runtime closed, or came after that. | | `ChannelFullException` | A data channel already holds as many bytes waiting to be sent as its peer's `channelSendLimit` allows. | +| `AudioQueueFullException` | Pushed audio would take a `CustomAudio` queue beyond its `queueLimit`, with `AudioOverflow.REJECT`. | | `MediaException` | A device is missing, busy, refused access, or already open with other options. | | `ConfigurationException` | A call does not fit how the runtime was built, or WebRTC refused a configuration. | | `BlockingCallException` | A future was waited on from an event thread. | diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioOverflow.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioOverflow.java new file mode 100644 index 000000000..ab4c03b9e --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioOverflow.java @@ -0,0 +1,41 @@ +/* + * 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.time.Duration; + +/** + * What a {@link CustomAudio} does with audio pushed beyond its {@link + * CustomAudio#queueLimit(Duration, AudioOverflow) queue limit}. + */ +public enum AudioOverflow { + + /** + * Refuse the push with an {@link AudioQueueFullException}, keeping none of + * it, so that it can be pushed again once the queue shrank. Suits audio + * that must arrive whole, such as a file. + */ + REJECT, + + /** + * Take the push and drop the oldest queued audio to make room, so that + * what is sent stays at most the limit behind. Suits live audio, where + * late audio is worth less than lost audio. + */ + DROP_OLDEST + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioQueueFullException.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioQueueFullException.java new file mode 100644 index 000000000..3901e7c8c --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioQueueFullException.java @@ -0,0 +1,40 @@ +/* + * 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.time.Duration; + +/** + * Pushed audio was not queued, since it would take the queue of its {@link + * CustomAudio} beyond the limit that {@link CustomAudio#queueLimit(Duration, + * AudioOverflow)} set with {@link AudioOverflow#REJECT}. None of it was kept, + * so it can be pushed again once the queue shrank. + */ +public class AudioQueueFullException extends WebRtcException { + + private static final long serialVersionUID = 1L; + + /** + * Creates the exception with a message that says what went wrong. + * + * @param message the detail message. + */ + public AudioQueueFullException(String message) { + super(message); + } + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudio.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudio.java index d21e4fac5..e23566ca7 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudio.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudio.java @@ -16,6 +16,8 @@ package dev.onvoid.webrtc.client; +import java.time.Duration; + /** * An audio track fed with audio the application pushes, made by {@link * LocalMedia#customAudio(String)}. @@ -28,6 +30,12 @@ * makes up for at most the last 50 ms of the stall. The audio of the rest is * not sent faster but later, so what is queued then stays that much behind, * unless {@link #clear()} drops it. + *

+ * The queue holds at most 10 seconds by default, beyond which a push fails + * with an {@link AudioQueueFullException}, so that a producer faster than real + * time cannot fill memory and let the delay grow without end. {@link + * #queueLimit(Duration, AudioOverflow)} changes the limit and what happens + * beyond it. */ public interface CustomAudio extends LocalAudio { @@ -39,9 +47,30 @@ public interface CustomAudio extends LocalAudio { * @param format the sample rate and channel count. A format other than the * one before starts a new stream: audio still queued in the * old format is sent first. + * + * @throws AudioQueueFullException if the audio would take the queue beyond + * its limit and the overflow is {@link + * AudioOverflow#REJECT}. None of it is + * queued then. */ void push(byte[] pcm, PcmFormat format); + /** + * Limits how much audio the queue holds; 10 seconds with {@link + * AudioOverflow#REJECT} by default. The audio of a push that is shorter + * than 10 ms, or does not end on a 10 ms boundary, waits for the next push + * and does not count until it fills 10 ms. + *

+ * A limit lower than what is queued drops the oldest audio at once with + * {@link AudioOverflow#DROP_OLDEST}; with {@link AudioOverflow#REJECT} the + * queued audio is sent, and pushes fail until it drained below the limit. + * + * @param max the longest the queue may hold, at least 10 ms. It is + * rounded down to whole 10 ms. + * @param overflow what happens to audio pushed beyond the limit. + */ + void queueLimit(Duration max, AudioOverflow overflow); + /** * @return the audio queued and not sent yet, in milliseconds. */ 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 295150a88..fdb55d3da 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java @@ -18,6 +18,7 @@ import static java.util.Objects.requireNonNull; +import java.time.Duration; import java.util.ArrayDeque; import java.util.Arrays; import java.util.concurrent.ScheduledFuture; @@ -46,6 +47,11 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { */ private static final long MAX_LATE_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + private static final Duration CHUNK = Duration.ofNanos(TICK_NANOS); + + /** The queue limit by default, 10 seconds in chunks. */ + private static final int DEFAULT_MAX_CHUNKS = 1000; + private final CustomAudioSource source; // Confined to the pacer, once the ticker is scheduled. @@ -66,6 +72,10 @@ final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio { private int partialLength; + private int maxChunks = DEFAULT_MAX_CHUNKS; + + private AudioOverflow overflow = AudioOverflow.REJECT; + private ScheduledFuture ticker; private boolean stopped; @@ -94,7 +104,22 @@ public void push(byte[] pcm, PcmFormat pcmFormat) { return; } - if (!pcmFormat.equals(format)) { + boolean newFormat = !pcmFormat.equals(format); + + if (overflow == AudioOverflow.REJECT) { + // Checked before anything is queued, so that a refused push + // leaves no part of itself behind. + long added = newFormat + ? (partialLength > 0 ? 1 : 0) + pcm.length / pcmFormat.bytesPer10Ms() + : (partialLength + (long) pcm.length) / format.bytesPer10Ms(); + + if (queue.size() + added > maxChunks) { + throw new AudioQueueFullException("The queue holds " + queue.size() * 10L + " ms, and the " + + "audio would add " + added * 10 + " ms, beyond the limit of " + maxChunks * 10L + " ms"); + } + } + + if (newFormat) { flushPartial(); format = pcmFormat; partial = new byte[pcmFormat.bytesPer10Ms()]; @@ -111,7 +136,7 @@ public void push(byte[] pcm, PcmFormat pcmFormat) { offset += count; if (partialLength == partial.length) { - queue.add(new Chunk(partial, format)); + enqueue(new Chunk(partial, format)); partial = new byte[format.bytesPer10Ms()]; partialLength = 0; } @@ -124,6 +149,23 @@ public void push(byte[] pcm, PcmFormat pcmFormat) { } } + @Override + public void queueLimit(Duration max, AudioOverflow overflow) { + requireNonNull(max, "max"); + requireNonNull(overflow, "overflow"); + + if (max.compareTo(CHUNK) < 0) { + throw new IllegalArgumentException("The limit must be at least 10 ms, got " + max); + } + + synchronized (queue) { + this.maxChunks = (int) Math.min(max.dividedBy(CHUNK), Integer.MAX_VALUE); + this.overflow = overflow; + + dropOverflow(); + } + } + @Override public long queuedMillis() { synchronized (queue) { @@ -157,13 +199,32 @@ private void flushPartial() { if (partialLength > 0) { // What lies beyond may be audio that clear() dropped. Arrays.fill(partial, partialLength, partial.length, (byte) 0); - queue.add(new Chunk(partial, format)); + enqueue(new Chunk(partial, format)); } partial = null; partialLength = 0; } + /** + * Queues a chunk. With {@link AudioOverflow#DROP_OLDEST} the queue is kept + * within its limit chunk by chunk, so that even a long push holds no more + * than that; {@link AudioOverflow#REJECT} has checked the push before. + */ + private void enqueue(Chunk chunk) { + queue.add(chunk); + + dropOverflow(); + } + + private void dropOverflow() { + if (overflow == AudioOverflow.DROP_OLDEST) { + while (queue.size() > maxChunks) { + queue.poll(); + } + } + } + private void tick() { long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS); 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 6485cb3b8..44eeaec20 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java @@ -175,6 +175,142 @@ void stalledAudioNotBurst() throws Exception { } } + @Test + void defaultQueueLimit() throws Exception { + ManualTimer pacer = new ManualTimer(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .audioPacer(pacer) + .build(); + + try { + CustomAudioImpl voice = recordingAudio(runtime, data -> { }); + PcmFormat format = PcmFormat.of(8000, 1); + + // Ten seconds fit, not a chunk more. + voice.push(new byte[160000], format); + assertThrows(AudioQueueFullException.class, () -> voice.push(new byte[160], format)); + assertEquals(10000, voice.queuedMillis()); + } + finally { + runtime.close(); + } + } + + @Test + void fullQueueRejectsPush() throws Exception { + // A refused push leaves nothing of itself behind, not even in the + // chunk begun before it. + ManualTimer pacer = new ManualTimer(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .audioPacer(pacer) + .build(); + List sent = new ArrayList<>(); + + try { + CustomAudioImpl voice = recordingAudio(runtime, sent::add); + Duration tick = Duration.ofMillis(10); + + // 160 bytes in 10 ms. + PcmFormat format = PcmFormat.of(8000, 1); + voice.queueLimit(Duration.ofMillis(50), AudioOverflow.REJECT); + + // 45 ms, 5 of them begin a chunk. + voice.push(filled(720, 1), format); + voice.push(filled(160, 1), format); + assertEquals(50, voice.queuedMillis()); + + // Would complete the begun chunk. + assertThrows(AudioQueueFullException.class, () -> voice.push(filled(80, 9), format)); + // So would a new format, which sends the begun chunk. + assertThrows(AudioQueueFullException.class, () -> voice.push(new byte[2], PcmFormat.of(16000, 1))); + assertEquals(50, voice.queuedMillis()); + + pacer.fire(tick); + voice.push(filled(80, 2), format); + assertEquals(50, voice.queuedMillis()); + + for (int i = 0; i < 5; i++) { + pacer.fire(tick); + } + + assertEquals(6, sent.size()); + + for (byte[] chunk : sent) { + for (byte b : chunk) { + assertTrue(b == 1 || b == 2); + } + } + + assertEquals(2, sent.get(5)[159]); + } + finally { + runtime.close(); + } + } + + @Test + void fullQueueDropsOldest() throws Exception { + ManualTimer pacer = new ManualTimer(); + WebRtc runtime = WebRtc.builder() + .audio(AudioMode.HEADLESS) + .errorHandler(errors::add) + .audioPacer(pacer) + .build(); + List sent = new ArrayList<>(); + + try { + CustomAudioImpl voice = recordingAudio(runtime, sent::add); + Duration tick = Duration.ofMillis(10); + PcmFormat format = PcmFormat.of(8000, 1); + voice.queueLimit(Duration.ofMillis(39), AudioOverflow.DROP_OLDEST); + + // Five chunks, of which the limit, rounded down to 30 ms, keeps + // the newest three. + for (int i = 1; i <= 5; i++) { + voice.push(filled(160, i), format); + } + + assertEquals(30, voice.queuedMillis()); + + // A push longer than the limit keeps its own end. + byte[] burst = new byte[800]; + + for (int i = 0; i < 5; i++) { + Arrays.fill(burst, i * 160, (i + 1) * 160, (byte) (6 + i)); + } + + voice.push(burst, format); + assertEquals(30, voice.queuedMillis()); + + // A lower limit drops at once. + voice.queueLimit(Duration.ofMillis(20), AudioOverflow.DROP_OLDEST); + assertEquals(20, voice.queuedMillis()); + + for (int i = 0; i < 3; i++) { + pacer.fire(tick); + } + + assertEquals(2, sent.size()); + assertEquals(9, sent.get(0)[0]); + assertEquals(10, sent.get(1)[0]); + } + finally { + runtime.close(); + } + } + + @Test + void queueLimitBelowChunkRejected() { + CustomAudio voice = rtc.media().customAudio("voice"); + + assertThrows(IllegalArgumentException.class, + () -> voice.queueLimit(Duration.ofMillis(9), AudioOverflow.REJECT)); + } + @Test void slowPushLeavesTimerFree() throws Exception { // Pushed audio is sent on a thread of its own: a push that hangs in @@ -518,6 +654,14 @@ private void feedVideo(CustomVideo video, int width, int height) { }, 0, 33, TimeUnit.MILLISECONDS); } + /** PCM of the given length with every byte set to the value. */ + private static byte[] filled(int length, int value) { + byte[] pcm = new byte[length]; + Arrays.fill(pcm, (byte) value); + + return pcm; + } + private static byte[] tone(int sampleRate, int channels, int millis) { int frames = sampleRate * millis / 1000; byte[] pcm = new byte[frames * channels * 2];