fix(camera): negotiate preview surfaces and gate diagnostic recovery
This commit is contained in:
@@ -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. */
|
||||
|
||||
@@ -37,8 +37,8 @@ android {
|
||||
applicationId 'com.gorios.lanvoice.cameraprobe'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 3
|
||||
versionName 'camera-probe-0.1.2'
|
||||
versionCode 4
|
||||
versionName 'camera-probe-0.1.3'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -21,6 +21,8 @@ class CameraProbeWorkerService : Service(), LifecycleOwner {
|
||||
const val SNAPSHOT = 3
|
||||
const val END_SAMPLING = 4
|
||||
const val DONE = 5
|
||||
const val SURFACE_REQUEST = 6
|
||||
const val SURFACE_READY = 7
|
||||
const val PROCESS_SUFFIX = ":camera_probe_worker"
|
||||
}
|
||||
private val registry = LifecycleRegistry(this)
|
||||
@@ -30,10 +32,17 @@ class CameraProbeWorkerService : Service(), LifecycleOwner {
|
||||
private var runner: CameraProbeController? = null
|
||||
private var lastWireMs = -1L
|
||||
private var lastSignature = ""
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var localHolder: LocalPreviewHolder? = null
|
||||
private var resizeSerial = 0L
|
||||
private data class PendingSurface(val id: Long, val width: Int, val height: Int, val complete: (Boolean)->Unit, val timeout: Runnable)
|
||||
private var pendingSurface: PendingSurface? = null
|
||||
private val ipc = Messenger(Handler(Looper.getMainLooper()) { message ->
|
||||
if (message.sendingUid != android.os.Process.myUid()) return@Handler true
|
||||
when (message.what) {
|
||||
START -> start(message)
|
||||
END_SAMPLING -> if (message.data.getLong("epoch", -1) == epoch) runner?.endSampling()
|
||||
SURFACE_READY -> acceptSurface(message)
|
||||
}
|
||||
true
|
||||
})
|
||||
@@ -59,28 +68,51 @@ class CameraProbeWorkerService : Service(), LifecycleOwner {
|
||||
send(READY, null)
|
||||
registry.currentState = Lifecycle.State.STARTED
|
||||
CameraProbeStore.begin()
|
||||
runner = CameraProbeController(this, this, LocalPreviewHolder(surface, width, height),
|
||||
val previewHolder = LocalPreviewHolder(surface, width, height); localHolder = previewHolder
|
||||
runner = CameraProbeController(this, this, previewHolder,
|
||||
config = CameraProbeConfig(listOf(mode), IsolatedProbeSuite.RUN_LIMIT_MS, IsolatedProbeSuite.CLOSE_LIMIT_MS),
|
||||
onSnapshot = { row ->
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val signature = "${row.nativeOperation}/${row.nativeCallState}/${row.failure}/${row.closeConfirmed}"
|
||||
val signature = "${row.nativeOperation}/${row.nativeCallState}/${row.failure}/${row.closeConfirmed}/${row.surfacePreparation}/${row.sessionErrorCode}/${row.firstExceptionOperation}"
|
||||
synchronized(this) {
|
||||
if (signature != lastSignature || now - lastWireMs >= 250) {
|
||||
lastSignature = signature; lastWireMs = now; send(SNAPSHOT, row)
|
||||
}
|
||||
}
|
||||
}, done = {
|
||||
}, prepareLegacySurface = ::requestSurface, done = {
|
||||
val row = CameraProbeStore.results.lastOrNull()
|
||||
?: CameraProbeResult(mode, SystemClock.elapsedRealtime(), failure = CameraProbeStore.entryFailure)
|
||||
send(SNAPSHOT, row); send(DONE, null)
|
||||
})
|
||||
runner!!.start()
|
||||
}
|
||||
private fun send(what: Int, row: CameraProbeResult?) {
|
||||
private fun requestSurface(width: Int, height: Int, complete: (Boolean)->Unit) {
|
||||
if (pendingSurface != null || width !in 1..4096 || height !in 1..4096) { complete(false); return }
|
||||
val id = ++resizeSerial
|
||||
val timeout = Runnable {
|
||||
if (pendingSurface?.id == id) { pendingSurface = null; complete(false) }
|
||||
}
|
||||
pendingSurface = PendingSurface(id, width, height, complete, timeout)
|
||||
main.postDelayed(timeout, 2_000)
|
||||
send(SURFACE_REQUEST, null, width, height, id)
|
||||
}
|
||||
private fun acceptSurface(message: Message) {
|
||||
val data = message.data
|
||||
val pending = pendingSurface ?: return
|
||||
if (data.getLong("epoch", -1) != epoch || data.getLong("resize_id", -1) != pending.id) return
|
||||
@Suppress("DEPRECATION") val surface = data.getParcelable<Surface>("surface") ?: return
|
||||
val width = data.getInt("width"); val height = data.getInt("height")
|
||||
if (!surface.isValid || width != pending.width || height != pending.height) return
|
||||
localHolder?.update(surface, width, height) ?: return
|
||||
main.removeCallbacks(pending.timeout); pendingSurface = null
|
||||
pending.complete(true)
|
||||
}
|
||||
private fun send(what: Int, row: CameraProbeResult?, width: Int=0, height: Int=0, resizeId: Long=0) {
|
||||
val message = Message.obtain(null, what).apply {
|
||||
arg1 = android.os.Process.myPid()
|
||||
data = Bundle().apply {
|
||||
putLong("epoch", epoch)
|
||||
if (what == SURFACE_REQUEST) { putInt("width", width); putInt("height", height); putLong("resize_id", resizeId) }
|
||||
if (row != null) putSerializable("result", row)
|
||||
}
|
||||
}
|
||||
@@ -96,10 +128,11 @@ class CameraProbeWorkerService : Service(), LifecycleOwner {
|
||||
|
||||
/** SurfaceView remains owned by the foreground parent. Sizes are set there before start IPC. */
|
||||
@Suppress("DEPRECATION")
|
||||
private class LocalPreviewHolder(private val previewSurface: Surface, width: Int, height: Int) : SurfaceHolder {
|
||||
private val frame = Rect(0, 0, width, height)
|
||||
override fun getSurface() = previewSurface
|
||||
override fun getSurfaceFrame() = frame
|
||||
private class LocalPreviewHolder(private var previewSurface: Surface, width: Int, height: Int) : SurfaceHolder {
|
||||
private var frame = Rect(0, 0, width, height)
|
||||
@Synchronized fun update(surface: Surface, width: Int, height: Int) { previewSurface = surface; frame = Rect(0, 0, width, height) }
|
||||
@Synchronized override fun getSurface() = previewSurface
|
||||
@Synchronized override fun getSurfaceFrame() = Rect(frame)
|
||||
override fun isCreating() = false
|
||||
override fun setFixedSize(width: Int, height: Int) {
|
||||
check(width == frame.width() && height == frame.height())
|
||||
|
||||
+44
-6
@@ -23,13 +23,17 @@ import com.gorios.lanvoice.expression.*
|
||||
/** The foreground UI/report owner never calls a native camera API. A private bound worker
|
||||
* runs one configuration, then must demonstrably exit before the next owner is launched. */
|
||||
class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
private val suite = IsolatedProbeSuite(SystemClock.elapsedRealtime())
|
||||
private val suite = IsolatedProbeSuite(SystemClock.elapsedRealtime(), requireAvailability = true,
|
||||
modes = IsolatedProbeSuite.RECOMMENDED_ORDER)
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var holder: SurfaceHolder? = null
|
||||
private var foreground = false
|
||||
private var admitted = false
|
||||
private var pendingStart: ProbeIsolationEffect.Start? = null
|
||||
private var lease: WorkerLease? = null
|
||||
private var availabilityMonitor: ProbeAvailabilityMonitor? = null
|
||||
private data class SurfaceResize(val epoch: Long, val id: Long, val width: Int, val height: Int)
|
||||
private var pendingResize: SurfaceResize? = null
|
||||
private var phase by mutableStateOf(ProbeIsolationPhase.IDLE)
|
||||
private var rows by mutableStateOf<List<CameraProbeResult>>(emptyList())
|
||||
private var sending by mutableStateOf(false)
|
||||
@@ -57,6 +61,14 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
if (row != null) dispatch(suite.snapshot(token, row, now()))
|
||||
}
|
||||
CameraProbeWorkerService.DONE -> dispatch(suite.completed(token, now()))
|
||||
CameraProbeWorkerService.SURFACE_REQUEST -> {
|
||||
val width = message.data.getInt("width"); val height = message.data.getInt("height")
|
||||
if (suite.phase == ProbeIsolationPhase.RUNNING && foreground && width in 1..4096 && height in 1..4096) {
|
||||
pendingResize = SurfaceResize(token, message.data.getLong("resize_id", -1), width, height)
|
||||
holder?.setFixedSize(width, height)
|
||||
sendSurfaceReady()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
@@ -80,12 +92,12 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
Column(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)
|
||||
.verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
Text("前置相机一键诊断", style = MaterialTheme.typography.titleLarge)
|
||||
Text("七项依次检查;每项采样5秒、关闭等待2秒。卡住时结束工作进程,确认退出后继续。仅发送状态,不保存画面、不收音。")
|
||||
Text("七项自动检查,默认预览放最后。每项采样5秒、关闭等待2秒;下一项等待相机可用最多5秒,不可用记为未测试。仅发送状态,不保存画面、不收音。")
|
||||
AndroidView(factory = { context -> SurfaceView(context).apply {
|
||||
holder.addCallback(object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(h: SurfaceHolder) { this@IsolatedCameraDiagnosticsActivity.holder = h }
|
||||
override fun surfaceChanged(h: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
if (width > 0 && height > 0) main.post { startIfReady(); bindIfSurfaceReady() }
|
||||
if (width > 0 && height > 0) main.post { startIfReady(); bindIfSurfaceReady(); sendSurfaceReady() }
|
||||
}
|
||||
override fun surfaceDestroyed(h: SurfaceHolder) {
|
||||
this@IsolatedCameraDiagnosticsActivity.holder = null
|
||||
@@ -95,6 +107,7 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
} }, modifier = Modifier.fillMaxWidth().height(220.dp))
|
||||
Text("配置 ${rows.size}/7 · " + when (phase) {
|
||||
ProbeIsolationPhase.IDLE, ProbeIsolationPhase.STARTING -> "准备预览与工作进程"
|
||||
ProbeIsolationPhase.WAITING_CAMERA -> "等待系统前置相机可用"
|
||||
ProbeIsolationPhase.RUNNING -> "采样中"
|
||||
ProbeIsolationPhase.CLOSING -> "关闭当前配置"
|
||||
ProbeIsolationPhase.WAITING_EXIT -> "等待工作进程退出"
|
||||
@@ -102,7 +115,7 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
ProbeIsolationPhase.DONE -> "已结束,自动发送报告"
|
||||
ProbeIsolationPhase.BLOCKED -> "系统未确认进程退出,已发送卡点;剩余项目未运行"
|
||||
})
|
||||
rows.forEach { row -> Text("${row.mode.name.lowercase()} · ${row.failure.name.lowercase()} · 帧 ${row.frames} / capture ${row.captureCompleted} · 原生关闭${if (row.closeConfirmed) "已确认" else "未确认"} · 进程退出${if (row.processExitConfirmed) "已确认" else "等待"}") }
|
||||
rows.forEach { row -> Text("${row.mode.name.lowercase()} · ${if(row.attempted) "已运行" else "未运行"} · ${row.failure.name.lowercase()} · 帧 ${row.frames} / capture ${row.captureCompleted} · 原生关闭${if (row.closeConfirmed) "已确认" else "未确认"}") }
|
||||
rows.lastOrNull()?.let { Text("当前原生调用 ${it.nativeOperation.name.lowercase()} / ${it.nativeCallState.name.lowercase()}") }
|
||||
Text(if (sending) "正在发送报告…" else receipt ?: "报告会在检查结束后自动发送")
|
||||
if (receipt == "发送失败") TextButton(onClick = ::sendReport) { Text("重发报告") }
|
||||
@@ -111,6 +124,9 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
Text("默认 Camera1 项仅预览、没有图像回调,帧0不能证明无画面。进程退出确认不等于原生关闭成功;报告分别记录。")
|
||||
}
|
||||
} }
|
||||
availabilityMonitor = ProbeAvailabilityMonitor(this) { epoch, state -> main.post {
|
||||
if (!isDestroyed) dispatch(suite.availability(state, now(), epoch))
|
||||
} }
|
||||
main.post(tick)
|
||||
}
|
||||
private fun startIfReady() {
|
||||
@@ -124,6 +140,7 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
DiagnosticLog.state("camera_probe_suite", "${suite.epoch}/$phase/${row?.failure}/${row?.nativeOperation}/${row?.nativeCallState}",
|
||||
"camera_probe phase=${phase.name.lowercase()} mode=${row?.mode?.name?.lowercase() ?: "none"} frames=${row?.frames ?: 0} operation=${row?.nativeOperation?.name?.lowercase() ?: "none"} call_state=${row?.nativeCallState?.name?.lowercase() ?: "none"} failure=${row?.failure?.name?.lowercase() ?: "none"}")
|
||||
effects.forEach { effect -> when (effect) {
|
||||
is ProbeIsolationEffect.ObserveAvailability -> availabilityMonitor?.observe(effect.epoch)
|
||||
is ProbeIsolationEffect.Start -> {
|
||||
pendingStart = effect
|
||||
val width = effect.mode.width.takeIf { it > 0 } ?: 640
|
||||
@@ -132,7 +149,7 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
bindIfSurfaceReady()
|
||||
}
|
||||
is ProbeIsolationEffect.EndSampling -> sendEndSampling(effect.epoch)
|
||||
is ProbeIsolationEffect.Terminate -> { pendingStart = null; lease?.let(::terminate) ?: dispatch(suite.exited(effect.epoch, now())) }
|
||||
is ProbeIsolationEffect.Terminate -> { pendingStart = null; pendingResize = null; lease?.let(::terminate) ?: dispatch(suite.exited(effect.epoch, now())) }
|
||||
ProbeIsolationEffect.Report -> {
|
||||
main.removeCallbacks(tick)
|
||||
CameraProbeStore.finish(suite.phase == ProbeIsolationPhase.BLOCKED)
|
||||
@@ -140,6 +157,24 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
}
|
||||
} }
|
||||
}
|
||||
/** Resize the real parent SurfaceView and acknowledge only its observed matching buffer size.
|
||||
* No Camera1 startPreview is allowed on a stale/pre-resize handle. */
|
||||
private fun sendSurfaceReady() {
|
||||
val resize = pendingResize ?: return
|
||||
val current = lease ?: return
|
||||
val h = holder ?: return
|
||||
if (!foreground || suite.phase != ProbeIsolationPhase.RUNNING || current.epoch != resize.epoch ||
|
||||
!h.surface.isValid || h.isCreating || h.surfaceFrame.width() != resize.width || h.surfaceFrame.height() != resize.height) return
|
||||
try {
|
||||
current.messenger?.send(Message.obtain(null, CameraProbeWorkerService.SURFACE_READY).apply {
|
||||
data = Bundle().apply {
|
||||
putLong("epoch", resize.epoch); putLong("resize_id", resize.id)
|
||||
putParcelable("surface", h.surface); putInt("width", h.surfaceFrame.width()); putInt("height", h.surfaceFrame.height())
|
||||
}
|
||||
}) ?: return
|
||||
pendingResize = null
|
||||
} catch (_: RemoteException) { workerExited(current) }
|
||||
}
|
||||
private fun bindIfSurfaceReady() {
|
||||
val request = pendingStart ?: return
|
||||
val h = holder ?: return
|
||||
@@ -205,6 +240,7 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
unbind(current)
|
||||
try { current.death?.let { current.binder?.unlinkToDeath(it, 0) } } catch (_: java.util.NoSuchElementException) {}
|
||||
lease = null
|
||||
pendingResize = null
|
||||
dispatch(suite.exited(current.epoch, now()))
|
||||
}
|
||||
private fun sendEndSampling(token: Long) {
|
||||
@@ -222,10 +258,12 @@ class IsolatedCameraDiagnosticsActivity : ComponentActivity() {
|
||||
connection = "LOCAL_CAMERA_PROBE", voiceActive = false, phase = "IDLE", aec = "NOT_RUNNING",
|
||||
avatarMode = "camera_probe", cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
|
||||
cameraProbeStage = stage, cameraProbes = suite.results, cameraProbeIsolated = true,
|
||||
cameraProbeRunLimitMs = IsolatedProbeSuite.RUN_LIMIT_MS.toInt(), cameraProbeCloseLimitMs = IsolatedProbeSuite.CLOSE_LIMIT_MS.toInt(), cameraProbeExitLimitMs = IsolatedProbeSuite.EXIT_LIMIT_MS.toInt())
|
||||
cameraProbeRunLimitMs = IsolatedProbeSuite.RUN_LIMIT_MS.toInt(), cameraProbeCloseLimitMs = IsolatedProbeSuite.CLOSE_LIMIT_MS.toInt(), cameraProbeExitLimitMs = IsolatedProbeSuite.EXIT_LIMIT_MS.toInt(),
|
||||
cameraProbeAvailabilityLimitMs = IsolatedProbeSuite.AVAILABILITY_LIMIT_MS.toInt())
|
||||
DiagnosticReportUpload.send(info) { ok -> main.post { sending = false; receipt = if (ok) "已自动发送" else "发送失败" } }
|
||||
}
|
||||
override fun onResume() { super.onResume(); hideSystemBars(window); foreground = true; main.post { startIfReady(); bindIfSurfaceReady() } }
|
||||
override fun onPause() { foreground = false; if(admitted) dispatch(suite.cancel(now())); super.onPause() }
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus); if (hasFocus) hideSystemBars(window) }
|
||||
override fun onDestroy() { availabilityMonitor?.stop(); super.onDestroy() }
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ package com.gorios.lanvoice
|
||||
|
||||
import com.gorios.lanvoice.expression.*
|
||||
|
||||
enum class ProbeIsolationPhase { IDLE, STARTING, RUNNING, CLOSING, WAITING_EXIT, SETTLING, DONE, BLOCKED }
|
||||
enum class ProbeIsolationPhase { IDLE, WAITING_CAMERA, STARTING, RUNNING, CLOSING, WAITING_EXIT, SETTLING, DONE, BLOCKED }
|
||||
sealed interface ProbeIsolationEffect {
|
||||
data class ObserveAvailability(val epoch: Long): ProbeIsolationEffect
|
||||
data class Start(val epoch: Long, val mode: CameraProbeMode) : ProbeIsolationEffect
|
||||
data class EndSampling(val epoch: Long) : ProbeIsolationEffect
|
||||
data class Terminate(val epoch: Long, val pid: Int) : ProbeIsolationEffect
|
||||
@@ -12,14 +13,20 @@ sealed interface ProbeIsolationEffect {
|
||||
|
||||
/** Actual parent watchdog policy. A timeout alone NEVER permits overlapping camera owners.
|
||||
* Native close ACK and confirmed process death are different facts in every result. */
|
||||
class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
class IsolatedProbeSuite(private val seed: Long = 0, private val requireAvailability: Boolean = false,
|
||||
private val modes: List<CameraProbeMode> = CameraProbeMode.entries.toList()) {
|
||||
companion object {
|
||||
const val START_LIMIT_MS = 4_000L
|
||||
const val RUN_LIMIT_MS = 5_000L
|
||||
const val CLOSE_LIMIT_MS = 2_000L
|
||||
const val EXIT_LIMIT_MS = 4_000L
|
||||
const val SETTLE_MS = 500L
|
||||
const val AVAILABILITY_LIMIT_MS = 5_000L
|
||||
const val AVAILABLE_STABLE_MS = 500L
|
||||
// Avoid putting the known default-preview stopPreview stall before all other probes.
|
||||
val RECOMMENDED_ORDER = CameraProbeMode.entries.filter { it != CameraProbeMode.CAMERA1_DEFAULT_PREVIEW } + CameraProbeMode.CAMERA1_DEFAULT_PREVIEW
|
||||
}
|
||||
init { require(modes.isNotEmpty() && modes.size <= 7 && modes.distinct().size == modes.size) }
|
||||
var phase = ProbeIsolationPhase.IDLE; private set
|
||||
var epoch = seed; private set
|
||||
var results: List<CameraProbeResult> = emptyList(); private set
|
||||
@@ -27,6 +34,8 @@ class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
private var since = 0L
|
||||
private var cancelled = false
|
||||
private var reported = false
|
||||
private var availability = ProbeCameraAvailability.UNKNOWN
|
||||
private var availableSince = -1L
|
||||
private fun update(change: (CameraProbeResult) -> CameraProbeResult) {
|
||||
results = results.dropLast(1) + change(checkNotNull(current))
|
||||
}
|
||||
@@ -35,15 +44,46 @@ class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
return next(now)
|
||||
}
|
||||
private fun next(now: Long): List<ProbeIsolationEffect> {
|
||||
if (cancelled || results.size == CameraProbeMode.entries.size) return finish(false)
|
||||
val mode = CameraProbeMode.entries[results.size]
|
||||
epoch++; since = now; phase = ProbeIsolationPhase.STARTING
|
||||
results = results + CameraProbeResult(mode, now)
|
||||
if (cancelled || results.size == modes.size) return finish(false)
|
||||
val mode = modes[results.size]
|
||||
val priorUnconfirmed = results.lastOrNull { it.attempted }?.let { !it.closeConfirmed } ?: false
|
||||
epoch++; since = now; phase = if (requireAvailability) ProbeIsolationPhase.WAITING_CAMERA else ProbeIsolationPhase.STARTING
|
||||
results = results + CameraProbeResult(mode, now, attempted = false, previousCloseUnconfirmed = priorUnconfirmed)
|
||||
if (requireAvailability) {
|
||||
availability = ProbeCameraAvailability.UNKNOWN; availableSince = -1
|
||||
return listOf(ProbeIsolationEffect.ObserveAvailability(epoch))
|
||||
}
|
||||
return listOf(ProbeIsolationEffect.Start(epoch, mode))
|
||||
}
|
||||
/** Availability is an OS eligibility signal, never proof of streaming or HAL recovery. */
|
||||
fun availability(state: ProbeCameraAvailability, now: Long, token: Long = epoch): List<ProbeIsolationEffect> {
|
||||
if (token != epoch || phase !in setOf(ProbeIsolationPhase.WAITING_CAMERA, ProbeIsolationPhase.STARTING, ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING)) return emptyList()
|
||||
if (state != availability) availableSince = if (state == ProbeCameraAvailability.AVAILABLE) now else -1
|
||||
availability = state
|
||||
return if (phase == ProbeIsolationPhase.WAITING_CAMERA) awaitAvailability(now) else emptyList()
|
||||
}
|
||||
private fun awaitAvailability(now: Long): List<ProbeIsolationEffect> {
|
||||
update { it.copy(preflightAvailability = availability, availabilityWaitMs = (now - since).coerceAtLeast(0)) }
|
||||
if (availability == ProbeCameraAvailability.AVAILABLE && availableSince >= 0 && now - availableSince >= AVAILABLE_STABLE_MS) {
|
||||
phase = ProbeIsolationPhase.STARTING; since = now
|
||||
return listOf(ProbeIsolationEffect.Start(epoch, checkNotNull(current).mode))
|
||||
}
|
||||
if (availability == ProbeCameraAvailability.NO_FRONT || now - since >= AVAILABILITY_LIMIT_MS) {
|
||||
val failure = when (availability) {
|
||||
ProbeCameraAvailability.NO_FRONT -> CameraProbeFailure.NO_FRONT
|
||||
ProbeCameraAvailability.UNAVAILABLE -> CameraProbeFailure.CAMERA_UNAVAILABLE
|
||||
ProbeCameraAvailability.AVAILABLE -> CameraProbeFailure.AVAILABILITY_UNSTABLE
|
||||
else -> CameraProbeFailure.AVAILABILITY_UNKNOWN
|
||||
}
|
||||
update { it.copy(failure = failure, initialFailure = failure, finishedMs = now) }
|
||||
// No owner was opened. Retain not-attempted; do not invent native/process close ACKs.
|
||||
return next(now)
|
||||
}
|
||||
return emptyList()
|
||||
}
|
||||
fun ready(token: Long, pid: Int, now: Long): List<ProbeIsolationEffect> {
|
||||
if (token != epoch || phase != ProbeIsolationPhase.STARTING || pid <= 0) return emptyList()
|
||||
update { it.copy(workerPid = pid) }
|
||||
update { it.copy(workerPid = pid, attempted = true) }
|
||||
since = now; phase = ProbeIsolationPhase.RUNNING
|
||||
return emptyList()
|
||||
}
|
||||
@@ -51,7 +91,9 @@ class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
if (token != epoch || phase !in setOf(ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING) ||
|
||||
row.mode != current?.mode) return emptyList()
|
||||
val pid = checkNotNull(current).workerPid
|
||||
update { row.copy(workerPid = pid, processStopRequired = false, processExitConfirmed = false) }
|
||||
update { row.copy(workerPid = pid, processStopRequired = false, processExitConfirmed = false,
|
||||
preflightAvailability = it.preflightAvailability, availabilityWaitMs = it.availabilityWaitMs,
|
||||
previousCloseUnconfirmed = it.previousCloseUnconfirmed) }
|
||||
if (row.closeStartedMs >= 0 && phase == ProbeIsolationPhase.RUNNING) {
|
||||
phase = ProbeIsolationPhase.CLOSING; since = row.closeStartedMs.coerceAtMost(now)
|
||||
}
|
||||
@@ -86,6 +128,7 @@ class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
return emptyList()
|
||||
}
|
||||
fun tick(now: Long): List<ProbeIsolationEffect> = when (phase) {
|
||||
ProbeIsolationPhase.WAITING_CAMERA -> awaitAvailability(now)
|
||||
ProbeIsolationPhase.STARTING -> if (now - since >= START_LIMIT_MS) retire(CameraProbeFailure.WORKER_START_TIMEOUT, now) else emptyList()
|
||||
ProbeIsolationPhase.RUNNING -> if (now - since >= RUN_LIMIT_MS) {
|
||||
phase = ProbeIsolationPhase.CLOSING; since = now
|
||||
@@ -101,6 +144,10 @@ class IsolatedProbeSuite(private val seed: Long = 0) {
|
||||
fun cancel(now: Long): List<ProbeIsolationEffect> {
|
||||
cancelled = true
|
||||
return when (phase) {
|
||||
ProbeIsolationPhase.WAITING_CAMERA -> {
|
||||
update { it.copy(failure = CameraProbeFailure.CANCELLED, initialFailure = CameraProbeFailure.CANCELLED, finishedMs = now) }
|
||||
finish(false)
|
||||
}
|
||||
ProbeIsolationPhase.STARTING, ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING -> retire(CameraProbeFailure.CANCELLED, now)
|
||||
ProbeIsolationPhase.SETTLING, ProbeIsolationPhase.IDLE -> finish(false)
|
||||
else -> emptyList()
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import com.gorios.lanvoice.expression.ProbeCameraAvailability
|
||||
|
||||
/** Observe OS front-camera eligibility without opening a camera. No identifiers or images reported.
|
||||
* AVAILABLE is not evidence of frames or of vendor HAL recovery. Binder queries stay off the UI. */
|
||||
class ProbeAvailabilityMonitor(context: Context, private val changed: (Long,ProbeCameraAvailability)->Unit) {
|
||||
private val manager = context.getSystemService(CameraManager::class.java)
|
||||
private val thread = HandlerThread("camera-probe-availability").apply { start() }
|
||||
private val worker = Handler(thread.looper)
|
||||
@Volatile private var stopped = false
|
||||
private var callback: CameraManager.AvailabilityCallback? = null
|
||||
fun observe(epoch: Long) { worker.post {
|
||||
if (stopped) return@post
|
||||
try {
|
||||
callback?.let { manager.unregisterAvailabilityCallback(it) }; callback = null
|
||||
val frontId = manager.cameraIdList.firstOrNull {
|
||||
manager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT
|
||||
}
|
||||
if (stopped) return@post
|
||||
if (frontId == null) changed(epoch,ProbeCameraAvailability.NO_FRONT)
|
||||
else {
|
||||
val observer = object: CameraManager.AvailabilityCallback() {
|
||||
override fun onCameraAvailable(cameraId: String) { if (!stopped && cameraId == frontId) changed(epoch,ProbeCameraAvailability.AVAILABLE) }
|
||||
override fun onCameraUnavailable(cameraId: String) { if (!stopped && cameraId == frontId) changed(epoch,ProbeCameraAvailability.UNAVAILABLE) }
|
||||
}
|
||||
callback = observer; manager.registerAvailabilityCallback(observer, worker)
|
||||
}
|
||||
} catch (_: Exception) { if (!stopped) changed(epoch,ProbeCameraAvailability.UNKNOWN) }
|
||||
} }
|
||||
fun stop() {
|
||||
stopped = true
|
||||
worker.post { try { callback?.let { manager.unregisterAvailabilityCallback(it) } } catch (_: Exception) {} finally { thread.quitSafely() } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
# 相机诊断:Surface 协商与下一项可用性 — 0.1.3 / code4
|
||||
|
||||
本次只更新独立 `com.gorios.lanvoice.cameraprobe` 诊断 APK。主角色包0.7.14/code33、角色素材、gateway、时间、provider、TTS和模型服务均不部署或替换。无付费/模型调用。保留旧主包和相机code3用于回退。
|
||||
|
||||
## 本次真实设备证据
|
||||
|
||||
gateway收到用户 camera-probe-0.1.2/code3 报告:上海时间2026-10-14 12:04:50.955701,报告生成于12:04:46.200。七个不同配置全部有结果、stage=done、七个工作进程退出确认。流程完成不表示相机成功。
|
||||
|
||||
| 配置 | code3结果 |
|
||||
|---|---|
|
||||
| camera1_default_preview | setPreviewDisplay/startPreview返回;Surface 640×480,实际默认preview 1920×1080;stop_preview保持pending,close_timeout |
|
||||
| camera1_640 | Camera.open约3秒后抛错,尚未配置分辨率 |
|
||||
| camera1_320 | Camera.open约3秒后抛错,尚未配置分辨率 |
|
||||
| camerax_preview | capture_completed=0,frame_timeout,原生close_timeout |
|
||||
| camerax_visible_dual | analysis_returned=0,frame_timeout,session_failure=other,关闭确认 |
|
||||
| camerax_analysis | analysis_returned=0,frame_timeout,session_failure=other,关闭确认 |
|
||||
| camerax_gl_dual | available/latch_completed/analysis_returned均0,frame_timeout,原生close_timeout |
|
||||
|
||||
默认Camera1没有注册图像回调,frames=0不能独立判定没有显示画面。报告没有vendor ISP原日志,不能确认本次又出现`viewfinder is not opened yet`。Surface尺寸差异是需要修正/验证的应用路径,不是已证实的全部设备根因。第一项close异常可能影响后续open;不能从本轮断定640/320分辨率不兼容或设备永久损坏。
|
||||
|
||||
## code4实现
|
||||
|
||||
1. 仍是一个按钮运行、结束自动发送。顺序改为camera1_640、camera1_320、camerax_preview、camerax_visible_dual、camerax_analysis、camerax_gl_dual,已知关闭易卡的默认Camera1放最后。未增加分辨率盲试或相机API重写。
|
||||
2. Camera1在工作线程读取相机实际preview尺寸。私有Worker通过内部Binder要求前台父页面调整真正SurfaceView;父页面确认surfaceChanged后有效、非creating、实际buffer尺寸匹配,才回传Surface handle和尺寸。Worker再次核对epoch/resize_id/尺寸,生产CameraProbeController再次检查,之后才附加Surface/startPreview。请求最多等2秒;没有同步阻塞主线程。默认preview参数不强改为640;适配其真实1920×1080或设备实际返回的合法尺寸。
|
||||
3. Surface回复只处理一次;取消/后台/旧epoch后的回复不能重新启动。未曾请求startPreview的相机清理直接release,不额外调用stopPreview。已请求start的相机仍需真实stop/release,不吞掉关闭超时。
|
||||
4. 每项仍采样5秒、关闭等待2秒、工作进程退出等待最多4秒,确认退出后500ms间隔。下一项另有最多5秒的前置相机可用性门禁:CameraManager查询/注册在专用线程,每项重新注册,必须收到本epoch的AVAILABLE并稳定500ms。旧配置的缓存AVAILABLE或迟到通知不能开放新配置。
|
||||
5. AVAILABLE仅表示操作系统允许尝试打开,不证明vendor HAL完全恢复,更不证明已有视频帧。若未获准,标记attempted=false及camera_unavailable/availability_unknown/availability_unstable/no_front,继续有界处理其余项并自动报告;不伪造native close或process exit。若工作进程退出本身仍无法确认,保持既有BLOCKED保护,不重叠打开相机。
|
||||
6. 保留第一处抛错的native operation与固定异常类别,并单独记录Camera1错误数字码、CameraX CameraState错误数字码。后续release/unbind不覆盖首错。只传枚举、数字、时间和Surface本地句柄;报告不包含图像、像素、脸、声音、聊天、相机ID、原始异常或设备vendor日志。
|
||||
|
||||
生产controller新增的Surface准备回调由独立Worker注入。共享源码可编译,旧主包APK没有重建/替换;原直接诊断入口的默认行为没有冒称已获同等真机验证。
|
||||
|
||||
## 新报告字段与下一次判读
|
||||
|
||||
每项新增:attempted、preflight_availability、availability_wait_ms、previous_close_unconfirmed、surface_preparation、surface_requested_width/height、surface_ready_ms、first_exception_operation/kind、session_error_code、camera_error_code。顶层新增availability_limit_ms。原有frames/capture/GL trace、initial_failure、close_confirmed、process_exit_confirmed继续独立保留。
|
||||
|
||||
- 默认预览需要surface_preparation=matched且Surface尺寸等于实际preview,才说明新的尺寸协商走通。
|
||||
- 分辨率配置必须Camera.open成功并真正进入参数/启动分支,不能把open失败当作该分辨率测试结论。
|
||||
- attempted=false是门禁未放行,不能统计为已测试无帧。
|
||||
- 正值analysis/capture/GL锁存提供各自的出帧证据;关闭成功或AVAILABLE不能代替它们。
|
||||
- 若640在干净准入状态下能够出帧,才考虑把该路径接回主App的本地presence分析;不提前开放或宣称人脸检测恢复。
|
||||
|
||||
报告读取继续使用`scripts/collect-camera-probe-metadata.py --output <新的ignored logs路径>`;脚本在gateway端筛选上述固定字段,原报告留在gateway,已有code3证据不覆盖。
|
||||
|
||||
## 验证与交付边界
|
||||
|
||||
既有生产相机回放121断言、隔离suite120断言保留;新增77断言覆盖实际生产controller的1920×1080准备/重复ACK/未匹配/取消后迟到回复/2秒失败/首错保留,以及suite的新鲜可用通知、500ms防抖、5秒边界、退出不等于恢复、未测试与失败区别、自动报告一次。回放使用Android API doubles,不是设备HAL或GPU验证。
|
||||
|
||||
其余会话/播放/动作/捕获/协议/表情/UI回归及59包装测试通过。独立APK构建、共享主包Kotlin与instrumentation Kotlin编译通过;未运行设备instrumentation。本次没有自动打开用户设备摄像头、安装、配置无线ADB、重启相机服务或清数据。
|
||||
|
||||
下载文件:`lan-voice-camera-probe-v013-code4-debug.apk`,camera-probe-0.1.3/code4,arm64-v8a,min26/target34,同debug证书SHA256 `b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`。
|
||||
|
||||
URL:<http://192.168.31.124:8080/lan-voice-camera-probe-v013-code4-debug.apk>
|
||||
|
||||
校验文件:<http://192.168.31.124:8080/lan-voice-camera-probe-v013-code4-debug.apk.sha256>
|
||||
|
||||
APK SHA256:`5e373fcc7ead71897f655a15881ecdb3ecabe7ec3e8ee8b6de8199fa48a0f0ec`,11358168 bytes;HTTP字节核验通过。交付与source fingerprints写入ignored `logs/camera-isolation-012/code4-delivery.json`。源码/测试/文档可提交;APK、原始报告、用户素材和日志不入Git。
|
||||
|
||||
用户操作仍为覆盖安装相机检查包后,打开、点一次“一键诊断并发送”,授权相机并保持前台。无需逐项点击。code4是有针对性的诊断/准备路径修正版,MTK设备是否实际出帧及stopPreview是否恢复,需下一份真机报告确认。
|
||||
@@ -19,3 +19,4 @@ with tempfile.TemporaryDirectory(prefix='camera-controller-check-') as folder:
|
||||
subprocess.run([ns['JAVA'],'-cp',folder+':'+ns['cp'],'CameraControllerCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
subprocess.run([ns['JAVA'],'-cp',folder+':'+ns['cp'],'CameraProbeCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
subprocess.run([ns['JAVA'],'-cp',folder+':'+ns['cp'],'IsolatedProbeSuiteCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
subprocess.run([ns['JAVA'],'-cp',folder+':'+ns['cp'],'ProbeRecoveryCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
|
||||
@@ -16,16 +16,16 @@ def clock(v,ms=False):
|
||||
return datetime.datetime.fromtimestamp(v/1000 if ms else v,zoneinfo.ZoneInfo('Asia/Shanghai')).isoformat()
|
||||
reportdata=get('debug/report');reports=reportdata.get('reports',[])
|
||||
rows=[]
|
||||
allowed={'mode','failure','started_ms','finished_ms','bound_ms','open_ms','surface_provided_ms','surface_ack_ms','surface_result_code','surface_created','surface_released','first_frame_ms','frames','analysis_returned','capture_completed','capture_failed','width','height','callback_bytes','native_state','session_failure','close_started_ms','close_returned_ms','closed_ms','close_confirmed','provided_surfaces','acknowledged_surfaces','native_operation','native_call_state','native_call_started_ms','native_call_returned_ms','initial_failure','frame_observation','worker_pid','process_stop_required','process_exit_confirmed','surface_valid_before_attach','surface_valid_before_start','surface_creating_at_attach','surface_width','surface_height'}
|
||||
allowed={'mode','failure','started_ms','finished_ms','bound_ms','open_ms','surface_provided_ms','surface_ack_ms','surface_result_code','surface_created','surface_released','first_frame_ms','frames','analysis_returned','capture_completed','capture_failed','width','height','callback_bytes','native_state','session_failure','close_started_ms','close_returned_ms','closed_ms','close_confirmed','provided_surfaces','acknowledged_surfaces','native_operation','native_call_state','native_call_started_ms','native_call_returned_ms','initial_failure','frame_observation','worker_pid','process_stop_required','process_exit_confirmed','surface_valid_before_attach','surface_valid_before_start','surface_creating_at_attach','surface_width','surface_height','attempted','preflight_availability','availability_wait_ms','previous_close_unconfirmed','surface_preparation','surface_requested_width','surface_requested_height','surface_ready_ms','first_exception_operation','first_exception_kind','session_error_code','camera_error_code'}
|
||||
tracekeys={'available','latch_started','latch_completed','first_available_ms','latch_started_ms','latch_completed_ms','worker_heartbeat_ms','result_acks','result_code','consumer_closed'}
|
||||
def safe(v):return isinstance(v,(int,float,bool)) or isinstance(v,str) and bool(re.fullmatch('[a-zA-Z0-9_]{1,48}',v))
|
||||
for wrap in reports[-10:]:
|
||||
r=wrap.get('report',{});p=r.get('camera_probe',{})
|
||||
row={'received_shanghai':clock(wrap.get('received_at')),'report_shanghai':clock(r.get('timestamp'),True),'version_code':r.get('version_code'),'app_version':r.get('app_version'),'mode':r.get('avatar_runtime',{}).get('mode'),'camera_probe':{}}
|
||||
for k in ('stage','entry_failure','max_tests','run_limit_ms','close_limit_ms','process_isolated','process_exit_limit_ms'):
|
||||
for k in ('stage','entry_failure','max_tests','run_limit_ms','close_limit_ms','process_isolated','process_exit_limit_ms','availability_limit_ms'):
|
||||
if safe(p.get(k)):row['camera_probe'][k]=p[k]
|
||||
row['camera_probe']['results']=[dict({k:v for k,v in x.items() if k in allowed and safe(v)},preview_trace={k:v for k,v in x.get('preview_trace',{}).items() if k in tracekeys and safe(v)}) for x in p.get('results',[])[:7]]
|
||||
if r.get('version_code') in (28,29):
|
||||
if r.get('version_code') in (28,29,3,4):
|
||||
row['events']=[]
|
||||
for e in r.get('logs',[]):
|
||||
msg=e.get('msg','')
|
||||
|
||||
@@ -32,8 +32,8 @@ def digest(path):
|
||||
|
||||
def verify(apk):
|
||||
badge = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'badging', str(apk)], text=True)
|
||||
for value in ("name='com.gorios.lanvoice.cameraprobe'", "versionCode='3'",
|
||||
"versionName='camera-probe-0.1.2'", "sdkVersion:'26'", "targetSdkVersion:'34'"):
|
||||
for value in ("name='com.gorios.lanvoice.cameraprobe'", "versionCode='4'",
|
||||
"versionName='camera-probe-0.1.3'", "sdkVersion:'26'", "targetSdkVersion:'34'"):
|
||||
require(value in badge, 'APK metadata: '+value)
|
||||
permissions = set(re.findall(r"^uses-permission: name='([^']+)'", badge, re.M))
|
||||
require(permissions == {'android.permission.CAMERA', 'android.permission.INTERNET',
|
||||
@@ -68,6 +68,7 @@ def verify(apk):
|
||||
'Lcom/gorios/lanvoice/IsolatedCameraDiagnosticsActivity;',
|
||||
'Lcom/gorios/lanvoice/CameraProbeWorkerService;',
|
||||
'Lcom/gorios/lanvoice/IsolatedProbeSuite;',
|
||||
'Lcom/gorios/lanvoice/ProbeAvailabilityMonitor;',
|
||||
'Lcom/gorios/lanvoice/expression/CameraProbeController;',
|
||||
'Lcom/gorios/lanvoice/diag/DiagnosticReportUpload;'):
|
||||
require(klass.encode() in dex, 'missing production diagnostic component: '+klass)
|
||||
@@ -81,12 +82,13 @@ def verify(apk):
|
||||
trust = ROOT/'camera-probe/build/generated/cameraTrust/res/raw/gateway_cert.pem'
|
||||
require(trust.read_bytes() == (ROOT/'app/src/main/res/raw/gateway_cert.pem').read_bytes(), 'gateway trust drift')
|
||||
camera_sources = {str(p.relative_to(ROOT)): digest(p) for p in sorted((ROOT/'camera-probe/src').rglob('*')) if p.is_file()}
|
||||
return {'package': 'com.gorios.lanvoice.cameraprobe', 'version_name': 'camera-probe-0.1.2',
|
||||
'version_code': 3, 'min_sdk': 26, 'target_sdk': 34, 'certificate_sha256': CERT,
|
||||
return {'package': 'com.gorios.lanvoice.cameraprobe', 'version_name': 'camera-probe-0.1.3',
|
||||
'version_code': 4, 'min_sdk': 26, 'target_sdk': 34, 'certificate_sha256': CERT,
|
||||
'abi': 'arm64-v8a', 'assets': 0, 'microphone_permission': False,
|
||||
'shared_production_sources': sources, 'camera_application_sources': camera_sources,
|
||||
'camera_tests': 7, 'process_isolated': True,
|
||||
'run_limit_ms': 5000, 'close_limit_ms': 2000, 'process_exit_limit_ms': 4000, 'device': 'not_run'}
|
||||
'run_limit_ms': 5000, 'close_limit_ms': 2000, 'process_exit_limit_ms': 4000, 'availability_limit_ms': 5000, 'surface_resize_handshake': True,
|
||||
'availability_is_streaming_proof': False, 'default_preview_last': True, 'device': 'not_run'}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
@@ -99,7 +101,7 @@ def main():
|
||||
subprocess.run([str(ROOT/'scripts/build.sh'), ':camera-probe:assembleDebug'], cwd=ROOT, check=True)
|
||||
built = ROOT/'camera-probe/build/outputs/apk/debug/camera-probe-debug.apk'
|
||||
report = verify(built)
|
||||
artifact = ROOT/'artifacts/lan-voice-camera-probe-v012-code3-debug.apk'
|
||||
artifact = ROOT/'artifacts/lan-voice-camera-probe-v013-code4-debug.apk'
|
||||
require(not artifact.exists() and not artifact.with_suffix('.apk.sha256').exists(), 'published camera version occupied')
|
||||
with artifact.open('xb') as target, built.open('rb') as source:
|
||||
shutil.copyfileobj(source, target)
|
||||
|
||||
@@ -16,6 +16,7 @@ class Camera {
|
||||
var setParameterCalls=0;var getParameterCalls=0
|
||||
var bufferInstalls=0;var bufferReturns=0;var onStop: (()->Unit)?=null
|
||||
var started=false;var released=false
|
||||
var stopCalls=0
|
||||
var callback: ((ByteArray?,Camera)->Unit)?=null
|
||||
var error: ((Int,Camera)->Unit)?=null
|
||||
private var buffers=mutableListOf<ByteArray>()
|
||||
@@ -24,7 +25,7 @@ class Camera {
|
||||
fun setPreviewCallbackWithBuffer(cb: ((ByteArray?,Camera)->Unit)?) {if(cb!=null) bufferInstalls++;callback=cb}
|
||||
fun addCallbackBuffer(data: ByteArray) {bufferReturns++;buffers+=data}
|
||||
fun startPreview() {started=true}
|
||||
fun stopPreview() {onStop?.invoke();started=false}
|
||||
fun stopPreview() {stopCalls++;onStop?.invoke();started=false}
|
||||
fun release() {check(!released);released=true}
|
||||
fun frame() {if(started) callback?.invoke(buffers.removeAt(0),this)}
|
||||
companion object {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import com.gorios.lanvoice.*
|
||||
import com.gorios.lanvoice.expression.*
|
||||
import android.os.CameraClock
|
||||
import android.hardware.Camera
|
||||
import androidx.camera.core.CameraState
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
|
||||
fun main() {
|
||||
var checks=0
|
||||
fun verify(value: Boolean) { checks++; check(value) { "recovery check $checks" } }
|
||||
val order=IsolatedProbeSuite.RECOMMENDED_ORDER
|
||||
verify(order.size==7 && order.distinct().size==7 && order.last()==CameraProbeMode.CAMERA1_DEFAULT_PREVIEW)
|
||||
// Availability must be observed and stable; Binder death alone cannot trigger another open.
|
||||
val s=IsolatedProbeSuite(requireAvailability=true,modes=order)
|
||||
verify(s.start(0).single() is ProbeIsolationEffect.ObserveAvailability && s.phase==ProbeIsolationPhase.WAITING_CAMERA)
|
||||
verify(s.availability(ProbeCameraAvailability.AVAILABLE,0).isEmpty())
|
||||
verify(s.tick(499).isEmpty())
|
||||
verify(s.availability(ProbeCameraAvailability.AVAILABLE,499).isEmpty()) // Same event must not reset stable clock.
|
||||
val start=s.tick(500).single() as ProbeIsolationEffect.Start
|
||||
verify(start.mode==CameraProbeMode.CAMERA1_640 && s.current!!.availabilityWaitMs==500L)
|
||||
s.ready(start.epoch,31,500)
|
||||
s.availability(ProbeCameraAvailability.UNAVAILABLE,501) // This worker owns the camera.
|
||||
verify(s.snapshot(start.epoch,CameraProbeResult(start.mode,500,
|
||||
failure=CameraProbeFailure.FRAME_TIMEOUT,initialFailure=CameraProbeFailure.FRAME_TIMEOUT,
|
||||
closeStartedMs=5500,finishedMs=5500),5500).isEmpty())
|
||||
verify(s.current!!.preflightAvailability==ProbeCameraAvailability.AVAILABLE && s.current!!.attempted)
|
||||
verify(s.tick(7500).single() is ProbeIsolationEffect.Terminate)
|
||||
s.exited(start.epoch,7501)
|
||||
verify(s.tick(8001).single() is ProbeIsolationEffect.ObserveAvailability && s.phase==ProbeIsolationPhase.WAITING_CAMERA)
|
||||
verify(s.current!!.previousCloseUnconfirmed && !s.current!!.attempted)
|
||||
verify(s.availability(ProbeCameraAvailability.AVAILABLE,8002,start.epoch).isEmpty()) // Prior owner's queued signal cannot reopen.
|
||||
s.availability(ProbeCameraAvailability.UNAVAILABLE,8002)
|
||||
verify(s.tick(13000).isEmpty())
|
||||
verify(s.tick(13001).single() is ProbeIsolationEffect.ObserveAvailability)
|
||||
val skipped=s.results[1]
|
||||
verify(skipped.failure==CameraProbeFailure.CAMERA_UNAVAILABLE && !skipped.attempted)
|
||||
verify(!skipped.processExitConfirmed && !skipped.closeConfirmed)
|
||||
verify(s.snapshot(start.epoch,CameraProbeResult(start.mode,0,closeConfirmed=true),13002).isEmpty())
|
||||
s.availability(ProbeCameraAvailability.AVAILABLE,13002)
|
||||
verify(s.tick(13501).isEmpty())
|
||||
val next=s.tick(13502).single() as ProbeIsolationEffect.Start
|
||||
verify(next.mode==CameraProbeMode.CAMERAX_PREVIEW && s.current!!.previousCloseUnconfirmed)
|
||||
verify(s.current!!.preflightAvailability==ProbeCameraAvailability.AVAILABLE)
|
||||
|
||||
// Missing availability cannot produce seven fake camera failures or wait forever.
|
||||
val unknown=IsolatedProbeSuite(requireAvailability=true,modes=order)
|
||||
unknown.start(0)
|
||||
for(i in 1..7) {
|
||||
val effects=unknown.tick(i*5000L)
|
||||
verify(unknown.results[i-1].failure==CameraProbeFailure.AVAILABILITY_UNKNOWN)
|
||||
verify(!unknown.results[i-1].attempted && !unknown.results[i-1].processExitConfirmed)
|
||||
verify(if(i==7) effects.single()==ProbeIsolationEffect.Report else effects.single() is ProbeIsolationEffect.ObserveAvailability)
|
||||
}
|
||||
verify(unknown.phase==ProbeIsolationPhase.DONE && unknown.tick(40000).isEmpty())
|
||||
val unstable=IsolatedProbeSuite(requireAvailability=true,modes=listOf(order.first()))
|
||||
unstable.start(0);unstable.availability(ProbeCameraAvailability.AVAILABLE,4999)
|
||||
verify(unstable.tick(5000).single()==ProbeIsolationEffect.Report)
|
||||
verify(unstable.current!!.failure==CameraProbeFailure.AVAILABILITY_UNSTABLE && !unstable.current!!.attempted)
|
||||
val cancelled=IsolatedProbeSuite(requireAvailability=true)
|
||||
cancelled.start(0)
|
||||
verify(cancelled.cancel(1).single()==ProbeIsolationEffect.Report)
|
||||
verify(cancelled.availability(ProbeCameraAvailability.AVAILABLE,600).isEmpty() && cancelled.tick(1100).isEmpty())
|
||||
verify(cancelled.current!!.failure==CameraProbeFailure.CANCELLED && !cancelled.current!!.attempted)
|
||||
val fresh=IsolatedProbeSuite(requireAvailability=true,modes=order.take(2))
|
||||
fresh.start(0);fresh.availability(ProbeCameraAvailability.AVAILABLE,0)
|
||||
val f=fresh.tick(500).single() as ProbeIsolationEffect.Start
|
||||
fresh.ready(f.epoch,99,500)
|
||||
fresh.snapshot(f.epoch,CameraProbeResult(f.mode,500,closeStartedMs=1000,closeConfirmed=true),1000)
|
||||
fresh.exited(f.epoch,1001)
|
||||
verify(fresh.tick(1501).single() is ProbeIsolationEffect.ObserveAvailability)
|
||||
verify(fresh.current!!.preflightAvailability==ProbeCameraAvailability.UNKNOWN)
|
||||
verify(fresh.tick(2001).isEmpty()) // Even a cached AVAILABLE from a clean previous run is insufficient.
|
||||
verify(fresh.availability(ProbeCameraAvailability.AVAILABLE,2002,f.epoch).isEmpty())
|
||||
fresh.availability(ProbeCameraAvailability.AVAILABLE,2003)
|
||||
verify(fresh.tick(2502).isEmpty() && fresh.tick(2503).single() is ProbeIsolationEffect.Start)
|
||||
|
||||
// Replay through the actual production controller: native default 1920x1080 vs parent 640x480.
|
||||
fun reset() {
|
||||
CameraClock.reset();Camera.opened.clear();Camera.failOpen=false;Camera.onOpen=null
|
||||
ProcessCameraProvider.instance=ProcessCameraProvider().apply {autoClose=true}
|
||||
CameraProbeStore.inhibitNormal=false;CameraProbeStore.stage=CameraProbeStage.IDLE;CameraProbeStore.results=emptyList()
|
||||
CameraProbeStore.begin()
|
||||
}
|
||||
val owner=object: androidx.lifecycle.LifecycleOwner {}
|
||||
reset();Camera.onOpen={it.parameters.previewSize=Camera.Size(1920,1080)}
|
||||
val holder=android.view.SurfaceHolder();var complete: ((Boolean)->Unit)?=null;var done=0
|
||||
val runner=CameraProbeController(android.content.Context(),owner,holder,
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_DEFAULT_PREVIEW),5000,2000),
|
||||
prepareLegacySurface={w,h,cb -> verify(w==1920 && h==1080);complete=cb},done={done++})
|
||||
runner.start();CameraClock.advance()
|
||||
verify(!Camera.opened.single().second.started && complete!=null)
|
||||
verify(CameraProbeStore.results.single().surfacePreparation==ProbeSurfacePreparation.WAITING)
|
||||
holder.surfaceFrame=android.graphics.Rect(0,0,1920,1080);complete!!(true);CameraClock.advance()
|
||||
val camera=Camera.opened.single().second
|
||||
verify(camera.started && camera.setParameterCalls==0 && camera.bufferInstalls==0)
|
||||
verify(CameraProbeStore.results.single().surfacePreparation==ProbeSurfacePreparation.MATCHED)
|
||||
verify(CameraProbeStore.results.single().surfaceWidth==1920 && CameraProbeStore.results.single().surfaceHeight==1080)
|
||||
complete!!(false);CameraClock.advance();verify(camera.started) // Duplicate reply must not cancel a running camera.
|
||||
CameraClock.advance(5500);verify(done==1 && camera.released)
|
||||
verify(CameraProbeStore.results.single().failure==CameraProbeFailure.NONE) // Preview pixels remain unmeasured.
|
||||
|
||||
// A false/mismatched Surface ACK never permits startPreview; stale ACK after cancel cannot reopen.
|
||||
for(cancel in listOf(false,true)) {
|
||||
reset();Camera.onOpen={it.parameters.previewSize=Camera.Size(1920,1080)}
|
||||
val h=android.view.SurfaceHolder();var cb: ((Boolean)->Unit)?=null;var reports=0
|
||||
val r=CameraProbeController(android.content.Context(),owner,h,
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_DEFAULT_PREVIEW),5000,2000),
|
||||
prepareLegacySurface={_,_,reply->cb=reply},done={reports++})
|
||||
r.start();CameraClock.advance()
|
||||
val c=Camera.opened.single().second
|
||||
if(cancel) {r.cancel();CameraClock.advance();h.surfaceFrame=android.graphics.Rect(0,0,1920,1080)}
|
||||
cb!!(true);CameraClock.advance(10000)
|
||||
verify(!c.started && c.released && reports==1 && c.stopCalls==0)
|
||||
verify(CameraProbeStore.results.single().initialFailure==if(cancel) CameraProbeFailure.CANCELLED else CameraProbeFailure.SURFACE)
|
||||
verify(Camera.opened.size==1)
|
||||
}
|
||||
reset();Camera.failOpen=true
|
||||
CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder(),
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_640),5000,2000)) {}.start()
|
||||
CameraClock.advance(10000)
|
||||
val openFailed=CameraProbeStore.results.single()
|
||||
verify(openFailed.initialFailure==CameraProbeFailure.OPEN && openFailed.firstExceptionOperation==CameraNativeOperation.OPEN)
|
||||
verify(openFailed.firstExceptionKind==ProbeExceptionKind.STATE && openFailed.nativeOperation==CameraNativeOperation.RELEASE)
|
||||
verify(openFailed.openMs<0 && Camera.opened.isEmpty())
|
||||
reset();Camera.onOpen={it.parameters.previewSize=Camera.Size(1920,1080)}
|
||||
var timeoutReports=0
|
||||
CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder(),
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_DEFAULT_PREVIEW),5000,2000),
|
||||
prepareLegacySurface={_,_,cb -> android.os.Handler().postDelayed({cb(false)},2000)},done={timeoutReports++}).start()
|
||||
CameraClock.advance(1999);verify(!Camera.opened.single().second.started && timeoutReports==0)
|
||||
CameraClock.advance(8010)
|
||||
verify(timeoutReports==1 && !Camera.opened.single().second.started && Camera.opened.single().second.released)
|
||||
verify(CameraProbeStore.results.single().surfacePreparation==ProbeSurfacePreparation.FAILED && CameraProbeStore.results.single().initialFailure==CameraProbeFailure.SURFACE)
|
||||
|
||||
reset()
|
||||
CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder(),
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERAX_ANALYSIS),5000,2000)) {}.start()
|
||||
CameraClock.advance()
|
||||
val state=ProcessCameraProvider.instance.camera.cameraInfo.cameraState
|
||||
state.emit(CameraState(CameraState.StateError(CameraState.ERROR_CAMERA_DISABLED),CameraState.Type.OPENING))
|
||||
CameraClock.advance(10000)
|
||||
verify(CameraProbeStore.results.single().sessionErrorCode==CameraState.ERROR_CAMERA_DISABLED)
|
||||
verify(CameraProbeStore.results.single().sessionFailure==CameraSessionFailure.OTHER)
|
||||
reset()
|
||||
CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder(),
|
||||
config=CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_640),5000,2000)) {}.start()
|
||||
CameraClock.advance();val c=Camera.opened.single().second;c.error!!(100,c);CameraClock.advance(10000)
|
||||
verify(CameraProbeStore.results.single().cameraErrorCode==100)
|
||||
verify(CameraProbeStore.results.single().initialFailure==CameraProbeFailure.CAMERA_ERROR)
|
||||
println("PASS: $checks actual production Surface-ACK/default-size/duplicate/stale-callback/first-error preservation + availability stability/retirement-not-recovery/skipped-vs-failed/once-report checks; device HAL/GPU not_run")
|
||||
}
|
||||
@@ -44,3 +44,24 @@ class CameraStandaloneTests(unittest.TestCase):
|
||||
self.assertIn('CameraProbeController(',worker);self.assertIn('listOf(mode)',worker)
|
||||
self.assertIn('message.sendingUid != android.os.Process.myUid()',worker)
|
||||
self.assertNotIn('DiagnosticReportUpload',worker)
|
||||
def test_surface_resize_ack_stays_local_and_preserves_native_defaults(self):
|
||||
worker=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/CameraProbeWorkerService.kt').read_text()
|
||||
owner=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/IsolatedCameraDiagnosticsActivity.kt').read_text()
|
||||
runner=(ROOT/'app/src/main/java/com/gorios/lanvoice/expression/CameraProbeController.kt').read_text()
|
||||
self.assertIn('prepareLegacySurface = ::requestSurface',worker)
|
||||
self.assertIn('SURFACE_READY',owner);self.assertIn('h.surfaceFrame.width() != resize.width',owner)
|
||||
self.assertIn('data.getLong("resize_id", -1) != pending.id',worker)
|
||||
self.assertIn('main.postDelayed(timeout, 2_000)',worker)
|
||||
self.assertIn('surface_resize_ready',runner)
|
||||
self.assertNotIn('Bitmap',worker);self.assertNotIn('ByteArray',worker)
|
||||
def test_fresh_availability_observations_are_bounded_and_not_streaming_proof(self):
|
||||
monitor=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/ProbeAvailabilityMonitor.kt').read_text()
|
||||
suite=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/IsolatedProbeSuite.kt').read_text()
|
||||
owner=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/IsolatedCameraDiagnosticsActivity.kt').read_text()
|
||||
self.assertIn('requireAvailability = true',owner)
|
||||
self.assertIn('ProbeIsolationEffect.ObserveAvailability',owner)
|
||||
self.assertIn('availability = ProbeCameraAvailability.UNKNOWN; availableSince = -1',suite)
|
||||
self.assertIn('val AVAILABILITY_LIMIT_MS = 5_000L',suite)
|
||||
self.assertIn('val AVAILABLE_STABLE_MS = 500L',suite)
|
||||
self.assertIn('unregisterAvailabilityCallback',monitor);self.assertIn('registerAvailabilityCallback',monitor)
|
||||
self.assertNotIn('openCamera(',monitor)
|
||||
|
||||
Reference in New Issue
Block a user