Clarify blocked camera suite and trace native calls with default preview baseline

This commit is contained in:
zenord
2026-10-13 19:55:23 +08:00
parent 8cf7d7316c
commit c3fe22b8bf
12 changed files with 366 additions and 118 deletions
+2 -2
View File
@@ -46,7 +46,7 @@ if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !a
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
if (cameraCompatibilityFix && (!faceDiagnosticsFix || actionVersionCode < 25)) throw new GradleException('Camera compatibility requires face diagnostics and fresh code >=25')
if (cameraDirectYuv && (!cameraCompatibilityFix || actionVersionCode < 26)) throw new GradleException('Direct YUV validation requires camera diagnostics and fresh code >=26')
if (cameraProbeDiagnostic && (!cameraPreviewStream || actionVersionCode < 28)) throw new GradleException('Camera probe diagnostics requires fresh code >=28')
if (cameraProbeDiagnostic && (!cameraPreviewStream || actionVersionCode < 29)) throw new GradleException('Camera probe diagnostics requires fresh code >=29')
if (cameraPreviewStream && (!cameraDirectYuv || actionVersionCode < 27)) throw new GradleException('Preview stream validation requires camera diagnostics and fresh code >=27')
if (faceDiagnosticsFix && (!presenceCandidate || actionVersionCode < 24)) throw new GradleException('Face diagnostics fix requires presence and fresh code >=24')
if (presenceCandidate && (!avatarStartupFix || actionVersionCode < 23)) throw new GradleException('Presence candidate requires startup fix and fresh code >=23')
@@ -103,7 +103,7 @@ android {
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = cameraProbeDiagnostic ? '0.7.10' : cameraPreviewStream ? '0.7.9' : cameraDirectYuv ? '0.7.8' : cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
versionName = cameraProbeDiagnostic ? '0.7.11' : cameraPreviewStream ? '0.7.9' : cameraDirectYuv ? '0.7.8' : cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -39,7 +39,7 @@ class CameraDiagnosticsActivity: ComponentActivity() {
MaterialTheme {Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()
.verticalScroll(rememberScrollState()).padding(16.dp)) {
Text("前置相机一键诊断",style=MaterialTheme.typography.titleLarge)
Text("自动检查六条路径,结束后发送状态报告。约一分钟;此页不收音、不运行模型、不保存或上传画面。")
Text("自动检查七条路径,结束后发送状态报告。约一分钟;此页不收音、不运行模型、不保存或上传画面。")
AndroidView(factory={context->SurfaceView(context).apply {
holder.addCallback(object: SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
@@ -49,16 +49,21 @@ class CameraDiagnosticsActivity: ComponentActivity() {
override fun surfaceDestroyed(holder: SurfaceHolder) {runner?.cancel()}
})
}},modifier=Modifier.fillMaxWidth().height(220.dp))
Text("${stage.name.lowercase()} · 已开始 ${rows.size}/6")
Text(when(stage) {
CameraProbeStage.DONE->"检查结束 · 已结束 ${rows.count {it.closeConfirmed}}/${CameraProbeMode.entries.size}"
CameraProbeStage.BLOCKED->"检查已停止 · 已开始 ${rows.size}/${CameraProbeMode.entries.size},其余因关闭未确认未运行"
else->"检查中 · 已开始 ${rows.size}/${CameraProbeMode.entries.size}"
})
rows.forEach {r->
Text("${r.mode.name.lowercase()} · 回调 ${r.frames} / capture ${r.captureCompleted} · ${r.frameWidth}×${r.frameHeight} · ${r.failure.name.lowercase()} · 关闭${if(r.closeConfirmed) "已确认" else "待确认"}")
}
rows.lastOrNull()?.let {r->Text("原生调用 ${r.nativeOperation.name.lowercase()} · ${r.nativeCallState.name.lowercase()}")}
if(stage==CameraProbeStage.BLOCKED) Text("关闭未确认,后续测试已停止。报告会标明卡点;不会强抢相机。")
Text(if(sending) "正在发送报告…" else receipt ?: "诊断进行中…")
Text(if(sending) "正在发送报告…" else receipt ?: if(stage in setOf(CameraProbeStage.DONE,CameraProbeStage.BLOCKED)) "检查已结束,正在整理发送" else "诊断进行中…")
if(receipt=="发送失败") TextButton(onClick=::sendReport) {Text("重发报告")}
TextButton(onClick={runner?.cancel()}) {Text("停止诊断并发送")}
TextButton(onClick={runner?.cancel();finish()}) {Text("返回")}
Text("CameraX Preview 单路的 capture 计数表示原生捕获完成,不能证明显示首帧;实际分析回调与 EGL 锁存分开记录。")
Text("首项 Camera1默认配置仅预览,不请求图像回调;回调0不代表无画面。CameraX Preview 单路的 capture 计数表示原生捕获完成,不能证明显示首帧;实际分析回调与 EGL 锁存分开记录。")
}}
}
}
@@ -87,7 +87,11 @@ object DiagnosticReportUpload {
.put("result_acks",t.resultAcks).put("result_code",t.resultCode).put("consumer_closed",t.closed)
private fun probeReport(info: DiagnosticReportInfo): JSONObject {
val rows=JSONArray()
info.cameraProbes.take(6).forEach {r->rows.put(JSONObject()
info.cameraProbes.take(CameraProbeMode.entries.size).forEach {r->rows.put(JSONObject()
.put("native_operation",r.nativeOperation.name.lowercase()).put("native_call_state",r.nativeCallState.name.lowercase())
.put("native_call_started_ms",r.nativeCallStartedMs).put("native_call_returned_ms",r.nativeCallReturnedMs)
.put("initial_failure",r.initialFailure.name.lowercase())
.put("frame_observation",if(r.mode==CameraProbeMode.CAMERA1_DEFAULT_PREVIEW) "not_sampled" else "callback_counted")
.put("mode",r.mode.name.lowercase()).put("failure",r.failure.name.lowercase())
.put("started_ms",r.startedMs).put("finished_ms",r.finishedMs).put("bound_ms",r.boundMs)
.put("open_ms",r.openMs).put("surface_provided_ms",r.surfaceProvidedMs)
@@ -101,7 +105,7 @@ object DiagnosticReportUpload {
.put("close_started_ms",r.closeStartedMs).put("close_returned_ms",r.closeReturnedMs)
.put("closed_ms",r.closedMs).put("close_confirmed",r.closeConfirmed).put("preview_trace",previewTrace(r.previewTrace)))}
return JSONObject().put("stage",info.cameraProbeStage.name.lowercase())
.put("entry_failure",info.cameraProbeEntryFailure.name.lowercase()).put("max_tests",6)
.put("entry_failure",info.cameraProbeEntryFailure.name.lowercase()).put("max_tests",CameraProbeMode.entries.size)
.put("run_limit_ms",8000).put("close_limit_ms",8000).put("results",rows)
}
@@ -33,17 +33,21 @@ class CameraProbeController(private val context: Context,private val owner: Life
private val main=Handler(Looper.getMainLooper())
private var generation=0L
@Volatile private var active: Run?=null
private var cancelled=false
@Volatile private var cancelled=false
private val notified=java.util.concurrent.atomic.AtomicBoolean()
private var nextIndex=0
private val progressLock=Any()
private val watchThread=HandlerThread("lan-voice-camera-watchdog").apply {start()}
private val watchdog=Handler(watchThread.looper)
private val watchTick=object: Runnable { override fun run() {
if(notified.get()) return
val run=active
if(run!=null && !run.retired && SystemClock.elapsedRealtime()-run.result.startedMs>=8_000) {
finishRun(run)
}
if(run!=null && run.retired && closeAt>=0 && SystemClock.elapsedRealtime()-closeAt>=8_000) {
// Still works if CameraX unbind or the camera worker is blocked.
run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT)
run.update {it.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT,initialFailure=if(it.initialFailure==CameraProbeFailure.NONE) CameraProbeFailure.CLOSE_TIMEOUT else it.initialFailure)}
publish(run);event(run,"close_watchdog_blocked");finish(true)
main.post {run.observer?.let {run.states?.removeObserver(it)}}
} else watchdog.postDelayed(this,500)
@@ -56,6 +60,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
val captures=AtomicInteger();val captureFailures=AtomicInteger()
val frames=AtomicInteger();val returned=AtomicInteger();val first=AtomicLong(-1)
@Volatile var width=0;@Volatile var height=0;@Volatile var bytes=0
val closing=java.util.concurrent.atomic.AtomicBoolean()
@Volatile var retired=false
@Volatile var legacy: Camera?=null
var provider: ProcessCameraProvider?=null
@@ -63,6 +68,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
var sink: CameraPreviewSurface?=null
var states: LiveData<CameraState>?=null;var observer: Observer<CameraState>?=null
@Volatile var result=CameraProbeResult(mode,SystemClock.elapsedRealtime())
@Synchronized fun update(change: (CameraProbeResult)->CameraProbeResult) {result=change(result)}
}
fun start() {
if(active!=null || notified.get() || CameraProbeStore.stage!=CameraProbeStage.RUNNING) return
@@ -77,14 +83,19 @@ class CameraProbeController(private val context: Context,private val owner: Life
CameraProbeStore.entryFailure=CameraProbeFailure.PERMISSION;finish(false);return
}
if(cancelled || nextIndex>=CameraProbeMode.entries.size) {finish(false);return}
val run=Run(++generation,CameraProbeMode.entries[nextIndex++]);active=run
closeAt=-1;CameraProbeStore.stage=CameraProbeStage.RUNNING;publish(run);event(run,"start")
val run=synchronized(progressLock) {
if(notified.get() || cancelled) return
Run(++generation,CameraProbeMode.entries[nextIndex++]).also {
active=it;closeAt=-1;CameraProbeStore.stage=CameraProbeStage.RUNNING
}
}
publish(run);event(run,"start")
main.post(tick)
if(run.mode.legacy) startLegacy(run) else startCameraX(run)
}
private fun valid(run: Run)=active===run && !run.retired && !cancelled && run.token==generation
private fun error(run: Run,reason: CameraProbeFailure) {
main.post { if(valid(run)) {run.result=run.result.copy(failure=reason);close(run)} }
main.post { if(valid(run)) {close(run,reason)} }
}
private fun frame(run: Run,width: Int,height: Int,bytes: Int=0) {
if(run.retired) return
@@ -98,40 +109,52 @@ class CameraProbeController(private val context: Context,private val owner: Life
var camera: Camera?=null
var failure=CameraProbeFailure.OPEN
try {
val info=Camera.CameraInfo()
val id=(0 until Camera.getNumberOfCameras()).firstOrNull {
Camera.getCameraInfo(it,info);info.facing==Camera.CameraInfo.CAMERA_FACING_FRONT
val id=nativeCall(run,CameraNativeOperation.ENUMERATE) {
val info=Camera.CameraInfo()
(0 until Camera.getNumberOfCameras()).firstOrNull {
Camera.getCameraInfo(it,info);info.facing==Camera.CameraInfo.CAMERA_FACING_FRONT
}
}
if(id==null) {error(run,CameraProbeFailure.NO_FRONT);return@post}
camera=Camera.open(id);run.legacy=camera
camera=nativeCall(run,CameraNativeOperation.OPEN) {Camera.open(id)};run.legacy=camera
if(run.retired) return@post
failure=CameraProbeFailure.UNSUPPORTED_SIZE
val params=camera.parameters
check(params.supportedPreviewSizes.any {it.width==run.mode.width && it.height==run.mode.height})
check(ImageFormat.NV21 in params.supportedPreviewFormats)
params.setPreviewSize(run.mode.width,run.mode.height);params.previewFormat=ImageFormat.NV21
failure=CameraProbeFailure.START
camera.parameters=params
val actual=camera.parameters.previewSize
run.width=actual.width;run.height=actual.height
val expected=actual.width*actual.height*3/2
camera.setErrorCallback {_,_->error(run,CameraProbeFailure.CAMERA_ERROR)}
camera.setPreviewDisplay(holder)
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 params=nativeCall(run,CameraNativeOperation.GET_PARAMETERS) {camera.parameters}
val baseline=run.mode==CameraProbeMode.CAMERA1_DEFAULT_PREVIEW
if(!baseline) {
failure=CameraProbeFailure.UNSUPPORTED_SIZE
check(params.supportedPreviewSizes.any {it.width==run.mode.width && it.height==run.mode.height})
check(ImageFormat.NV21 in params.supportedPreviewFormats)
params.setPreviewSize(run.mode.width,run.mode.height);params.previewFormat=ImageFormat.NV21
failure=CameraProbeFailure.START
nativeCall(run,CameraNativeOperation.SET_PARAMETERS) {camera.parameters=params}
}
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)}
}
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)}
}
}
nativeCall(run,CameraNativeOperation.ADD_BUFFERS) {repeat(3) {camera.addCallbackBuffer(ByteArray(expected))}}
}
repeat(3) {camera.addCallbackBuffer(ByteArray(expected))}
if(run.retired) return@post
camera.startPreview()
nativeCall(run,CameraNativeOperation.START_PREVIEW) {camera.startPreview()}
main.post {if(valid(run)) {
val now=SystemClock.elapsedRealtime()
run.result=run.result.copy(boundMs=now,openMs=now,surfaceProvidedMs=now,
nativeState=CameraNativeState.OPEN,surfaceCreated=true)
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)}
@@ -140,20 +163,23 @@ class CameraProbeController(private val context: Context,private val owner: Life
}
private fun releaseLegacy(run: Run,camera: Camera?) {
try {
camera?.setPreviewCallbackWithBuffer(null);camera?.setErrorCallback(null)
camera?.stopPreview();camera?.release();run.legacy=null
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()}
nativeCall(run,CameraNativeOperation.RELEASE) {camera?.release()};run.legacy=null
main.post {
val now=SystemClock.elapsedRealtime()
run.result=run.result.copy(closeReturnedMs=now,nativeState=CameraNativeState.CLOSED,
surfaceAckMs=now,surfaceReleased=true)
run.update {it.copy(closeReturnedMs=now,nativeState=CameraNativeState.CLOSED,
surfaceAckMs=now,surfaceReleased=true)}
publish(run);event(run,"release_returned")
if(notified.get()) run.workerThread.quitSafely()
}
} catch(_: Exception) {main.post {run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run)}}
} catch(_: Exception) {main.post {run.update {it.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT,initialFailure=if(it.initialFailure==CameraProbeFailure.NONE) CameraProbeFailure.CLOSE_TIMEOUT else it.initialFailure)};publish(run)}}
}
private fun startCameraX(run: Run) {
try {
val future=ProcessCameraProvider.getInstance(context)
val future=nativeCall(run,CameraNativeOperation.PROVIDER_WAIT) {ProcessCameraProvider.getInstance(context)}
future.addListener({
if(!valid(run)) return@addListener
try {
@@ -190,9 +216,9 @@ class CameraProbeController(private val context: Context,private val owner: Life
if(run.mode==CameraProbeMode.CAMERAX_GL_DUAL) {
val sink=CameraPreviewSurface({e,w,h->main.post {
if(active!==run) return@post
if(e==CameraPreviewEvent.PROVIDED) {run.provided.incrementAndGet();run.result=run.result.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime())}
if(e==CameraPreviewEvent.RESULT_ACK) {run.acks.incrementAndGet();run.result=run.result.copy(surfaceAckMs=SystemClock.elapsedRealtime(),surfaceResult=run.sink?.trace()?.resultCode ?: -1)}
if(e==CameraPreviewEvent.RELEASED) run.result=run.result.copy(surfaceReleased=true)
if(e==CameraPreviewEvent.PROVIDED) {run.provided.incrementAndGet();run.update {it.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime())}}
if(e==CameraPreviewEvent.RESULT_ACK) {run.acks.incrementAndGet();run.update {it.copy(surfaceAckMs=SystemClock.elapsedRealtime(),surfaceResult=run.sink?.trace()?.resultCode ?: -1)}}
if(e==CameraPreviewEvent.RELEASED) run.update {it.copy(surfaceReleased=true)}
publish(run);event(run,"gl_${e.name.lowercase()}")
}},{error(run,CameraProbeFailure.SURFACE)})
run.sink=sink;preview.setSurfaceProvider(sink)
@@ -203,13 +229,13 @@ class CameraProbeController(private val context: Context,private val owner: Life
val ack=java.util.concurrent.atomic.AtomicBoolean()
run.provided.incrementAndGet()
holder.setFixedSize(request.resolution.width,request.resolution.height)
run.result=run.result.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime(),
frameWidth=request.resolution.width,frameHeight=request.resolution.height)
run.update {it.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime(),
frameWidth=request.resolution.width,frameHeight=request.resolution.height)}
request.provideSurface(holder.surface,{task->main.post(task)}) {result->
if(!ack.compareAndSet(false,true)) return@provideSurface
run.acks.incrementAndGet()
run.result=run.result.copy(surfaceAckMs=SystemClock.elapsedRealtime(),
surfaceResult=result.resultCode,surfaceReleased=true)
run.update {it.copy(surfaceAckMs=SystemClock.elapsedRealtime(),
surfaceResult=result.resultCode,surfaceReleased=true)}
publish(run);event(run,"surface_ack")
}
event(run,"surface_provided")
@@ -218,19 +244,19 @@ class CameraProbeController(private val context: Context,private val owner: Life
}
}
}
val camera=provider.bindToLifecycle(owner,CameraSelector.DEFAULT_FRONT_CAMERA,*cases.toTypedArray())
run.result=run.result.copy(boundMs=SystemClock.elapsedRealtime())
val camera=nativeCall(run,CameraNativeOperation.BIND) {provider.bindToLifecycle(owner,CameraSelector.DEFAULT_FRONT_CAMERA,*cases.toTypedArray())}
run.update {it.copy(boundMs=SystemClock.elapsedRealtime())}
val states=camera.cameraInfo.cameraState
val observer=Observer<CameraState> {state ->
val native=CameraNativeState.entries.firstOrNull {it.name==state.type.name} ?: CameraNativeState.UNKNOWN
val changed=run.result.nativeState!=native || state.error!=null
run.result=run.result.copy(nativeState=native,
openMs=if(native==CameraNativeState.OPEN && run.result.openMs<0) SystemClock.elapsedRealtime() else run.result.openMs)
if(state.error!=null) run.result=run.result.copy(sessionFailure=when(state.error!!.code) {
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) {
CameraState.ERROR_STREAM_CONFIG->CameraSessionFailure.STREAM_CONFIG
CameraState.ERROR_CAMERA_IN_USE->CameraSessionFailure.IN_USE
CameraState.ERROR_CAMERA_FATAL_ERROR->CameraSessionFailure.FATAL
else->CameraSessionFailure.OTHER})
else->CameraSessionFailure.OTHER})}
publish(run);if(changed) event(run,"native_${native.name.lowercase()}")
}
run.states=states;run.observer=observer;states.observeForever(observer)
@@ -244,25 +270,20 @@ class CameraProbeController(private val context: Context,private val owner: Life
val run=active ?: return
val now=SystemClock.elapsedRealtime();publish(run)
if(!run.retired && context.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
cancelled=true;run.result=run.result.copy(failure=CameraProbeFailure.PERMISSION);close(run)
}
if(!run.retired && now-run.result.startedMs>=8_000) {
// Visible Preview alone has no software frame callback: do not claim frames from OPEN.
val got=run.frames.get()>0 || (run.mode==CameraProbeMode.CAMERAX_PREVIEW && run.captures.get()>0) || (run.sink?.trace()?.latchCompleted ?: 0)>0
if(!got) run.result=run.result.copy(failure=CameraProbeFailure.FRAME_TIMEOUT)
close(run)
cancelled=true;close(run,CameraProbeFailure.PERMISSION)
}
if(!run.retired && now-run.result.startedMs>=8_000) finishRun(run)
if(run.retired) {
val safe=probeCloseSafe(run.mode.legacy,run.result.boundMs>=0,
run.result.nativeState==CameraNativeState.CLOSED,run.result.surfaceCreated,
(run.result.surfaceAckMs>=0 && run.provided.get()==run.acks.get()),if(run.sink!=null) run.sink!!.trace().closed else run.result.surfaceReleased,
run.result.closeReturnedMs>=0)
if(safe) {
run.result=run.result.copy(closedMs=now,closeConfirmed=true);publish(run);event(run,"close_confirmed")
run.update {it.copy(closedMs=now,closeConfirmed=true)};publish(run);event(run,"close_confirmed")
detach(run);active=null;main.removeCallbacks(this);next();return
}
if(now-closeAt>=8_000) {
run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run);event(run,"close_blocked")
run.update {it.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT,initialFailure=if(it.initialFailure==CameraProbeFailure.NONE) CameraProbeFailure.CLOSE_TIMEOUT else it.initialFailure)};publish(run);event(run,"close_blocked")
// Retain producer-owned Surface/blocked worker; never force release or start next API.
run.observer?.let {run.states?.removeObserver(it)}
finish(true);return
@@ -270,44 +291,75 @@ class CameraProbeController(private val context: Context,private val owner: Life
}
main.postDelayed(this,250)
}}
private fun close(run: Run) {
if(run.retired) return
run.retired=true;closeAt=SystemClock.elapsedRealtime()
run.result=run.result.copy(finishedMs=closeAt,closeStartedMs=closeAt)
private fun close(run: Run,reason: CameraProbeFailure?=null) {
if(!run.closing.compareAndSet(false,true)) return
closeAt=SystemClock.elapsedRealtime()
run.retired=true
run.update {it.copy(finishedMs=closeAt,closeStartedMs=closeAt,
failure=reason ?: it.failure,
initialFailure=if(it.initialFailure==CameraProbeFailure.NONE) reason ?: it.failure else it.initialFailure)}
CameraProbeStore.stage=CameraProbeStage.CLOSING;publish(run);event(run,"close_requested")
if(run.mode.legacy) run.worker.post {releaseLegacy(run,run.legacy)}
else {
else main.post {
run.analysis?.clearAnalyzer();run.sink?.close()
try {
val cases=listOfNotNull(run.preview,run.analysis)
if(cases.isNotEmpty()) run.provider?.unbind(*cases.toTypedArray())
run.result=run.result.copy(closeReturnedMs=SystemClock.elapsedRealtime())
if(cases.isNotEmpty()) nativeCall(run,CameraNativeOperation.UNBIND) {run.provider?.unbind(*cases.toTypedArray())}
run.update {it.copy(closeReturnedMs=SystemClock.elapsedRealtime())}
publish(run);event(run,"unbind_returned")
} catch(_: Exception) {run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run)}
} catch(_: Exception) {run.update {it.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT,initialFailure=if(it.initialFailure==CameraProbeFailure.NONE) CameraProbeFailure.CLOSE_TIMEOUT else it.initialFailure)};publish(run)}
}
}
private fun finishRun(run: Run) {
val got=run.frames.get()>0 || (run.mode==CameraProbeMode.CAMERAX_PREVIEW && run.captures.get()>0) ||
(run.sink?.trace()?.latchCompleted ?: 0)>0
// A pure native Preview has no analysis callback by design; visibility is unmeasured.
val reason=when {
run.result.nativeCallState==CameraNativeCallState.PENDING -> CameraProbeFailure.NATIVE_TIMEOUT
!got && run.mode!=CameraProbeMode.CAMERA1_DEFAULT_PREVIEW -> CameraProbeFailure.FRAME_TIMEOUT
else -> null
}
close(run,reason)
}
private inline fun <T> nativeCall(run: Run,operation: CameraNativeOperation,call: ()->T): T {
run.update {it.copy(nativeOperation=operation,nativeCallState=CameraNativeCallState.PENDING,
nativeCallStartedMs=SystemClock.elapsedRealtime(),nativeCallReturnedMs=-1)}
publish(run);event(run,"native_call_start")
try {
val value=call()
run.update {it.copy(nativeCallState=CameraNativeCallState.RETURNED,nativeCallReturnedMs=SystemClock.elapsedRealtime())}
publish(run);event(run,"native_call_return")
return value
} catch(error: Exception) {
run.update {it.copy(nativeCallState=CameraNativeCallState.THREW,nativeCallReturnedMs=SystemClock.elapsedRealtime())}
publish(run);event(run,"native_call_threw");throw error
}
}
private fun publish(run: Run) {
run.result=run.result.copy(providedSurfaces=run.provided.get(),acknowledgedSurfaces=run.acks.get(),captureCompleted=run.captures.get(),captureFailed=run.captureFailures.get(),frames=run.frames.get(),analysisReturned=run.returned.get(),
firstFrameMs=run.first.get(),frameWidth=if(run.width>0) run.width else run.result.frameWidth,
frameHeight=if(run.height>0) run.height else run.result.frameHeight,callbackBytes=run.bytes,
previewTrace=run.sink?.trace() ?: run.result.previewTrace)
run.update {it.copy(providedSurfaces=run.provided.get(),acknowledgedSurfaces=run.acks.get(),captureCompleted=run.captures.get(),captureFailed=run.captureFailures.get(),frames=run.frames.get(),analysisReturned=run.returned.get(),
firstFrameMs=run.first.get(),frameWidth=if(run.width>0) run.width else it.frameWidth,
frameHeight=if(run.height>0) run.height else it.frameHeight,callbackBytes=run.bytes,
previewTrace=run.sink?.trace() ?: it.previewTrace)}
CameraProbeStore.put(run.result)
}
private fun event(run: Run,event: String) {
val msg="camera_probe event=$event mode=${run.mode.name.lowercase()} elapsed_ms=${SystemClock.elapsedRealtime()-run.result.startedMs} frames=${run.frames.get()} native=${run.result.nativeState.name.lowercase()} failure=${run.result.failure.name.lowercase()}"
val msg="camera_probe event=$event mode=${run.mode.name.lowercase()} elapsed_ms=${SystemClock.elapsedRealtime()-run.result.startedMs} frames=${run.frames.get()} native=${run.result.nativeState.name.lowercase()} failure=${run.result.failure.name.lowercase()} operation=${run.result.nativeOperation.name.lowercase()} call_state=${run.result.nativeCallState.name.lowercase()}"
android.util.Log.i("LanVoiceCameraProbe",msg);DiagnosticLog.record("camera_probe",msg)
}
private fun detach(run: Run) {run.observer?.let {run.states?.removeObserver(it)};run.workerThread.quitSafely()}
private fun finish(blocked: Boolean) {
if(!notified.compareAndSet(false,true)) return
synchronized(progressLock) {
if(!notified.compareAndSet(false,true)) return
CameraProbeStore.finish(blocked)
}
main.removeCallbacks(tick);watchdog.removeCallbacks(watchTick);watchThread.quitSafely()
CameraProbeStore.finish(blocked);done()
done()
}
fun cancel() {
cancelled=true
val run=active
if(run!=null && !notified.get()) {
if(!run.retired) {run.result=run.result.copy(failure=CameraProbeFailure.CANCELLED);close(run)}
if(!run.retired) close(run,CameraProbeFailure.CANCELLED)
} else if(!notified.get()) finish(false)
}
}
@@ -2,15 +2,19 @@ package com.gorios.lanvoice.expression
/** Fixed bounded metadata; this object never receives pixel contents, face geometry or voice. */
enum class CameraProbeMode(val width: Int,val height: Int) {
CAMERA1_640(640,480), CAMERA1_320(320,240), CAMERAX_PREVIEW(640,480),
CAMERA1_DEFAULT_PREVIEW(0,0), CAMERA1_640(640,480), CAMERA1_320(320,240), CAMERAX_PREVIEW(640,480),
CAMERAX_VISIBLE_DUAL(640,480), CAMERAX_ANALYSIS(640,480), CAMERAX_GL_DUAL(640,480);
val legacy get()=this==CAMERA1_640 || this==CAMERA1_320
val legacy get()=this==CAMERA1_DEFAULT_PREVIEW || this==CAMERA1_640 || this==CAMERA1_320
val analysis get()=this==CAMERAX_VISIBLE_DUAL || this==CAMERAX_ANALYSIS || this==CAMERAX_GL_DUAL
val visible get()=legacy || this==CAMERAX_PREVIEW || this==CAMERAX_VISIBLE_DUAL
}
enum class CameraNativeOperation { NONE, ENUMERATE, OPEN, GET_PARAMETERS, SET_PARAMETERS, SET_ERROR_CALLBACK,
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 CameraProbeStage { IDLE, RUNNING, CLOSING, DONE, BLOCKED }
enum class CameraProbeFailure { NONE, PERMISSION, NO_FRONT, UNSUPPORTED_SIZE, PROVIDER, BIND, OPEN,
START, CAMERA_ERROR, SURFACE, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED }
START, CAMERA_ERROR, SURFACE, NATIVE_TIMEOUT, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED }
data class CameraProbeResult(val mode: CameraProbeMode,val startedMs: Long,
val finishedMs: Long=-1,val closeStartedMs: Long=-1,val closeReturnedMs: Long=-1,
val closedMs: Long=-1,val firstFrameMs: Long=-1,val frames: Int=0,val analysisReturned: Int=0,
@@ -22,6 +26,10 @@ data class CameraProbeResult(val mode: CameraProbeMode,val startedMs: Long,
val providedSurfaces: Int=0,val acknowledgedSurfaces: Int=0,
val surfaceAckMs: Long=-1,val surfaceResult: Int=-1,val surfaceReleased: Boolean=false,
val surfaceCreated: Boolean=false,val closeConfirmed: Boolean=false,
val initialFailure: CameraProbeFailure=CameraProbeFailure.NONE,
val nativeOperation: CameraNativeOperation=CameraNativeOperation.NONE,
val nativeCallState: CameraNativeCallState=CameraNativeCallState.NONE,
val nativeCallStartedMs: Long=-1,val nativeCallReturnedMs: Long=-1,
val previewTrace: CameraPreviewTrace=CameraPreviewTrace(),val failure: CameraProbeFailure=CameraProbeFailure.NONE)
/** One foreground suite per process at a time. A timed-out close keeps normal camera inhibited. */
@@ -36,7 +44,7 @@ object CameraProbeStore {
}
@Synchronized fun put(result: CameraProbeResult) {
val rows=results.toMutableList();val index=rows.indexOfFirst {it.mode==result.mode}
if(index<0) {if(rows.size<6) rows+=result} else rows[index]=result
if(index<0) {if(rows.size<CameraProbeMode.entries.size) rows+=result} else rows[index]=result
results=rows.toList()
}
@Synchronized fun finish(blocked: Boolean) {