Skip to content

Commit 00c182b

Browse files
committed
fix: keep local track releases independent of handlers and cancelled futures
Ended and device handlers run on an event executor of local media, after the release completed internally. Lifecycle futures are handed out as copies, so cancelling one no longer fails the runtime's close.
1 parent 3a9d903 commit 00c182b

13 files changed

Lines changed: 201 additions & 39 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ Every method of the client API may be called from any thread, including from ins
204204
| Your calls into the API | your thread | They don't block. The exceptions are `WebRtc.createPeer`, which waits briefly for the connection, and `WebRtc.close()`, which waits up to the close timeout. |
205205
| Peer, track and channel handlers, future callbacks, `Signaling.send` | the peer's event thread | Yes, but that delays only the events of this peer. They must not wait for a future of this API, see below. |
206206
| `onFrame` and `onAudio` handlers | a thread of each subscription | Better not. A slow video handler gets the newest frame next, and the frames in between are dropped; a slow audio handler loses the oldest audio beyond its buffer. |
207-
| `LocalTrack.onEnded` and `Devices.onChange` handlers | a background thread of the runtime | Briefly. |
207+
| `LocalTrack.onEnded` and `Devices.onChange` handlers, callbacks of the futures of local tracks and devices | the event thread of the runtime's local media | Yes, but that delays the other events of local media. They must not wait for a future of this API either. A track is released before its `onEnded` handlers run, so they never hold up a release. |
208208
| WebRTC's own callbacks | WebRTC's threads | Not your code. The library only copies what they report and queues it. |
209209

210210
The handlers of one peer never run at the same time, and they run in the order of the events. The handlers of different peers may run at the same time. With the default executor, the event thread is named after its peer, such as `webrtc-client-events-alice`, which shows up in thread dumps.
@@ -329,6 +329,8 @@ peer.onChannel(channel -> {
329329

330330
A future that is already done may be read anywhere, and any thread that is not an event thread, such as `main`, may wait.
331331

332+
Each call returns a future of its own, also of `closeAsync()`, `whenClosed()`, `whenConnected()` and `whenOpen()`. Cancelling one only stops waiting: the close goes on, and the futures of other callers, and of the runtime's own close, are not affected.
333+
332334
::: warning
333335
On Java 8, only the futures the API returns refuse to be waited on. Futures derived from them with `thenApply` and the like do not, so waiting for one of those in a handler hangs that peer. From Java 9 on, the derived futures refuse too.
334336

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,21 @@ static <T> ClientFuture<T> completed(T value) {
4646
return future;
4747
}
4848

49+
/**
50+
* Hands out a future of its own for a future shared by many callers: a
51+
* caller that cancels or completes its copy changes nothing for the
52+
* others, nor for what waits for the shared one.
53+
*
54+
* @param shared the future the copy completes with, on the same thread.
55+
*
56+
* @return a new future.
57+
*/
58+
static <T> ClientFuture<T> copyOf(CompletableFuture<T> shared) {
59+
ClientFuture<T> copy = new ClientFuture<>();
60+
shared.whenComplete((value, error) -> PeerImpl.complete(copy, value, error));
61+
return copy;
62+
}
63+
4964
@Override
5065
public T get() throws InterruptedException, ExecutionException {
5166
checkBlocking();

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ public ChannelState state() {
157157

158158
@Override
159159
public CompletableFuture<DataChannel> whenOpen() {
160-
return opened;
160+
return ClientFuture.copyOf(opened);
161161
}
162162

163163
@Override

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ public interface Devices {
8585
/**
8686
* Calls the handler after a device was connected or disconnected.
8787
*
88-
* @param handler called on a background thread with the new snapshot.
88+
* @param handler called on an event thread of the runtime with the new
89+
* snapshot.
8990
*
9091
* @return the subscription that removes the handler.
9192
*/

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ void dispose() {
164164
private void changed() {
165165
media.executor.execute(() -> {
166166
refresh();
167-
handlers.accept(this);
167+
media.events.execute(() -> handlers.accept(this));
168168
});
169169
}
170170

@@ -247,7 +247,9 @@ private static List<DesktopSource> desktopSources(DesktopCapturer capturer) {
247247
* Runs a switch, which uses the audio module, on the media executor. It
248248
* is registered like the creation of a track, so that a runtime that
249249
* begins to close either waits for it before it frees the module, or is
250-
* seen closing here.
250+
* seen closing here. The future handed out completes on the event
251+
* executor, so that the application's callbacks never hold up the media
252+
* executor.
251253
*/
252254
private <T> CompletableFuture<T> onMediaExecutor(Supplier<T> action) {
253255
CompletableFuture<T> result = new CompletableFuture<>();
@@ -279,6 +281,6 @@ private <T> CompletableFuture<T> onMediaExecutor(Supplier<T> action) {
279281
result.completeExceptionally(new PeerClosedException("The runtime is closed"));
280282
});
281283

282-
return result;
284+
return media.toPublic(result);
283285
}
284286
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ public CompletableFuture<Void> closeAsync() {
113113
.whenComplete((ignored, error) -> closed.complete(null));
114114
}
115115

116-
return closed;
116+
return ClientFuture.copyOf(closed);
117117
}
118118

119119
/**

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,9 @@ public CompletableFuture<Void> switchCamera(VideoDevice device) {
7575
}
7676
});
7777

78-
return switched;
78+
// Completed on the event executor, so that the application's
79+
// callbacks never hold up the media executor.
80+
return media.toPublic(switched);
7981
}
8082

8183
private void switchTo(VideoDevice device) {

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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,16 @@ final class LocalMediaImpl implements LocalMedia {
5050

5151
final WebRtc rtc;
5252

53-
/** Releases tracks and runs their ended handlers, off WebRTC's and the application's threads. */
53+
/** Releases tracks and switches devices, off WebRTC's and the application's threads. */
5454
final SerialExecutor executor;
5555

56+
/**
57+
* Runs the ended and device handlers and completes the futures handed
58+
* out, as a peer's event executor does, so that no application code holds
59+
* up a release.
60+
*/
61+
final SerialExecutor events;
62+
5663
private final AudioDeviceModuleBase audioModule;
5764

5865
private final Set<LocalTrackImpl> tracks = Collections.newSetFromMap(new ConcurrentHashMap<>());
@@ -76,6 +83,8 @@ final class LocalMediaImpl implements LocalMedia {
7683
this.rtc = rtc;
7784
this.audioModule = audioModule;
7885
this.executor = new SerialExecutor(rtc.controlPool, rtc.controlWork, rtc::reportError, false, null);
86+
this.events = new SerialExecutor(rtc.eventExecutor, rtc.eventWork, rtc::reportError, true,
87+
rtc.ownsEventExecutor ? "webrtc-client-events-media" : null);
7988
}
8089

8190
@Override
@@ -310,6 +319,29 @@ List<CompletableFuture<Void>> closeAll() {
310319
return closing;
311320
}
312321

322+
/**
323+
* Hands a future out to the application: it completes on the event
324+
* executor, after the handlers queued before, and cancelling it leaves the
325+
* internal one alone.
326+
*/
327+
<T> CompletableFuture<T> toPublic(CompletableFuture<T> internal) {
328+
ClientFuture<T> result = new ClientFuture<>();
329+
330+
internal.whenComplete((value, error) -> {
331+
Runnable deliver = () -> PeerImpl.complete(result, value, error);
332+
333+
// Completed in any case: should the event executor reject the
334+
// task, on the thread that found it rejected.
335+
events.execute(deliver, deliver);
336+
});
337+
338+
// Tracked after, so that a track released before the runtime stopped
339+
// its threads still reports that, rather than the runtime's close.
340+
rtc.track(result, events);
341+
342+
return result;
343+
}
344+
313345
synchronized void dispose() {
314346
if (devices != null) {
315347
devices.dispose();

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,12 @@ public interface LocalTrack extends AutoCloseable {
4848
void setEnabled(boolean enabled);
4949

5050
/**
51-
* Calls the handler once the track ended. A handler added after that is
52-
* called at once.
51+
* Calls the handler once the track ended and its native track is
52+
* released. A handler added after that is called at once.
5353
*
54-
* @param handler called on a background thread.
54+
* @param handler called on an event thread of the runtime, where waiting
55+
* for a future of this API that is not done throws a
56+
* {@link BlockingCallException}.
5557
*
5658
* @return the subscription that removes the handler.
5759
*/
@@ -71,6 +73,9 @@ public interface LocalTrack extends AutoCloseable {
7173
* LocalMedia#videoTrack} or {@link LocalMedia#audioTrack}, may be closed;
7274
* or fails with a {@link WebRtcException} when the track or its source
7375
* could not be released, which then fails the runtime's close as well.
76+
* It completes on an event thread, after the ended handlers ran. Each
77+
* call returns a future of its own: cancelling it stops waiting, not the
78+
* close.
7479
*/
7580
CompletableFuture<Void> closeAsync();
7681

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

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@
3232
* Calls on the native track and source happen under this object's lock and
3333
* only while the track has not ended, so that closing never races with them.
3434
* Closing first makes every sender let go of the track, each on its peer's
35-
* control executor, and only then releases the native track and source.
35+
* control executor, and only then releases the native track and source. The
36+
* ended handlers and the futures handed out follow on the media's event
37+
* executor, so that neither holds up a release nor the runtime's close.
3638
*/
3739
abstract class LocalTrackImpl implements LocalTrack {
3840

@@ -50,7 +52,12 @@ abstract class LocalTrackImpl implements LocalTrack {
5052
/** Guarded by this. */
5153
private Runnable releaseSource;
5254

53-
private final CompletableFuture<Void> closed = new CompletableFuture<>();
55+
/**
56+
* Completed on the media executor once the native track is released,
57+
* before the handlers hear of it. Never handed out, so that no caller can
58+
* cancel what the runtime waits for.
59+
*/
60+
private final CompletableFuture<Void> closedInternal = new CompletableFuture<>();
5461

5562
private volatile boolean enabled = true;
5663

@@ -117,7 +124,7 @@ public Subscription onEnded(Runnable handler) {
117124
}
118125
}
119126

120-
media.executor.execute(handler);
127+
media.events.execute(handler);
121128

122129
return () -> { };
123130
}
@@ -129,7 +136,7 @@ public synchronized boolean isEnded() {
129136

130137
@Override
131138
public CompletableFuture<Void> closeAsync() {
132-
return closeInternal();
139+
return media.toPublic(closeInternal());
133140
}
134141

135142
@Override
@@ -205,12 +212,18 @@ boolean isLive() {
205212
return !ended;
206213
}
207214

215+
/**
216+
* Starts closing, once.
217+
*
218+
* @return a future that completes on the media executor once the native
219+
* track is released, before the handlers hear of it.
220+
*/
208221
CompletableFuture<Void> closeInternal() {
209222
List<SenderImpl> using;
210223

211224
synchronized (this) {
212225
if (ended) {
213-
return closed;
226+
return closedInternal;
214227
}
215228

216229
ended = true;
@@ -227,7 +240,7 @@ CompletableFuture<Void> closeInternal() {
227240
CompletableFuture.allOf(detached.toArray(new CompletableFuture[0]))
228241
.whenComplete((ignored, error) -> media.executor.execute(this::release));
229242

230-
return closed;
243+
return closedInternal;
231244
}
232245

233246
/**
@@ -270,20 +283,25 @@ private void release() {
270283
endedHandlers.clear();
271284
}
272285

273-
for (Runnable handler : handlers) {
274-
try {
275-
handler.run();
276-
}
277-
catch (Throwable e) {
278-
rtc.reportError(e);
286+
// Queued before the release completes, so that the futures handed out
287+
// complete after the handlers ran, and the runtime cannot stop the
288+
// event executor in between.
289+
media.events.execute(() -> {
290+
for (Runnable handler : handlers) {
291+
try {
292+
handler.run();
293+
}
294+
catch (Throwable e) {
295+
rtc.reportError(e);
296+
}
279297
}
280-
}
298+
});
281299

282300
if (failure == null) {
283-
closed.complete(null);
301+
closedInternal.complete(null);
284302
}
285303
else {
286-
closed.completeExceptionally(failure);
304+
closedInternal.completeExceptionally(failure);
287305
}
288306
}
289307

0 commit comments

Comments
 (0)