Skip to content
Open
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
26 changes: 25 additions & 1 deletion docs/guide/data/data-channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/include/JNI_RTCDataChannel.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
186 changes: 170 additions & 16 deletions webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
*/
Expand All @@ -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.
Expand Down Expand Up @@ -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.
* <p>
* 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.
* <p>
* 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.
Expand Down Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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.
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
Loading
Loading