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: + *
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. + * + *
( ) = 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. + * + *
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. + * + *
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. + * + *
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 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 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