Skip to content

Commit a15436d

Browse files
authored
fix: keep camera ownership consistent and fail switches peers did not take (#427)
1 parent ffbb8d9 commit a15436d

7 files changed

Lines changed: 357 additions & 33 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ camera.switchCamera(media.devices().cameras().get(1))
402402
.thenRun(() -> System.out.println("Now sending " + camera.device().getName()));
403403
```
404404

405-
The new camera keeps the resolution and frame rate of the old one, as far as it supports them. The switch opens the new camera before it closes the old one, so that the peers see no gap. Some devices cannot capture with two cameras at once, such as the two sensors of a laptop camera; then the old camera closes first, and the switch takes about half a second. If the new camera cannot be opened, the future fails with a `MediaException`, and the track keeps sending the camera it had.
405+
The new camera keeps the resolution and frame rate of the old one, as far as it supports them. The switch opens the new camera before it closes the old one, so that the peers see no gap. Some devices cannot capture with two cameras at once, such as the two sensors of a laptop camera; then the old camera closes first, and the switch takes about half a second. If the new camera cannot be opened, the future fails with a `MediaException`, and the track keeps sending the camera it had. If a peer does not take the new camera within the operation timeout, the future fails with a `WebRtcException`; the track goes back to the old camera, or keeps the new one when the old one had to close first. A track that closed its camera first and can open neither camera ends.
406406

407407
### Devices
408408

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ public interface LocalCamera extends LocalVideo {
4141
* @return a future that completes once every peer sends the new camera. It
4242
* fails with a {@link MediaException} if the camera cannot be opened, or is
4343
* already open with other options, and the track keeps its camera then.
44+
* It fails with a {@link WebRtcException} if a peer does not take the new
45+
* camera within the operation timeout; the track goes back to its camera
46+
* then, or keeps the new one if the device had to close the old one first.
47+
* A track that closed its camera first and can open neither one ends.
4448
*/
4549
CompletableFuture<Void> switchCamera(VideoDevice device);
4650

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

Lines changed: 210 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
import java.util.List;
2323
import java.util.UUID;
2424
import java.util.concurrent.CompletableFuture;
25+
import java.util.concurrent.ExecutionException;
2526
import java.util.concurrent.TimeUnit;
27+
import java.util.concurrent.TimeoutException;
2628

2729
import dev.onvoid.webrtc.media.video.VideoDevice;
2830
import dev.onvoid.webrtc.media.video.VideoTrack;
@@ -34,9 +36,13 @@
3436
*/
3537
final class LocalCameraImpl extends LocalVideoImpl implements LocalCamera {
3638

37-
/** Guarded by this. */
39+
// Guarded by this.
40+
3841
private LocalMediaImpl.SharedCamera camera;
3942

43+
/** Replaced native tracks with their cameras, which late senders may still send. */
44+
private final List<LocalTrackImpl.Replaced> retiring = new ArrayList<>();
45+
4046

4147
LocalCameraImpl(LocalMediaImpl media, VideoTrack track, LocalMediaImpl.SharedCamera camera) {
4248
super(media, track, () -> media.releaseCamera(camera));
@@ -59,7 +65,8 @@ public CompletableFuture<Void> switchCamera(VideoDevice device) {
5965
// Opening a camera can take a moment, so it happens off the caller's thread.
6066
media.executor.execute(() -> {
6167
try {
62-
switchTo(device, switched);
68+
switchTo(device);
69+
switched.complete(null);
6370
}
6471
catch (Throwable e) {
6572
switched.completeExceptionally(e instanceof WebRtcException
@@ -70,22 +77,19 @@ public CompletableFuture<Void> switchCamera(VideoDevice device) {
7077
return switched;
7178
}
7279

73-
private void switchTo(VideoDevice device, CompletableFuture<Void> switched) {
80+
private void switchTo(VideoDevice device) {
7481
LocalMediaImpl.SharedCamera current;
7582

7683
synchronized (this) {
7784
current = camera;
7885
}
7986

8087
if (current.options.device.equals(device)) {
81-
switched.complete(null);
8288
return;
8389
}
8490

8591
CameraOptions target = current.options.withDevice(device);
8692
LocalMediaImpl.SharedCamera next;
87-
boolean currentReleased = false;
88-
MediaException failure = null;
8993

9094
try {
9195
// Opened first, so that peers see no gap.
@@ -94,13 +98,36 @@ private void switchTo(VideoDevice device, CompletableFuture<Void> switched) {
9498
catch (MediaException beside) {
9599
// Some cameras cannot capture at the same time, such as two
96100
// sensors of one device. Unless another track shares the current
97-
// camera, it is let go first, and comes back if the new one fails.
101+
// camera, it is let go first.
98102
if (!media.isOnlyUser(current)) {
99103
throw beside;
100104
}
101105

102-
media.releaseCamera(current);
103-
currentReleased = true;
106+
switchInstead(current, target);
107+
return;
108+
}
109+
110+
WebRtcException notTaken = replace(next, true);
111+
112+
if (notTaken != null) {
113+
throw notTaken;
114+
}
115+
}
116+
117+
/**
118+
* Switches after letting go of the current camera, which comes back if
119+
* the new one fails. A track left without either camera ends.
120+
*/
121+
private void switchInstead(LocalMediaImpl.SharedCamera current, CameraOptions target) {
122+
// The track no longer owns the camera, so that it does not let go of
123+
// it a second time when it is released.
124+
takeRelease().run();
125+
126+
MediaException failure = null;
127+
WebRtcException notTaken;
128+
129+
try {
130+
LocalMediaImpl.SharedCamera next;
104131

105132
try {
106133
next = media.openCamera(target);
@@ -109,24 +136,45 @@ private void switchTo(VideoDevice device, CompletableFuture<Void> switched) {
109136
failure = instead;
110137
next = media.openCamera(current.options);
111138
}
139+
140+
notTaken = replace(next, false);
112141
}
142+
catch (RuntimeException e) {
143+
closeInternal();
113144

114-
replace(next, currentReleased);
145+
MediaException ended = new MediaException("The track let go of the camera "
146+
+ current.options.device.getName() + " to switch, got no camera back, and ended", e);
147+
148+
if (failure != null && failure != e) {
149+
ended.addSuppressed(failure);
150+
}
151+
152+
throw ended;
153+
}
115154

116155
if (failure != null) {
117-
switched.completeExceptionally(failure);
156+
if (notTaken != null) {
157+
failure.addSuppressed(notTaken);
158+
}
159+
160+
throw failure;
118161
}
119-
else {
120-
switched.complete(null);
162+
if (notTaken != null) {
163+
throw notTaken;
121164
}
122165
}
123166

124167
/**
125168
* Puts a track over the camera in place of the current one, on this
126-
* track and on every sender, and lets the old one go once no sender sends
127-
* it any more.
169+
* track and on every sender, and lets the old one go once every sender
170+
* sends the new one. When not every sender does in time, the track goes
171+
* back to the old camera if it can, and keeps the new one otherwise.
172+
*
173+
* @param canGoBack whether the old camera is still open.
174+
*
175+
* @return null once every sender sends the new track, else why not.
128176
*/
129-
private void replace(LocalMediaImpl.SharedCamera next, boolean oldCameraReleased) {
177+
private WebRtcException replace(LocalMediaImpl.SharedCamera next, boolean canGoBack) {
130178
VideoTrack nextTrack;
131179

132180
try {
@@ -138,9 +186,11 @@ private void replace(LocalMediaImpl.SharedCamera next, boolean oldCameraReleased
138186
+ " could not be created", e);
139187
}
140188

189+
LocalMediaImpl.SharedCamera previous;
141190
LocalTrackImpl.Replaced replaced;
142191

143192
synchronized (this) {
193+
previous = camera;
144194
replaced = replaceNative(nextTrack, () -> media.releaseCamera(next));
145195

146196
if (replaced != null) {
@@ -156,23 +206,159 @@ private void replace(LocalMediaImpl.SharedCamera next, boolean oldCameraReleased
156206
throw new MediaException("The camera track is closed");
157207
}
158208

209+
CompletableFuture<Void> sent = send(replaced.senders);
210+
WebRtcException notTaken = await(sent, "Not every peer took the camera " + next.options.device.getName());
211+
212+
if (notTaken != null && canGoBack && goBack(replaced, previous, sent)) {
213+
return notTaken;
214+
}
215+
216+
retire(replaced, sent);
217+
218+
return notTaken;
219+
}
220+
221+
/**
222+
* Puts the replaced track and camera back, on this track and on every
223+
* sender, and lets go of the new ones.
224+
*
225+
* @return false if the track closed meanwhile, whose release then lets go
226+
* of the new ones.
227+
*/
228+
private boolean goBack(LocalTrackImpl.Replaced replaced, LocalMediaImpl.SharedCamera previous,
229+
CompletableFuture<Void> sent) {
230+
LocalTrackImpl.Replaced undone;
231+
232+
synchronized (this) {
233+
undone = replaceNative(replaced.track, replaced.release);
234+
235+
if (undone != null) {
236+
moveSinks((VideoTrack) undone.track);
237+
camera = previous;
238+
}
239+
}
240+
241+
if (undone == null) {
242+
return false;
243+
}
244+
245+
// A sender that is late sends the old track anyway, as it reads the
246+
// track when its task runs.
247+
CompletableFuture<Void> back = send(undone.senders);
248+
WebRtcException notBack = await(back,
249+
"Not every peer went back to the camera " + previous.options.device.getName());
250+
251+
if (notBack != null) {
252+
rtc.reportError(notBack);
253+
}
254+
255+
retire(undone, CompletableFuture.allOf(sent, back));
256+
257+
return true;
258+
}
259+
260+
/**
261+
* Lets go of a replaced native track and its camera once no sender uses
262+
* them any more, or when this track is released, if that comes first.
263+
* Late senders are done by then, as the senders detach from this track
264+
* on the same executors.
265+
*/
266+
private void retire(LocalTrackImpl.Replaced replaced, CompletableFuture<Void> sent) {
267+
if (sent.isDone()) {
268+
retireNow(replaced);
269+
return;
270+
}
271+
272+
synchronized (this) {
273+
retiring.add(replaced);
274+
}
275+
276+
sent.whenComplete((ignored, error) -> media.executor.execute(() -> {
277+
boolean pending;
278+
279+
synchronized (this) {
280+
pending = retiring.remove(replaced);
281+
}
282+
283+
if (pending) {
284+
retireNow(replaced);
285+
}
286+
}));
287+
}
288+
289+
private void retireNow(LocalTrackImpl.Replaced replaced) {
290+
try {
291+
letGo(replaced);
292+
}
293+
catch (Throwable e) {
294+
rtc.reportError(new WebRtcException("Releasing the camera track replaced failed", e));
295+
}
296+
}
297+
298+
@Override
299+
void beforeRelease() {
300+
List<LocalTrackImpl.Replaced> left;
301+
302+
synchronized (this) {
303+
left = new ArrayList<>(retiring);
304+
retiring.clear();
305+
}
306+
307+
Throwable failure = attempt(null, super::beforeRelease);
308+
309+
for (LocalTrackImpl.Replaced replaced : left) {
310+
failure = attempt(failure, () -> letGo(replaced));
311+
}
312+
313+
if (failure instanceof RuntimeException) {
314+
throw (RuntimeException) failure;
315+
}
316+
if (failure instanceof Error) {
317+
throw (Error) failure;
318+
}
319+
}
320+
321+
/**
322+
* Makes the senders send the native track this track has now.
323+
*/
324+
private CompletableFuture<Void> send(List<SenderImpl> senders) {
159325
List<CompletableFuture<Void>> sending = new ArrayList<>();
160326

161-
for (SenderImpl sender : replaced.senders) {
327+
for (SenderImpl sender : senders) {
162328
sending.add(sender.trackReplaced(this));
163329
}
164330

331+
return CompletableFuture.allOf(sending.toArray(new CompletableFuture[0]));
332+
}
333+
334+
/**
335+
* @return null once the senders send within the operation timeout, else
336+
* why not.
337+
*/
338+
private WebRtcException await(CompletableFuture<Void> sent, String failure) {
165339
try {
166-
CompletableFuture.allOf(sending.toArray(new CompletableFuture[0]))
167-
.get(rtc.operationTimeout.toMillis(), TimeUnit.MILLISECONDS);
340+
sent.get(rtc.operationTimeout.toMillis(), TimeUnit.MILLISECONDS);
341+
342+
return null;
168343
}
169-
catch (Exception e) {
170-
rtc.reportError(new WebRtcException("Not every peer took the new camera in time", e));
344+
catch (ExecutionException e) {
345+
return new WebRtcException(failure, e.getCause());
171346
}
347+
catch (TimeoutException e) {
348+
return new WebRtcException(failure + " within " + rtc.operationTimeout, e);
349+
}
350+
catch (InterruptedException e) {
351+
Thread.currentThread().interrupt();
352+
return new WebRtcException(failure, e);
353+
}
354+
}
172355

173-
replaced.track.dispose();
174-
175-
if (!oldCameraReleased) {
356+
private static void letGo(LocalTrackImpl.Replaced replaced) {
357+
try {
358+
replaced.track.dispose();
359+
}
360+
finally {
361+
// The camera holds a reference of its own, so it goes even when the track does not.
176362
replaced.release.run();
177363
}
178364
}

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,8 @@ void releaseCamera(SharedCamera camera) {
379379
return;
380380
}
381381

382-
cameras.remove(camera.key);
382+
// Another camera of the same device may have been opened since.
383+
cameras.remove(camera.key, camera);
383384
}
384385

385386
camera.source.stop();

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,19 @@ synchronized Replaced replaceNative(MediaStreamTrack next, Runnable nextRelease)
167167
return replaced;
168168
}
169169

170+
/**
171+
* Takes the release of the source from the track, which then no longer
172+
* lets go of the source, even once it ended.
173+
*
174+
* @return the release taken.
175+
*/
176+
synchronized Runnable takeRelease() {
177+
Runnable taken = releaseSource;
178+
releaseSource = () -> { };
179+
180+
return taken;
181+
}
182+
170183
synchronized boolean register(SenderImpl sender) {
171184
if (ended) {
172185
return false;
@@ -279,7 +292,7 @@ private void release() {
279292
*
280293
* @return the failure so far, with the step's added to it.
281294
*/
282-
private static Throwable attempt(Throwable failure, Runnable step) {
295+
static Throwable attempt(Throwable failure, Runnable step) {
283296
try {
284297
step.run();
285298
}

0 commit comments

Comments
 (0)