From 4544423be01884f5ce7bc973f990e3b23db53588 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 26 Nov 2026 00:21:43 +0100 Subject: [PATCH] feat: tell data channel observers when the buffered amount is low --- docs/guide/data/data-channels.md | 26 ++- .../src/main/cpp/include/JNI_RTCDataChannel.h | 4 +- .../src/main/cpp/src/JNI_RTCDataChannel.cpp | 2 +- .../dev/onvoid/webrtc/RTCDataChannel.java | 186 ++++++++++++++-- .../onvoid/webrtc/RTCDataChannelObserver.java | 9 + .../RTCDataChannelBufferedAmountLowTests.java | 203 ++++++++++++++++++ .../onvoid/webrtc/TestDataChannelPair.java | 8 + 7 files changed, 418 insertions(+), 20 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/RTCDataChannelBufferedAmountLowTests.java diff --git a/docs/guide/data/data-channels.md b/docs/guide/data/data-channels.md index 26598fca5..e9855723b 100644 --- a/docs/guide/data/data-channels.md +++ b/docs/guide/data/data-channels.md @@ -209,6 +209,30 @@ The observer is called exactly once, with a failure if the operation is discarde Callbacks run on a native callback thread shared with other WebRTC observers. They may call other WebRTC methods, but should not block, so dispatch long work to an executor of your own. Without an observer, `sendAsync` logs failures and reports nothing to the caller. +### Sending More When the Buffer Drains + +A sender of a large amount of data should not queue all of it at once. It keeps the buffer between two marks instead: it pauses above a high mark of its own, and resumes once the buffered amount falls to a low threshold. `setBufferedAmountLowThreshold` sets that threshold, and `onBufferedAmountLow` tells the observer when the buffered amount falls to it: + +```java +long highMark = 1024 * 1024; + +dataChannel.setBufferedAmountLowThreshold(256 * 1024); + +dataChannel.registerObserver(new RTCDataChannelObserver() { + @Override + public void onBufferedAmountLow() { + // Room again: send until the high mark is reached. + executor.execute(() -> sendWhileBelow(highMark)); + } + + // onBufferedAmountChange, onStateChange and onMessage as above. +}); +``` + +The event comes once each time the buffered amount falls from above the threshold to the threshold or below. The threshold is 0 until set, so by default the event tells when the buffer is empty. + +WebRTC reports the buffered amount in steps of about 100 KiB, not for every message. The event may therefore come only once the amount has fallen somewhat below the threshold. A message sent with `sendAsync` before the channel is open is refused and not counted. + ### Receiving Data To receive data, implement the `onMessage` method in your `RTCDataChannelObserver`: @@ -306,7 +330,7 @@ Unlike other disposable objects, a data channel is not disposed by `close()`, wh 1. **Error Handling**: Always wrap `send` calls in try-catch blocks as they can throw exceptions if the buffer is full or the channel is not in the `OPEN` state. -2. **Buffer Management**: Monitor the buffered amount to avoid overwhelming the channel. If `getBufferedAmount()` returns a large value, consider pausing sending until it decreases. +2. **Buffer Management**: Monitor the buffered amount to avoid overwhelming the channel. If `getBufferedAmount()` returns a large value, pause sending until [`onBufferedAmountLow`](#sending-more-when-the-buffer-drains) tells you it has room again. 3. **Copy Received Data**: Remember that the data in the `RTCDataChannelBuffer` will be freed after the `onMessage` method returns. If you need to process the data asynchronously, make a copy of it. diff --git a/webrtc-jni/src/main/cpp/include/JNI_RTCDataChannel.h b/webrtc-jni/src/main/cpp/include/JNI_RTCDataChannel.h index 9adc51368..4382d6371 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_RTCDataChannel.h +++ b/webrtc-jni/src/main/cpp/include/JNI_RTCDataChannel.h @@ -9,10 +9,10 @@ extern "C" { #endif /* * Class: dev_onvoid_webrtc_RTCDataChannel - * Method: registerObserver + * Method: registerNativeObserver * Signature: (Ldev/onvoid/webrtc/RTCDataChannelObserver;)V */ - JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerObserver + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerNativeObserver (JNIEnv *, jobject, jobject); /* diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp index 57f71ba6e..823ae0ecf 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp @@ -51,7 +51,7 @@ namespace } } -JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerObserver +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_registerNativeObserver (JNIEnv * env, jobject caller, jobject jObserver) { try { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java index 143f18cd3..e803fe8cf 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java @@ -20,6 +20,7 @@ import java.nio.ByteBuffer; import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; /** * Represents a bidirectional data channel between two peers. An RTCDataChannel @@ -39,6 +40,20 @@ public class RTCDataChannel extends DisposableNativeObject { @SuppressWarnings("unused") private long observerHandle; + /** + * The threshold at which the buffered amount counts as low. + */ + private volatile long bufferedAmountLowThreshold; + + /** + * The buffered amount as the events of the channel tell it: raised by + * every message sent through this object, lowered by every decrease the + * observer hears of. Unlike the native value, read at once on the + * observer's thread, it is the amount at the time of each event. + */ + private final AtomicLong bufferedAmountTold = new AtomicLong(); + + /** * Used by the native api. */ @@ -58,7 +73,9 @@ private RTCDataChannel() { * * @param observer The new data channel observer. */ - public native void registerObserver(RTCDataChannelObserver observer); + public void registerObserver(RTCDataChannelObserver observer) { + registerNativeObserver(observer != null ? new ThresholdObserver(observer) : null); + } /** * Unregister the last set RTCDataChannelObserver. @@ -162,6 +179,45 @@ private RTCDataChannel() { */ public native long getBufferedAmount(); + /** + * Sets the threshold at which the buffered amount counts as low. Once + * the buffered amount falls from above the threshold to the threshold or + * below, the observer is told through {@link + * RTCDataChannelObserver#onBufferedAmountLow()}. A sender that keeps the + * buffer filled between the threshold and a high mark of its own uses + * this to send more as soon as the channel has room. + *

+ * WebRTC reports the buffered amount in steps rather than for every + * message sent, as it does for {@link + * RTCDataChannelObserver#onBufferedAmountChange(long)}. The observer may + * therefore hear of the low buffered amount only once it has fallen + * somewhat further. It always hears of it when the buffer is empty. + *

+ * The threshold belongs to this object and is 0 until it is set. + * + * @param threshold The threshold in bytes. + * + * @throws IllegalArgumentException if the threshold is negative. + */ + public void setBufferedAmountLowThreshold(long threshold) { + if (threshold < 0) { + throw new IllegalArgumentException("The threshold must not be negative, got " + threshold); + } + + bufferedAmountLowThreshold = threshold; + } + + /** + * Returns the threshold at which the buffered amount counts as low. + * + * @return The threshold in bytes, 0 unless set. + * + * @see #setBufferedAmountLowThreshold(long) + */ + public long getBufferedAmountLowThreshold() { + return bufferedAmountLowThreshold; + } + /** * Closes this RTCDataChannel. It may be called regardless of whether the * RTCDataChannel was created by this peer or the remote peer. @@ -189,17 +245,27 @@ private RTCDataChannel() { */ public void send(RTCDataChannelBuffer buffer) throws Exception { ByteBuffer data = buffer.data; - - if (data.isDirect()) { - if (data.position() == 0 && data.limit() == data.capacity()) { - sendDirectBuffer(data, buffer.binary); + long size = data.remaining(); + + // Counted before WebRTC queues it, so that no decrease comes first. + bufferedAmountTold.addAndGet(size); + + try { + if (data.isDirect()) { + if (data.position() == 0 && data.limit() == data.capacity()) { + sendDirectBuffer(data, buffer.binary); + } + else { + sendDirectBuffer(data.slice(), buffer.binary); + } } else { - sendDirectBuffer(data.slice(), buffer.binary); + sendByteArrayBuffer(copyWindow(data), buffer.binary); } } - else { - sendByteArrayBuffer(copyWindow(data), buffer.binary); + catch (Throwable e) { + bufferedAmountTold.addAndGet(-size); + throw e; } } @@ -241,12 +307,19 @@ static byte[] copyWindow(ByteBuffer data) { */ public void sendAsync(RTCDataChannelBuffer buffer) { ByteBuffer data = buffer.data; + long size = countAsync(data.remaining()); - if (data.isDirect()) { - sendDirectBufferAsync(data, data.position(), data.remaining(), buffer.binary); + try { + if (data.isDirect()) { + sendDirectBufferAsync(data, data.position(), data.remaining(), buffer.binary); + } + else { + sendByteArrayBufferAsync(copyWindow(data), buffer.binary); + } } - else { - sendByteArrayBufferAsync(copyWindow(data), buffer.binary); + catch (Throwable e) { + bufferedAmountTold.addAndGet(-size); + throw e; } } @@ -279,18 +352,99 @@ public void sendAsync(RTCDataChannelBuffer buffer) { public void sendAsync(RTCDataChannelBuffer buffer, RTCDataChannelSendObserver observer) { Objects.requireNonNull(observer, "observer"); ByteBuffer data = Objects.requireNonNull(buffer.data, "buffer.data"); - if (data.isDirect()) { - sendDirectBufferAsyncWithObserver(data, data.position(), data.remaining(), buffer.binary, observer); + long size = countAsync(data.remaining()); + + try { + if (data.isDirect()) { + sendDirectBufferAsyncWithObserver(data, data.position(), data.remaining(), buffer.binary, observer); + } + else { + sendByteArrayBufferAsyncWithObserver(copyWindow(data), buffer.binary, observer); + } } - else { - sendByteArrayBufferAsyncWithObserver(copyWindow(data), buffer.binary, observer); + catch (Throwable e) { + bufferedAmountTold.addAndGet(-size); + throw e; } } + /** + * Counts a message sent asynchronously, which WebRTC queues only while the + * channel is open. One it refuses otherwise is never taken off again. A + * channel that closes meanwhile has no more decreases to tell. + * + * @return The bytes counted. + */ + private long countAsync(long size) { + try { + if (getState() != RTCDataChannelState.OPEN) { + return 0; + } + } + catch (IllegalStateException e) { + // Disposed, which the send itself reports. + return 0; + } + + bufferedAmountTold.addAndGet(size); + + return size; + } + private native void sendDirectBufferAsyncWithObserver(ByteBuffer buffer, int position, int length, boolean binary, RTCDataChannelSendObserver observer); private native void sendByteArrayBufferAsyncWithObserver(byte[] buffer, boolean binary, RTCDataChannelSendObserver observer); + private native void registerNativeObserver(RTCDataChannelObserver observer); + + + /** + * Hands the events of the channel to the observer of the application, + * and tells it when the buffered amount falls to the threshold. It goes + * by the amount the events tell, as browsers do: the native one has + * often fallen further by the time an event reaches this thread, which + * would hide where the event crossed the threshold. + */ + private final class ThresholdObserver implements RTCDataChannelObserver { + + private final RTCDataChannelObserver observer; + + + ThresholdObserver(RTCDataChannelObserver observer) { + this.observer = observer; + } + + @Override + public void onBufferedAmountChange(long sentDataSize) { + // Never below zero, e.g. for a message counted as refused that + // WebRTC took after all. + long after = bufferedAmountTold.accumulateAndGet(sentDataSize, (told, sent) -> Math.max(0, told - sent)); + long before = after + sentDataSize; + long threshold = bufferedAmountLowThreshold; + + observer.onBufferedAmountChange(sentDataSize); + + if (before > threshold && after <= threshold) { + observer.onBufferedAmountLow(); + } + } + + @Override + public void onStateChange() { + observer.onStateChange(); + } + + @Override + public void onMessage(RTCDataChannelBuffer buffer) { + observer.onMessage(buffer); + } + + @Override + public void onBufferedAmountLow() { + // Called only by this class itself. + } + } + } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannelObserver.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannelObserver.java index 30e85fd11..f7ddecc2b 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannelObserver.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannelObserver.java @@ -32,6 +32,15 @@ public interface RTCDataChannelObserver { */ void onBufferedAmountChange(long sentDataSize); + /** + * The RTCDataChannel's buffered amount has fallen from above its {@link + * RTCDataChannel#setBufferedAmountLowThreshold(long) threshold} to the + * threshold or below. Called on the same thread as {@link + * #onBufferedAmountChange(long)}, right after it. + */ + default void onBufferedAmountLow() { + } + /** * The RTCDataChannel's state has changed. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCDataChannelBufferedAmountLowTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCDataChannelBufferedAmountLowTests.java new file mode 100644 index 000000000..54784249f --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCDataChannelBufferedAmountLowTests.java @@ -0,0 +1,203 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * Tests the threshold at which the buffered amount of a data channel counts + * as low, and the event that tells of it. + */ +@Execution(ExecutionMode.SAME_THREAD) +class RTCDataChannelBufferedAmountLowTests extends TestBase { + + private static final int MESSAGE_SIZE = 64 * 1024; + + + @Test + void thresholdDefaultsToZero() throws Exception { + try (TestDataChannelPair pair = new TestDataChannelPair(factory)) { + assertEquals(0, pair.sender.getBufferedAmountLowThreshold()); + + pair.sender.setBufferedAmountLowThreshold(1024); + assertEquals(1024, pair.sender.getBufferedAmountLowThreshold()); + + assertThrows(IllegalArgumentException.class, () -> pair.sender.setBufferedAmountLowThreshold(-1)); + assertEquals(1024, pair.sender.getBufferedAmountLowThreshold()); + } + } + + @Test + void lowOnceEmpty() throws Exception { + try (TestDataChannelPair pair = new TestDataChannelPair(factory)) { + pair.connect(); + + Drain drain = new Drain(pair.sender); + pair.sender.registerObserver(drain); + + send(pair.sender, 4); + drain.await(4L * MESSAGE_SIZE); + // The low comes right after the decrease that emptied the buffer. + pair.awaitSenderEvents(); + + assertEquals(List.of(0L), drain.lows); + } + } + + @Test + void lowAtThreshold() throws Exception { + long threshold = 512 * 1024; + + try (TestDataChannelPair pair = new TestDataChannelPair(factory)) { + pair.connect(); + + Drain drain = new Drain(pair.sender); + pair.sender.setBufferedAmountLowThreshold(threshold); + pair.sender.registerObserver(drain); + + // 2 MiB, far above the threshold. + send(pair.sender, 32); + drain.await(32L * MESSAGE_SIZE); + pair.awaitSenderEvents(); + + // Falling through the threshold once, whatever steps it fell in. + assertEquals(1, drain.lows.size(), "lows: " + drain.lows); + assertTrue(drain.lows.get(0) <= threshold, "low at " + drain.lows.get(0)); + } + } + + @Test + void asyncSendsCounted() throws Exception { + long threshold = 512 * 1024; + + try (TestDataChannelPair pair = new TestDataChannelPair(factory)) { + // Refused before the channel is open, so never counted. + pair.sender.sendAsync(new RTCDataChannelBuffer(ByteBuffer.wrap(new byte[MESSAGE_SIZE]), true)); + + pair.connect(); + + Drain drain = new Drain(pair.sender); + pair.sender.setBufferedAmountLowThreshold(threshold); + pair.sender.registerObserver(drain); + + CountDownLatch completed = new CountDownLatch(32); + + for (int i = 0; i < 32; i++) { + pair.sender.sendAsync(new RTCDataChannelBuffer(ByteBuffer.wrap(new byte[MESSAGE_SIZE]), true), + new RTCDataChannelSendObserver() { + @Override + public void onSuccess() { + completed.countDown(); + } + + @Override + public void onFailure(String error) { } + }); + } + + drain.await(32L * MESSAGE_SIZE); + pair.awaitSenderEvents(); + + assertTrue(completed.await(5, TimeUnit.SECONDS), "sends failed"); + assertEquals(1, drain.lows.size(), "lows: " + drain.lows); + } + } + + @Test + void notLowWhenNeverAbove() throws Exception { + try (TestDataChannelPair pair = new TestDataChannelPair(factory)) { + pair.connect(); + + Drain drain = new Drain(pair.sender); + pair.sender.setBufferedAmountLowThreshold(16L * MESSAGE_SIZE); + pair.sender.registerObserver(drain); + + send(pair.sender, 4); + drain.await(4L * MESSAGE_SIZE); + pair.awaitSenderEvents(); + + assertTrue(drain.lows.isEmpty(), "lows: " + drain.lows); + } + } + + private static void send(RTCDataChannel channel, int messages) throws Exception { + for (int i = 0; i < messages; i++) { + channel.send(new RTCDataChannelBuffer(ByteBuffer.wrap(new byte[MESSAGE_SIZE]), true)); + } + } + + + /** + * Counts what has drained, and records the buffered amount at each low. + */ + private static class Drain implements RTCDataChannelObserver { + + final List lows = new CopyOnWriteArrayList<>(); + + private final RTCDataChannel channel; + private final AtomicLong drained = new AtomicLong(); + private final CountDownLatch empty = new CountDownLatch(1); + private volatile long expected = Long.MAX_VALUE; + + + Drain(RTCDataChannel channel) { + this.channel = channel; + } + + void await(long bytes) throws InterruptedException { + expected = bytes; + + if (drained.get() >= bytes) { + empty.countDown(); + } + + assertTrue(empty.await(10, TimeUnit.SECONDS), "drained " + drained.get() + " of " + bytes + " bytes"); + } + + @Override + public void onBufferedAmountChange(long sentDataSize) { + if (drained.addAndGet(sentDataSize) >= expected) { + empty.countDown(); + } + } + + @Override + public void onBufferedAmountLow() { + lows.add(channel.getBufferedAmount()); + } + + @Override + public void onStateChange() { } + + @Override + public void onMessage(RTCDataChannelBuffer buffer) { } + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/TestDataChannelPair.java b/webrtc/src/test/java/dev/onvoid/webrtc/TestDataChannelPair.java index c5afa1e00..4655eb1b5 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/TestDataChannelPair.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/TestDataChannelPair.java @@ -51,6 +51,14 @@ void connect() throws Exception { assertTrue(open.await(5, TimeUnit.SECONDS), "Data channels did not open"); } + /** + * Returns once the sender's signaling thread has run what it was given + * before, such as the observer calls of an event. + */ + void awaitSenderEvents() { + caller.getSignalingState(); + } + private static void setDescription(RTCPeerConnection peer, RTCSessionDescription description, boolean local) throws Exception { TestSetDescObserver observer = new TestSetDescObserver();