Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions design/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
```

Expand Down
13 changes: 13 additions & 0 deletions docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. |
Expand Down
41 changes: 41 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/AudioOverflow.java
Original file line number Diff line number Diff line change
@@ -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

}
Original file line number Diff line number Diff line change
@@ -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);
}

}
29 changes: 29 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudio.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)}.
Expand All @@ -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.
* <p>
* 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 {

Expand All @@ -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.
* <p>
* 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.
*/
Expand Down
67 changes: 64 additions & 3 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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()];
Expand All @@ -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;
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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);

Expand Down
Loading
Loading