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
1 change: 1 addition & 0 deletions docs/guide/client-api-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,7 @@ public interface RemoteTrack {
RemoteVideo asVideo(); // IllegalStateException for audio
RemoteAudio asAudio();
CompletableFuture<Void> transform(RTCEncodedFrameTransformer transform);
CompletableFuture<Void> setJitterBufferTarget(Duration target); // 0 to 4 s, null for the default
boolean isMuted();
Subscription onMute(Consumer<Boolean> handler);
Subscription onEnded(Runnable handler);
Expand Down
13 changes: 13 additions & 0 deletions docs/guide/client/receiving-media.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@ Subscription speaking = microphone.onVoiceActivity(

Which audio is analyzed is described under [Details](#speech-detection).

## Smoother Playout

A remote track holds media in its jitter buffer for as short a time as the network allows. On a network with much jitter, this can make playout stutter. A jitter buffer target makes the track hold media longer, trading latency for smoother playout:

```java
track.setJitterBufferTarget(Duration.ofMillis(300));

// Back to the delay WebRTC chooses on its own.
track.setJitterBufferTarget(null);
```

The target goes from zero to four seconds. It is a hint: the delay never falls below what the network needs, and WebRTC may shorten it to keep audio and video in sync. The future fails once the track ended.

## Receiving Without Sending

A viewer that sends nothing asks for what it wants to receive, so that the offer includes it:
Expand Down
16 changes: 16 additions & 0 deletions docs/guide/core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,22 @@ public void onTrack(RTCRtpTransceiver transceiver) {

An observer belongs to the `RTCRtpReceiver` or `RTCRtpSender` object it was set through, and is removed when that object is disposed. `getId()` identifies a sender or receiver, and `RTCRtpSender.getStreams()` returns the stream IDs its track was added with.

### Trading Latency for Smooth Playout

A receiver holds media in its jitter buffer for as short a time as the network allows. On a network with much jitter, this can make playout stutter. Give the receiver a jitter buffer target to hold media longer:

```java
// Hold media at least 300 ms before it is played out.
receiver.setJitterBufferTarget(300.0);

// Return to the delay WebRTC chooses on its own.
receiver.setJitterBufferTarget(null);
```

The target is in milliseconds, from 0 to 4000. It is a hint: the delay never falls below what the network needs, and WebRTC may shorten it to keep audio and video in sync. The target belongs to the receiver, not to the `RTCRtpReceiver` object it was set through.

To see its effect, divide `jitterBufferTargetDelay` by `jitterBufferEmittedCount` in the receiver's `inbound-rtp` [statistics](/guide/monitoring/rtc-stats).

## Cleanup

Always properly dispose of resources when you're done:
Expand Down
8 changes: 8 additions & 0 deletions webrtc-jni/src/main/cpp/include/JNI_RTCRtpReceiver.h

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

17 changes: 17 additions & 0 deletions webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,23 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_requestKeyFrame
});
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_applyJitterBufferTarget
(JNIEnv * env, jobject caller, jdouble seconds)
{
jni::CallFromJava(env, [&]() {
jni::NativeLease<webrtc::RtpReceiverInterface> receiver(env, caller);
CHECK_HANDLE(receiver);

std::optional<double> delay;

if (seconds >= 0) {
delay = seconds;
}

receiver->SetJitterBufferMinimumDelay(delay);
});
}

JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getId
(JNIEnv * env, jobject caller)
{
Expand Down
44 changes: 44 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@
*/
public class RTCRtpReceiver extends DisposableNativeObject {

/**
* The largest jitter buffer target in milliseconds that {@link
* #setJitterBufferTarget(Double)} takes, as the WebRTC specification
* limits it.
*/
public static final double MAX_JITTER_BUFFER_TARGET = 4000;

/*
* The native observer set through this object, owned by it and freed when
* replaced, removed or disposed.
Expand Down Expand Up @@ -159,6 +166,38 @@ public void setTransform(RTCEncodedFrameTransformer transformer) {
*/
public native void requestKeyFrame();

/**
* Sets how long, in milliseconds, the jitter buffer of this receiver should
* hold media at least before it is played out, as {@code
* jitterBufferTarget} of the WebRTC specification does. A larger target
* trades latency for smoother playout on a network with much jitter; a
* target of 0 asks for as little delay as the network allows. {@code null}
* returns to the delay that WebRTC chooses on its own.
* <p>
* The target is a hint, not a guarantee: the delay the receiver ends up
* with is the larger one of the target and what the network needs, and
* WebRTC may cut it short to keep audio and video in sync. The {@code
* jitterBufferTargetDelay} of the receiver's {@code inbound-rtp}
* statistics shows its effect.
* <p>
* The target applies to the receiver, not to this object: it holds for
* every RTCRtpReceiver instance of the same receiver, and the last one
* set wins.
*
* @param target The target in milliseconds, from 0 to 4000, or {@code
* null} for the default.
*
* @throws IllegalArgumentException if the target is outside of that range.
*/
public void setJitterBufferTarget(Double target) {
if (target != null && !(target >= 0 && target <= MAX_JITTER_BUFFER_TARGET)) {
throw new IllegalArgumentException("The jitter buffer target must be from 0 to "
+ MAX_JITTER_BUFFER_TARGET + " ms, not " + target);
}

applyJitterBufferTarget(target != null ? target / 1000 : -1);
}

/**
* Releases the native reference held by this RTCRtpReceiver instance.
* <p>
Expand Down Expand Up @@ -200,4 +239,9 @@ public int hashCode() {

private native void applyTransform(RTCEncodedFrameTransformer transformer, boolean sealed);

/*
* Sets the minimum delay in seconds, or the default for a negative one.
*/
private native void applyJitterBufferTarget(double seconds);

}
19 changes: 19 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTrack.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package dev.onvoid.webrtc.client;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
Expand Down Expand Up @@ -91,6 +92,24 @@ default boolean isAudio() {
*/
CompletableFuture<Void> transform(RTCEncodedFrameTransformer transform);

/**
* Sets how long the jitter buffer of this track should hold media at
* least before it is played out. A longer target trades latency for
* smoother playout on a network with much jitter. The target is a hint:
* the delay never falls below what the network needs, and WebRTC may
* shorten it to keep audio and video in sync.
*
* @param target the target, from zero to four seconds, or null for the
* delay WebRTC chooses on its own.
*
* @return a future that completes once the target is set, and fails with
* an {@link IllegalStateException} once the track ended.
*
* @throws IllegalArgumentException if the target is negative or longer
* than four seconds.
*/
CompletableFuture<Void> setJitterBufferTarget(Duration target);

/**
* @return true when the remote peer sends no media on the track for now.
*/
Expand Down
22 changes: 22 additions & 0 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTrackImpl.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.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
Expand All @@ -37,6 +38,9 @@
*/
abstract class RemoteTrackImpl implements RemoteTrack {

private static final Duration MAX_JITTER_BUFFER_TARGET =
Duration.ofMillis((long) RTCRtpReceiver.MAX_JITTER_BUFFER_TARGET);

final PeerImpl peer;

private final RTCRtpReceiver receiver;
Expand Down Expand Up @@ -142,6 +146,24 @@ public CompletableFuture<Void> transform(RTCEncodedFrameTransformer transform) {
return onReceiver("Setting the transform", receiver -> receiver.setTransform(guarded));
}

@Override
public CompletableFuture<Void> setJitterBufferTarget(Duration target) {
Double millis = null;

if (target != null) {
if (target.isNegative() || target.compareTo(MAX_JITTER_BUFFER_TARGET) > 0) {
throw new IllegalArgumentException("The jitter buffer target must be from zero to "
+ MAX_JITTER_BUFFER_TARGET.getSeconds() + " seconds, got " + target);
}

millis = target.toNanos() / 1e6;
}

Double value = millis;

return onReceiver("Setting the jitter buffer target", receiver -> receiver.setJitterBufferTarget(value));
}

@Override
public String toString() {
return "RemoteTrack[" + kind + ", " + id + "]";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* 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.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;

/**
* Tests the jitter buffer target of a receiver.
*/
@Execution(ExecutionMode.SAME_THREAD)
class RTCRtpReceiverJitterBufferTests extends TestBase {

private static final long TIMEOUT_SECONDS = 15;

/** The frames to wait for before the delay is measured. */
private static final long FRAMES = 30;


@Test
void targetRaisesTargetDelay() throws Exception {
try (TestMediaCall call = new TestMediaCall(factory, true, false)) {
call.negotiate();

RTCRtpReceiver receiver = call.getReceiver("video");

try {
// Set before media flows, so that every frame counted has it.
receiver.setJitterBufferTarget(400.0);

call.awaitConnected();
call.startMedia();

Map<String, Object> stats = awaitEmittedFrames(call);

// Both are sums over the emitted frames. For video, WebRTC
// counts the target in the target delay; its minimum delay is
// what the jitter estimate asks for.
double emitted = number(stats, "jitterBufferEmittedCount");
double target = number(stats, "jitterBufferTargetDelay") / emitted;

assertTrue(target >= 0.3, "The target delay per frame is " + target + " s");
}
finally {
receiver.dispose();
}
}
}

@Test
void targetOutsideRangeIsRejected() throws Exception {
try (TestMediaCall call = new TestMediaCall(factory, true, false)) {
call.negotiate();

RTCRtpReceiver receiver = call.getReceiver("video");

try {
assertThrows(IllegalArgumentException.class, () -> receiver.setJitterBufferTarget(-1.0));
assertThrows(IllegalArgumentException.class, () -> receiver.setJitterBufferTarget(4000.5));
assertThrows(IllegalArgumentException.class, () -> receiver.setJitterBufferTarget(Double.NaN));

assertDoesNotThrow(() -> receiver.setJitterBufferTarget(0.0));
assertDoesNotThrow(() -> receiver.setJitterBufferTarget(RTCRtpReceiver.MAX_JITTER_BUFFER_TARGET));
assertDoesNotThrow(() -> receiver.setJitterBufferTarget(null));
}
finally {
receiver.dispose();
}
}
}

@Test
void disposedReceiverIsRejected() throws Exception {
try (TestMediaCall call = new TestMediaCall(factory, true, false)) {
call.negotiate();

RTCRtpReceiver receiver = call.getReceiver("video");
receiver.dispose();

assertThrows(IllegalStateException.class, () -> receiver.setJitterBufferTarget(100.0));
}
}

private static Map<String, Object> awaitEmittedFrames(TestMediaCall call) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS);

while (true) {
Map<String, Object> stats = call.getInboundVideoStats();

if (stats != null && stats.get("jitterBufferEmittedCount") != null
&& number(stats, "jitterBufferEmittedCount") >= FRAMES) {
return stats;
}
if (System.nanoTime() > deadline) {
fail("Fewer than " + FRAMES + " frames emitted: " + stats);
}

Thread.sleep(100);
}
}

private static double number(Map<String, Object> stats, String name) {
return ((Number) stats.get(name)).doubleValue();
}

}
Loading
Loading