diff --git a/.eslintignore b/.eslintignore index 81234885b..6fc154050 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ +android/build examples lib src/vendor diff --git a/android/build.gradle b/android/build.gradle index 5653b1e8c..2f3ec63c0 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -91,6 +91,13 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } + + // JVM unit tests (src/test) run with Robolectric. + testOptions { + unitTests { + includeAndroidResources = true + } + } } def kotlin_version = getExtOrDefault('kotlinVersion', '1.8.10') @@ -102,4 +109,9 @@ dependencies { implementation "com.facebook.react:react-android:+" implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "androidx.core:core:1.7.0" + + // Test-only: not part of what apps get from this library. + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.robolectric:robolectric:4.14.1' + testImplementation 'org.mockito:mockito-core:5.14.2' } diff --git a/android/src/main/java/com/oney/WebRTCModule/AbstractVideoCaptureController.java b/android/src/main/java/com/oney/WebRTCModule/AbstractVideoCaptureController.java index cf8fe6c83..910beaf45 100644 --- a/android/src/main/java/com/oney/WebRTCModule/AbstractVideoCaptureController.java +++ b/android/src/main/java/com/oney/WebRTCModule/AbstractVideoCaptureController.java @@ -1,5 +1,6 @@ package com.oney.WebRTCModule; +import android.util.Log; import androidx.annotation.Nullable; import androidx.core.util.Consumer; @@ -24,6 +25,7 @@ public abstract class AbstractVideoCaptureController { protected VideoCapturer videoCapturer; protected CapturerEventsListener capturerEventsListener; + private String TAG = "AbsVidCaptControl"; public AbstractVideoCaptureController(int width, int height, int fps) { this.targetWidth = width; @@ -78,9 +80,10 @@ public void startCapture() { try { videoCapturer.startCapture(targetWidth, targetHeight, targetFps); } catch (RuntimeException e) { - // XXX This can only fail if we initialize the capturer incorrectly, - // which we don't. Thus, ignore any failures here since we trust - // ourselves. + // CameraCapturer throws only if it was not initialized, which we always do first. Other + // capturers may throw at runtime (for example screen capture). Log it: an error here + // never reaches CameraEventsHandler, so nothing else would report it. + Log.e(TAG, "[startCapture] failed", e); } } @@ -111,5 +114,11 @@ public void setCapturerEventsListener(CapturerEventsListener listener) { public interface CapturerEventsListener { /** Called when the capturer is ended and in an irrecoverable state. */ public void onCapturerEnded(); + + /** + * Called when the capturer stops sending frames for a reason outside the app + * (muted = true), and when frames come back (muted = false). The track stays live. + */ + default void onCapturerMuteChanged(boolean muted) {} } } diff --git a/android/src/main/java/com/oney/WebRTCModule/CameraCaptureController.java b/android/src/main/java/com/oney/WebRTCModule/CameraCaptureController.java index 357210e97..ecaf0df44 100644 --- a/android/src/main/java/com/oney/WebRTCModule/CameraCaptureController.java +++ b/android/src/main/java/com/oney/WebRTCModule/CameraCaptureController.java @@ -15,6 +15,7 @@ import org.webrtc.Camera1Capturer; import org.webrtc.Camera1Helper; import org.webrtc.Camera2Capturer; +import org.webrtc.Camera2Enumerator; import org.webrtc.Camera2Helper; import org.webrtc.CameraEnumerator; import org.webrtc.CameraVideoCapturer; @@ -60,13 +61,70 @@ public void onCameraOpening(String cameraName) { int cameraIndex = findCameraIndex(cameraName); updateActualSize(cameraIndex, cameraName, videoCapturer); CameraCaptureController.this.currentDeviceId = cameraIndex == -1 ? null : String.valueOf(cameraIndex); + CameraCaptureController.this.currentCameraName = cameraName; + } + + // Android took our camera (another app opened a camera). + @Override + public void onCameraDisconnected() { + super.onCameraDisconnected(); + cameraRecovery.onCameraDisconnected(currentCameraManagerId()); + } + + // The camera could not be opened, a fatal camera error happened, or the camera is slow to + // start (a warning: the open continues). + @Override + public void onCameraError(String errorDescription) { + super.onCameraError(errorDescription); + cameraRecovery.onCameraError(errorDescription); + } + + @Override + public void onFirstFrameAvailable() { + super.onFirstFrameAvailable(); + cameraRecovery.onFramesArrived(); } }; + /** Gets the camera back after another app took it. See its class doc for which Android versions. */ + private final CameraRecoveryController cameraRecovery; + + /** Name of the camera that was opened last. For Camera2 this is the CameraManager id. */ + @Nullable + private volatile String currentCameraName; + + /** + * The CameraManager id of the camera that was opened last, or null if unknown. Camera2: the + * camera name is the CameraManager id. Camera1: the camera index is the same number. + */ + @Nullable + private String currentCameraManagerId() { + return cameraEnumerator instanceof Camera2Enumerator ? currentCameraName : currentDeviceId; + } + public CameraCaptureController(Context context, CameraEnumerator cameraEnumerator, ReadableMap constraints) { super(constraints.getInt("width"), constraints.getInt("height"), constraints.getInt("frameRate")); this.context = context; + this.cameraRecovery = new CameraRecoveryController( + context, + // The parent's startCapture: the app's request (appRequestsCapture) does not change. + CameraCaptureController.super::startCapture, + new CameraRecoveryController.Listener() { + @Override + public void onCaptureInterruptedChanged(boolean interrupted) { + if (capturerEventsListener != null) { + capturerEventsListener.onCapturerMuteChanged(interrupted); + } + } + + @Override + public void onRecoveryFailed() { + if (capturerEventsListener != null) { + capturerEventsListener.onCapturerEnded(); + } + } + }); this.cameraEnumerator = cameraEnumerator; this.constraints = constraints; @@ -80,6 +138,25 @@ public String getDeviceId() { return currentDeviceId; } + @Override + public void startCapture() { + cameraRecovery.setCaptureRequested(true); + super.startCapture(); + } + + @Override + public boolean stopCapture() { + // First, so a reopen that is waiting can't turn the camera back on. + cameraRecovery.setCaptureRequested(false); + return super.stopCapture(); + } + + @Override + public void dispose() { + cameraRecovery.setCaptureRequested(false); + super.dispose(); + } + private int findCameraIndex(String cameraName) { String[] deviceNames = cameraEnumerator.getDeviceNames(); for (int i = 0; i < deviceNames.length; i++) { diff --git a/android/src/main/java/com/oney/WebRTCModule/CameraErrorDescriptions.java b/android/src/main/java/com/oney/WebRTCModule/CameraErrorDescriptions.java new file mode 100644 index 000000000..61ca80f31 --- /dev/null +++ b/android/src/main/java/com/oney/WebRTCModule/CameraErrorDescriptions.java @@ -0,0 +1,36 @@ +package com.oney.WebRTCModule; + +import androidx.annotation.Nullable; + +/** + * Error descriptions that libwebrtc passes to {@code CameraEventsHandler.onCameraError}, and what + * they mean for {@link CameraRecoveryController}. + * + *

Copied from io.getstream:stream-video-webrtc-android 156.0.7. Check them when updating WebRTC: + * if one changes, that error no longer matches and counts as an ordinary failed try. The Camera1 + * capturer uses other descriptions, so none of these match there. + */ +final class CameraErrorDescriptions { + + /** CameraCapturer: a warning after 10 s. The open continues and may still succeed. */ + static final String CAMERA_START_TIMEOUT = "Camera failed to start within timeout."; + + /** Camera2Session, ERROR_CAMERA_IN_USE: another app holds the camera. */ + static final String CAMERA_IN_USE = "Camera device is in use already."; + + /** Camera2Session, ERROR_MAX_CAMERAS_IN_USE: another app holds a camera. Seen on Samsung. */ + static final String MAX_CAMERAS_IN_USE = + "Camera device could not be opened because there are too many other open camera devices."; + + /** True if the camera is only slow to start: the open continues. */ + static boolean isStartTimeout(@Nullable String errorDescription) { + return CAMERA_START_TIMEOUT.equals(errorDescription); + } + + /** True if another app holds the camera, so a later try may work. */ + static boolean isCameraHeldByAnotherApp(@Nullable String errorDescription) { + return CAMERA_IN_USE.equals(errorDescription) || MAX_CAMERAS_IN_USE.equals(errorDescription); + } + + private CameraErrorDescriptions() {} +} diff --git a/android/src/main/java/com/oney/WebRTCModule/CameraRecoveryController.java b/android/src/main/java/com/oney/WebRTCModule/CameraRecoveryController.java new file mode 100644 index 000000000..4ba79adcc --- /dev/null +++ b/android/src/main/java/com/oney/WebRTCModule/CameraRecoveryController.java @@ -0,0 +1,649 @@ +package com.oney.WebRTCModule; + +import android.content.Context; +import android.hardware.camera2.CameraManager; +import android.os.Handler; +import android.os.Looper; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.util.HashMap; +import java.util.Map; + +/** + * Gets the camera back after Android disconnected it while the app still requests capture, + * usually because another app opened a camera. libwebrtc stops capturing in that case and never + * opens the camera again by itself. We reopen it on the same capturer, so the same track + * continues. + * + *

Three views of the same recovery follow. Each answers a different question: + *

    + *
  1. Normal path: which methods run, and in what order?
  2. + *
  3. Flow diagram: how does recovery move between states and outcomes?
  4. + *
  5. Race handling: what happens when callbacks and the app's own actions overlap?
  6. + *
+ * + *

1. Normal path

+ * + *

The successful recovery only. Each "Later" starts on its own; this is not one call stack. + * + *

{@code
+ * The capturer reports the disconnect:
+ *   onCameraDisconnected(cameraId)
+ *     -> startRecovery()                    [remember which camera to wait for]
+ *          -> setCaptureInterrupted(true)   [track: mute]
+ *          -> startListening()              [register with CameraManager]
+ *
+ * Later, Android reports a change:
+ *   onAvailabilityChanged(cameraId, true)   [our camera is free]
+ *     -> onCameraMayBeFree()
+ *   or onCameraAccessPrioritiesChanged()    [API 29+]
+ *     -> onCameraMayBeFree()
+ *   onCameraMayBeFree()
+ *     -> scheduleReopen()                   [recoveryState: REOPEN_SCHEDULED]
+ *
+ * Later, after REOPEN_DELAY_MS (500 ms):
+ *   reopenNow()
+ *     -> CameraReopener.reopenCamera()      [same capturer, same track]
+ *
+ * Later, the capturer reports its first frame:
+ *   onFramesArrived()
+ *     -> endRecovery()                      [unregister, recoveryState: NOT_RECOVERING]
+ *     -> setCaptureInterrupted(false)       [track: unmute]
+ * }
+ * + *

There is no polling: the delay starts only after an Android callback. The first availability + * report after we start listening also allows one try if it says our camera is already free. A + * priority change means a try may work now, not that the camera is free. Recovery succeeds when + * the first frame arrives, not when {@code reopenCamera()} returns. + * + *

2. Flow diagram

+ * + *

( ) = start or end, [ ] = recovery state, < > = question, text beside an arrow = the event. + * + *

{@code
+ * ( START: capture runs and the app requests it )
+ *     |
+ *     | capturer: camera disconnected
+ *     v
+ * < event still current? > --no--> ( END: drop the outdated event )
+ *     | yes
+ *     v
+ * [ WAITING_FOR_SIGNAL ]  (jump target WAIT)      track: mute, listening to CameraManager
+ *     |
+ *     | Android: priorities changed, or our camera in use -> free,
+ *     | or the first report says it is free (once per recovery)
+ *     v
+ * [ REOPEN_SCHEDULED ]  (jump target SCHEDULE)    more signals join this try
+ *     |
+ *     | 500 ms later
+ *     v
+ * < app still requests capture, no start or stop since? > --no--> ( END: cancel the outdated recovery )
+ *     | yes (checked under captureStateLock)
+ *     v
+ * [ REOPENING ]                                   camera opened again; a signal now is kept
+ *     |
+ *     | the capturer reports one of:
+ *     |
+ *     |-- first frame --------------> ( END: recovery succeeded: track: unmute, same track )
+ *     |
+ *     |-- start timeout warning ----> stay in REOPENING: the open still runs
+ *     |
+ *     |-- camera in use, too many --> < 5 tries? >  --yes--> ( END: recovery failed:
+ *     |   cameras open, or                 | no                 track: ended )
+ *     |   disconnected again               v
+ *     |   (not a failed try)          go to NEXT
+ *     |
+ *     '-- any other error ----------> [ count a failed try ]
+ *                                          |
+ *                                          v
+ *                           < 3 failed tries, or 5 tries? >  --yes--> ( END: recovery failed:
+ *                                          | no                         track: ended )
+ *                                          v
+ *                                     go to NEXT
+ *
+ * NEXT: < signal kept during the try? >
+ *            | yes              | no
+ *            v                  v
+ *      go to SCHEDULE      go to WAIT
+ *
+ * Other way out, at any point:
+ *   app stops capture (or stops and starts it)
+ *     --> ( END: cancel the outdated recovery; we never reopen for it )
+ * }
+ * + *

Not drawn: a disconnect or error while {@code WAITING_FOR_SIGNAL} or {@code REOPEN_SCHEDULED} + * is ignored, and a signal is ignored when no recovery runs. An error in {@code NOT_RECOVERING} is only + * logged, as before this class existed: it is a slow first open (the camera may still start) or a + * rejected camera switch, not something a recovery can fix. "track: ended" is the event this class + * causes; the SDK or app decides what the user then sees. + * + *

3. Race handling

+ * + *

The same path, with each safeguard shown where it acts. + * + *

{@code
+ * A capturer event arrives (camera thread; the start timeout comes from the main thread):
+ *   onCameraDisconnected() / onCameraError() / onFramesArrived()
+ *     -> currentStartStopCount()            [volatile read, never takes captureStateLock]
+ *     -> queue the work on the main thread
+ *   On the main thread:
+ *     -> isStillCurrent(eventStartStopCount)?  [under captureStateLock]
+ *        no:  drop the outdated event
+ *        yes: handle it by recoveryState
+ *
+ *   onCameraDisconnected():  NOT_RECOVERING -> startRecovery()   REOPENING -> onReopenBlocked()
+ *   onCameraError():         REOPENING only, by description:
+ *                              start timeout              -> ignore (the open continues)
+ *                              in use / too many cameras  -> onReopenBlocked()
+ *                              anything else              -> onReopenFailed()
+ *                            NOT_RECOVERING -> ignore (not a recovery; the capturer logged it)
+ *   Both, in WAITING_FOR_SIGNAL or REOPEN_SCHEDULED: ignore (already recovering)
+ *
+ * An Android signal arrives (main thread) -> onCameraMayBeFree():
+ *   WAITING_FOR_SIGNAL -> scheduleReopen()   [one try]
+ *   REOPEN_SCHEDULED   -> ignore             [the scheduled try starts after this signal]
+ *   REOPENING          -> cameraMayBeFreeDuringReopen = true
+ *   NOT_RECOVERING     -> ignore
+ *
+ * The scheduled try runs (main thread) -> reopenNow():
+ *   take captureStateLock
+ *     -> appRequestsCapture, and startStopCount unchanged?  no: endRecovery()
+ *     -> recoveryState: REOPENING, CameraReopener.reopenCamera()
+ *        [enters the capturer, takes its lock]
+ *   release captureStateLock
+ *
+ * Another app blocks the try -> onReopenBlocked():
+ *   -> at MAX_REOPEN_ATTEMPTS tries: failRecovery() -> Listener.onRecoveryFailed()
+ *   -> below: waitForNextSignal()
+ *
+ * The try fails for another reason -> onReopenFailed():
+ *   -> count it; at MAX_FAILED_REOPENS (or MAX_REOPEN_ATTEMPTS tries): failRecovery()
+ *   -> below: waitForNextSignal()
+ *
+ * waitForNextSignal():
+ *   -> WAITING_FOR_SIGNAL; if cameraMayBeFreeDuringReopen: scheduleReopen() now
+ *
+ * The app stops capture (any thread) -> setCaptureRequested(false):
+ *   under captureStateLock: appRequestsCapture = false, startStopCount + 1
+ *     -> queue: end any recovery from an older startStopCount
+ *   then CameraCaptureController stops the capturer
+ *
+ * The first frame arrives -> onFramesArrived():
+ *   drop it if outdated; otherwise endRecovery(), setCaptureInterrupted(false)
+ * }
+ * + *

Stop against reopen: if the app's stop clears the request first, {@code reopenNow()} sees it + * and does not open the camera. If {@code reopenNow()} takes captureStateLock first, the stop waits for + * the open to finish and then stops the capturer, so the camera never stays open after a stop. + * + *

Kept signals: we stay registered with CameraManager while a try is scheduled or running. A + * signal that arrives during a failed try schedules the next try, so Android does not have to + * send it again. A repeated "still free" report without a change never schedules another try. + * + *

{@link #MAX_FAILED_REOPENS} counts failed tries, not time. A try blocked by another app (the + * camera is in use, too many cameras are open, or we are disconnected again) is not a failed try: + * the other app may keep the camera for a while. {@link #MAX_REOPEN_ATTEMPTS} bounds all tries of + * one recovery, in case Android keeps sending signals while the other app holds the camera. If + * Android never sends another useful signal, the recovery waits until the app stops capture. + * + *

Errors are told apart by their description, which libwebrtc defines: see + * {@link CameraErrorDescriptions}. The Camera1 capturer uses other descriptions, so there a blocked + * try counts as a failed try. + * + *

Android versions

+ * + *

Access priority changes exist from API 29. Before that, recovery relies on availability + * changes and the first availability report. If the other app holds the camera through a + * different or private camera id there, and the first try fails, no later signal may come, and + * capture stays interrupted until the app stops and starts capture. + * + *

Threads and locks

+ * + * + * + *

Lock rule: capturer callbacks never take captureStateLock. Reopening takes captureStateLock + * before it enters the capturer. Never add the reverse (taking captureStateLock from a capturer + * callback), or the two threads can deadlock. + */ +class CameraRecoveryController { + + /** Opens the camera again. Implemented by CameraCaptureController. */ + interface CameraReopener { + /** Open the camera again on the same capturer, so the same track continues. */ + void reopenCamera(); + } + + /** Hears what happens to capture during a recovery. Implemented by CameraCaptureController. */ + interface Listener { + /** + * Capture was interrupted by the system (true) or works again (false). The track stays + * live. This is not the user pausing their video. + */ + void onCaptureInterruptedChanged(boolean interrupted); + + /** We could not get the camera back. End the track, so the app shows the camera as off. */ + void onRecoveryFailed(); + } + + /** How far we are in getting the camera back. Not the camera's state: libwebrtc tracks that. */ + private enum RecoveryState { + /** The camera may be on or off. Only a disconnect starts a recovery. */ + NOT_RECOVERING, + /** Recovering: another app took the camera. We wait for Android to say "try again". */ + WAITING_FOR_SIGNAL, + /** Recovering: Android said "try again". We reopen the camera after {@link #REOPEN_DELAY_MS}. */ + REOPEN_SCHEDULED, + /** Recovering: we reopened the camera. We wait for the first frame or an error. */ + REOPENING + } + + /** Gives the other app time to finish closing the camera. */ + static final long REOPEN_DELAY_MS = 500; + + /** + * Failed tries before we give up. A try blocked by another app does not count. Not a time + * limit: see the class doc. + */ + static final int MAX_FAILED_REOPENS = 3; + + /** + * Tries per recovery, whatever their outcome. Bounds the tries blocked by another app, which do + * not count toward {@link #MAX_FAILED_REOPENS}, in case Android keeps sending signals while the + * other app holds the camera. + */ + static final int MAX_REOPEN_ATTEMPTS = 5; + + private final CameraManager cameraManager; + private final CameraReopener reopener; + private final Listener listener; + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + private final Runnable reopenNowRunnable = this::reopenNow; + + // Recovery state: main thread only. + private RecoveryState recoveryState = RecoveryState.NOT_RECOVERING; + private int failedReopens = 0; + /** Tries started in this recovery, whatever their outcome. */ + private int reopenAttempts = 0; + /** We told the listener capture is interrupted, and frames have not come back yet. */ + private boolean captureInterrupted = false; + /** + * Android hinted that our camera may be free while a try was running. If that try fails, + * schedule another one at once instead of waiting for a hint that already came. + */ + private boolean cameraMayBeFreeDuringReopen = false; + /** The startStopCount when the current recovery started. A newer count means it is outdated. */ + private int recoveryStartStopCount = 0; + /** The CameraManager id of the camera we are getting back. */ + @Nullable + private String recoveryCameraId; + /** Last known state of each camera id while listening: true = free, false = in use. */ + private final Map knownAvailability = new HashMap<>(); + /** + * This recovery already used its one try for "the first report says our camera is free". + * Set even when a try was already scheduled and the report only joined it. + */ + private boolean initialAvailabilityRetryUsed = false; + private boolean listening = false; + + // Shared between threads: see "Threads and locks" in the class doc. + // + // The capturer calls our package-level methods on its camera thread while holding its own lock, + // so the camera thread must never wait for captureStateLock: it reads startStopCount without the + // lock (it is volatile). Only the main thread and the thread that starts or stops capture take + // captureStateLock. reopenNow() holds it while it starts the capturer (which takes the + // capturer's lock), so the order is always: captureStateLock, then the capturer's lock. + // + // Queued work carries the startStopCount it was created with, and isStillCurrent() drops it if + // the app stopped or restarted capture since. + + /** Guards appRequestsCapture and every write of startStopCount. */ + private final Object captureStateLock = new Object(); + + /** + * The app wants the camera on: true from its startCapture until its stopCapture. Not proof + * that the camera runs. Guarded by {@link #captureStateLock}. + */ + private boolean appRequestsCapture = false; + + /** + * Goes up by one every time the app starts or stops capture. Written under + * {@link #captureStateLock}; read without it on the camera thread. + */ + private volatile int startStopCount = 0; + + private final CameraManager.AvailabilityCallback availabilityCallback = + new CameraManager.AvailabilityCallback() { + @Override + public void onCameraAvailable(@NonNull String cameraId) { + onAvailabilityChanged(cameraId, true); + } + + @Override + public void onCameraUnavailable(@NonNull String cameraId) { + onAvailabilityChanged(cameraId, false); + } + + // API 29+. No @Override, so this compiles with a compileSdkVersion below 29. + // Seen on a Samsung Galaxy S21 Ultra (Android 15): the system Camera app uses a + // private camera id, so our camera never looks busy and no availability change + // comes when the Camera app closes. This signal is what brings the camera back. + public void onCameraAccessPrioritiesChanged() { + onCameraMayBeFree(); + } + }; + + CameraRecoveryController(Context context, CameraReopener reopener, Listener listener) { + this.cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); + this.reopener = reopener; + this.listener = listener; + } + + // ---- Normal path, in order ---- + + /** + * Called by the capturer (camera thread) when Android closed our camera device, usually + * because another app opened a camera. {@code cameraId} is the CameraManager id of the camera + * that was disconnected, or null if unknown. On the main thread: starts a recovery, or, if we + * were reopening, waits for the next signal. Next: {@link #startRecovery} or + * {@link #onReopenBlocked}. + */ + void onCameraDisconnected(@Nullable String cameraId) { + final int eventStartStopCount = currentStartStopCount(); + mainHandler.post(() -> { + if (!isStillCurrent(eventStartStopCount)) { + return; + } + switch (recoveryState) { + case NOT_RECOVERING: + startRecovery(eventStartStopCount, cameraId); + break; + case REOPENING: + // Our try was blocked: the other app still has the camera. + onReopenBlocked(); + break; + case WAITING_FOR_SIGNAL: + case REOPEN_SCHEDULED: + // Called again while we already wait: nothing to do. + break; + } + }); + } + + /** Main thread. Tells the listener capture is interrupted and starts listening to Android. */ + private void startRecovery(int eventStartStopCount, @Nullable String cameraId) { + recoveryStartStopCount = eventStartStopCount; + recoveryCameraId = cameraId; + failedReopens = 0; + reopenAttempts = 0; + cameraMayBeFreeDuringReopen = false; + initialAvailabilityRetryUsed = false; + setCaptureInterrupted(true); + recoveryState = RecoveryState.WAITING_FOR_SIGNAL; + startListening(); + } + + /** Main thread. Android then reports every camera's current state, and later changes. */ + private void startListening() { + if (listening) { + return; + } + listening = true; + knownAvailability.clear(); + cameraManager.registerAvailabilityCallback(availabilityCallback, mainHandler); + } + + /** + * Main thread, from the availability callback. Turns "our camera is free" into a signal: + * a change from in use to free, or the first report (once per recovery). + * Next: {@link #onCameraMayBeFree}. + */ + private void onAvailabilityChanged(String cameraId, boolean available) { + if (!listening) { + return; + } + Boolean wasAvailable = knownAvailability.put(cameraId, available); + if (!available || !cameraId.equals(recoveryCameraId)) { + // Only our camera becoming free matters. + return; + } + if (Boolean.FALSE.equals(wasAvailable)) { + // Our camera changed from in use to free. + onCameraMayBeFree(); + } else if (wasAvailable == null && !initialAvailabilityRetryUsed) { + // Android reports how every camera is right after we register. Our camera may already + // be free (the other app released it before we started listening), so try once. + // Seen on Samsung: our camera is reported free while the Camera app holds a private + // camera id, so this try fails and we wait for a priority change. + initialAvailabilityRetryUsed = true; + onCameraMayBeFree(); + } + } + + /** + * Main thread. Android hinted that our camera may be usable again: it became free, or access + * priorities changed. This is an input, not a try: while waiting, it schedules one try; while + * a try runs, it remembers the hint in case that try fails. Next: {@link #scheduleReopen}, + * then {@link #reopenNow}. + */ + private void onCameraMayBeFree() { + switch (recoveryState) { + case WAITING_FOR_SIGNAL: + scheduleReopen(); + break; + case REOPENING: + // The other app may have released the camera after our try started. If the try + // fails, try again instead of waiting for a signal that already came. + cameraMayBeFreeDuringReopen = true; + break; + case REOPEN_SCHEDULED: + // The scheduled try starts after this signal, so it already covers it. + case NOT_RECOVERING: + break; + } + } + + /** Main thread. Runs {@link #reopenNow} after {@link #REOPEN_DELAY_MS}. */ + private void scheduleReopen() { + recoveryState = RecoveryState.REOPEN_SCHEDULED; + mainHandler.postDelayed(reopenNowRunnable, REOPEN_DELAY_MS); + } + + /** + * Main thread, {@link #REOPEN_DELAY_MS} after a signal. Opens the camera again if the app still + * requests capture and has not stopped or restarted it since. Next: {@link #onFramesArrived} on success, or + * {@link #onCameraDisconnected} / {@link #onCameraError} leading to {@link #onReopenBlocked} + * or {@link #onReopenFailed}. + */ + private void reopenNow() { + if (recoveryState != RecoveryState.REOPEN_SCHEDULED) { + return; + } + // Check and open while holding captureStateLock: a setCaptureRequested(false) from another thread + // either runs before (we don't open) or after (its stopCapture closes what we opened). + // Lock order: captureStateLock, then the capturer's. The camera thread never takes ours. + synchronized (captureStateLock) { + if (!appRequestsCapture || startStopCount != recoveryStartStopCount) { + endRecovery(); + return; + } + recoveryState = RecoveryState.REOPENING; + cameraMayBeFreeDuringReopen = false; + reopenAttempts++; + reopener.reopenCamera(); + } + } + + /** + * Called by the capturer (camera thread) when the first frame arrives from a newly opened + * camera. On the main thread: ends a recovery and tells the listener capture works again. + */ + void onFramesArrived() { + final int eventStartStopCount = currentStartStopCount(); + mainHandler.post(() -> { + if (!isStillCurrent(eventStartStopCount)) { + return; + } + endRecovery(); + setCaptureInterrupted(false); + }); + } + + /** Main thread. Stops listening and cancels a scheduled try. */ + private void endRecovery() { + stopListening(); + mainHandler.removeCallbacks(reopenNowRunnable); + recoveryState = RecoveryState.NOT_RECOVERING; + failedReopens = 0; + reopenAttempts = 0; + cameraMayBeFreeDuringReopen = false; + initialAvailabilityRetryUsed = false; + recoveryCameraId = null; + } + + // ---- Failures ---- + + /** + * Called by the capturer when the camera could not be opened, a fatal camera error happened, or + * the camera is slow to start ({@link CameraErrorDescriptions#CAMERA_START_TIMEOUT}, sent from + * the main thread). On + * the main thread, and only while reopening: keeps waiting on the start timeout, waits for the + * next signal if another app holds the camera, and counts a failed try otherwise. + * + *

In any other recovery state the error changes nothing (the capturer already logged it). In + * {@code NOT_RECOVERING} it is not about a recovery: a slow first open, or a rejected camera switch. + * Ending the track there would be final, even though the camera may still start. + */ + void onCameraError(@Nullable String errorDescription) { + final int eventStartStopCount = currentStartStopCount(); + mainHandler.post(() -> { + if (!isStillCurrent(eventStartStopCount) || recoveryState != RecoveryState.REOPENING) { + return; + } + if (CameraErrorDescriptions.isStartTimeout(errorDescription)) { + // Only a warning: the open continues. Wait for the first frame or a real failure. + return; + } + if (CameraErrorDescriptions.isCameraHeldByAnotherApp(errorDescription)) { + // The other app still has the camera. Seen on Samsung while its Camera app runs: + // "too many other open camera devices". + onReopenBlocked(); + } else { + onReopenFailed(); + } + }); + } + + /** + * Main thread. Our try was blocked because another app still has the camera. Does not count + * toward {@link #MAX_FAILED_REOPENS}: waits for the next signal. After + * {@link #MAX_REOPEN_ATTEMPTS}: {@link #failRecovery}. + */ + private void onReopenBlocked() { + if (reopenAttempts >= MAX_REOPEN_ATTEMPTS) { + failRecovery(); + return; + } + waitForNextSignal(); + } + + /** + * Main thread. Counts a failed try. After {@link #MAX_FAILED_REOPENS} failed tries or + * {@link #MAX_REOPEN_ATTEMPTS} tries: {@link #failRecovery}. Otherwise waits for the next signal. + */ + private void onReopenFailed() { + failedReopens++; + if (failedReopens >= MAX_FAILED_REOPENS || reopenAttempts >= MAX_REOPEN_ATTEMPTS) { + failRecovery(); + return; + } + waitForNextSignal(); + } + + /** Main thread. Waits again, and schedules another try at once if a hint came during this one. */ + private void waitForNextSignal() { + recoveryState = RecoveryState.WAITING_FOR_SIGNAL; + if (cameraMayBeFreeDuringReopen) { + cameraMayBeFreeDuringReopen = false; + onCameraMayBeFree(); + } + } + + /** Main thread. Ends the recovery and tells the listener to end the track. */ + private void failRecovery() { + endRecovery(); + captureInterrupted = false; + listener.onRecoveryFailed(); + } + + // ---- The app starts and stops capture ---- + + /** + * Called by the camera controller (any thread) when the app started (true) or stopped (false) + * capture. Increases startStopCount, so work queued before is dropped, and on the main thread + * ends a recovery from an earlier count. While capture is not requested, we never open + * the camera by ourselves. + */ + void setCaptureRequested(boolean requested) { + final int newStartStopCount; + synchronized (captureStateLock) { + appRequestsCapture = requested; + startStopCount++; + newStartStopCount = startStopCount; + } + mainHandler.post(() -> { + // A recovery started at this count or a newer one is not ours to end. + if (recoveryState != RecoveryState.NOT_RECOVERING && recoveryStartStopCount >= newStartStopCount) { + return; + } + endRecovery(); + // Keep captureInterrupted: if the app starts capture again, the first frame clears it. + }); + } + + // ---- Small helpers (main thread) ---- + + private void stopListening() { + if (!listening) { + return; + } + listening = false; + knownAvailability.clear(); + cameraManager.unregisterAvailabilityCallback(availabilityCallback); + } + + private void setCaptureInterrupted(boolean interrupted) { + if (captureInterrupted == interrupted) { + return; + } + captureInterrupted = interrupted; + listener.onCaptureInterruptedChanged(interrupted); + } + + // ---- Capture session safeguards (see the shared fields at the top) ---- + + /** Any thread, without captureStateLock: the camera thread must never wait for it. */ + private int currentStartStopCount() { + return startStopCount; + } + + /** Main thread. True if the app still requests capture and did not stop or start it since. */ + private boolean isStillCurrent(int eventStartStopCount) { + synchronized (captureStateLock) { + return appRequestsCapture && startStopCount == eventStartStopCount; + } + } +} diff --git a/android/src/main/java/com/oney/WebRTCModule/TrackCapturerEventsEmitter.java b/android/src/main/java/com/oney/WebRTCModule/TrackCapturerEventsEmitter.java index 876af9ec7..84d125283 100644 --- a/android/src/main/java/com/oney/WebRTCModule/TrackCapturerEventsEmitter.java +++ b/android/src/main/java/com/oney/WebRTCModule/TrackCapturerEventsEmitter.java @@ -31,4 +31,18 @@ public void onCapturerEnded() { webRTCModule.sendEvent("mediaStreamTrackEnded", params); } + + /** Notify that the capturer stopped or started sending frames, without ending the track. */ + @Override + public void onCapturerMuteChanged(boolean muted) { + WritableMap params = Arguments.createMap(); + // -1 marks a local track, the same value VideoTrackAdapter uses for local tracks. + params.putInt("pcId", -1); + params.putString("trackId", trackId); + params.putBoolean("muted", muted); + + Log.d(TAG, (muted ? "mute" : "unmute") + " event trackId: " + trackId); + + webRTCModule.sendEvent("mediaStreamTrackMuteChanged", params); + } } diff --git a/android/src/test/java/com/oney/WebRTCModule/CameraErrorDescriptionsTest.java b/android/src/test/java/com/oney/WebRTCModule/CameraErrorDescriptionsTest.java new file mode 100644 index 000000000..deaa31e1f --- /dev/null +++ b/android/src/test/java/com/oney/WebRTCModule/CameraErrorDescriptionsTest.java @@ -0,0 +1,31 @@ +package com.oney.WebRTCModule; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** Tests for {@link CameraErrorDescriptions}: which libwebrtc errors mean what. */ +public class CameraErrorDescriptionsTest { + + private static final String FATAL_ERROR = "Camera device has encountered a fatal error."; + + @Test + public void recognizesTheStartTimeoutOnly() { + assertTrue(CameraErrorDescriptions.isStartTimeout(CameraErrorDescriptions.CAMERA_START_TIMEOUT)); + + assertFalse(CameraErrorDescriptions.isStartTimeout(CameraErrorDescriptions.CAMERA_IN_USE)); + assertFalse(CameraErrorDescriptions.isStartTimeout(FATAL_ERROR)); + assertFalse(CameraErrorDescriptions.isStartTimeout(null)); + } + + @Test + public void recognizesBothWaysAnotherAppHoldsTheCamera() { + assertTrue(CameraErrorDescriptions.isCameraHeldByAnotherApp(CameraErrorDescriptions.CAMERA_IN_USE)); + assertTrue(CameraErrorDescriptions.isCameraHeldByAnotherApp(CameraErrorDescriptions.MAX_CAMERAS_IN_USE)); + + assertFalse(CameraErrorDescriptions.isCameraHeldByAnotherApp(CameraErrorDescriptions.CAMERA_START_TIMEOUT)); + assertFalse(CameraErrorDescriptions.isCameraHeldByAnotherApp(FATAL_ERROR)); + assertFalse(CameraErrorDescriptions.isCameraHeldByAnotherApp(null)); + } +} diff --git a/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryConcurrencyTest.java b/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryConcurrencyTest.java new file mode 100644 index 000000000..9a8cb79a8 --- /dev/null +++ b/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryConcurrencyTest.java @@ -0,0 +1,219 @@ +package com.oney.WebRTCModule; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.robolectric.shadows.ShadowLooper.shadowMainLooper; + +import android.content.Context; +import android.hardware.camera2.CameraManager; +import android.os.Handler; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.LooperMode; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Forces specific interleavings with a real worker thread and a paused main looper. + * Timeouts bound failures; latches and blocked-thread observation establish the ordering. + * No camera hardware or changes to production lock visibility are required. + */ +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 34) +@LooperMode(LooperMode.Mode.PAUSED) +public class CameraRecoveryConcurrencyTest { + private static final long TIMEOUT_SECONDS = 5; + private static final String CAMERA_ID = "1"; + + private CameraManager cameraManager; + private CameraRecoveryController.CameraReopener reopener; + private CameraRecoveryController.Listener listener; + private CameraRecoveryController recovery; + private ExecutorService cameraThread; + + @Before + public void setUp() { + cameraManager = mock(CameraManager.class); + Context context = mock(Context.class); + when(context.getSystemService(Context.CAMERA_SERVICE)).thenReturn(cameraManager); + reopener = mock(CameraRecoveryController.CameraReopener.class); + listener = mock(CameraRecoveryController.Listener.class); + recovery = new CameraRecoveryController(context, reopener, listener); + cameraThread = Executors.newSingleThreadExecutor(work -> { + Thread thread = new Thread(work, "camera-recovery-test-worker"); + thread.setDaemon(true); + return thread; + }); + recovery.setCaptureRequested(true); + shadowMainLooper().idle(); + } + + @After + public void tearDown() throws Exception { + cameraThread.shutdownNow(); + assertTrue("Worker did not terminate", cameraThread.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + recovery.setCaptureRequested(false); + shadowMainLooper().idle(); + } + + @Test + public void cameraThreadIsNotBlockedWhenItReportsADisconnectDuringAReopen() { + assertCallbackReturnsDuringReopen(() -> recovery.onCameraDisconnected(CAMERA_ID)); + } + + @Test + public void cameraThreadIsNotBlockedWhenItReportsAnErrorDuringAReopen() { + assertCallbackReturnsDuringReopen(() -> recovery.onCameraError(CameraErrorDescriptions.CAMERA_IN_USE)); + } + + @Test + public void cameraThreadIsNotBlockedWhenItReportsTheFirstFrameDuringAReopen() { + assertCallbackReturnsDuringReopen(recovery::onFramesArrived); + } + + @Test + public void stoppingTheCameraBeforeTheDelayEndsMeansItIsNeverReopened() throws Exception { + scheduleReopen(); + + finish(cameraThread.submit(() -> recovery.setCaptureRequested(false))); + runScheduledReopen(); + + verify(reopener, never()).reopenCamera(); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + @Test + public void stoppingTheCameraDuringAReopenWaitsAndThenStopsTheReopenedCamera() throws Exception { + AtomicBoolean nativeCaptureRunning = new AtomicBoolean(); + AtomicReference stoppingThread = new AtomicReference<>(); + AtomicReference> stopWork = new AtomicReference<>(); + CountDownLatch stopSubmitted = new CountDownLatch(1); + + doAnswer(invocation -> { + stopWork.set(cameraThread.submit(() -> { + stoppingThread.set(Thread.currentThread()); + stopSubmitted.countDown(); + // Mirrors CameraCaptureController.stopCapture(): intent first, native stop second. + recovery.setCaptureRequested(false); + nativeCaptureRunning.set(false); + })); + assertTrue("Stop worker did not start", stopSubmitted.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + awaitBlockedInCaptureRequest(stoppingThread.get()); + nativeCaptureRunning.set(true); + return null; + }).when(reopener).reopenCamera(); + + scheduleReopen(); + runScheduledReopen(); + finish(stopWork.get()); + shadowMainLooper().idle(); + + assertFalse("Native stop must run after the protected native open", nativeCaptureRunning.get()); + verify(reopener).reopenCamera(); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + @Test + public void eventsQueuedBeforeTheCameraWasTurnedOffAndOnAreIgnored() throws Exception { + finish(cameraThread.submit(() -> { + recovery.onCameraDisconnected(CAMERA_ID); + recovery.onCameraError(CameraErrorDescriptions.CAMERA_IN_USE); + recovery.onFramesArrived(); + })); + finish(cameraThread.submit(() -> { + recovery.setCaptureRequested(false); + recovery.setCaptureRequested(true); + })); + + shadowMainLooper().idle(); + + verify(listener, never()).onCaptureInterruptedChanged(anyBoolean()); + verify(listener, never()).onRecoveryFailed(); + verify(cameraManager, never()).registerAvailabilityCallback(any(), any(Handler.class)); + } + + @Test + public void aTryScheduledBeforeTheCameraWasTurnedOffAndOnNeverRuns() throws Exception { + scheduleReopen(); + finish(cameraThread.submit(() -> { + recovery.setCaptureRequested(false); + recovery.setCaptureRequested(true); + })); + + runScheduledReopen(); + + verify(reopener, never()).reopenCamera(); + verify(listener, never()).onRecoveryFailed(); + } + + private void assertCallbackReturnsDuringReopen(Runnable event) { + doAnswer(invocation -> { + // Production holds its recovery lock while calling reopenCamera(). The worker must + // enqueue its camera event and return without acquiring that lock. + finish(cameraThread.submit(event)); + return null; + }).when(reopener).reopenCamera(); + + scheduleReopen(); + runScheduledReopen(); + + verify(reopener).reopenCamera(); + } + + private void scheduleReopen() { + recovery.onCameraDisconnected(CAMERA_ID); + shadowMainLooper().idle(); + ArgumentCaptor callback = + ArgumentCaptor.forClass(CameraManager.AvailabilityCallback.class); + verify(cameraManager).registerAvailabilityCallback(callback.capture(), any(Handler.class)); + callback.getValue().onCameraAccessPrioritiesChanged(); + } + + private static void runScheduledReopen() { + shadowMainLooper().idleFor(Duration.ofMillis(CameraRecoveryController.REOPEN_DELAY_MS)); + } + + private static void finish(Future work) throws Exception { + work.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + private static void awaitBlockedInCaptureRequest(Thread thread) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + while (System.nanoTime() < deadline) { + if (thread.getState() == Thread.State.BLOCKED) { + for (StackTraceElement frame : thread.getStackTrace()) { + if (frame.getClassName().equals(CameraRecoveryController.class.getName()) + && frame.getMethodName().equals("setCaptureRequested")) { + return; + } + } + } + if (!thread.isAlive()) { + fail("Stop completed without waiting for the protected reopen"); + } + Thread.yield(); + } + fail("Stop did not block on the thread performing the protected reopen"); + } +} diff --git a/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryControllerTest.java b/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryControllerTest.java new file mode 100644 index 000000000..7635e2ada --- /dev/null +++ b/android/src/test/java/com/oney/WebRTCModule/CameraRecoveryControllerTest.java @@ -0,0 +1,513 @@ +package com.oney.WebRTCModule; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.robolectric.shadows.ShadowLooper.shadowMainLooper; + +import android.content.Context; +import android.hardware.camera2.CameraManager; +import android.os.Handler; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Tests for {@link CameraRecoveryController}: what happens after another app takes our camera. + * + *

Android's CameraManager is replaced by a mock. The test plays Android: it reports the camera + * as taken, sends "try again" signals, and reports frames or failures, then checks what + * CameraRecoveryController asked the camera controller to do. + */ +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 34) +public class CameraRecoveryControllerTest { + + private static final String OUR_CAMERA = "1"; + + /** A libwebrtc error that is not about another app holding the camera. */ + private static final String FATAL_ERROR = "Camera device has encountered a fatal error."; + + private CameraManager cameraManager; + private FakeController controller; + private CameraRecoveryController recovery; + + @Before + public void setUp() { + cameraManager = mock(CameraManager.class); + Context context = mock(Context.class); + when(context.getSystemService(Context.CAMERA_SERVICE)).thenReturn(cameraManager); + controller = new FakeController(); + recovery = new CameraRecoveryController(context, controller, controller); + + // The app turns the camera on. + recovery.setCaptureRequested(true); + runMainThread(); + } + + // ---- The normal path ---- + + @Test + public void pausesTheVideoAndStartsListeningWhenAnotherAppTakesTheCamera() { + cameraTaken(); + + assertEquals(Arrays.asList("interrupted"), controller.calls); + verify(cameraManager, times(1)).registerAvailabilityCallback(any(), any(Handler.class)); + } + + @Test + public void opensTheCameraAgainHalfASecondAfterAndroidSaysTryAgain() { + cameraTaken(); + + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS - 1); + assertEquals(0, controller.reopens()); + + passTime(1); + assertEquals(1, controller.reopens()); + } + + @Test + public void resumesTheVideoAndStopsListeningWhenTheFirstFrameArrives() { + cameraTaken(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + framesArrived(); + + assertEquals(Arrays.asList("interrupted", "reopen", "resumed"), controller.calls); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + @Test + public void listensOnlyOnceWhenTheCameraIsReportedTakenTwice() { + cameraTaken(); + cameraTaken(); + + assertEquals(Arrays.asList("interrupted"), controller.calls); + verify(cameraManager, times(1)).registerAvailabilityCallback(any(), any(Handler.class)); + } + + @Test + public void opensTheCameraOnlyOnceWhenSeveralSignalsArriveTogether() { + cameraTaken(); + + prioritiesChanged(); + prioritiesChanged(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(1, controller.reopens()); + } + + // ---- Review finding 1: no signal may be lost while a try is scheduled or running ---- + + @Test + public void triesAgainWithoutANewSignalWhenTheCameraWasFreedDuringAFailedTry() { + cameraTaken(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + assertEquals(1, controller.reopens()); + + // The other app frees the camera while our try is still running... + prioritiesChanged(); + // ...and our try fails, because it started before the camera was free. + openFailed(); + + // No new signal comes from Android, but the signal during the try is not lost. + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + assertEquals(2, controller.reopens()); + } + + @Test + public void keepsListeningWhileATryIsScheduledAndAfterTheTryFails() { + cameraTaken(); + prioritiesChanged(); + prioritiesChanged(); // arrives while the try is scheduled: the scheduled try covers it + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openFailed(); + + // Still listening, so the next signal opens the camera again. + verify(cameraManager, never()).unregisterAvailabilityCallback(any()); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + assertEquals(2, controller.reopens()); + } + + // ---- Review finding 2: "our camera is free" is a signal too ---- + + @Test + public void opensTheCameraAgainWhenOurCameraBecomesFreeWithoutAPrioritySignal() { + cameraTaken(); + CameraManager.AvailabilityCallback android = registeredCallback(); + android.onCameraUnavailable(OUR_CAMERA); // first report: the other app has it + + android.onCameraAvailable(OUR_CAMERA); // the other app freed it + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(1, controller.reopens()); + } + + // ---- Follow-up review: our camera is already free when we start listening ---- + + @Test + public void triesOnceWhenOurCameraIsAlreadyFreeWhenListeningStarts() { + cameraTaken(); + CameraManager.AvailabilityCallback android = registeredCallback(); + + // The other app released the camera before we started listening, and no priority + // signal will come. The only thing Android sends is how our camera is now: free. + android.onCameraAvailable(OUR_CAMERA); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(1, controller.reopens()); + } + + @Test + public void opensTheCameraOnALaterSignalWhenTheTryFromTheFirstReportFails() { + cameraTaken(); + CameraManager.AvailabilityCallback android = registeredCallback(); + + // Samsung: our camera looks free while the Camera app holds a private camera id, so + // the try from the first report fails... + android.onCameraAvailable(OUR_CAMERA); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openFailed(); + + // ...and the Camera app closing later still brings the camera back. + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(Arrays.asList("interrupted", "reopen", "reopen"), controller.calls); + } + + @Test + public void doesNotTryAgainWhenOurCameraIsReportedFreeAgainWithoutChanging() { + cameraTaken(); + CameraManager.AvailabilityCallback android = registeredCallback(); + android.onCameraAvailable(OUR_CAMERA); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openFailed(); + + // Still free, nothing changed: not a reason to try again. + android.onCameraAvailable(OUR_CAMERA); + android.onCameraAvailable(OUR_CAMERA); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(1, controller.reopens()); + } + + @Test + public void ignoresOtherCamerasBecomingFree() { + cameraTaken(); + CameraManager.AvailabilityCallback android = registeredCallback(); + + android.onCameraUnavailable("20"); + android.onCameraAvailable("20"); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(0, controller.reopens()); + } + + // ---- Review finding 3: work queued for an old session must not touch a new one ---- + + @Test + public void doesNotPauseARestartedTrackBecauseOfADisconnectFromTheStoppedSession() { + // A disconnect from the current session is queued for the main thread... + recovery.onCameraDisconnected(OUR_CAMERA); + // ...and before it runs, the app turns the camera off and on again. + recovery.setCaptureRequested(false); + recovery.setCaptureRequested(true); + runMainThread(); + + assertEquals(new ArrayList(), controller.calls); + verify(cameraManager, never()).registerAvailabilityCallback(any(), any(Handler.class)); + } + + @Test + public void doesNotCountAFailureFromTheStoppedSessionAgainstTheNewOne() { + cameraTaken(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + // The reopen fails, but the app turns the camera off and on before the error is handled. + recovery.onCameraError(FATAL_ERROR); + recovery.setCaptureRequested(false); + recovery.setCaptureRequested(true); + runMainThread(); + + assertEquals(Arrays.asList("interrupted", "reopen"), controller.calls); + } + + @Test + public void doesNotLetAnOldTurnOffCancelARecoveryOfTheNewSession() { + recovery.setCaptureRequested(false); + recovery.setCaptureRequested(true); + recovery.onCameraDisconnected(OUR_CAMERA); + runMainThread(); + + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(Arrays.asList("interrupted", "reopen"), controller.calls); + } + + // ---- The app turns the camera off ---- + + @Test + public void neverOpensTheCameraAfterTheAppTurnedItOffWhileWaiting() { + cameraTaken(); + + recovery.setCaptureRequested(false); + runMainThread(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(0, controller.reopens()); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + @Test + public void neverOpensTheCameraWhenTheAppTurnsItOffDuringTheDelay() { + cameraTaken(); + prioritiesChanged(); + + passTime(CameraRecoveryController.REOPEN_DELAY_MS / 2); + recovery.setCaptureRequested(false); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(0, controller.reopens()); + } + + @Test + public void ignoresTheCameraBeingTakenWhileTheAppHasItTurnedOff() { + recovery.setCaptureRequested(false); + runMainThread(); + + cameraTaken(); + + assertEquals(new ArrayList(), controller.calls); + verify(cameraManager, never()).registerAvailabilityCallback(any(), any(Handler.class)); + } + + // ---- Errors while no recovery runs ---- + + @Test + public void keepsTheTrackLiveWhenTheFirstOpenIsSlowOrFailsWithoutARecovery() { + // A slow first open (the camera may still start), then an ordinary error, for example a + // rejected camera switch. Neither is about another app taking the camera. + recovery.onCameraError(CameraErrorDescriptions.CAMERA_START_TIMEOUT); + recovery.onCameraError(FATAL_ERROR); + runMainThread(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS * 10); + + assertEquals(new ArrayList(), controller.calls); + verify(cameraManager, never()).registerAvailabilityCallback(any(), any(Handler.class)); + } + + // ---- Errors during a reopen ---- + + @Test + public void waitsForTheFirstFrameWhenTheReopenIsSlowToStart() { + cameraTaken(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + // libwebrtc warns after 10 s, but the open continues... + openTimedOut(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS * 10); + // ...and delivers its first frame later. + framesArrived(); + + assertEquals(Arrays.asList("interrupted", "reopen", "resumed"), controller.calls); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + @Test + public void keepsWaitingForTheCameraWhileAnotherAppBlocksEveryTry() { + cameraTaken(); + int blockedTries = CameraRecoveryController.MAX_FAILED_REOPENS + 1; + for (int i = 1; i <= blockedTries; i++) { + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openBlocked(); + + // No polling: time alone never starts another try. + passTime(CameraRecoveryController.REOPEN_DELAY_MS * 10); + assertEquals(i, controller.reopens()); + } + + // The other app closes the camera: the next signal brings it back on the same track. + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + framesArrived(); + + assertEquals(blockedTries + 1, controller.reopens()); + assertEquals("resumed", controller.calls.get(controller.calls.size() - 1)); + assertEquals(0, controller.count("recoveryFailed")); + } + + @Test + public void doesNotCountBeingDisconnectedAgainDuringAReopenAsAFailedTry() { + cameraTaken(); + for (int i = 0; i < CameraRecoveryController.MAX_FAILED_REOPENS; i++) { + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + cameraTaken(); // the other app takes the camera again during our try + } + + assertEquals(CameraRecoveryController.MAX_FAILED_REOPENS, controller.reopens()); + assertEquals(0, controller.count("recoveryFailed")); + verify(cameraManager, never()).unregisterAvailabilityCallback(any()); + } + + @Test + public void triesAgainWithoutANewSignalWhenTheCameraWasFreedDuringABlockedTry() { + cameraTaken(); + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + prioritiesChanged(); // kept: arrives while our try runs + openBlocked(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + + assertEquals(2, controller.reopens()); + } + + // ---- Giving up ---- + + @Test + public void endsTheTrackAfterTheMostTriesWhileAnotherAppBlocksTheCamera() { + cameraTaken(); + for (int i = 0; i < CameraRecoveryController.MAX_REOPEN_ATTEMPTS; i++) { + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openBlocked(); + } + + assertEquals(CameraRecoveryController.MAX_REOPEN_ATTEMPTS, controller.reopens()); + assertEquals("recoveryFailed", controller.calls.get(controller.calls.size() - 1)); + verify(cameraManager).unregisterAvailabilityCallback(any()); + + // Further signals change nothing. + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + assertEquals(CameraRecoveryController.MAX_REOPEN_ATTEMPTS, controller.reopens()); + } + + @Test + public void endsTheTrackAfterThreeFailedTries() { + cameraTaken(); + for (int i = 0; i < CameraRecoveryController.MAX_FAILED_REOPENS; i++) { + prioritiesChanged(); + passTime(CameraRecoveryController.REOPEN_DELAY_MS); + openFailed(); + } + + assertEquals(CameraRecoveryController.MAX_FAILED_REOPENS, controller.reopens()); + assertEquals("recoveryFailed", controller.calls.get(controller.calls.size() - 1)); + verify(cameraManager).unregisterAvailabilityCallback(any()); + } + + // ---- Helpers: the test plays Android and the camera ---- + + private void cameraTaken() { + recovery.onCameraDisconnected(OUR_CAMERA); + runMainThread(); + } + + /** The try failed for a reason other than another app: counts as a failed try. */ + private void openFailed() { + recovery.onCameraError(FATAL_ERROR); + runMainThread(); + } + + /** Another app still holds the camera: not a failed try. */ + private void openBlocked() { + recovery.onCameraError(CameraErrorDescriptions.CAMERA_IN_USE); + runMainThread(); + } + + /** libwebrtc's 10 s warning while the open continues. */ + private void openTimedOut() { + recovery.onCameraError(CameraErrorDescriptions.CAMERA_START_TIMEOUT); + runMainThread(); + } + + private void framesArrived() { + recovery.onFramesArrived(); + runMainThread(); + } + + private void prioritiesChanged() { + registeredCallback().onCameraAccessPrioritiesChanged(); + runMainThread(); + } + + private CameraManager.AvailabilityCallback registeredCallback() { + ArgumentCaptor captor = + ArgumentCaptor.forClass(CameraManager.AvailabilityCallback.class); + verify(cameraManager, org.mockito.Mockito.atLeastOnce()) + .registerAvailabilityCallback(captor.capture(), any(Handler.class)); + return captor.getValue(); + } + + /** Runs the work that is queued on the main thread now. */ + private static void runMainThread() { + shadowMainLooper().idle(); + } + + /** Moves the main thread's clock forward and runs what is due. */ + private static void passTime(long millis) { + shadowMainLooper().idleFor(Duration.ofMillis(millis)); + } + + /** Records what CameraRecoveryController asked the camera controller to do, in order. */ + private static class FakeController + implements CameraRecoveryController.CameraReopener, CameraRecoveryController.Listener { + final List calls = new ArrayList<>(); + + @Override + public void reopenCamera() { + calls.add("reopen"); + } + + @Override + public void onCaptureInterruptedChanged(boolean interrupted) { + calls.add(interrupted ? "interrupted" : "resumed"); + } + + @Override + public void onRecoveryFailed() { + calls.add("recoveryFailed"); + } + + + int reopens() { + return count("reopen"); + } + + int count(String name) { + int count = 0; + for (String call : calls) { + if (call.equals(name)) { + count++; + } + } + return count; + } + } +} diff --git a/examples/GumTestApp/App.js b/examples/GumTestApp/App.js index 19f1572e3..4e0f8bab4 100644 --- a/examples/GumTestApp/App.js +++ b/examples/GumTestApp/App.js @@ -14,6 +14,17 @@ import { } from 'react-native'; import { mediaDevices, RTCView } from '@stream-io/react-native-webrtc'; +// Logs what the JS track sees, so e2e/camera-taken-by-other-app.sh can check that the +// mute / unmute / ended events reach JavaScript (not only the native side). +const logTrackEvents = (track) => { + const log = (what) => + console.log(`GumTestApp track ${what} id=${track.id} muted=${track.muted} readyState=${track.readyState}`); + log('started'); + ['mute', 'unmute', 'ended'].forEach((type) => { + track.addEventListener(type, () => log(type)); + }); +}; + const App = () => { const [stream, setStream] = useState(null); const start = async () => { @@ -21,6 +32,7 @@ const App = () => { if (!stream) { try { const s = await mediaDevices.getUserMedia({ video: true }); + logTrackEvents(s.getVideoTracks()[0]); setStream(s); } catch(e) { console.error(e); @@ -35,6 +47,13 @@ const App = () => { } }; + const flip = () => { + console.log('flip'); + if (stream) { + stream.getVideoTracks()[0]._switchCamera(); + } + }; + const clone = () => { console.log('clone'); if (stream) { @@ -63,6 +82,9 @@ const App = () => {