fix(camera): negotiate preview surfaces and gate diagnostic recovery

This commit is contained in:
zenord
2026-10-14 12:28:19 +08:00
parent 5339949534
commit 14f1194a95
15 changed files with 523 additions and 76 deletions
@@ -51,6 +51,7 @@ data class DiagnosticReportInfo(
val cameraProbeIsolated: Boolean=false,
val cameraProbeRunLimitMs: Int=8000,val cameraProbeCloseLimitMs: Int=8000,
val cameraProbeExitLimitMs: Int=0,
val cameraProbeAvailabilityLimitMs: Int=0,
val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(),
val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(),
val presence: PresenceDiagnosticsSnapshot = PresenceDiagnosticsSnapshot(),
@@ -96,6 +97,12 @@ object DiagnosticReportUpload {
.put("initial_failure",r.initialFailure.name.lowercase())
.put("worker_pid",r.workerPid).put("process_stop_required",r.processStopRequired)
.put("process_exit_confirmed",r.processExitConfirmed)
.put("attempted",r.attempted).put("preflight_availability",r.preflightAvailability.name.lowercase())
.put("availability_wait_ms",r.availabilityWaitMs).put("previous_close_unconfirmed",r.previousCloseUnconfirmed)
.put("surface_preparation",r.surfacePreparation.name.lowercase())
.put("surface_requested_width",r.surfaceRequestedWidth).put("surface_requested_height",r.surfaceRequestedHeight).put("surface_ready_ms",r.surfaceReadyMs)
.put("first_exception_operation",r.firstExceptionOperation.name.lowercase()).put("first_exception_kind",r.firstExceptionKind.name.lowercase())
.put("session_error_code",r.sessionErrorCode).put("camera_error_code",r.cameraErrorCode)
.put("surface_valid_before_attach",r.surfaceValidBeforeAttach).put("surface_valid_before_start",r.surfaceValidBeforeStart)
.put("surface_creating_at_attach",r.surfaceCreatingAtAttach).put("surface_width",r.surfaceWidth).put("surface_height",r.surfaceHeight)
.put("frame_observation",if(r.mode==CameraProbeMode.CAMERA1_DEFAULT_PREVIEW) "not_sampled" else "callback_counted")
@@ -115,7 +122,7 @@ object DiagnosticReportUpload {
.put("entry_failure",info.cameraProbeEntryFailure.name.lowercase()).put("max_tests",CameraProbeMode.entries.size)
.put("process_isolated",info.cameraProbeIsolated)
.put("run_limit_ms",info.cameraProbeRunLimitMs).put("close_limit_ms",info.cameraProbeCloseLimitMs)
.put("process_exit_limit_ms",info.cameraProbeExitLimitMs).put("results",rows)
.put("process_exit_limit_ms",info.cameraProbeExitLimitMs).put("availability_limit_ms",info.cameraProbeAvailabilityLimitMs).put("results",rows)
}
/** Result arrives on an OkHttp worker (or immediately if setup fails). */
@@ -30,7 +30,8 @@ import java.util.concurrent.atomic.AtomicLong
@Suppress("DEPRECATION")
class CameraProbeController(private val context: Context,private val owner: LifecycleOwner,
private val holder: SurfaceHolder,private val config: CameraProbeConfig=CameraProbeConfig(),
private val onSnapshot: (CameraProbeResult)->Unit={},private val done: ()->Unit) {
private val onSnapshot: (CameraProbeResult)->Unit={},
private val prepareLegacySurface: ((Int,Int,(Boolean)->Unit)->Unit)?=null,private val done: ()->Unit) {
private val main=Handler(Looper.getMainLooper())
private var generation=0L
@Volatile private var active: Run?=null
@@ -64,6 +65,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
val closing=java.util.concurrent.atomic.AtomicBoolean()
@Volatile var retired=false
@Volatile var legacy: Camera?=null
@Volatile var previewStartRequested=false
var provider: ProcessCameraProvider?=null
var analysis: ImageAnalysis?=null;var preview: Preview?=null
var sink: CameraPreviewSurface?=null
@@ -110,7 +112,6 @@ class CameraProbeController(private val context: Context,private val owner: Life
if(!holder.surface.isValid || holder.isCreating || holder.surfaceFrame.width()<=0 || holder.surfaceFrame.height()<=0) {
error(run,CameraProbeFailure.SURFACE);return@post
}
var camera: Camera?=null
var failure=CameraProbeFailure.OPEN
try {
val id=nativeCall(run,CameraNativeOperation.ENUMERATE) {
@@ -120,11 +121,10 @@ class CameraProbeController(private val context: Context,private val owner: Life
}
}
if(id==null) {error(run,CameraProbeFailure.NO_FRONT);return@post}
camera=nativeCall(run,CameraNativeOperation.OPEN) {Camera.open(id)};run.legacy=camera
val camera=nativeCall(run,CameraNativeOperation.OPEN) {Camera.open(id)};run.legacy=camera
if(run.retired) return@post
val params=nativeCall(run,CameraNativeOperation.GET_PARAMETERS) {camera.parameters}
val baseline=run.mode==CameraProbeMode.CAMERA1_DEFAULT_PREVIEW
if(!baseline) {
if(run.mode!=CameraProbeMode.CAMERA1_DEFAULT_PREVIEW) {
failure=CameraProbeFailure.UNSUPPORTED_SIZE
check(params.supportedPreviewSizes.any {it.width==run.mode.width && it.height==run.mode.height})
check(ImageFormat.NV21 in params.supportedPreviewFormats)
@@ -134,49 +134,78 @@ class CameraProbeController(private val context: Context,private val owner: Life
}
val actual=nativeCall(run,CameraNativeOperation.GET_PARAMETERS) {camera.parameters.previewSize}
run.width=actual.width;run.height=actual.height
failure=CameraProbeFailure.START
nativeCall(run,CameraNativeOperation.SET_ERROR_CALLBACK) {
camera.setErrorCallback {_,_->error(run,CameraProbeFailure.CAMERA_ERROR)}
}
val surfaceReady=holder.surface.isValid && !holder.isCreating && holder.surfaceFrame.width()>0 && holder.surfaceFrame.height()>0
run.update {it.copy(surfaceValidBeforeAttach=surfaceReady,surfaceCreatingAtAttach=holder.isCreating,
surfaceWidth=holder.surfaceFrame.width(),surfaceHeight=holder.surfaceFrame.height())}
if(!surfaceReady) {error(run,CameraProbeFailure.SURFACE);return@post}
nativeCall(run,CameraNativeOperation.ATTACH_SURFACE) {camera.setPreviewDisplay(holder)}
if(!baseline) {
val expected=actual.width*actual.height*3/2
nativeCall(run,CameraNativeOperation.SET_FRAME_CALLBACK) {
camera.setPreviewCallbackWithBuffer {data,c ->
if(!run.retired) {
if(data!=null && data.size==expected) frame(run,actual.width,actual.height,data.size)
else error(run,CameraProbeFailure.CAMERA_ERROR)
}
if(!run.retired && data!=null) try {c.addCallbackBuffer(data)}
catch(_: Exception) {error(run,CameraProbeFailure.CAMERA_ERROR)}
}
val prepare=prepareLegacySurface
if(prepare==null) startLegacyPreview(run,camera,actual)
else main.post {
if(!valid(run)) return@post
run.update {it.copy(surfacePreparation=ProbeSurfacePreparation.WAITING,
surfaceRequestedWidth=actual.width,surfaceRequestedHeight=actual.height)}
publish(run);event(run,"surface_resize_requested")
val accepted=java.util.concurrent.atomic.AtomicBoolean()
try {prepare(actual.width,actual.height, complete@ {ready ->
if(!valid(run) || !accepted.compareAndSet(false,true)) return@complete
val matched=ready && holder.surface.isValid && !holder.isCreating &&
holder.surfaceFrame.width()==actual.width && holder.surfaceFrame.height()==actual.height
run.update {it.copy(surfacePreparation=if(matched) ProbeSurfacePreparation.MATCHED else ProbeSurfacePreparation.FAILED,
surfaceReadyMs=if(matched) SystemClock.elapsedRealtime() else -1)}
publish(run);event(run,if(matched) "surface_resize_ready" else "surface_resize_failed")
if(matched) run.worker.post {if(valid(run)) startLegacyPreview(run,camera,actual)}
else error(run,CameraProbeFailure.SURFACE)
})} catch(_: Exception) {
run.update {it.copy(surfacePreparation=ProbeSurfacePreparation.FAILED)}
error(run,CameraProbeFailure.SURFACE)
}
nativeCall(run,CameraNativeOperation.ADD_BUFFERS) {repeat(3) {camera.addCallbackBuffer(ByteArray(expected))}}
}
if(run.retired) return@post
run.update {it.copy(surfaceValidBeforeStart=holder.surface.isValid && !holder.isCreating)}
if(!run.result.surfaceValidBeforeStart) {error(run,CameraProbeFailure.SURFACE);return@post}
nativeCall(run,CameraNativeOperation.START_PREVIEW) {camera.startPreview()}
main.post {if(valid(run)) {
val now=SystemClock.elapsedRealtime()
run.update {it.copy(boundMs=now,openMs=now,surfaceProvidedMs=now,
nativeState=CameraNativeState.OPEN,surfaceCreated=true)}
event(run,"opened");publish(run)
}}
} catch(_: Exception) {error(run,failure)}
}
}
private fun startLegacyPreview(run: Run,camera: Camera,actual: Camera.Size) {
if(!valid(run)) return
try {
nativeCall(run,CameraNativeOperation.SET_ERROR_CALLBACK) {
camera.setErrorCallback {code,_->
run.update {it.copy(cameraErrorCode=if(it.cameraErrorCode<0) code else it.cameraErrorCode)}
error(run,CameraProbeFailure.CAMERA_ERROR)
}
}
val surfaceReady=holder.surface.isValid && !holder.isCreating && holder.surfaceFrame.width()>0 && holder.surfaceFrame.height()>0
run.update {it.copy(surfaceValidBeforeAttach=surfaceReady,surfaceCreatingAtAttach=holder.isCreating,
surfaceWidth=holder.surfaceFrame.width(),surfaceHeight=holder.surfaceFrame.height())}
if(!surfaceReady) {error(run,CameraProbeFailure.SURFACE);return}
nativeCall(run,CameraNativeOperation.ATTACH_SURFACE) {camera.setPreviewDisplay(holder)}
if(run.mode!=CameraProbeMode.CAMERA1_DEFAULT_PREVIEW) {
val expected=actual.width*actual.height*3/2
nativeCall(run,CameraNativeOperation.SET_FRAME_CALLBACK) {
camera.setPreviewCallbackWithBuffer {data,c ->
if(!run.retired) {
if(data!=null && data.size==expected) frame(run,actual.width,actual.height,data.size)
else error(run,CameraProbeFailure.CAMERA_ERROR)
}
if(!run.retired && data!=null) try {c.addCallbackBuffer(data)}
catch(_: Exception) {error(run,CameraProbeFailure.CAMERA_ERROR)}
}
}
nativeCall(run,CameraNativeOperation.ADD_BUFFERS) {repeat(3) {camera.addCallbackBuffer(ByteArray(expected))}}
}
if(run.retired) return
run.update {it.copy(surfaceValidBeforeStart=holder.surface.isValid && !holder.isCreating)}
if(!run.result.surfaceValidBeforeStart) {error(run,CameraProbeFailure.SURFACE);return}
run.previewStartRequested=true
nativeCall(run,CameraNativeOperation.START_PREVIEW) {camera.startPreview()}
main.post {if(valid(run)) {
val now=SystemClock.elapsedRealtime()
run.update {it.copy(boundMs=now,openMs=now,surfaceProvidedMs=now,
nativeState=CameraNativeState.OPEN,surfaceCreated=true)}
event(run,"opened");publish(run)
}}
} catch(_: Exception) {error(run,CameraProbeFailure.START)}
}
private fun releaseLegacy(run: Run,camera: Camera?) {
try {
if(run.mode!=CameraProbeMode.CAMERA1_DEFAULT_PREVIEW)
nativeCall(run,CameraNativeOperation.CLEAR_FRAME_CALLBACK) {camera?.setPreviewCallbackWithBuffer(null)}
nativeCall(run,CameraNativeOperation.CLEAR_ERROR_CALLBACK) {camera?.setErrorCallback(null)}
nativeCall(run,CameraNativeOperation.STOP_PREVIEW) {camera?.stopPreview()}
if(run.previewStartRequested) nativeCall(run,CameraNativeOperation.STOP_PREVIEW) {camera?.stopPreview()}
nativeCall(run,CameraNativeOperation.RELEASE) {camera?.release()};run.legacy=null
main.post {
val now=SystemClock.elapsedRealtime()
@@ -262,7 +291,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
val changed=run.result.nativeState!=native || state.error!=null
run.update {it.copy(nativeState=native,
openMs=if(native==CameraNativeState.OPEN && it.openMs<0) SystemClock.elapsedRealtime() else it.openMs)}
if(state.error!=null) run.update {it.copy(sessionFailure=when(state.error!!.code) {
if(state.error!=null) run.update {it.copy(sessionErrorCode=if(it.sessionErrorCode<0) state.error!!.code else it.sessionErrorCode,sessionFailure=when(state.error!!.code) {
CameraState.ERROR_STREAM_CONFIG->CameraSessionFailure.STREAM_CONFIG
CameraState.ERROR_CAMERA_IN_USE->CameraSessionFailure.IN_USE
CameraState.ERROR_CAMERA_FATAL_ERROR->CameraSessionFailure.FATAL
@@ -341,7 +370,16 @@ class CameraProbeController(private val context: Context,private val owner: Life
publish(run);event(run,"native_call_return")
return value
} catch(error: Exception) {
run.update {it.copy(nativeCallState=CameraNativeCallState.THREW,nativeCallReturnedMs=SystemClock.elapsedRealtime())}
run.update {it.copy(nativeCallState=CameraNativeCallState.THREW,nativeCallReturnedMs=SystemClock.elapsedRealtime(),
firstExceptionOperation=if(it.firstExceptionOperation==CameraNativeOperation.NONE) operation else it.firstExceptionOperation,
firstExceptionKind=if(it.firstExceptionKind==ProbeExceptionKind.NONE) when(error) {
is SecurityException -> ProbeExceptionKind.SECURITY
is IllegalArgumentException -> ProbeExceptionKind.ARGUMENT
is IllegalStateException -> ProbeExceptionKind.STATE
is java.io.IOException -> ProbeExceptionKind.IO
is RuntimeException -> ProbeExceptionKind.RUNTIME
else -> ProbeExceptionKind.OTHER
} else it.firstExceptionKind)}
publish(run);event(run,"native_call_threw");throw error
}
}
@@ -12,10 +12,13 @@ enum class CameraNativeOperation { NONE, ENUMERATE, OPEN, GET_PARAMETERS, SET_PA
ATTACH_SURFACE, SET_FRAME_CALLBACK, ADD_BUFFERS, START_PREVIEW, CLEAR_FRAME_CALLBACK, CLEAR_ERROR_CALLBACK,
STOP_PREVIEW, RELEASE, PROVIDER_WAIT, BIND, UNBIND }
enum class CameraNativeCallState { NONE, PENDING, RETURNED, THREW }
enum class ProbeCameraAvailability { UNKNOWN, AVAILABLE, UNAVAILABLE, NO_FRONT }
enum class ProbeSurfacePreparation { NOT_REQUESTED, WAITING, MATCHED, FAILED }
enum class ProbeExceptionKind { NONE, SECURITY, ARGUMENT, STATE, IO, RUNTIME, OTHER }
enum class CameraProbeStage { IDLE, RUNNING, CLOSING, DONE, BLOCKED }
enum class CameraProbeFailure { NONE, PERMISSION, NO_FRONT, UNSUPPORTED_SIZE, PROVIDER, BIND, OPEN,
START, CAMERA_ERROR, SURFACE, NATIVE_TIMEOUT, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED,
WORKER_START_TIMEOUT, WORKER_DIED, PROCESS_EXIT_TIMEOUT }
WORKER_START_TIMEOUT, WORKER_DIED, PROCESS_EXIT_TIMEOUT, CAMERA_UNAVAILABLE, AVAILABILITY_UNKNOWN, AVAILABILITY_UNSTABLE }
data class CameraProbeConfig(
val modes: List<CameraProbeMode> = CameraProbeMode.entries.toList(),
val runLimitMs: Long = 8_000, val closeLimitMs: Long = 8_000,
@@ -44,6 +47,13 @@ data class CameraProbeResult(val mode: CameraProbeMode,val startedMs: Long,
val workerPid: Int=-1,val processStopRequired: Boolean=false,val processExitConfirmed: Boolean=false,
val surfaceValidBeforeAttach: Boolean=false,val surfaceValidBeforeStart: Boolean=false,
val surfaceCreatingAtAttach: Boolean=false,val surfaceWidth: Int=0,val surfaceHeight: Int=0,
val attempted: Boolean=true,val preflightAvailability: ProbeCameraAvailability=ProbeCameraAvailability.UNKNOWN,
val availabilityWaitMs: Long=0,val previousCloseUnconfirmed: Boolean=false,
val surfacePreparation: ProbeSurfacePreparation=ProbeSurfacePreparation.NOT_REQUESTED,
val surfaceRequestedWidth: Int=0,val surfaceRequestedHeight: Int=0,val surfaceReadyMs: Long=-1,
val firstExceptionOperation: CameraNativeOperation=CameraNativeOperation.NONE,
val firstExceptionKind: ProbeExceptionKind=ProbeExceptionKind.NONE,
val sessionErrorCode: Int=-1,val cameraErrorCode: Int=-1,
) : java.io.Serializable
/** One foreground suite per process at a time. A timed-out close keeps normal camera inhibited. */