fix: Always call CaptureSession fully synchronously under Mutex (#1972)

* fix: Always call `CaptureSession` fully synchronously under Mutex

* Update CameraView.kt

* chore: Format
This commit is contained in:
Marc Rousavy 2023-10-10 18:51:46 +02:00 committed by GitHub
parent 915ef331d3
commit 18b30cd073
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 63 deletions

View File

@ -28,8 +28,8 @@ import com.mrousavy.camera.parsers.PixelFormat
import com.mrousavy.camera.parsers.ResizeMode
import com.mrousavy.camera.parsers.Torch
import com.mrousavy.camera.parsers.VideoStabilizationMode
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
//
@ -42,7 +42,9 @@ import kotlinx.coroutines.launch
// TODO: takePhoto() return with jsi::Value Image reference for faster capture
@SuppressLint("ClickableViewAccessibility", "ViewConstructor", "MissingPermission")
class CameraView(context: Context) : FrameLayout(context) {
class CameraView(context: Context) :
FrameLayout(context),
CoroutineScope {
companion object {
const val TAG = "CameraView"
@ -104,6 +106,8 @@ class CameraView(context: Context) : FrameLayout(context) {
internal val outputOrientation: Orientation
get() = orientation ?: inputOrientation
override val coroutineContext: CoroutineContext = CameraQueues.cameraQueue.coroutineDispatcher
init {
this.installHierarchyFitter()
setupPreviewView()
@ -116,12 +120,12 @@ class CameraView(context: Context) : FrameLayout(context) {
isMounted = true
invokeOnViewReady()
}
updateLifecycle()
launch { updateLifecycle() }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
updateLifecycle()
launch { updateLifecycle() }
}
private fun getPreviewTargetSize(): Size {
@ -142,7 +146,7 @@ class CameraView(context: Context) : FrameLayout(context) {
val previewView = PreviewView(context, this.getPreviewTargetSize(), resizeMode) { surface ->
previewSurface = surface
configureSession()
launch { configureSession() }
}
previewView.layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
@ -164,6 +168,8 @@ class CameraView(context: Context) : FrameLayout(context) {
val shouldCheckActive = shouldReconfigureFormat || changedProps.contains("isActive")
val shouldReconfigureZoomGesture = changedProps.contains("enableZoomGesture")
launch {
// Expensive Calls
if (shouldReconfigurePreview) {
setupPreviewView()
}
@ -176,7 +182,7 @@ class CameraView(context: Context) : FrameLayout(context) {
if (shouldCheckActive) {
updateLifecycle()
}
// Fast Calls
if (shouldReconfigureZoom) {
updateZoom()
}
@ -186,13 +192,14 @@ class CameraView(context: Context) : FrameLayout(context) {
if (shouldReconfigureZoomGesture) {
updateZoomGesture()
}
}
} catch (e: Throwable) {
Log.e(TAG, "update() threw: ${e.message}")
invokeOnError(e)
}
}
private fun configureSession() {
private suspend fun configureSession() {
try {
Log.i(TAG, "Configuring Camera Device...")
@ -236,23 +243,21 @@ class CameraView(context: Context) : FrameLayout(context) {
}
}
private fun configureFormat() {
private suspend fun configureFormat() {
cameraSession.configureFormat(fps, videoStabilizationMode, hdr, lowLightBoost)
}
private fun updateLifecycle() {
private suspend fun updateLifecycle() {
cameraSession.setIsActive(isActive && isAttachedToWindow)
}
private fun updateZoom() {
private suspend fun updateZoom() {
cameraSession.setZoom(zoom)
}
private fun updateTorch() {
CoroutineScope(Dispatchers.Default).launch {
private suspend fun updateTorch() {
cameraSession.setTorchMode(torch == Torch.ON)
}
}
@SuppressLint("ClickableViewAccessibility")
private fun updateZoomGesture() {
@ -262,7 +267,7 @@ class CameraView(context: Context) : FrameLayout(context) {
object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
zoom *= detector.scaleFactor
cameraSession.setZoom(zoom)
launch { updateZoom() }
return true
}
}

View File

@ -40,9 +40,6 @@ import com.mrousavy.camera.parsers.VideoFileType
import com.mrousavy.camera.parsers.VideoStabilizationMode
import java.io.Closeable
import java.util.concurrent.CancellationException
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@ -52,7 +49,6 @@ class CameraSession(
private val onInitialized: () -> Unit,
private val onError: (e: Throwable) -> Unit
) : CameraManager.AvailabilityCallback(),
CoroutineScope,
Closeable,
CameraOutputs.Callback {
companion object {
@ -112,8 +108,6 @@ class CameraSession(
updateVideoOutputs()
}
override val coroutineContext: CoroutineContext = CameraQueues.cameraQueue.coroutineDispatcher
init {
cameraManager.registerAvailabilityCallback(this, CameraQueues.cameraQueue.handler)
}
@ -135,7 +129,7 @@ class CameraSession(
return Orientation.fromRotationDegrees(sensorRotation)
}
fun configureSession(
suspend fun configureSession(
cameraId: String,
preview: CameraOutputs.PreviewOutput? = null,
photo: CameraOutputs.PhotoOutput? = null,
@ -165,12 +159,10 @@ class CameraSession(
updateVideoOutputs()
this.cameraId = cameraId
launch {
startRunning()
}
}
fun configureFormat(
suspend fun configureFormat(
fps: Int? = null,
videoStabilizationMode: VideoStabilizationMode? = null,
hdr: Boolean? = null,
@ -198,31 +190,27 @@ class CameraSession(
)
needsReconfiguration = true
}
launch {
if (needsReconfiguration) {
startRunning()
} else {
updateRepeatingRequest()
}
}
}
/**
* Starts or stops the Camera.
*/
fun setIsActive(isActive: Boolean) {
suspend fun setIsActive(isActive: Boolean) {
Log.i(TAG, "Setting isActive: $isActive (isRunning: $isRunning)")
this.isActive = isActive
if (isActive == isRunning) return
launch {
if (isActive) {
startRunning()
} else {
stopRunning()
}
}
}
private fun updateVideoOutputs() {
val videoPipeline = outputs?.videoOutput?.videoPipeline ?: return
@ -328,14 +316,12 @@ class CameraSession(
}
}
fun setZoom(zoom: Float) {
suspend fun setZoom(zoom: Float) {
if (this.zoom != zoom) {
this.zoom = zoom
launch {
updateRepeatingRequest()
}
}
}
suspend fun focus(x: Int, y: Int) {
val captureSession = captureSession ?: throw CameraNotReadyError()