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: 1 addition & 1 deletion docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ Peer peer = rtc.createPeer(PeerOptions.builder()
.build());
```

The peer sets the send transform on each sender as its track is added, before negotiation, so no frame leaves without it and the encoder needs no restart. It sets the receive transform on each receiver before `onTrack` hands out the track, so the transform is in place before the first frame arrives. The builders of [WHIP and WHEP](#whip-and-whep) take them too, `Whip`'s as `sendTransform(...)`, `Whep`'s as `receiveTransform(...)`.
The peer sets the send transform on each sender as its track is added, before negotiation, so no frame leaves without it and the encoder needs no restart. It sets the receive transform on each receiver before `onTrack` hands out the track, so the transform is in place before the first frame arrives. If installing the receive transform fails, the peer stops that track's transceiver and reports the failure through `onError`; the track is neither listed in `remoteTracks()` nor delivered through `onTrack`. If the receive path cannot be stopped, the peer closes. The builders of [WHIP and WHEP](#whip-and-whep) take them too, `Whip`'s as `sendTransform(...)`, `Whep`'s as `receiveTransform(...)`.

A single sender or remote track takes a transform of its own, in place of the peer's, and `null` removes it:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,9 @@ public Builder sendTransform(RTCEncodedFrameTransformer transform) {
* end-to-end encryption needs. It is set on each receiver before
* {@link Peer#onTrack} hands its track out, so it is in place before
* the first frame arrives. {@link RemoteTrack#transform} replaces it
* for one track.
* for one track. If installation fails, the transceiver is stopped,
* the track is not published, and the failure reaches {@code onError}.
* If the receive path cannot be stopped, the peer closes.
* <p>
* The transform runs on a thread of each receiver, not on the peer's
* event thread; see {@link RTCEncodedFrameTransformer}. A frame it
Expand Down
58 changes: 57 additions & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTracks.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import dev.onvoid.webrtc.RTCEncodedFrameTransformer;
import dev.onvoid.webrtc.RTCRtpReceiver;
import dev.onvoid.webrtc.RTCRtpTransceiver;
import dev.onvoid.webrtc.media.MediaStream;
import dev.onvoid.webrtc.media.MediaStreamTrack;
import dev.onvoid.webrtc.media.audio.AudioTrack;
Expand All @@ -50,6 +52,8 @@ final class RemoteTracks {
/** Set on each track before the application hears of it, or null. */
private final RTCEncodedFrameTransformer transform;

private final BiConsumer<RTCRtpReceiver, RTCEncodedFrameTransformer> installTransform;

private final CopyOnWriteArrayList<RemoteTrackImpl> tracks = new CopyOnWriteArrayList<>();

// Confined to the control executor.
Expand All @@ -70,7 +74,14 @@ final class RemoteTracks {


RemoteTracks(PeerImpl peer, RTCEncodedFrameTransformer transform) {
this(peer, transform, RTCRtpReceiver::setTransform);
}

/** Allows a test to fail installation before the native receiver takes the transform. */
RemoteTracks(PeerImpl peer, RTCEncodedFrameTransformer transform,
BiConsumer<RTCRtpReceiver, RTCEncodedFrameTransformer> installTransform) {
this.peer = peer;
this.installTransform = installTransform;
this.transform = transform;
this.handlers = new Handlers<>(peer.rtc::reportError);
}
Expand Down Expand Up @@ -139,11 +150,29 @@ void added(RTCRtpReceiver receiver, MediaStream[] streams) {
try {
// Before the application hears of the track, and so before
// its first frame arrives.
receiver.setTransform(peer.guard(transform, owner));
installTransform.accept(receiver, peer.guard(transform, owner));
}
catch (Throwable e) {
try {
stopReceiver(receiver);
}
catch (Throwable stopError) {
e.addSuppressed(stopError);
// A path that could not be stopped must not keep receiving.
peer.close();
peer.connection().close();
}
finally {
try {
track.dispose();
}
finally {
receiver.dispose();
}
}
peer.deliverError(PeerImpl.asWebRtcException(e, "Setting the receive transform of " + owner
+ " failed"));
return;
}
}

Expand All @@ -160,6 +189,33 @@ void added(RTCRtpReceiver receiver, MediaStream[] streams) {
});
}

/** Stops the native receive path, rather than only releasing its Java view. */
private void stopReceiver(RTCRtpReceiver receiver) {
RTCRtpTransceiver[] transceivers = peer.connection().getTransceivers();

try {
for (RTCRtpTransceiver transceiver : transceivers) {
RTCRtpReceiver candidate = transceiver.getReceiver();

try {
if (receiver.equals(candidate)) {
transceiver.stopImmediately();
return;
}
}
finally {
candidate.dispose();
}
}
}
finally {
for (RTCRtpTransceiver transceiver : transceivers) {
transceiver.dispose();
}
}
throw new IllegalStateException("The receiver has no transceiver to stop");
}

/**
* Ends a track WebRTC took away. On the control executor.
*/
Expand Down
23 changes: 19 additions & 4 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected int[] initialValue() {

private boolean scheduled;

private volatile Thread runner;
private final ThreadLocal<Boolean> running;


/**
Expand All @@ -99,6 +99,13 @@ protected int[] initialValue() {
*/
SerialExecutor(Executor executor, Workload workload, Consumer<Throwable> errorHandler,
boolean eventThread, String threadName) {
this(executor, workload, errorHandler, eventThread, threadName, new ThreadLocal<>());
}

/** Allows a test to hold a turn in its thread-local cleanup while the next starts. */
SerialExecutor(Executor executor, Workload workload, Consumer<Throwable> errorHandler,
boolean eventThread, String threadName, ThreadLocal<Boolean> running) {
this.running = running;
this.executor = executor;
this.workload = workload;
this.errorHandler = errorHandler;
Expand Down Expand Up @@ -149,7 +156,7 @@ private void submit(Task task) {
* @return true when the calling thread is running a task of this executor.
*/
boolean inExecutor() {
return runner == Thread.currentThread();
return Boolean.TRUE.equals(running.get());
}

private void schedule() {
Expand Down Expand Up @@ -204,7 +211,8 @@ private void drain() {
EVENT_DEPTH.get()[0]++;
}

runner = thread;
Boolean previous = running.get();
running.set(true);

try {
long start = workload.now();
Expand All @@ -229,7 +237,14 @@ private void drain() {
}
}
finally {
runner = null;
// A previous turn may still be cleaning up after the next
// started on another thread. Its marker belongs to this thread only.
if (previous == null) {
running.remove();
}
else {
running.set(previous);
}

if (eventThread) {
EVENT_DEPTH.get()[0]--;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

Expand Down Expand Up @@ -345,6 +348,74 @@ void failingExecutorRunsFallback() {
assertEquals(Arrays.asList("fallback", "later"), ran);
}

@Test
void idleCleanupCannotClearNextThreadsMarker() throws Exception {
CountDownLatch cleaning = new CountDownLatch(1);
CountDownLatch finishCleanup = new CountDownLatch(1);
CountDownLatch secondStarted = new CountDownLatch(1);
CountDownLatch checkMarker = new CountDownLatch(1);
AtomicBoolean holdCleanup = new AtomicBoolean(true);
AtomicBoolean marked = new AtomicBoolean();
ThreadLocal<Boolean> running = new ThreadLocal<Boolean>() {
@Override
public void remove() {
if (holdCleanup.compareAndSet(true, false)) {
// The queue is idle and another thread may start its turn,
// but this turn has not yet cleared its executor marker.
cleaning.countDown();
awaitLatch(finishCleanup);
}
super.remove();
}
};
SerialExecutor events = new SerialExecutor(pool, work, errors::add, true, null, running);
Thread first = new Thread(pool::runNext, "first-turn");
Thread second = new Thread(pool::runNext, "second-turn");

try {
events.execute(() -> assertTrue(events.inExecutor()));
first.start();
awaitLatch(cleaning);

events.execute(() -> {
secondStarted.countDown();
awaitLatch(checkMarker);
marked.set(events.inExecutor());
assertTrue(SerialExecutor.onEventThread());
});
second.start();
awaitLatch(secondStarted);

// Complete A's cleanup while B is still inside its event task.
finishCleanup.countDown();
first.join(5000);
assertFalse(first.isAlive());
checkMarker.countDown();
second.join(5000);
assertFalse(second.isAlive());

assertTrue(marked.get());
assertFalse(events.inExecutor());
assertTrue(errors.isEmpty(), () -> "Errors: " + errors);
}
finally {
finishCleanup.countDown();
checkMarker.countDown();
first.join(5000);
second.join(5000);
}
}

private static void awaitLatch(CountDownLatch latch) {
try {
assertTrue(latch.await(5, TimeUnit.SECONDS), "Timed out waiting for the other turn");
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}

@Test
void eventThreadMarked() {
SerialExecutor events = new SerialExecutor(pool, errors::add, true, "events-test");
Expand Down
Loading
Loading