diff --git a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp index e5e181e3d..3c05323e7 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp @@ -31,6 +31,21 @@ namespace jni { namespace { + // A direct buffer over a plane, or throws: the allocation may fail, with or without an exception pending. + JavaLocalRef NewPlane(JNIEnv * env, const char * name, const uint8_t * data, jlong size) + { + JavaLocalRef plane(env, env->NewDirectByteBuffer(const_cast(data), size)); + + if (plane.get() == nullptr) { + ExceptionCheck(env); + + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The %s plane could not be wrapped in a direct buffer", name))); + } + + return plane; + } + // 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) { @@ -187,20 +202,26 @@ namespace jni return static_cast(stride) * (height - 1) + width; }; - jobject yBuffer = env->NewDirectByteBuffer(const_cast(buffer->DataY()), planeSize(buffer->StrideY(), buffer->width(), buffer->height())); - jobject uBuffer = env->NewDirectByteBuffer(const_cast(buffer->DataU()), planeSize(buffer->StrideU(), buffer->ChromaWidth(), buffer->ChromaHeight())); - jobject vBuffer = env->NewDirectByteBuffer(const_cast(buffer->DataV()), planeSize(buffer->StrideV(), buffer->ChromaWidth(), buffer->ChromaHeight())); + JavaLocalRef yBuffer = NewPlane(env, "Y", buffer->DataY(), planeSize(buffer->StrideY(), buffer->width(), buffer->height())); + 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())); - jobject jBuffer = env->NewObject(javaClass->cls, javaClass->ctor, buffer->width(), buffer->height(), - yBuffer, buffer->StrideY(), uBuffer, buffer->StrideU(), vBuffer, buffer->StrideV()); + 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())); - SetHandle(env, jBuffer, buffer.get()); + if (jBuffer.get() == nullptr) { + ExceptionCheck(env); - env->DeleteLocalRef(yBuffer); - env->DeleteLocalRef(uBuffer); - env->DeleteLocalRef(vBuffer); + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The I420 buffer could not be created"))); + } + + // Last, once nothing can fail: the caller hands the wrapper its + // reference only when it gets the wrapper back. + SetHandle(env, jBuffer.get(), buffer.get()); + ExceptionCheck(env); - return JavaLocalRef(env, jBuffer); + return jBuffer; } } diff --git a/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp b/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp index c6b41ce68..7006d1257 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoTrackSink.cpp @@ -49,16 +49,24 @@ namespace jni } webrtc::scoped_refptr i420BufferCopy = webrtc::I420Buffer::Copy(*i420Buffer); - i420BufferCopy->AddRef(); jint rotation = static_cast(frame.rotation()); jlong timestamp = frame.timestamp_us() * webrtc::kNumNanosecsPerMicrosec; try { JavaLocalRef jBuffer = I420Buffer::toJava(env, i420BufferCopy); + + // The reference the Java frame gives up when it is released. + i420BufferCopy->AddRef(); + JavaLocalRef jFrame(env, env->NewObject(javaFrameClass->cls, javaFrameClass->ctor, jBuffer.get(), rotation, timestamp)); - if (jFrame.get() != nullptr) { + if (jFrame.get() == nullptr) { + // No frame got the buffer that would release it. + i420BufferCopy->Release(); + ExceptionCheck(env); + } + else { env->CallVoidMethod(sink, javaClass->onFrame, jFrame.get()); } } diff --git a/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCaptureCallback.cpp b/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCaptureCallback.cpp index ea0931c31..d54a27b87 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCaptureCallback.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopCaptureCallback.cpp @@ -117,14 +117,22 @@ namespace jni jlong timestamp = webrtc::TimeMicros() * webrtc::kNumNanosecsPerMicrosec; webrtc::scoped_refptr i420BufferCopy = webrtc::I420Buffer::Copy(*i420Buffer); - i420BufferCopy->AddRef(); try { auto jresult = JavaEnums::toJava(env, result); JavaLocalRef jBuffer = I420Buffer::toJava(env, i420BufferCopy); + + // The reference the Java frame gives up when it is released. + i420BufferCopy->AddRef(); + JavaLocalRef jFrame(env, env->NewObject(javaFrameClass->cls, javaFrameClass->ctor, jBuffer.get(), rotation, timestamp)); - if (jFrame.get() != nullptr) { + if (jFrame.get() == nullptr) { + // No frame got the buffer that would release it. + i420BufferCopy->Release(); + ExceptionCheck(env); + } + else { env->CallVoidMethod(callback, javaClass->onCaptureResult, jresult.get(), jFrame.get()); } } diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java index 83e4cca4a..3fd968200 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java @@ -20,6 +20,7 @@ import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; import dev.onvoid.webrtc.media.audio.CustomAudioSource; import dev.onvoid.webrtc.media.video.CustomVideoSource; @@ -158,26 +159,46 @@ public MediaFileSource(String source, Duration timeout) throws IOException { * @throws IOException if the source cannot be opened in time, or decoded. */ public MediaFileSource(String source, Duration timeout, boolean hardwareDecoding) throws IOException { - MediaReader reader = new MediaReader(source, timeout); - - // Read while the reader is still ours: the player takes it over. - info = reader.getInfo(); + this(new MediaReader(source, timeout), CustomVideoSource::new, CustomAudioSource::new, + hardwareDecoding); + } - videoSource = info.hasVideo() ? new CustomVideoSource() : null; - audioSource = info.hasAudio() ? new CustomAudioSource() : null; + /** + * Builds on a reader that is open, which this source takes over whether + * or not it is made. The suppliers make the media sources, which tests + * fail on purpose. + */ + MediaFileSource(MediaReader reader, Supplier videoSources, + Supplier audioSources, boolean hardwareDecoding) throws IOException { + MediaInfo readerInfo; + CustomVideoSource video = null; + CustomAudioSource audio = null; + MediaPlayer created; try { - player = new MediaPlayer(reader, videoSource, audioSource, hardwareDecoding); - } - catch (IOException | RuntimeException | Error e) { - // The player did not take charge, so what was made here has to be - // unwound rather than left to leak. - disposeSources(); + // Read while the reader is still ours: the player takes it over. + readerInfo = reader.getInfo(); - reader.close(); + video = readerInfo.hasVideo() ? videoSources.get() : null; + audio = readerInfo.hasAudio() ? audioSources.get() : null; + + created = new MediaPlayer(reader, video, audio, hardwareDecoding); + } + catch (Throwable e) { + // Nothing was taken over by a player, so whatever was made here, + // the reader with its open file included, is released rather than + // left to leak. Closing a reader a player took over does nothing. + release(e, video != null ? video::dispose : null); + release(e, audio != null ? audio::dispose : null); + release(e, reader::close); throw e; } + + info = readerInfo; + videoSource = video; + audioSource = audio; + player = created; } /** @@ -314,4 +335,21 @@ private void disposeSources() { } } + /** + * Releases something made before the error, which a failing release only + * adds to. + */ + private static void release(Throwable error, Runnable release) { + if (release == null) { + return; + } + + try { + release.run(); + } + catch (Throwable e) { + error.addSuppressed(e); + } + } + } diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java index 375aa6e97..640dc79ca 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java @@ -139,6 +139,13 @@ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, throw new IllegalArgumentException("A player needs at least one media source"); } + // Before the reader is taken over: should these fail, such as when the + // library of the sources cannot be loaded, the caller still has the + // reader to close. + long tableAddress = NativeApi.tableAddress(); + long videoSourceHandle = videoSource != null ? NativeApi.handleOf(videoSource) : 0; + long audioSourceHandle = audioSource != null ? NativeApi.handleOf(audioSource) : 0; + // Taking the reader over rather than sharing it: the native player // owns it from here, and a Java reader that still held the same // pointer would release it a second time. @@ -148,9 +155,7 @@ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, throw new IOException("The reader is closed"); } - handle = create(readerHandle, NativeApi.tableAddress(), - videoSource != null ? NativeApi.handleOf(videoSource) : 0, - audioSource != null ? NativeApi.handleOf(audioSource) : 0, + handle = create(readerHandle, tableAddress, videoSourceHandle, audioSourceHandle, hardwareDecoding); } diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaFileSourceTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaFileSourceTest.java index bf4eb72c0..685051eb2 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaFileSourceTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaFileSourceTest.java @@ -36,6 +36,7 @@ import dev.onvoid.webrtc.media.audio.AudioLayer; import dev.onvoid.webrtc.media.audio.AudioTrack; import dev.onvoid.webrtc.media.audio.AudioTrackSink; +import dev.onvoid.webrtc.media.video.CustomVideoSource; import dev.onvoid.webrtc.media.video.VideoTrack; import dev.onvoid.webrtc.media.video.VideoTrackSink; @@ -133,6 +134,32 @@ void missingFileFails() { assertThrows(IOException.class, () -> new MediaFileSource(Paths.get("no-such-file.webm"))); } + @Test + void failedSetupReleasesReader() throws Exception { + // As when the library of the sources cannot be loaded: the video + // source was made, the audio source fails, and no player was made. + MediaReader reader = new MediaReader(asset()); + AtomicInteger disposed = new AtomicInteger(); + + assertThrows(UnsatisfiedLinkError.class, () -> new MediaFileSource(reader, + () -> new CustomVideoSource() { + + @Override + public void dispose() { + disposed.incrementAndGet(); + super.dispose(); + } + }, + () -> { + throw new UnsatisfiedLinkError("no library"); + }, + false)); + + // Closed, which releases the file it had open. + assertThrows(IllegalStateException.class, reader::getInfo); + assertEquals(1, disposed.get()); + } + @Test void closesTwice() throws Exception { MediaFileSource source = new MediaFileSource(asset()); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java index 9aca15673..5c1135953 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtlsTransport.java @@ -130,9 +130,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java index 2eb92c21f..7c8cd3fc9 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCDtmfSender.java @@ -196,9 +196,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java index 1742300ec..12c48aa3b 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCPeerConnection.java @@ -536,9 +536,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } private native RTCRtpSender addTrackInternal(MediaStreamTrack track, diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java index c6b346e66..b8aaa107c 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpReceiver.java @@ -181,9 +181,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java index 604785032..80fb08a55 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpSender.java @@ -285,9 +285,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpTransceiver.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpTransceiver.java index c2ddf01ac..80ac96a7d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpTransceiver.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCRtpTransceiver.java @@ -185,9 +185,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - long handle = getNativeHandle(); - - return handle == 0 ? System.identityHashCode(this) : Long.hashCode(handle); + return nativeHashCode(); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java index d39cd5bfb..1a5bf67e0 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/DataChannelImpl.java @@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; +import java.util.function.Supplier; import dev.onvoid.webrtc.RTCDataChannel; import dev.onvoid.webrtc.RTCDataChannelBuffer; @@ -164,24 +165,37 @@ public CompletableFuture whenOpen() { public CompletableFuture send(String text) { requireNonNull(text, "text"); - return enqueue(text.getBytes(StandardCharsets.UTF_8), false); + // UTF-8 takes at least a byte for each char, so a text that cannot + // fit is refused before it is encoded. + long waiting = held.get(); + + if (waiting + text.length() > sendLimit) { + return full(waiting, "at least " + text.length()); + } + + byte[] encoded = text.getBytes(StandardCharsets.UTF_8); + + return enqueue(encoded.length, false, () -> encoded); } @Override public CompletableFuture send(byte[] data) { requireNonNull(data, "data"); - return enqueue(data.clone(), true); + return enqueue(data.length, true, data::clone); } @Override public CompletableFuture send(ByteBuffer data) { requireNonNull(data, "data"); - byte[] copy = new byte[data.remaining()]; - data.duplicate().get(copy); + int size = data.remaining(); - return enqueue(copy, true); + return enqueue(size, true, () -> { + byte[] copy = new byte[size]; + data.duplicate().get(copy); + return copy; + }); } @Override @@ -281,32 +295,53 @@ void closeFromPeer(WebRtcException error) { () -> settleOpened(ChannelState.CLOSED, error)); } - private CompletableFuture enqueue(byte[] data, boolean binary) { - long size = data.length; + /** + * Takes the size out of the send limit, and only then makes the copy that + * waits: a message too large for the limit is refused without the memory + * of a copy. A copy that fails gives its share back. + */ + private CompletableFuture enqueue(long size, boolean binary, Supplier copy) { long before = held.getAndUpdate(amount -> amount + size <= sendLimit ? amount + size : amount); if (before + size > sendLimit) { - return peer.toPublic(ClientFuture.failed(new ChannelFullException("The data channel " + label - + " holds " + before + " bytes waiting to be sent, and " + size + " more would exceed " - + "its limit of " + sendLimit))); + return full(before, Long.toString(size)); + } + + byte[] data; + + try { + data = copy.get(); + } + catch (Throwable e) { + held.addAndGet(-size); + throw e; } CompletableFuture sent = new CompletableFuture<>(); + Runnable closed = () -> { + held.addAndGet(-size); + sent.completeExceptionally(new PeerClosedException("The data channel " + label + " is closed")); + }; peer.control.execute(() -> { if (released || state == ChannelState.CLOSING || state == ChannelState.CLOSED) { - held.addAndGet(-data.length); - sent.completeExceptionally(new PeerClosedException("The data channel " + label + " is closed")); + closed.run(); return; } pending.add(new Pending(data, binary, sent)); pump(); - }); + }, closed); return peer.toPublic(sent); } + private CompletableFuture full(long waiting, String size) { + return peer.toPublic(ClientFuture.failed(new ChannelFullException("The data channel " + label + + " holds " + waiting + " bytes waiting to be sent, and " + size + " more would exceed " + + "its limit of " + sendLimit))); + } + /** Hands waiting messages to the transport while it has room. */ private void pump() { if (released || channel == null || state != ChannelState.OPEN) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Dispatcher.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Dispatcher.java index 9e4bae339..30c02af73 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Dispatcher.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Dispatcher.java @@ -46,6 +46,8 @@ abstract class Dispatcher { private final Runnable next = this::handleNext; + private final Runnable dropped = this::dropWaiting; + private final Workload.Backlog backlog = this::count; private long queuedWeight; @@ -115,7 +117,7 @@ final void offer(T item) { } if (schedule) { - executor.execute(next); + executor.execute(next, dropped); } } @@ -180,7 +182,29 @@ private void handleNext() { if (more) { // Behind what else the executor has, which ends its turn on the // pool once the turn has run long enough. - executor.execute(next); + executor.execute(next, dropped); + } + } + + /** + * Runs instead of the next item when the executor rejects the task: lets + * go of what waits, counted as dropped, and leaves nothing scheduled, so + * that the next item offered tries the executor again. + */ + private void dropWaiting() { + synchronized (queue) { + if (!queue.isEmpty()) { + workload.dropped(queue.size()); + workload.idle(backlog); + } + + for (Entry entry : queue) { + release(entry.item); + } + + queue.clear(); + queuedWeight = 0; + scheduled = false; } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java index ec06212bc..3d9aaa42f 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java @@ -34,6 +34,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -189,9 +190,9 @@ private WebRtc(Builder builder) { : Executors.newCachedThreadPool(threads("webrtc-client-control-" + runtime + "-")); this.framePool = pool(builder.frameThreads, "webrtc-client-frames-" + runtime + "-"); this.timer = builder.timer != null ? builder.timer - : Executors.newSingleThreadScheduledExecutor(threads("webrtc-client-timer-" + runtime + "-")); + : scheduler("webrtc-client-timer-" + runtime + "-"); this.audioPacer = builder.audioPacer != null ? builder.audioPacer - : Executors.newSingleThreadScheduledExecutor(threads("webrtc-client-audio-" + runtime + "-")); + : scheduler("webrtc-client-audio-" + runtime + "-"); this.clock = builder.clock; if (builder.eventExecutor != null) { @@ -678,6 +679,18 @@ private static int poolSize(Executor executor) { return executor instanceof ThreadPoolExecutor ? ((ThreadPoolExecutor) executor).getPoolSize() : 0; } + /** + * A scheduler of one thread that forgets a task once it is cancelled. + * Operations cancel their timeouts as they complete, and without that each + * would stay queued until it was due, for as long as the timeout. + */ + static ScheduledThreadPoolExecutor scheduler(String prefix) { + ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, threads(prefix)); + scheduler.setRemoveOnCancelPolicy(true); + + return scheduler; + } + private static ThreadFactory threads(String prefix) { AtomicInteger count = new AtomicInteger(); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java index 285a70cbf..50de85c01 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeObject.java @@ -16,6 +16,8 @@ package dev.onvoid.webrtc.internal; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + /** * Binds a native object pointer to a Java object extending this class. * @@ -42,6 +44,12 @@ public abstract class NativeObject { @SuppressWarnings("unused") private long nativeHandle; + /** The hash code of {@link #nativeHashCode()}, or 0 until it is asked for. */ + private volatile int nativeHash; + + private static final AtomicIntegerFieldUpdater NATIVE_HASH = + AtomicIntegerFieldUpdater.newUpdater(NativeObject.class, "nativeHash"); + /** * Returns the native pointer bound to this object, so that subclasses @@ -55,4 +63,42 @@ protected final long getNativeHandle() { return nativeHandle; } + /** + * Returns a hash code for subclasses whose {@code equals()} compares + * native handles, which stays the same for the whole life of this + * object, unlike the handle: it is taken from the handle the first time + * it is asked for, and kept after disposal, so that a disposed object + * is still found in the hash set it was added to before. + *

+ * Equal objects share their handle, and so their hash code: a native + * object stays alive, at the same address, while any undisposed wrapper + * of it does, and a disposed wrapper is equal only to itself. A new + * native object at the address of a freed one hashes the same as the + * old wrapper without being equal to it, which costs a collision only. + * + * @return the hash code of this object's native identity. + */ + protected final int nativeHashCode() { + int hash = nativeHash; + + if (hash == 0) { + long handle = nativeHandle; + + hash = handle != 0 ? Long.hashCode(handle) : System.identityHashCode(this); + + // Zero marks a hash code not taken yet. + if (hash == 0) { + hash = 1; + } + + // The first one taken wins, should a disposal on another thread + // race with the first call. + if (!NATIVE_HASH.compareAndSet(this, 0, hash)) { + hash = nativeHash; + } + } + + return hash; + } + } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionTests.java index be9be63af..f60a9f0cb 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCPeerConnectionTests.java @@ -27,7 +27,9 @@ import dev.onvoid.webrtc.media.video.VideoTrack; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -191,6 +193,40 @@ void queriedRefsDisposeIndependently() { assertDoesNotThrow(() -> secondTransceivers[0].dispose()); } + @Test + void hashStableAfterDispose() { + AudioTrackSource audioSource = factory.createAudioSource(new AudioOptions()); + AudioTrack audioTrack = factory.createAudioTrack("audioTrack", audioSource); + + peerConnection.addTrack(audioTrack, List.of("stream-0")); + + RTCRtpSender sender = peerConnection.getSenders()[0]; + RTCRtpReceiver receiver = peerConnection.getReceivers()[0]; + RTCRtpTransceiver transceiver = peerConnection.getTransceivers()[0]; + RTCRtpSender sameSender = peerConnection.getSenders()[0]; + + Set wrappers = new HashSet<>(List.of(sender, receiver, transceiver)); + int senderHash = sender.hashCode(); + + // Another wrapper of the same sender finds it while both are bound. + assertTrue(wrappers.contains(sameSender)); + + sender.dispose(); + receiver.dispose(); + transceiver.dispose(); + + // Hashed as when they were added, so they are still found. + assertEquals(senderHash, sender.hashCode()); + assertTrue(wrappers.contains(sender)); + assertFalse(wrappers.contains(sameSender)); + assertTrue(wrappers.remove(sender)); + assertTrue(wrappers.remove(receiver)); + assertTrue(wrappers.remove(transceiver)); + assertTrue(wrappers.isEmpty()); + + sameSender.dispose(); + } + @Test void removeTrack() { AudioTrackSource audioSource = factory.createAudioSource(new AudioOptions()); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/DispatcherTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/DispatcherTests.java index 83f66670c..75e9d7780 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/DispatcherTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/DispatcherTests.java @@ -17,6 +17,7 @@ package dev.onvoid.webrtc.client; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; @@ -166,6 +167,36 @@ void framesReleased() { assertEquals(0, work.snapshot().queued()); } + @Test + void rejectedFramesReleased() { + List shown = new ArrayList<>(); + CountedBuffer rejected = new CountedBuffer(); + CountedBuffer accepted = new CountedBuffer(); + FrameDispatcher video = new FrameDispatcher(frame -> shown.add((int) frame.timestampNs), + FrameDelivery.queue(2), executor(), work, errors::add); + + pool.rejecting(true); + video.onVideoFrame(new VideoFrame(rejected, 0)); + + // Let go of at once, not only at close. + assertEquals(1, rejected.released); + assertEquals(1, work.snapshot().dropped()); + assertEquals(0, work.snapshot().queued()); + assertEquals(1, errors.size()); + assertInstanceOf(WebRtcException.class, errors.remove(0)); + + // Nothing is left scheduled, so the next frame tries again. + pool.rejecting(false); + video.onVideoFrame(new VideoFrame(accepted, 1)); + pool.runAll(); + + assertEquals(Arrays.asList(1), shown); + assertEquals(1, accepted.released); + assertTrue(errors.isEmpty(), () -> "Errors: " + errors); + + video.close(); + } + private AudioDispatcher audio(Duration buffer, Consumer handler) { return new AudioDispatcher(handler, buffer, executor(), work, errors::add); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/LoadTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/LoadTests.java index 4b466e2c8..99e20418d 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/LoadTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/LoadTests.java @@ -23,9 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; +import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; @@ -56,6 +59,21 @@ void limitsChecked() { assertTrue(e.getMessage().contains("eventExecutor"), e::getMessage); } + @Test + void cancelledTimeoutsDequeued() { + // As an operation that completes long before its timeout is due. + for (ScheduledExecutorService scheduler : Arrays.asList(rtc.timer, rtc.audioPacer)) { + ScheduledThreadPoolExecutor pool = assertInstanceOf(ScheduledThreadPoolExecutor.class, scheduler); + int before = pool.getQueue().size(); + + for (int i = 0; i < 100; i++) { + pool.schedule(() -> { }, 1, TimeUnit.HOURS).cancel(false); + } + + assertEquals(before, pool.getQueue().size()); + } + } + @Test void eventsWaitTheirTurn() throws Exception { replaceRuntime(WebRtc.builder().eventThreads(1)); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java index 3ac42bb9d..6787660fa 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java @@ -23,6 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -569,10 +575,66 @@ void sendBeyondLimitFails() throws Exception { .negotiation(Negotiation.MANUAL) .channelSendLimit(10) .build()); + DataChannel small = other.createChannel("small"); ExecutionException tooLarge = assertThrows(ExecutionException.class, - () -> await(other.createChannel("small").send(new byte[11]))); + () -> await(small.send(new byte[11]))); + ExecutionException tooLong = assertThrows(ExecutionException.class, + () -> await(small.send("x".repeat(11)))); assertInstanceOf(ChannelFullException.class, tooLarge.getCause()); + assertInstanceOf(ChannelFullException.class, tooLong.getCause()); + assertEquals(0, small.bufferedAmount()); + } + + @Test + void oversizedBufferNotCopied() throws Exception { + // A sparse file mapped read-only, whose pages are never touched: a + // copy of its 2 GiB could not even be allocated as a byte array. + Path dir = Files.createTempDirectory("channel-send"); + Path file = dir.resolve("sparse.bin"); + + try { + try (FileChannel writer = FileChannel.open(file, StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, StandardOpenOption.SPARSE)) { + writer.write(ByteBuffer.wrap(new byte[1]), Integer.MAX_VALUE - 1); + } + + ByteBuffer huge; + + try (FileChannel reader = FileChannel.open(file, StandardOpenOption.READ)) { + huge = reader.map(FileChannel.MapMode.READ_ONLY, 0, Integer.MAX_VALUE); + } + + Peer peer = rtc.createPeer(PeerOptions.builder() + .negotiation(Negotiation.MANUAL) + .channelSendLimit(1000) + .build()); + DataChannel channel = peer.createChannel("bounded"); + + ExecutionException full = assertThrows(ExecutionException.class, () -> await(channel.send(huge))); + + assertInstanceOf(ChannelFullException.class, full.getCause()); + assertEquals(0, channel.bufferedAmount()); + + // Nothing of the limit stayed taken. + CompletableFuture fitting = channel.send(new byte[1000]); + + assertEquals(1000, channel.bufferedAmount()); + assertFalse(fitting.isDone()); + + peer.close(); + } + finally { + // Windows keeps a mapped file until the mapping is collected. + try { + Files.deleteIfExists(file); + Files.deleteIfExists(dir); + } + catch (IOException e) { + file.toFile().deleteOnExit(); + dir.toFile().deleteOnExit(); + } + } } private static PeerOptions manualOptions() {