Skip to content

Commit fa5322f

Browse files
committed
fix: settle and release recorder sources of the client API
EncodedFrames futures fail at once when the runtime stopped or the control executor rejects the task. A source owns its native reference until the recorder takes it; a recorder that gives up cancels and closes late sources.
1 parent a059f8d commit fa5322f

10 files changed

Lines changed: 338 additions & 51 deletions

File tree

‎webrtc-java-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorder.java‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -316,30 +316,42 @@ public void close() {
316316

317317
/** Called with the lock held, in the idle state. */
318318
private void addTrack(EncodedFrames.Source source) {
319-
addTrack(source.frames(), source::requestKeyFrame);
319+
addTrack(source.take(), source::requestKeyFrame);
320320
}
321321

322322
/**
323323
* Waits for the client API's peer to hand over the encoded frames. Its
324324
* control thread never takes this recorder's lock, so waiting under it
325325
* cannot deadlock.
326326
*/
327-
private static EncodedFrames.Source sourceOf(CompletableFuture<EncodedFrames.Source> future) {
327+
static EncodedFrames.Source sourceOf(CompletableFuture<EncodedFrames.Source> future) {
328328
try {
329329
return future.get(10, TimeUnit.SECONDS);
330330
}
331331
catch (InterruptedException e) {
332+
giveUp(future);
332333
Thread.currentThread().interrupt();
333334
throw new IllegalStateException("Interrupted while adding the track", e);
334335
}
335336
catch (ExecutionException e) {
336337
throw new IllegalArgumentException(e.getCause().getMessage(), e.getCause());
337338
}
338339
catch (TimeoutException e) {
340+
giveUp(future);
339341
throw new IllegalStateException("The peer did not hand over the track in time", e);
340342
}
341343
}
342344

345+
/**
346+
* Stops waiting for a source. The peer closes one that comes after the
347+
* cancellation; this closes one that came before it, since no recorder
348+
* takes it over.
349+
*/
350+
static void giveUp(CompletableFuture<EncodedFrames.Source> future) {
351+
future.cancel(false);
352+
future.thenAccept(EncodedFrames.Source::close);
353+
}
354+
343355
private void addTrack(long frames, Runnable keyFrameRequest) {
344356
if (frames == 0) {
345357
throw new IllegalArgumentException("The sender or receiver was disposed");

‎webrtc-java-media/src/test/java/dev/onvoid/webrtc/media/recorder/ClientApiRecorderTest.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
import dev.onvoid.webrtc.client.Signaling;
4444
import dev.onvoid.webrtc.client.SignalingPair;
4545
import dev.onvoid.webrtc.client.WebRtc;
46+
import dev.onvoid.webrtc.client.internal.EncodedFrames;
4647
import dev.onvoid.webrtc.media.player.MediaInfo;
4748
import dev.onvoid.webrtc.media.player.MediaReader;
4849
import dev.onvoid.webrtc.media.video.NativeI420Buffer;
@@ -210,6 +211,31 @@ void removedSenderRefused() throws Exception {
210211
}
211212
}
212213

214+
@Test
215+
void interruptedWaitCancels() {
216+
// The peer has not handed the source over yet; once it does, it finds
217+
// the future cancelled and closes the source itself.
218+
CompletableFuture<EncodedFrames.Source> pending = new CompletableFuture<>();
219+
220+
Thread.currentThread().interrupt();
221+
222+
assertThrows(IllegalStateException.class, () -> MediaRecorder.sourceOf(pending));
223+
assertTrue(Thread.interrupted());
224+
assertTrue(pending.isCancelled());
225+
}
226+
227+
@Test
228+
void sourceBeforeGivingUpClosed() throws Exception {
229+
// The source arrived just as the recorder stopped waiting, so no
230+
// recorder takes it over, and giving up drops its reference.
231+
CompletableFuture<EncodedFrames.Source> frames = EncodedFrames.of(videoSender);
232+
EncodedFrames.Source source = frames.get(10, TimeUnit.SECONDS);
233+
234+
MediaRecorder.giveUp(frames);
235+
236+
assertThrows(IllegalStateException.class, source::take);
237+
}
238+
213239
private interface Tracks {
214240

215241
void addTo(MediaRecorder recorder);

‎webrtc-jni/src/main/cpp/include/JNI_NativeApi.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ extern "C" {
5454
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_receiverFrames
5555
(JNIEnv *, jclass, jlong);
5656

57+
/*
58+
* Class: dev_onvoid_webrtc_internal_NativeApi
59+
* Method: releaseFrames
60+
* Signature: (J)V
61+
*/
62+
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseFrames
63+
(JNIEnv *, jclass, jlong);
64+
5765
#ifdef __cplusplus
5866
}
5967
#endif

‎webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,9 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_receiverFrames
5656

5757
return receiver != nullptr ? Retained(jni::EncodedFrameTransformer::Of(receiver)) : 0;
5858
}
59+
60+
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseFrames
61+
(JNIEnv * env, jclass caller, jlong frames)
62+
{
63+
jni::GetExtensionApi()->encoded_frames_release(reinterpret_cast<void *>(frames));
64+
}

‎webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,44 @@ <T> CompletableFuture<T> toPublic(CompletableFuture<T> internal) {
576576
return result;
577577
}
578578

579+
/**
580+
* Hands a native extension a source of encoded frames, taken on the
581+
* control executor. The future fails once the runtime has stopped the
582+
* threads that would take it, and a source that comes too late for the
583+
* future, which the caller cancelled meanwhile, is closed rather than
584+
* left with its reference.
585+
*
586+
* @param take takes the source, or throws why it cannot.
587+
*/
588+
CompletableFuture<EncodedFrames.Source> encodedFrames(Supplier<EncodedFrames.Source> take) {
589+
CompletableFuture<EncodedFrames.Source> result = new CompletableFuture<>();
590+
591+
rtc.track(result, null);
592+
593+
control.execute(() -> {
594+
if (result.isDone()) {
595+
// The caller stopped waiting before this ran.
596+
return;
597+
}
598+
599+
try {
600+
EncodedFrames.Source source = take.get();
601+
602+
if (!result.complete(source)) {
603+
source.close();
604+
}
605+
}
606+
catch (Throwable e) {
607+
result.completeExceptionally(e);
608+
}
609+
}, () -> {
610+
// A runtime that stopped its threads dropped the task.
611+
result.completeExceptionally(closedError());
612+
});
613+
614+
return result;
615+
}
616+
579617
void deliverError(WebRtcException error) {
580618
events.execute(() -> {
581619
if (errorHandlers.isEmpty()) {

‎webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteTrackImpl.java‎

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -157,32 +157,23 @@ void onControl(Runnable change) {
157157
* too.
158158
*/
159159
CompletableFuture<EncodedFrames.Source> encodedFrames() {
160-
CompletableFuture<EncodedFrames.Source> result = new CompletableFuture<>();
160+
return peer.encodedFrames(() -> {
161+
if (ended) {
162+
throw new IllegalStateException("The track " + id + " ended");
163+
}
161164

162-
peer.control.execute(() -> {
163-
try {
164-
if (ended) {
165-
throw new IllegalStateException("The track " + id + " ended");
166-
}
165+
long frames = NativeApi.encodedFramesOf(receiver);
167166

168-
long frames = NativeApi.encodedFramesOf(receiver);
167+
if (frames == 0) {
168+
throw new IllegalStateException("The track " + id + " ended");
169+
}
169170

170-
if (frames == 0) {
171-
throw new IllegalStateException("The track " + id + " ended");
171+
return new EncodedFrames.Source(frames, () -> onControl(() -> {
172+
if (kind == MediaKind.VIDEO) {
173+
receiver.requestKeyFrame();
172174
}
173-
174-
result.complete(new EncodedFrames.Source(frames, () -> onControl(() -> {
175-
if (kind == MediaKind.VIDEO) {
176-
receiver.requestKeyFrame();
177-
}
178-
})));
179-
}
180-
catch (Throwable e) {
181-
result.completeExceptionally(e);
182-
}
175+
}));
183176
});
184-
185-
return result;
186177
}
187178

188179
/** Detaches everything from the native track, on the control executor. */

‎webrtc/src/main/java/dev/onvoid/webrtc/client/SenderImpl.java‎

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -314,30 +314,21 @@ CompletableFuture<Void> trackReplaced(LocalTrackImpl replacedIn) {
314314
* peer's control executor, where key frames are asked for too.
315315
*/
316316
CompletableFuture<EncodedFrames.Source> encodedFrames() {
317-
CompletableFuture<EncodedFrames.Source> result = new CompletableFuture<>();
317+
return peer.encodedFrames(() -> {
318+
checkUsable();
318319

319-
peer.control.execute(() -> {
320-
try {
321-
checkUsable();
320+
long frames = NativeApi.encodedFramesOf(sender);
322321

323-
long frames = NativeApi.encodedFramesOf(sender);
322+
if (frames == 0) {
323+
throw new IllegalStateException("The sender was removed");
324+
}
324325

325-
if (frames == 0) {
326-
throw new IllegalStateException("The sender was removed");
326+
return new EncodedFrames.Source(frames, () -> peer.control.execute(() -> {
327+
if (kind == MediaKind.VIDEO && !removed && sender != null && !peer.isClosed()) {
328+
sender.generateKeyFrame();
327329
}
328-
329-
result.complete(new EncodedFrames.Source(frames, () -> peer.control.execute(() -> {
330-
if (kind == MediaKind.VIDEO && !removed && sender != null && !peer.isClosed()) {
331-
sender.generateKeyFrame();
332-
}
333-
})));
334-
}
335-
catch (Throwable e) {
336-
result.completeExceptionally(e);
337-
}
330+
}));
338331
});
339-
340-
return result;
341332
}
342333

343334
/**

‎webrtc/src/main/java/dev/onvoid/webrtc/client/internal/EncodedFrames.java‎

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919
import static java.util.Objects.requireNonNull;
2020

2121
import java.util.concurrent.CompletableFuture;
22+
import java.util.concurrent.atomic.AtomicLong;
2223

2324
import dev.onvoid.webrtc.client.RemoteTrack;
2425
import dev.onvoid.webrtc.client.Sender;
26+
import dev.onvoid.webrtc.internal.NativeApi;
2527

2628
/**
2729
* Lets a native extension, such as the media module's recorder, observe the
@@ -32,6 +34,11 @@
3234
* them on the control executor of their peer. What this hands out keeps to
3335
* that: the handle is taken there, and key frames are asked for there, once
3436
* the sender or receiver is gone not at all.
37+
* <p>
38+
* The futures of {@link #of(Sender)} and {@link #of(RemoteTrack)} complete
39+
* in any case, failed once the peer or its runtime is closed. A caller that
40+
* stops waiting cancels the future and closes a source that completes it all
41+
* the same, see {@link Source}.
3542
*/
3643
public final class EncodedFrames {
3744

@@ -55,31 +62,54 @@ public interface Access {
5562
}
5663

5764
/**
58-
* Where a sender's or receiver's encoded frames come from.
65+
* Where a sender's or receiver's encoded frames come from. It owns the
66+
* reference of its handle until {@link #take()} hands it over; closing it
67+
* before drops the reference, closing it after does nothing. Whoever gets
68+
* a source does one or the other, so that no reference is left behind.
5969
*/
60-
public static final class Source {
70+
public static final class Source implements AutoCloseable {
6171

62-
private final long frames;
72+
/** The handle, or 0 once taken or released. */
73+
private final AtomicLong frames;
6374

6475
private final Runnable keyFrameRequest;
6576

6677

6778
/**
6879
* @param frames the handle of {@code NativeApi.encodedFramesOf},
69-
* whose reference the receiver of this source
70-
* drops.
80+
* whose reference this source takes over.
7181
* @param keyFrameRequest asks for a key frame, from any thread.
7282
*/
7383
public Source(long frames, Runnable keyFrameRequest) {
74-
this.frames = frames;
84+
this.frames = new AtomicLong(frames);
7585
this.keyFrameRequest = requireNonNull(keyFrameRequest, "keyFrameRequest");
7686
}
7787

7888
/**
79-
* @return the handle of the encoded frames, with a reference to drop.
89+
* Hands over the handle together with its reference, which the caller
90+
* drops from then on.
91+
*
92+
* @return the handle of the encoded frames.
93+
*
94+
* @throws IllegalStateException if it was taken or released before.
95+
*/
96+
public long take() {
97+
long handle = frames.getAndSet(0);
98+
99+
if (handle == 0) {
100+
throw new IllegalStateException("The encoded frames were taken or released");
101+
}
102+
103+
return handle;
104+
}
105+
106+
/**
107+
* Drops the reference of the handle, unless {@link #take()} handed it
108+
* over. Closing it again does nothing.
80109
*/
81-
public long frames() {
82-
return frames;
110+
@Override
111+
public void close() {
112+
NativeApi.releaseEncodedFrames(frames.getAndSet(0));
83113
}
84114

85115
/**

‎webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeApi.java‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,24 @@ public static long encodedFramesOf(RTCRtpReceiver receiver) {
128128
return receiverFrames(handleOf(receiver));
129129
}
130130

131+
/**
132+
* Drops the reference a handle of {@link #encodedFramesOf(RTCRtpSender)}
133+
* or {@link #encodedFramesOf(RTCRtpReceiver)} carries, as {@code
134+
* encoded_frames_release()} does, for a handle that never reaches native
135+
* code. The handle must not be used afterwards.
136+
*
137+
* @param frames The handle, or {@code 0}, which is ignored.
138+
*/
139+
public static void releaseEncodedFrames(long frames) {
140+
if (frames != 0) {
141+
releaseFrames(frames);
142+
}
143+
}
144+
131145
private static native long senderFrames(long senderHandle);
132146

133147
private static native long receiverFrames(long receiverHandle);
134148

149+
private static native void releaseFrames(long frames);
150+
135151
}

0 commit comments

Comments
 (0)