fix(camera): negotiate preview surfaces and gate diagnostic recovery
This commit is contained in:
@@ -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() } }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user