2222import java .util .List ;
2323import java .util .UUID ;
2424import java .util .concurrent .CompletableFuture ;
25+ import java .util .concurrent .ExecutionException ;
2526import java .util .concurrent .TimeUnit ;
27+ import java .util .concurrent .TimeoutException ;
2628
2729import dev .onvoid .webrtc .media .video .VideoDevice ;
2830import dev .onvoid .webrtc .media .video .VideoTrack ;
3436 */
3537final 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 }
0 commit comments