From abf06016b5953c353fca72f2e5e5e15451b399a4 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 18:48:18 +0100 Subject: [PATCH 1/3] fix: register track sinks atomically across threads AudioTrack and VideoTrack kept their sinks in unguarded maps, so two threads adding the same sink made two native registrations, and an add could overlap dispose(). A shared SinkRegistry now guards the map with a lock that is never held across a native call, and dispose() waits for the native calls still running. --- .../onvoid/webrtc/internal/SinkRegistry.java | 253 ++++++++++++++++++ .../onvoid/webrtc/media/audio/AudioTrack.java | 61 ++--- .../onvoid/webrtc/media/video/VideoTrack.java | 35 +-- .../webrtc/internal/SinkRegistryTests.java | 201 ++++++++++++++ 4 files changed, 490 insertions(+), 60 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java new file mode 100644 index 000000000..beb8cbbe2 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java @@ -0,0 +1,253 @@ +/* + * 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.internal; + +import static java.util.Objects.requireNonNull; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.LongConsumer; +import java.util.function.ToLongFunction; + +/** + * The sinks a track has registered in native code, each with the handle of + * its native counterpart. Not API for applications. + *

+ * Every method may be called from any thread at the same time. A sink is + * registered in native code at most once, however many threads add it, and + * {@link #close()} returns only once no native call made for a sink is still + * running, so that the track can be freed after it. + *

+ * The lock that guards the map is never held during a native call. WebRTC + * holds a lock of its own while it hands media to the sinks, and adding or + * removing a sink takes that lock too; a thread that waited for this lock + * while holding WebRTC's would deadlock with one that held this lock while + * waiting for WebRTC's. + * + * @param the type of the sinks. + */ +public final class SinkRegistry { + + private final Object lock = new Object(); + + /** Guarded by {@link #lock}. */ + private final Map registrations = new IdentityHashMap<>(); + + private final LongConsumer nativeRemove; + + /** Native calls still running for this registry. Guarded by {@link #lock}. */ + private int running; + + /** Guarded by {@link #lock}. */ + private boolean closed; + + + /** + * @param nativeRemove unregisters the native sink of a handle and frees it. + */ + public SinkRegistry(LongConsumer nativeRemove) { + this.nativeRemove = requireNonNull(nativeRemove); + } + + /** + * Registers the sink unless it is registered already. + * + * @param sink the sink. + * @param nativeAdd registers a native sink for it and returns its handle. + * + * @throws IllegalStateException if the registry has been closed. + */ + public void add(S sink, ToLongFunction nativeAdd) { + requireNonNull(sink); + + Registration registration = new Registration(); + + synchronized (lock) { + if (closed) { + throw new IllegalStateException("The track has been disposed"); + } + if (registrations.containsKey(sink)) { + return; + } + + // Taken before the native call, so that a second add of the same + // sink finds it and does not register it again. + registrations.put(sink, registration); + running++; + } + + long handle; + + try { + handle = nativeAdd.applyAsLong(sink); + } + catch (RuntimeException | Error e) { + synchronized (lock) { + registrations.remove(sink, registration); + registration.removed = true; + finished(); + } + throw e; + } + + boolean removed; + + synchronized (lock) { + registration.handle = handle; + removed = registration.removed; + + if (!removed) { + finished(); + } + } + + if (removed) { + // Removed, or the registry closed, while it was being added: the + // remover left the native sink to this thread. + release(registration); + } + } + + /** + * Unregisters the sink, if it is registered. + * + * @param sink the sink. + */ + public void remove(S sink) { + requireNonNull(sink); + + Registration registration; + + synchronized (lock) { + registration = registrations.remove(sink); + + if (registration == null || !take(registration)) { + return; + } + } + + release(registration); + } + + /** + * Unregisters every sink and waits for the native calls still running + * for this registry. Adding a sink afterwards fails; closing it again + * does nothing. + */ + public void close() { + List taken = new ArrayList<>(); + + synchronized (lock) { + closed = true; + + for (Registration registration : registrations.values()) { + if (take(registration)) { + taken.add(registration); + } + } + + registrations.clear(); + } + + RuntimeException failure = null; + + for (Registration registration : taken) { + try { + release(registration); + } + catch (RuntimeException e) { + if (failure == null) { + failure = e; + } + } + } + + awaitNativeCalls(); + + if (failure != null) { + throw failure; + } + } + + /** + * Marks a registration removed. Returns whether the caller is to release + * its native sink, which it is only once the native add has returned; the + * adder releases it otherwise. Called with {@link #lock} held. + */ + private boolean take(Registration registration) { + registration.removed = true; + + if (registration.handle == 0) { + return false; + } + + running++; + return true; + } + + private void release(Registration registration) { + try { + nativeRemove.accept(registration.handle); + } + finally { + synchronized (lock) { + finished(); + } + } + } + + /** Called with {@link #lock} held. */ + private void finished() { + if (--running == 0) { + lock.notifyAll(); + } + } + + private void awaitNativeCalls() { + boolean interrupted = false; + + synchronized (lock) { + while (running > 0) { + try { + lock.wait(); + } + catch (InterruptedException e) { + interrupted = true; + } + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + + + private static final class Registration { + + /** The native sink, 0 while it is being added. Guarded by {@link #lock}. */ + long handle; + + /** Guarded by {@link #lock}. */ + boolean removed; + + } + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java index 47b8f1428..db05dbcb8 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java @@ -17,19 +17,21 @@ package dev.onvoid.webrtc.media.audio; import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; import dev.onvoid.webrtc.RTCRtpPacketInfo; +import dev.onvoid.webrtc.internal.SinkRegistry; import dev.onvoid.webrtc.media.MediaStreamTrack; -import java.util.IdentityHashMap; -import java.util.Map; - +/** + * An audio track. Its sinks and voice activity listeners may be added and + * removed from any thread, also at the same time. + */ public class AudioTrack extends MediaStreamTrack { - private final Map sinks = new IdentityHashMap<>(); + private final SinkRegistry sinks = new SinkRegistry<>(this::removeSinkInternal); - private final Map voiceActivityListeners = new IdentityHashMap<>(); + private final SinkRegistry voiceActivityListeners = + new SinkRegistry<>(this::removeVoiceActivityListenerInternal); private AudioTrack() { @@ -38,18 +40,14 @@ private AudioTrack() { @Override public void dispose() { - for (long nativeSink : sinks.values()) { - removeSinkInternal(nativeSink); + // Each waits for what other threads are still adding or removing. + try { + sinks.close(); } - - sinks.clear(); - - for (long nativeSink : voiceActivityListeners.values()) { - removeVoiceActivityListenerInternal(nativeSink); + finally { + voiceActivityListeners.close(); } - voiceActivityListeners.clear(); - super.dispose(); } @@ -57,18 +55,16 @@ public void dispose() { * Adds an AudioSink to the track. A track can have any number of AudioSinks. * * @param sink The audio sink that will receive audio data from the track. + * Adding it again does nothing. + * + * @throws IllegalStateException if the track has been disposed. */ public void addSink(AudioTrackSink sink) { if (isNull(sink)) { throw new NullPointerException(); } - if (sinks.containsKey(sink)) { - return; - } - final long nativeSink = addSinkInternal(sink, takesPacketInfos(sink)); - - sinks.put(sink, nativeSink); + sinks.add(sink, s -> addSinkInternal(s, takesPacketInfos(s))); } /** @@ -94,11 +90,7 @@ public void removeSink(AudioTrackSink sink) { throw new NullPointerException(); } - final Long nativeSink = sinks.remove(sink); - - if (nonNull(nativeSink)) { - removeSinkInternal(nativeSink); - } + sinks.remove(sink); } /** @@ -112,23 +104,20 @@ public void removeSink(AudioTrackSink sink) { * * @param config when audio counts as speech. * @param listener the listener. Adding it again does nothing. + * + * @throws IllegalStateException if the track has been disposed. */ public void addVoiceActivityListener(VoiceActivityConfig config, VoiceActivityListener listener) { if (isNull(config) || isNull(listener)) { throw new NullPointerException(); } - if (voiceActivityListeners.containsKey(listener)) { - return; - } // Preserve partial milliseconds before native code rounds to 10 ms chunks. int hangoverMs = (int) config.getHangover().toMillis() + (config.getHangover().getNano() % 1_000_000 == 0 ? 0 : 1); - final long nativeSink = addVoiceActivityListenerInternal(listener, (float) config.getThreshold(), - hangoverMs); - - voiceActivityListeners.put(listener, nativeSink); + voiceActivityListeners.add(listener, l -> addVoiceActivityListenerInternal(l, + (float) config.getThreshold(), hangoverMs)); } /** @@ -141,11 +130,7 @@ public void removeVoiceActivityListener(VoiceActivityListener listener) { throw new NullPointerException(); } - final Long nativeSink = voiceActivityListeners.remove(listener); - - if (nonNull(nativeSink)) { - removeVoiceActivityListenerInternal(nativeSink); - } + voiceActivityListeners.remove(listener); } /** diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java index 85e3bcc43..059a88894 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java @@ -17,16 +17,17 @@ package dev.onvoid.webrtc.media.video; import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; +import dev.onvoid.webrtc.internal.SinkRegistry; import dev.onvoid.webrtc.media.MediaStreamTrack; -import java.util.IdentityHashMap; -import java.util.Map; - +/** + * A video track. Its sinks may be added and removed from any thread, also at + * the same time. + */ public class VideoTrack extends MediaStreamTrack { - private final Map sinks = new IdentityHashMap<>(); + private final SinkRegistry sinks = new SinkRegistry<>(this::removeSinkInternal); private VideoTrack() { @@ -35,11 +36,8 @@ private VideoTrack() { @Override public void dispose() { - for (long nativeSink : sinks.values()) { - removeSinkInternal(nativeSink); - } - - sinks.clear(); + // Waits for sinks that other threads are still adding or removing. + sinks.close(); super.dispose(); } @@ -48,19 +46,16 @@ public void dispose() { * Adds a VideoSink to the track. A track can have any number of * VideoSinks. * - * @param sink The video sink to add. + * @param sink The video sink to add. Adding it again does nothing. + * + * @throws IllegalStateException if the track has been disposed. */ public void addSink(VideoTrackSink sink) { if (isNull(sink)) { throw new NullPointerException(); } - if (sinks.containsKey(sink)) { - return; - } - - final long nativeSink = addSinkInternal(sink); - sinks.put(sink, nativeSink); + sinks.add(sink, this::addSinkInternal); } /** @@ -72,11 +67,7 @@ public void removeSink(VideoTrackSink sink) { throw new NullPointerException(); } - final Long nativeSink = sinks.remove(sink); - - if (nonNull(nativeSink)) { - removeSinkInternal(nativeSink); - } + sinks.remove(sink); } private native long addSinkInternal(VideoTrackSink sink); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java new file mode 100644 index 000000000..8804fc538 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java @@ -0,0 +1,201 @@ +/* + * 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.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.ToLongFunction; + +import org.junit.jupiter.api.Test; + +class SinkRegistryTests { + + /** What the native side was asked to do, in order. */ + private final List calls = new CopyOnWriteArrayList<>(); + + private final SinkRegistry registry = new SinkRegistry<>(handle -> calls.add("remove " + handle)); + + private final AtomicInteger nextHandle = new AtomicInteger(); + + + @Test + void secondAddDoesNothing() { + Object sink = new Object(); + + registry.add(sink, add()); + registry.add(sink, add()); + + assertEquals(List.of("add 1"), calls); + } + + @Test + void concurrentAddsRegisterOnce() throws Exception { + Object sink = new Object(); + BlockedAdd blocked = new BlockedAdd(); + + CompletableFuture first = CompletableFuture.runAsync(() -> registry.add(sink, blocked)); + blocked.awaitEntered(); + + // The first add is still in its native call, and this one must not + // make a second registration while it is. + registry.add(sink, add()); + + blocked.proceed(); + first.get(5, TimeUnit.SECONDS); + + assertEquals(List.of("add 1"), calls); + + registry.remove(sink); + + assertEquals(List.of("add 1", "remove 1"), calls); + } + + @Test + void removeDuringAddReleasesOnce() throws Exception { + Object sink = new Object(); + BlockedAdd blocked = new BlockedAdd(); + + CompletableFuture adding = CompletableFuture.runAsync(() -> registry.add(sink, blocked)); + blocked.awaitEntered(); + + // No handle yet, so the adder releases the native sink once it has one. + registry.remove(sink); + registry.remove(sink); + + assertEquals(Collections.emptyList(), calls); + + blocked.proceed(); + adding.get(5, TimeUnit.SECONDS); + + assertEquals(List.of("add 1", "remove 1"), calls); + + // Registered anew, with a native sink of its own. + registry.add(sink, add()); + + assertEquals(List.of("add 1", "remove 1", "add 2"), calls); + } + + @Test + void closeWaitsForAdd() throws Exception { + Object sink = new Object(); + BlockedAdd blocked = new BlockedAdd(); + + CompletableFuture adding = CompletableFuture.runAsync(() -> registry.add(sink, blocked)); + blocked.awaitEntered(); + + CompletableFuture closing = CompletableFuture.runAsync(() -> { + registry.close(); + calls.add("closed"); + }); + + blocked.proceed(); + adding.get(5, TimeUnit.SECONDS); + closing.get(5, TimeUnit.SECONDS); + + // The track is freed after close returns, so no native call may still + // be running then. + assertEquals(List.of("add 1", "remove 1", "closed"), calls); + } + + @Test + void closeRemovesAll() { + registry.add(new Object(), add()); + registry.add(new Object(), add()); + + registry.close(); + registry.close(); + + assertEquals(4, calls.size()); + assertTrue(calls.containsAll(List.of("remove 1", "remove 2"))); + } + + @Test + void addAfterCloseFails() { + registry.close(); + + assertThrows(IllegalStateException.class, () -> registry.add(new Object(), add())); + assertEquals(Collections.emptyList(), calls); + } + + @Test + void failedAddLeavesNothing() { + Object sink = new Object(); + RuntimeException failure = new RuntimeException("Not added"); + + RuntimeException thrown = assertThrows(RuntimeException.class, () -> registry.add(sink, s -> { + throw failure; + })); + + assertSame(failure, thrown); + + registry.add(sink, add()); + registry.close(); + + assertEquals(List.of("add 1", "remove 1"), calls); + } + + private ToLongFunction add() { + return sink -> { + long handle = nextHandle.incrementAndGet(); + calls.add("add " + handle); + return handle; + }; + } + + + + /** A native add that waits, once it has been entered, until the test lets it return. */ + private final class BlockedAdd implements ToLongFunction { + + private final CountDownLatch entered = new CountDownLatch(1); + + private final CountDownLatch proceed = new CountDownLatch(1); + + + @Override + public long applyAsLong(Object sink) { + entered.countDown(); + + try { + assertTrue(proceed.await(5, TimeUnit.SECONDS)); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + + return add().applyAsLong(sink); + } + + void awaitEntered() throws InterruptedException { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + } + + void proceed() { + proceed.countDown(); + } + } +} From 8bfd54dbb871806e2e5c8b13fa728357c0968d4f Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 18:58:37 +0100 Subject: [PATCH 2/3] fix: let sinks add and remove sinks from their callbacks A sink that removed itself in onVideoFrame() blocked for good: WebRTC holds the broadcaster's lock while it delivers a frame, and RemoveSink() takes it again on the worker thread the caller waits for. The same held for adding a sink, for audio sinks of a remote track or a CustomAudioSource, and for voice activity listeners. A change made within a callback now takes effect for the Java side at once and is made natively on another thread after the callback returned; dispose() there fails with an IllegalStateException. --- docs/guide/audio/custom-audio-source.md | 2 + docs/guide/video/camera-capture.md | 19 ++ .../onvoid/webrtc/internal/SinkRegistry.java | 248 ++++++++++++++---- .../onvoid/webrtc/media/audio/AudioTrack.java | 119 ++++++++- .../onvoid/webrtc/media/video/VideoTrack.java | 63 ++++- .../webrtc/internal/SinkRegistryTests.java | 150 ++++++++++- .../media/audio/CustomAudioSourceTest.java | 32 ++- .../webrtc/media/video/VideoTrackTests.java | 124 +++++++++ 8 files changed, 689 insertions(+), 68 deletions(-) diff --git a/docs/guide/audio/custom-audio-source.md b/docs/guide/audio/custom-audio-source.md index 99ea7182e..919f23fee 100644 --- a/docs/guide/audio/custom-audio-source.md +++ b/docs/guide/audio/custom-audio-source.md @@ -204,6 +204,8 @@ audioTrack.addSink(monitorSink); audioTrack.removeSink(monitorSink); ``` +As with video tracks, sinks may be added and removed from any thread, and also from within `onData`, the sink's own included. Only `dispose()` must not be called from within a callback. + ## Cleanup When you're done with the custom audio source, make sure to clean up resources: diff --git a/docs/guide/video/camera-capture.md b/docs/guide/video/camera-capture.md index c66f30e36..23fe5eaf9 100644 --- a/docs/guide/video/camera-capture.md +++ b/docs/guide/video/camera-capture.md @@ -162,6 +162,25 @@ videoTrack.addSink(localVideoSink); videoTrack.removeSink(localVideoSink); ``` +### Threads and Sink Changes + +`addSink` and `removeSink` may be called from any thread, also at the same time, and from within `onVideoFrame`, so a sink can remove itself once it has seen what it wanted: + +```java +videoTrack.addSink(new VideoTrackSink() { + @Override + public void onVideoFrame(VideoFrame frame) { + saveSnapshot(frame); + frame.release(); + + // Gets no further frames. + videoTrack.removeSink(this); + } +}); +``` + +WebRTC holds a lock while it hands a frame to the sinks, and adding or removing a sink takes the same lock. A change made from within a callback therefore takes effect for the sinks at once, while the native sink is added or removed on another thread right after the callback returned. Disposing the track is the one thing a callback cannot do: `dispose()` throws an `IllegalStateException` there, and belongs on another thread. + ### Receiving Remote Video Frames To receive frames from a remote peer, you need to add a sink to the remote video track when it's received. This is typically done in the `onTrack` method of your `PeerConnectionObserver`: diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java index beb8cbbe2..dfd8458fe 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/SinkRegistry.java @@ -18,12 +18,17 @@ import static java.util.Objects.requireNonNull; +import dev.onvoid.webrtc.logging.Logging; + import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.function.LongConsumer; -import java.util.function.ToLongFunction; /** * The sinks a track has registered in native code, each with the handle of @@ -34,16 +39,27 @@ * {@link #close()} returns only once no native call made for a sink is still * running, so that the track can be freed after it. *

- * The lock that guards the map is never held during a native call. WebRTC - * holds a lock of its own while it hands media to the sinks, and adding or - * removing a sink takes that lock too; a thread that waited for this lock - * while holding WebRTC's would deadlock with one that held this lock while - * waiting for WebRTC's. + * WebRTC holds a lock while it hands media to the sinks of a source, and + * adding or removing a sink takes that lock too, on another thread that the + * calling one waits for. A sink that adds or removes a sink from within its + * callback would wait for itself. So the native sink of the track wraps the + * sink of the application and tells this registry, through its {@link + * Registration}, when a thread is handing it media: a change made on such a + * thread takes effect at once for the Java side, a removed sink is not called + * again, and the native call follows on a thread of its own once the callback + * has returned. + *

+ * For the same reason the lock that guards the map is never held during a + * native call: a thread that waited for it while holding WebRTC's lock would + * deadlock with one that held it while waiting for WebRTC's. * * @param the type of the sinks. */ public final class SinkRegistry { + /** How many callbacks of sinks the current thread is in. */ + private static final ThreadLocal CALLBACK_DEPTH = ThreadLocal.withInitial(() -> new int[1]); + private final Object lock = new Object(); /** Guarded by {@link #lock}. */ @@ -51,7 +67,7 @@ public final class SinkRegistry { private final LongConsumer nativeRemove; - /** Native calls still running for this registry. Guarded by {@link #lock}. */ + /** Native calls running or deferred for this registry. Guarded by {@link #lock}. */ private int running; /** Guarded by {@link #lock}. */ @@ -66,15 +82,18 @@ public SinkRegistry(LongConsumer nativeRemove) { } /** - * Registers the sink unless it is registered already. + * Registers the sink unless it is registered already. Called from within + * the callback of a sink, it returns before the native sink is registered, + * which happens on another thread right after. * * @param sink the sink. * @param nativeAdd registers a native sink for it and returns its handle. * * @throws IllegalStateException if the registry has been closed. */ - public void add(S sink, ToLongFunction nativeAdd) { + public void add(S sink, NativeAdd nativeAdd) { requireNonNull(sink); + requireNonNull(nativeAdd); Registration registration = new Registration(); @@ -92,40 +111,19 @@ public void add(S sink, ToLongFunction nativeAdd) { running++; } - long handle; - - try { - handle = nativeAdd.applyAsLong(sink); - } - catch (RuntimeException | Error e) { - synchronized (lock) { - registrations.remove(sink, registration); - registration.removed = true; - finished(); - } - throw e; - } - - boolean removed; - - synchronized (lock) { - registration.handle = handle; - removed = registration.removed; - - if (!removed) { - finished(); - } + if (inCallback()) { + Deferred.run(() -> register(sink, registration, nativeAdd)); } - - if (removed) { - // Removed, or the registry closed, while it was being added: the - // remover left the native sink to this thread. - release(registration); + else { + register(sink, registration, nativeAdd); } } /** - * Unregisters the sink, if it is registered. + * Unregisters the sink, if it is registered. Once this returns, the sink + * is not called again, except by a callback that another thread is + * running at that moment. Called from within the callback of a sink, the + * native sink is unregistered on another thread right after. * * @param sink the sink. */ @@ -142,15 +140,28 @@ public void remove(S sink) { } } - release(registration); + if (inCallback()) { + Deferred.run(() -> release(registration)); + } + else { + release(registration); + } } /** - * Unregisters every sink and waits for the native calls still running - * for this registry. Adding a sink afterwards fails; closing it again - * does nothing. + * Unregisters every sink and waits for the native calls still running or + * deferred for this registry. Adding a sink afterwards fails; closing it + * again does nothing. + * + * @throws IllegalStateException if called from within the callback of a + * sink, which would wait for itself. */ public void close() { + if (inCallback()) { + throw new IllegalStateException("A track cannot be disposed on a thread that is handing media " + + "to a sink. Remove the sink there, and dispose the track on another thread"); + } + List taken = new ArrayList<>(); synchronized (lock) { @@ -185,6 +196,63 @@ public void close() { } } + /** + * Waits until the native calls deferred so far, by any registry, have + * been made. For tests. + */ + public static void awaitDeferred() throws InterruptedException { + CountDownLatch done = new CountDownLatch(1); + + Deferred.run(done::countDown); + + done.await(); + } + + private static boolean inCallback() { + return CALLBACK_DEPTH.get()[0] > 0; + } + + private void register(S sink, Registration registration, NativeAdd nativeAdd) { + synchronized (lock) { + if (registration.removed) { + // Removed before a deferred add got to it. + finished(); + return; + } + } + + long handle; + + try { + handle = nativeAdd.add(sink, registration); + } + catch (RuntimeException | Error e) { + synchronized (lock) { + registrations.remove(sink, registration); + registration.removed = true; + finished(); + } + throw e; + } + + boolean removed; + + synchronized (lock) { + registration.handle = handle; + removed = registration.removed; + + if (!removed) { + finished(); + } + } + + if (removed) { + // Removed, or the registry closed, while it was being added: the + // remover left the native sink to this thread. + release(registration); + } + } + /** * Marks a registration removed. Returns whether the caller is to release * its native sink, which it is only once the native add has returned; the @@ -240,13 +308,99 @@ private void awaitNativeCalls() { - private static final class Registration { + /** + * Registers the native sink of a sink. + * + * @param the type of the sinks. + */ + @FunctionalInterface + public interface NativeAdd { + + /** + * @param sink the sink of the application. + * @param registration what the native sink has to {@link + * Registration#enter() enter} before it calls the + * sink. + * + * @return the handle of the native sink. + */ + long add(S sink, Registration registration); - /** The native sink, 0 while it is being added. Guarded by {@link #lock}. */ - long handle; + } - /** Guarded by {@link #lock}. */ - boolean removed; + + + /** + * The registration of one sink, which the code that calls the sink tells + * when it does. + */ + public static final class Registration { + + /** The native sink, 0 while it is being added. Guarded by the registry's lock. */ + private long handle; + + /** Written with the registry's lock held, read without it by {@link #enter()}. */ + private volatile boolean removed; + + + private Registration() { + + } + + /** + * Called before the sink is handed media, on the thread that hands it + * over. Returns false, and the media is not to be handed over, once + * the sink has been removed; otherwise {@link #exit()} must follow + * once the sink returned. + * + * @return whether to call the sink. + */ + public boolean enter() { + if (removed) { + return false; + } + + CALLBACK_DEPTH.get()[0]++; + return true; + } + + /** + * Called once the sink returned from a call that {@link #enter()} + * allowed. + */ + public void exit() { + CALLBACK_DEPTH.get()[0]--; + } + + } + + + + /** + * Makes the native calls that a callback asked for, one after another, + * on a thread that never hands media to a sink. + */ + private static final class Deferred { + + private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), runnable -> { + Thread thread = new Thread(runnable, "webrtc-java-sink-changes"); + thread.setDaemon(true); + return thread; + }); + + + static void run(Runnable change) { + EXECUTOR.execute(() -> { + try { + change.run(); + } + catch (Throwable e) { + // No caller is left to hand it to. + Logging.error("A sink change made in a sink callback failed", e); + } + }); + } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java index db05dbcb8..bf3a629e0 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java @@ -24,7 +24,14 @@ /** * An audio track. Its sinks and voice activity listeners may be added and - * removed from any thread, also at the same time. + * removed from any thread, also at the same time, and also from within the + * callback of a sink or listener, its own included. + *

+ * WebRTC holds a lock while it hands audio to the sinks of some sources, such + * as that of a remote track or a {@link CustomAudioSource}, which adding and + * removing a sink take as well. A change made from within a callback + * therefore takes effect for the sinks at once, but the native sink is added + * or removed on another thread right after the callback has returned. */ public class AudioTrack extends MediaStreamTrack { @@ -38,9 +45,18 @@ private AudioTrack() { super(); } + /** + * {@inheritDoc} + *

+ * Removes the sinks and voice activity listeners of the track first, and + * waits for those that other threads are still adding or removing. + * + * @throws IllegalStateException if called from within the callback of a + * sink or listener, of this track or any + * other. + */ @Override public void dispose() { - // Each waits for what other threads are still adding or removing. try { sinks.close(); } @@ -53,6 +69,8 @@ public void dispose() { /** * Adds an AudioSink to the track. A track can have any number of AudioSinks. + * Called from within the callback of a sink, it returns before the sink is + * registered, and the sink gets the audio that follows once it is. * * @param sink The audio sink that will receive audio data from the track. * Adding it again does nothing. @@ -64,7 +82,8 @@ public void addSink(AudioTrackSink sink) { throw new NullPointerException(); } - sinks.add(sink, s -> addSinkInternal(s, takesPacketInfos(s))); + sinks.add(sink, (s, registration) -> addSinkInternal(new SinkDelivery(s, registration), + takesPacketInfos(s))); } /** @@ -83,7 +102,9 @@ private static boolean takesPacketInfos(AudioTrackSink sink) { /** * Removes an AudioSink from the track. If the AudioSink was not attached to - * the track, this is a no-op. + * the track, this is a no-op. Once this returns, the sink gets no further + * audio, except what another thread is handing it at that moment. A sink + * may remove itself in its {@code onData}. */ public void removeSink(AudioTrackSink sink) { if (isNull(sink)) { @@ -116,14 +137,15 @@ public void addVoiceActivityListener(VoiceActivityConfig config, VoiceActivityLi int hangoverMs = (int) config.getHangover().toMillis() + (config.getHangover().getNano() % 1_000_000 == 0 ? 0 : 1); - voiceActivityListeners.add(listener, l -> addVoiceActivityListenerInternal(l, - (float) config.getThreshold(), hangoverMs)); + voiceActivityListeners.add(listener, (l, registration) -> addVoiceActivityListenerInternal( + new ListenerDelivery(l, registration), (float) config.getThreshold(), hangoverMs)); } /** * Removes a listener added with {@link #addVoiceActivityListener}. Once - * this returns, it is no longer called. If it was not added, this is a - * no-op. + * this returns, it is no longer called, except by a call that another + * thread is making at that moment. If it was not added, this is a no-op. A + * listener may remove itself in its callback. */ public void removeVoiceActivityListener(VoiceActivityListener listener) { if (isNull(listener)) { @@ -170,4 +192,85 @@ private native long addVoiceActivityListenerInternal(VoiceActivityListener liste private native void removeVoiceActivityListenerInternal(long sinkHandle); + + + /** + * What the native sink calls: it tells the registry when a thread hands + * the sink audio, and drops the audio of a removed sink. + */ + private static final class SinkDelivery implements AudioTrackSink { + + private final AudioTrackSink sink; + + private final SinkRegistry.Registration registration; + + + SinkDelivery(AudioTrackSink sink, SinkRegistry.Registration registration) { + this.sink = sink; + this.registration = registration; + } + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames) { + if (!registration.enter()) { + return; + } + + try { + sink.onData(data, bitsPerSample, sampleRate, channels, frames); + } + finally { + registration.exit(); + } + } + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames, + RTCRtpPacketInfo[] packetInfos) { + if (!registration.enter()) { + return; + } + + try { + sink.onData(data, bitsPerSample, sampleRate, channels, frames, packetInfos); + } + finally { + registration.exit(); + } + } + } + + + + /** + * What the native sink of a voice activity listener calls, like {@link + * SinkDelivery}. + */ + private static final class ListenerDelivery implements VoiceActivityListener { + + private final VoiceActivityListener listener; + + private final SinkRegistry.Registration registration; + + + ListenerDelivery(VoiceActivityListener listener, SinkRegistry.Registration registration) { + this.listener = listener; + this.registration = registration; + } + + @Override + public void onVoiceActivity(boolean speaking) { + if (!registration.enter()) { + return; + } + + try { + listener.onVoiceActivity(speaking); + } + finally { + registration.exit(); + } + } + } + } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java index 059a88894..492d7f600 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java @@ -23,7 +23,13 @@ /** * A video track. Its sinks may be added and removed from any thread, also at - * the same time. + * the same time, and also from within the callback of a sink, the sink's own + * included. + *

+ * WebRTC holds a lock while it hands a frame to the sinks, which adding and + * removing a sink take as well. A change made from within a callback + * therefore takes effect for the sinks at once, but the native sink is added + * or removed on another thread right after the callback has returned. */ public class VideoTrack extends MediaStreamTrack { @@ -34,9 +40,17 @@ private VideoTrack() { super(); } + /** + * {@inheritDoc} + *

+ * Removes the sinks of the track first, and waits for those that other + * threads are still adding or removing. + * + * @throws IllegalStateException if called from within the callback of a + * sink, of this track or any other. + */ @Override public void dispose() { - // Waits for sinks that other threads are still adding or removing. sinks.close(); super.dispose(); @@ -44,7 +58,9 @@ public void dispose() { /** * Adds a VideoSink to the track. A track can have any number of - * VideoSinks. + * VideoSinks. Called from within the callback of a sink, it returns + * before the sink is registered, and the sink gets the frames that follow + * once it is. * * @param sink The video sink to add. Adding it again does nothing. * @@ -55,12 +71,14 @@ public void addSink(VideoTrackSink sink) { throw new NullPointerException(); } - sinks.add(sink, this::addSinkInternal); + sinks.add(sink, (s, registration) -> addSinkInternal(new Delivery(s, registration))); } /** * Removes a VideoSink from the track. If the VideoSink was not attached to - * the track, this is a no-op. + * the track, this is a no-op. Once this returns, the sink gets no further + * frames, except one that another thread is handing it at that moment. A + * sink may remove itself in its {@link VideoTrackSink#onVideoFrame}. */ public void removeSink(VideoTrackSink sink) { if (isNull(sink)) { @@ -74,4 +92,39 @@ public void removeSink(VideoTrackSink sink) { private native void removeSinkInternal(long sinkHandle); + + + /** + * What the native sink calls: it tells the registry when a thread hands + * the sink a frame, and drops the frames of a removed sink. + */ + private static final class Delivery implements VideoTrackSink { + + private final VideoTrackSink sink; + + private final SinkRegistry.Registration registration; + + + Delivery(VideoTrackSink sink, SinkRegistry.Registration registration) { + this.sink = sink; + this.registration = registration; + } + + @Override + public void onVideoFrame(VideoFrame frame) { + if (!registration.enter()) { + // The sink would have owned the reference. + frame.release(); + return; + } + + try { + sink.onVideoFrame(frame); + } + finally { + registration.exit(); + } + } + } + } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java index 8804fc538..20fd98a1e 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/SinkRegistryTests.java @@ -17,6 +17,7 @@ package dev.onvoid.webrtc.internal; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -28,7 +29,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.ToLongFunction; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; @@ -146,7 +147,7 @@ void failedAddLeavesNothing() { Object sink = new Object(); RuntimeException failure = new RuntimeException("Not added"); - RuntimeException thrown = assertThrows(RuntimeException.class, () -> registry.add(sink, s -> { + RuntimeException thrown = assertThrows(RuntimeException.class, () -> registry.add(sink, (s, r) -> { throw failure; })); @@ -158,8 +159,143 @@ void failedAddLeavesNothing() { assertEquals(List.of("add 1", "remove 1"), calls); } - private ToLongFunction add() { - return sink -> { + @Test + void removeInCallbackIsDeferred() throws Exception { + Object sink = new Object(); + AtomicReference registration = new AtomicReference<>(); + + registry.add(sink, (s, r) -> { + registration.set(r); + return add().add(s, r); + }); + + assertTrue(registration.get().enter()); + + try { + // WebRTC holds its lock here, so the native removal must wait. + registry.remove(sink); + + assertEquals(List.of("add 1"), calls); + + // Removed for the Java side at once. + assertFalse(registration.get().enter()); + } + finally { + registration.get().exit(); + } + + SinkRegistry.awaitDeferred(); + + assertEquals(List.of("add 1", "remove 1"), calls); + } + + @Test + void addInCallbackIsDeferred() throws Exception { + SinkRegistry.Registration callback = callback(); + Object sink = new Object(); + + assertTrue(callback.enter()); + + try { + registry.add(sink, add()); + registry.add(sink, add()); + + assertEquals(List.of("add 1"), calls); + } + finally { + callback.exit(); + } + + SinkRegistry.awaitDeferred(); + + assertEquals(List.of("add 1", "add 2"), calls); + } + + @Test + void addAndRemoveInCallback() throws Exception { + SinkRegistry.Registration callback = callback(); + Object sink = new Object(); + + assertTrue(callback.enter()); + + try { + registry.add(sink, add()); + registry.remove(sink); + } + finally { + callback.exit(); + } + + SinkRegistry.awaitDeferred(); + + // Removed before the deferred add got to it, so never registered. + assertEquals(List.of("add 1"), calls); + } + + @Test + void closeInCallbackFails() throws Exception { + SinkRegistry.Registration callback = callback(); + + assertTrue(callback.enter()); + + try { + assertThrows(IllegalStateException.class, registry::close); + } + finally { + callback.exit(); + } + + // Still open, and closes on another thread. + registry.add(new Object(), add()); + registry.close(); + + assertEquals(List.of("add 1", "add 2", "remove 2"), calls); + } + + @Test + void closeWaitsForDeferredChanges() throws Exception { + SinkRegistry.Registration callback = callback(); + BlockedAdd blocked = new BlockedAdd(); + + assertTrue(callback.enter()); + + try { + registry.add(new Object(), blocked); + } + finally { + callback.exit(); + } + + blocked.awaitEntered(); + + CompletableFuture closing = CompletableFuture.runAsync(() -> { + registry.close(); + calls.add("closed"); + }); + + blocked.proceed(); + closing.get(5, TimeUnit.SECONDS); + + assertEquals(List.of("add 1", "add 2", "remove 2", "closed"), calls); + } + + /** + * The registration of a sink of another registry, whose callback the test + * pretends to be in. + */ + private SinkRegistry.Registration callback() { + AtomicReference registration = new AtomicReference<>(); + + new SinkRegistry<>(handle -> { }).add(new Object(), (s, r) -> { + registration.set(r); + return add().add(s, r); + }); + + return registration.get(); + } + + private SinkRegistry.NativeAdd add() { + return (sink, registration) -> { long handle = nextHandle.incrementAndGet(); calls.add("add " + handle); return handle; @@ -169,7 +305,7 @@ private ToLongFunction add() { /** A native add that waits, once it has been entered, until the test lets it return. */ - private final class BlockedAdd implements ToLongFunction { + private final class BlockedAdd implements SinkRegistry.NativeAdd { private final CountDownLatch entered = new CountDownLatch(1); @@ -177,7 +313,7 @@ private final class BlockedAdd implements ToLongFunction { @Override - public long applyAsLong(Object sink) { + public long add(Object sink, SinkRegistry.Registration registration) { entered.countDown(); try { @@ -187,7 +323,7 @@ public long applyAsLong(Object sink) { throw new IllegalStateException(e); } - return add().applyAsLong(sink); + return SinkRegistryTests.this.add().add(sink, registration); } void awaitEntered() throws InterruptedException { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java index 8acfd931c..585b8e382 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Duration; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -305,4 +306,33 @@ private void testAudioFormat(int bitsPerSample, int sampleRate, int channels, in audioTrack.removeSink(testSink); audioTrack.dispose(); } -} \ No newline at end of file + + @Test + void sinkRemovesItself() { + AudioTrack audioTrack = factory.createAudioTrack("audioTrack", customAudioSource); + AtomicInteger chunks = new AtomicInteger(); + + audioTrack.addSink(new AudioTrackSink() { + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames) { + chunks.incrementAndGet(); + + // The source holds the lock that removing takes while it is here. + audioTrack.removeSink(this); + } + }); + + byte[] data = new byte[480 * 2 * 2]; + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + customAudioSource.pushAudio(data, 16, 48000, 2, 480); + customAudioSource.pushAudio(data, 16, 48000, 2, 480); + }); + + assertEquals(1, chunks.get()); + + audioTrack.dispose(); + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java index 7c0d28acf..ac6127c68 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java @@ -19,6 +19,11 @@ import static org.junit.jupiter.api.Assertions.*; import dev.onvoid.webrtc.TestBase; +import dev.onvoid.webrtc.internal.SinkRegistry; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -70,4 +75,123 @@ void addRemoveSink() { videoTrack.removeSink(sink); } + @Test + void sinkRemovesItself() { + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("selfRemoving", source); + AtomicInteger frames = new AtomicInteger(); + + track.addSink(new VideoTrackSink() { + + @Override + public void onVideoFrame(VideoFrame frame) { + frames.incrementAndGet(); + frame.release(); + + // WebRTC holds the lock that removing takes while it is here. + track.removeSink(this); + } + }); + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + pushFrame(source); + pushFrame(source); + }); + + assertEquals(1, frames.get()); + + track.dispose(); + source.dispose(); + } + + @Test + void sinkRemovesOtherSink() { + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("removingOther", source); + AtomicInteger otherFrames = new AtomicInteger(); + + VideoTrackSink other = frame -> { + otherFrames.incrementAndGet(); + frame.release(); + }; + + // Called first, as it was added first. + track.addSink(frame -> { + frame.release(); + track.removeSink(other); + }); + track.addSink(other); + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + pushFrame(source); + pushFrame(source); + }); + + assertEquals(0, otherFrames.get()); + + track.dispose(); + source.dispose(); + } + + @Test + void sinkAddsSink() throws Exception { + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("adding", source); + AtomicInteger addedFrames = new AtomicInteger(); + + VideoTrackSink added = frame -> { + addedFrames.incrementAndGet(); + frame.release(); + }; + + track.addSink(frame -> { + frame.release(); + track.addSink(added); + }); + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> pushFrame(source)); + + // The native sink is added once the callback returned. + SinkRegistry.awaitDeferred(); + + pushFrame(source); + + assertEquals(1, addedFrames.get()); + + track.dispose(); + source.dispose(); + } + + @Test + void disposeInCallbackFails() { + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("disposing", source); + AtomicReference failure = new AtomicReference<>(); + + track.addSink(frame -> { + frame.release(); + + try { + track.dispose(); + } + catch (RuntimeException e) { + failure.set(e); + } + }); + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> pushFrame(source)); + + assertInstanceOf(IllegalStateException.class, failure.get()); + + track.dispose(); + source.dispose(); + } + + private static void pushFrame(CustomVideoSource source) { + VideoFrame frame = new VideoFrame(NativeI420Buffer.allocate(320, 240), 0); + + source.pushFrame(frame); + frame.release(); + } + } From 6ec67d412c75f2d41770b7ece973b14807114663 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 19:06:55 +0100 Subject: [PATCH 3/3] feat: let video sinks share read-only frames VideoTrackSink copied every frame for each sink, so four sinks of a 1080p30 track copied about 356 MiB a second. addSink(sink, VideoFrameAccess.SHARED) hands a sink the pixels the source handed out, without a copy, in read-only byte buffers; frame.copy() gives a writable one. COPY stays the default and keeps sinks from seeing each other's writes. --- docs/guide/video/camera-capture.md | 12 ++++ .../src/main/cpp/include/JNI_VideoTrack.h | 4 +- .../src/main/cpp/include/api/VideoFrame.h | 7 +- .../src/main/cpp/include/api/VideoTrackSink.h | 6 +- .../src/main/cpp/src/JNI_VideoCapture.cpp | 2 +- .../src/main/cpp/src/JNI_VideoTrack.cpp | 4 +- .../src/main/cpp/src/api/VideoFrame.cpp | 22 ++++++- .../src/main/cpp/src/api/VideoTrackSink.cpp | 19 ++++-- .../webrtc/media/video/VideoFrameAccess.java | 51 ++++++++++++++ .../onvoid/webrtc/media/video/VideoTrack.java | 30 +++++++-- .../webrtc/media/video/VideoTrackTests.java | 66 +++++++++++++++++++ 11 files changed, 205 insertions(+), 18 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoFrameAccess.java diff --git a/docs/guide/video/camera-capture.md b/docs/guide/video/camera-capture.md index 23fe5eaf9..aeff3f2e2 100644 --- a/docs/guide/video/camera-capture.md +++ b/docs/guide/video/camera-capture.md @@ -181,6 +181,18 @@ videoTrack.addSink(new VideoTrackSink() { WebRTC holds a lock while it hands a frame to the sinks, and adding or removing a sink takes the same lock. A change made from within a callback therefore takes effect for the sinks at once, while the native sink is added or removed on another thread right after the callback returned. Disposing the track is the one thing a callback cannot do: `dispose()` throws an `IllegalStateException` there, and belongs on another thread. +### Sharing Frames Between Sinks + +By default each sink gets an I420 copy of each frame of its own, which it may write into without the other sinks or the encoder seeing it. That costs a full copy of the pixels per frame and sink: at 1080p and 30 frames a second about 89 MiB a second, for each sink. A sink that only reads the frames can share them instead: + +```java +import dev.onvoid.webrtc.media.video.VideoFrameAccess; + +videoTrack.addSink(previewSink, VideoFrameAccess.SHARED); +``` + +A shared sink gets the pixels the source handed out, without a copy, which the other shared sinks and the encoder use as well. The planes of its `NativeI420Buffer` are read-only, so a write throws a `ReadOnlyBufferException`; a sink that wants to change a frame takes a writable copy with `frame.copy()`. The frames may come from a pool of the decoder or capturer, so a shared sink should not hold on to them for long: keep a copy instead, and release the frame. + ### Receiving Remote Video Frames To receive frames from a remote peer, you need to add a sink to the remote video track when it's received. This is typically done in the `onTrack` method of your `PeerConnectionObserver`: diff --git a/webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h b/webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h index 5333b3d46..f9ee877c7 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h +++ b/webrtc-jni/src/main/cpp/include/JNI_VideoTrack.h @@ -10,10 +10,10 @@ extern "C" { /* * Class: dev_onvoid_webrtc_media_video_VideoTrack * Method: addSinkInternal - * Signature: (Ldev/onvoid/webrtc/media/video/VideoTrackSink;)J + * Signature: (Ldev/onvoid/webrtc/media/video/VideoTrackSink;Z)J */ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInternal - (JNIEnv *, jobject, jobject); + (JNIEnv *, jobject, jobject, jboolean); /* * Class: dev_onvoid_webrtc_media_video_VideoTrack diff --git a/webrtc-jni/src/main/cpp/include/api/VideoFrame.h b/webrtc-jni/src/main/cpp/include/api/VideoFrame.h index ce5205a8f..b1ff1d56c 100644 --- a/webrtc-jni/src/main/cpp/include/api/VideoFrame.h +++ b/webrtc-jni/src/main/cpp/include/api/VideoFrame.h @@ -48,7 +48,11 @@ namespace jni namespace I420Buffer { - JavaLocalRef toJava(JNIEnv * env, const webrtc::scoped_refptr & buffer); + // Wraps the pixels of the buffer in a NativeI420Buffer without + // copying them. With readOnly its planes are read-only byte buffers, + // for pixels that others share. + JavaLocalRef toJava(JNIEnv * env, const webrtc::scoped_refptr & buffer, + bool readOnly = false); } class JavaVideoFrameClass : public JavaClass @@ -96,6 +100,7 @@ namespace jni jfieldID strideV; jfieldID width; jfieldID height; + jmethodID asReadOnlyBuffer; }; } diff --git a/webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h b/webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h index a224d21b6..96f13fdbc 100644 --- a/webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h +++ b/webrtc-jni/src/main/cpp/include/api/VideoTrackSink.h @@ -31,7 +31,9 @@ namespace jni class VideoTrackSink : public webrtc::VideoSinkInterface { public: - VideoTrackSink(JNIEnv * env, const JavaGlobalRef & sink); + // A shared sink gets the pixels of the frames themselves, read-only, + // and any other a copy of its own. + VideoTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool shared); ~VideoTrackSink() = default; // VideoSinkInterface implementation. @@ -49,6 +51,8 @@ namespace jni private: JavaGlobalRef sink; + const bool shared; + const std::shared_ptr javaClass; const std::shared_ptr javaFrameClass; const std::shared_ptr javaBufferClass; diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp index 55c44f2db..863f0c06c 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp @@ -82,7 +82,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoS jni::VideoCaptureBase * videoSource = GetHandle(env, caller); CHECK_HANDLE(videoSource); - videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink))); + videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink), false)); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp index cfc2bf305..d253b6dbc 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp @@ -22,7 +22,7 @@ #include "api/media_stream_interface.h" JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInternal -(JNIEnv * env, jobject caller, jobject jsink) +(JNIEnv * env, jobject caller, jobject jsink, jboolean shared) { try { if (jsink == nullptr) { @@ -33,7 +33,7 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInt webrtc::VideoTrackInterface * track = GetHandle(env, caller); CHECK_HANDLEV(track, 0); - auto sink = new jni::VideoTrackSink(env, jni::JavaGlobalRef(env, jsink)); + auto sink = new jni::VideoTrackSink(env, jni::JavaGlobalRef(env, jsink), shared == JNI_TRUE); track->AddOrUpdateSink(sink, webrtc::VideoSinkWants()); diff --git a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp index 3c05323e7..21748f4f0 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp @@ -46,6 +46,15 @@ namespace jni return plane; } + // A read-only view of a plane, or throws. + JavaLocalRef ReadOnlyPlane(JNIEnv * env, jmethodID asReadOnlyBuffer, const JavaLocalRef & plane) + { + JavaLocalRef view(env, env->CallObjectMethod(plane, asReadOnlyBuffer)); + ExceptionCheck(env); + + return view; + } + // Throws unless the plane holds every byte a copy reads: the last row ends at the width. void CheckPlane(JNIEnv * env, const char * name, const JavaRef & data, jint stride, jint width, jint height) { @@ -193,7 +202,8 @@ namespace jni namespace I420Buffer { - JavaLocalRef toJava(JNIEnv * env, const webrtc::scoped_refptr & buffer) + JavaLocalRef toJava(JNIEnv * env, const webrtc::scoped_refptr & buffer, + bool readOnly) { const auto javaClass = JavaClasses::get(env); @@ -206,6 +216,12 @@ namespace jni JavaLocalRef uBuffer = NewPlane(env, "U", buffer->DataU(), planeSize(buffer->StrideU(), buffer->ChromaWidth(), buffer->ChromaHeight())); JavaLocalRef vBuffer = NewPlane(env, "V", buffer->DataV(), planeSize(buffer->StrideV(), buffer->ChromaWidth(), buffer->ChromaHeight())); + if (readOnly) { + yBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, yBuffer); + uBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, uBuffer); + vBuffer = ReadOnlyPlane(env, javaClass->asReadOnlyBuffer, vBuffer); + } + JavaLocalRef jBuffer(env, env->NewObject(javaClass->cls, javaClass->ctor, buffer->width(), buffer->height(), yBuffer.get(), buffer->StrideY(), uBuffer.get(), buffer->StrideU(), vBuffer.get(), buffer->StrideV())); @@ -269,5 +285,9 @@ namespace jni strideV = GetFieldID(env, cls, "strideV", "I"); width = GetFieldID(env, cls, "width", "I"); height = GetFieldID(env, cls, "height", "I"); + + jclass byteBufferClass = FindClass(env, "java/nio/ByteBuffer"); + + asReadOnlyBuffer = GetMethod(env, byteBufferClass, "asReadOnlyBuffer", "()" BYTE_BUFFER_SIG); } } diff --git a/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp b/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp index 7006d1257..af875009b 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp @@ -25,8 +25,9 @@ namespace jni { - VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef & sink) : + VideoTrackSink::VideoTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool shared) : sink(sink), + shared(shared), javaClass(JavaClasses::get(env)), javaFrameClass(JavaClasses::get(env)), javaBufferClass(JavaClasses::get(env)) @@ -48,22 +49,30 @@ namespace jni return; } - webrtc::scoped_refptr i420BufferCopy = webrtc::I420Buffer::Copy(*i420Buffer); + // The copy keeps sinks from seeing what another one writes into its + // pixels, at the cost of a full copy of each frame for each sink. A + // shared sink gets the pixels the source handed out instead, which it + // can only read, so that sinks and the encoder share one buffer. + webrtc::scoped_refptr javaBuffer = i420Buffer; + + if (!shared) { + javaBuffer = webrtc::I420Buffer::Copy(*i420Buffer); + } jint rotation = static_cast(frame.rotation()); jlong timestamp = frame.timestamp_us() * webrtc::kNumNanosecsPerMicrosec; try { - JavaLocalRef jBuffer = I420Buffer::toJava(env, i420BufferCopy); + JavaLocalRef jBuffer = I420Buffer::toJava(env, javaBuffer, shared); // The reference the Java frame gives up when it is released. - i420BufferCopy->AddRef(); + javaBuffer->AddRef(); JavaLocalRef jFrame(env, env->NewObject(javaFrameClass->cls, javaFrameClass->ctor, jBuffer.get(), rotation, timestamp)); if (jFrame.get() == nullptr) { // No frame got the buffer that would release it. - i420BufferCopy->Release(); + javaBuffer->Release(); ExceptionCheck(env); } else { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoFrameAccess.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoFrameAccess.java new file mode 100644 index 000000000..4db2e558b --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoFrameAccess.java @@ -0,0 +1,51 @@ +/* + * 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.media.video; + +/** + * How the frames of a video track reach a {@link VideoTrackSink}, chosen + * when the sink is added with {@link VideoTrack#addSink(VideoTrackSink, + * VideoFrameAccess)}. + */ +public enum VideoFrameAccess { + + /** + * Each sink gets an I420 copy of each frame of its own, which it may + * write into without the other sinks or the encoder seeing it. This costs + * a full copy of the pixels per frame and sink: at 1080p and 30 frames a + * second, about 89 MiB a second for each sink. + */ + COPY, + + /** + * The sink gets the pixels of the frame that the source handed out, which + * the other shared sinks of the track and the encoder use as well, so + * that no copy is made for it. Its {@link NativeI420Buffer} has read-only + * planes: writing to them throws a {@link java.nio.ReadOnlyBufferException}. + * A sink that wants to change a frame asks for a copy with {@link + * VideoFrame#copy()}. + *

+ * A source whose frames are not in I420, such as one with NV12 frames + * from a hardware decoder, has them converted for each sink still. + *

+ * The frames may come from a pool of the decoder or capturer, which runs + * dry while the sinks hold on to them. A sink that keeps a frame beyond a + * frame interval or so should keep a copy and release the frame. + */ + SHARED + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java index 492d7f600..6ad22e4c0 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoTrack.java @@ -56,22 +56,42 @@ public void dispose() { super.dispose(); } + /** + * Adds a VideoSink to the track, which gets a copy of each frame of its + * own, as with {@link VideoFrameAccess#COPY}. A track can have any number + * of VideoSinks. + * + * @param sink The video sink to add. Adding it again does nothing. + * + * @throws IllegalStateException if the track has been disposed. + * + * @see #addSink(VideoTrackSink, VideoFrameAccess) + */ + public void addSink(VideoTrackSink sink) { + addSink(sink, VideoFrameAccess.COPY); + } + /** * Adds a VideoSink to the track. A track can have any number of * VideoSinks. Called from within the callback of a sink, it returns * before the sink is registered, and the sink gets the frames that follow * once it is. * - * @param sink The video sink to add. Adding it again does nothing. + * @param sink The video sink to add. Adding it again does nothing, + * whatever the access. + * @param access Whether the sink gets a writable copy of each frame or + * the read-only pixels the source handed out. * * @throws IllegalStateException if the track has been disposed. */ - public void addSink(VideoTrackSink sink) { - if (isNull(sink)) { + public void addSink(VideoTrackSink sink, VideoFrameAccess access) { + if (isNull(sink) || isNull(access)) { throw new NullPointerException(); } - sinks.add(sink, (s, registration) -> addSinkInternal(new Delivery(s, registration))); + boolean shared = access == VideoFrameAccess.SHARED; + + sinks.add(sink, (s, registration) -> addSinkInternal(new Delivery(s, registration), shared)); } /** @@ -88,7 +108,7 @@ public void removeSink(VideoTrackSink sink) { sinks.remove(sink); } - private native long addSinkInternal(VideoTrackSink sink); + private native long addSinkInternal(VideoTrackSink sink, boolean shared); private native void removeSinkInternal(long sinkHandle); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java index ac6127c68..74588377a 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoTrackTests.java @@ -21,7 +21,11 @@ import dev.onvoid.webrtc.TestBase; import dev.onvoid.webrtc.internal.SinkRegistry; +import java.nio.ByteBuffer; +import java.nio.ReadOnlyBufferException; import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -187,6 +191,68 @@ void disposeInCallbackFails() { source.dispose(); } + @Test + void addSinkWithoutAccess() { + assertThrows(NullPointerException.class, () -> videoTrack.addSink(frame -> { }, null)); + } + + @Test + void sharedSinksShareThePixels() { + CustomVideoSource source = new CustomVideoSource(); + VideoTrack track = factory.createVideoTrack("shared", source); + List shared = new CopyOnWriteArrayList<>(); + List copied = new CopyOnWriteArrayList<>(); + + track.addSink(shared::add, VideoFrameAccess.SHARED); + track.addSink(shared::add, VideoFrameAccess.SHARED); + track.addSink(copied::add); + + NativeI420Buffer pushed = NativeI420Buffer.allocate(320, 240); + pushed.getDataY().put(0, (byte) 1); + + VideoFrame frame = new VideoFrame(pushed, 0); + source.pushFrame(frame); + + assertEquals(2, shared.size()); + assertEquals(1, copied.size()); + + // The pixels of the source change under the shared sinks, which got + // them without a copy, and not under the copy. + pushed.getDataY().put(0, (byte) 7); + + for (VideoFrame sharedFrame : shared) { + ByteBuffer y = dataY(sharedFrame); + + assertTrue(y.isReadOnly()); + assertEquals(7, y.get(0)); + assertThrows(ReadOnlyBufferException.class, () -> y.put(0, (byte) 9)); + } + + ByteBuffer copiedY = dataY(copied.get(0)); + + assertFalse(copiedY.isReadOnly()); + assertEquals(1, copiedY.get(0)); + + // A sink that wants to write asks for a copy. + VideoFrame writable = shared.get(0).copy(); + dataY(writable).put(0, (byte) 9); + + assertEquals(9, dataY(writable).get(0)); + assertEquals(7, dataY(shared.get(1)).get(0)); + + writable.release(); + shared.forEach(VideoFrame::release); + copied.forEach(VideoFrame::release); + frame.release(); + + track.dispose(); + source.dispose(); + } + + private static ByteBuffer dataY(VideoFrame frame) { + return ((I420Buffer) frame.buffer).getDataY(); + } + private static void pushFrame(CustomVideoSource source) { VideoFrame frame = new VideoFrame(NativeI420Buffer.allocate(320, 240), 0);