fix(camera): isolate stalled diagnostic modes and gate preview surfaces
This commit is contained in:
@@ -37,8 +37,8 @@ android {
|
||||
applicationId 'com.gorios.lanvoice.cameraprobe'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 2
|
||||
versionName 'camera-probe-0.1.1'
|
||||
versionCode 3
|
||||
versionName 'camera-probe-0.1.2'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
android:supportsRtl="true" android:usesCleartextTraffic="false" android:networkSecurityConfig="@xml/network_security_config">
|
||||
<activity android:name="com.gorios.lanvoice.CameraDiagnosticsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
|
||||
<activity android:name="com.gorios.lanvoice.IsolatedCameraDiagnosticsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
|
||||
<service android:name="com.gorios.lanvoice.CameraProbeWorkerService" android:exported="false"
|
||||
android:process=":camera_probe_worker" />
|
||||
<activity android:name="com.gorios.lanvoice.CameraProbeLauncherActivity" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -48,7 +48,7 @@ class CameraProbeLauncherActivity: ComponentActivity() {
|
||||
pending=false
|
||||
if(!CameraProbeStore.begin()) {status="上次关闭未确认,不能开启下一相机会话;已有报告请查看检查页。";return}
|
||||
status="检查已启动;结束或关闭超时后自动发送报告。"
|
||||
startActivity(Intent(this,CameraDiagnosticsActivity::class.java).putExtra("camera_probe_admitted",true))
|
||||
startActivity(Intent(this,IsolatedCameraDiagnosticsActivity::class.java).putExtra("camera_probe_admitted",true))
|
||||
}
|
||||
override fun onResume() {super.onResume();hideSystemBars(window);foreground=true;startIfReady()}
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Rect
|
||||
import android.os.*
|
||||
import android.view.Surface
|
||||
import android.view.SurfaceHolder
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import com.gorios.lanvoice.expression.*
|
||||
|
||||
/** One configuration per disposable private process. Its Binder carries a local Surface handle
|
||||
* and bounded enum/count snapshots, never copied images. It never performs a network upload. */
|
||||
class CameraProbeWorkerService : Service(), LifecycleOwner {
|
||||
companion object {
|
||||
const val START = 1
|
||||
const val READY = 2
|
||||
const val SNAPSHOT = 3
|
||||
const val END_SAMPLING = 4
|
||||
const val DONE = 5
|
||||
const val PROCESS_SUFFIX = ":camera_probe_worker"
|
||||
}
|
||||
private val registry = LifecycleRegistry(this)
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
private var reply: Messenger? = null
|
||||
private var epoch = -1L
|
||||
private var runner: CameraProbeController? = null
|
||||
private var lastWireMs = -1L
|
||||
private var lastSignature = ""
|
||||
private val ipc = Messenger(Handler(Looper.getMainLooper()) { message ->
|
||||
when (message.what) {
|
||||
START -> start(message)
|
||||
END_SAMPLING -> if (message.data.getLong("epoch", -1) == epoch) runner?.endSampling()
|
||||
}
|
||||
true
|
||||
})
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
override fun onBind(intent: Intent): IBinder = ipc.binder
|
||||
private fun start(message: Message) {
|
||||
if (runner != null || reply != null || message.sendingUid != android.os.Process.myUid()) return
|
||||
val data = message.data
|
||||
val token = data.getLong("epoch", -1)
|
||||
val mode = CameraProbeMode.entries.getOrNull(data.getInt("mode", -1)) ?: return
|
||||
@Suppress("DEPRECATION") val surface = data.getParcelable<Surface>("surface") ?: return
|
||||
val width = data.getInt("width"); val height = data.getInt("height")
|
||||
if (token < 0 || width !in 1..4096 || height !in 1..4096 || !surface.isValid) return
|
||||
reply = message.replyTo ?: return
|
||||
epoch = token
|
||||
try {
|
||||
// A lost owner must not leave a native camera running in this disposable process.
|
||||
reply!!.binder.linkToDeath({ android.os.Process.killProcess(android.os.Process.myPid()) }, 0)
|
||||
} catch (_: RemoteException) { android.os.Process.killProcess(android.os.Process.myPid()); return }
|
||||
send(READY, null)
|
||||
registry.currentState = Lifecycle.State.STARTED
|
||||
CameraProbeStore.begin()
|
||||
runner = CameraProbeController(this, this, LocalPreviewHolder(surface, width, height),
|
||||
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}"
|
||||
synchronized(this) {
|
||||
if (signature != lastSignature || now - lastWireMs >= 250) {
|
||||
lastSignature = signature; lastWireMs = now; send(SNAPSHOT, row)
|
||||
}
|
||||
}
|
||||
}, 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?) {
|
||||
val message = Message.obtain(null, what).apply {
|
||||
arg1 = android.os.Process.myPid()
|
||||
data = Bundle().apply {
|
||||
putLong("epoch", epoch)
|
||||
if (row != null) putSerializable("result", row)
|
||||
}
|
||||
}
|
||||
try { reply?.send(message) }
|
||||
catch (_: RemoteException) { android.os.Process.killProcess(android.os.Process.myPid()) }
|
||||
}
|
||||
override fun onDestroy() {
|
||||
// Unbinding retires this isolated owner. Do not re-enter a potentially blocked HAL close.
|
||||
android.os.Process.killProcess(android.os.Process.myPid())
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
override fun isCreating() = false
|
||||
override fun setFixedSize(width: Int, height: Int) {
|
||||
check(width == frame.width() && height == frame.height())
|
||||
}
|
||||
override fun addCallback(callback: SurfaceHolder.Callback) {}
|
||||
override fun removeCallback(callback: SurfaceHolder.Callback) {}
|
||||
override fun setType(type: Int) {}
|
||||
override fun setSizeFromLayout() {}
|
||||
override fun setFormat(format: Int) {}
|
||||
override fun setKeepScreenOn(keepScreenOn: Boolean) {}
|
||||
override fun lockCanvas(): Canvas? = throw UnsupportedOperationException()
|
||||
override fun lockCanvas(dirty: Rect?): Canvas? = throw UnsupportedOperationException()
|
||||
override fun lockHardwareCanvas(): Canvas = throw UnsupportedOperationException()
|
||||
override fun unlockCanvasAndPost(canvas: Canvas) = throw UnsupportedOperationException()
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import android.Manifest
|
||||
import android.app.ActivityManager
|
||||
import android.content.*
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.*
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.gorios.lanvoice.diag.*
|
||||
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 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 phase by mutableStateOf(ProbeIsolationPhase.IDLE)
|
||||
private var rows by mutableStateOf<List<CameraProbeResult>>(emptyList())
|
||||
private var sending by mutableStateOf(false)
|
||||
private var receipt by mutableStateOf<String?>(null)
|
||||
private class WorkerLease(val epoch: Long) {
|
||||
lateinit var connection: ServiceConnection
|
||||
var bound = false
|
||||
var binder: IBinder? = null
|
||||
var messenger: Messenger? = null
|
||||
var death: IBinder.DeathRecipient? = null
|
||||
var startSent = false
|
||||
var killedPid = -1
|
||||
}
|
||||
private val reply = Messenger(Handler(Looper.getMainLooper()) { message ->
|
||||
val token = message.data.getLong("epoch", -1)
|
||||
if (token == suite.epoch && lease?.epoch == token && message.sendingUid == android.os.Process.myUid()) {
|
||||
when (message.what) {
|
||||
CameraProbeWorkerService.READY -> {
|
||||
val pid = ownedWorkerPid()
|
||||
if (pid == message.arg1) dispatch(suite.ready(token, pid, now()))
|
||||
}
|
||||
CameraProbeWorkerService.SNAPSHOT -> {
|
||||
message.data.classLoader = CameraProbeResult::class.java.classLoader
|
||||
@Suppress("DEPRECATION") val row = message.data.getSerializable("result") as? CameraProbeResult
|
||||
if (row != null) dispatch(suite.snapshot(token, row, now()))
|
||||
}
|
||||
CameraProbeWorkerService.DONE -> dispatch(suite.completed(token, now()))
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
private fun now() = SystemClock.elapsedRealtime()
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!foreground && suite.phase !in setOf(ProbeIsolationPhase.IDLE, ProbeIsolationPhase.DONE, ProbeIsolationPhase.BLOCKED)) dispatch(suite.cancel(now()))
|
||||
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && suite.phase != ProbeIsolationPhase.IDLE) dispatch(suite.cancel(now()))
|
||||
if (suite.phase == ProbeIsolationPhase.WAITING_EXIT) lease?.let(::terminate)
|
||||
dispatch(suite.tick(now()))
|
||||
if (suite.phase !in setOf(ProbeIsolationPhase.DONE, ProbeIsolationPhase.BLOCKED)) main.postDelayed(this, 200)
|
||||
}
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (!BuildConfig.DEBUG || !intent.getBooleanExtra("camera_probe_admitted", false) || CameraProbeStore.stage != CameraProbeStage.RUNNING) { finish(); return }
|
||||
admitted = true
|
||||
hideSystemBars(window)
|
||||
setContent { MaterialTheme {
|
||||
Column(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)
|
||||
.verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
Text("前置相机一键诊断", style = MaterialTheme.typography.titleLarge)
|
||||
Text("七项依次检查;每项采样5秒、关闭等待2秒。卡住时结束工作进程,确认退出后继续。仅发送状态,不保存画面、不收音。")
|
||||
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() }
|
||||
}
|
||||
override fun surfaceDestroyed(h: SurfaceHolder) {
|
||||
this@IsolatedCameraDiagnosticsActivity.holder = null
|
||||
dispatch(suite.cancel(now()))
|
||||
}
|
||||
})
|
||||
} }, modifier = Modifier.fillMaxWidth().height(220.dp))
|
||||
Text("配置 ${rows.size}/7 · " + when (phase) {
|
||||
ProbeIsolationPhase.IDLE, ProbeIsolationPhase.STARTING -> "准备预览与工作进程"
|
||||
ProbeIsolationPhase.RUNNING -> "采样中"
|
||||
ProbeIsolationPhase.CLOSING -> "关闭当前配置"
|
||||
ProbeIsolationPhase.WAITING_EXIT -> "等待工作进程退出"
|
||||
ProbeIsolationPhase.SETTLING -> "退出已确认,准备下一项"
|
||||
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.lastOrNull()?.let { Text("当前原生调用 ${it.nativeOperation.name.lowercase()} / ${it.nativeCallState.name.lowercase()}") }
|
||||
Text(if (sending) "正在发送报告…" else receipt ?: "报告会在检查结束后自动发送")
|
||||
if (receipt == "发送失败") TextButton(onClick = ::sendReport) { Text("重发报告") }
|
||||
TextButton(onClick = { dispatch(suite.cancel(now())) }) { Text("停止诊断并发送") }
|
||||
TextButton(onClick = { dispatch(suite.cancel(now())); finish() }) { Text("返回") }
|
||||
Text("默认 Camera1 项仅预览、没有图像回调,帧0不能证明无画面。进程退出确认不等于原生关闭成功;报告分别记录。")
|
||||
}
|
||||
} }
|
||||
main.post(tick)
|
||||
}
|
||||
private fun startIfReady() {
|
||||
val h = holder ?: return
|
||||
if (foreground && suite.phase == ProbeIsolationPhase.IDLE && h.surface.isValid && !h.isCreating && h.surfaceFrame.width() > 0 && h.surfaceFrame.height() > 0) dispatch(suite.start(now()))
|
||||
}
|
||||
private fun dispatch(effects: List<ProbeIsolationEffect>) {
|
||||
phase = suite.phase; rows = suite.results
|
||||
rows.forEach(CameraProbeStore::put)
|
||||
val row = suite.current
|
||||
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.Start -> {
|
||||
pendingStart = effect
|
||||
val width = effect.mode.width.takeIf { it > 0 } ?: 640
|
||||
val height = effect.mode.height.takeIf { it > 0 } ?: 480
|
||||
holder?.setFixedSize(width, height)
|
||||
bindIfSurfaceReady()
|
||||
}
|
||||
is ProbeIsolationEffect.EndSampling -> sendEndSampling(effect.epoch)
|
||||
is ProbeIsolationEffect.Terminate -> { pendingStart = null; lease?.let(::terminate) ?: dispatch(suite.exited(effect.epoch, now())) }
|
||||
ProbeIsolationEffect.Report -> {
|
||||
main.removeCallbacks(tick)
|
||||
CameraProbeStore.finish(suite.phase == ProbeIsolationPhase.BLOCKED)
|
||||
sendReport()
|
||||
}
|
||||
} }
|
||||
}
|
||||
private fun bindIfSurfaceReady() {
|
||||
val request = pendingStart ?: return
|
||||
val h = holder ?: return
|
||||
val width = request.mode.width.takeIf { it > 0 } ?: 640
|
||||
val height = request.mode.height.takeIf { it > 0 } ?: 480
|
||||
if (!foreground || lease != null || suite.phase != ProbeIsolationPhase.STARTING || !h.surface.isValid || h.isCreating || h.surfaceFrame.width() != width || h.surfaceFrame.height() != height) return
|
||||
pendingStart = null
|
||||
val current = WorkerLease(request.epoch); lease = current
|
||||
current.connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
||||
if (lease !== current || suite.phase != ProbeIsolationPhase.STARTING) { unbind(current); return }
|
||||
current.binder = binder; current.messenger = Messenger(binder)
|
||||
val death = IBinder.DeathRecipient { main.post { workerExited(current) } }; current.death = death
|
||||
try {
|
||||
binder.linkToDeath(death, 0)
|
||||
val viewHolder = holder ?: return
|
||||
if (!viewHolder.surface.isValid || viewHolder.isCreating) return
|
||||
val start = Message.obtain(null, CameraProbeWorkerService.START).apply {
|
||||
replyTo = reply
|
||||
data = Bundle().apply {
|
||||
putLong("epoch", current.epoch); putInt("mode", request.mode.ordinal)
|
||||
putParcelable("surface", viewHolder.surface); putInt("width", viewHolder.surfaceFrame.width()); putInt("height", viewHolder.surfaceFrame.height())
|
||||
}
|
||||
}
|
||||
current.startSent = true; current.messenger!!.send(start)
|
||||
} catch (_: RemoteException) { workerExited(current) }
|
||||
}
|
||||
override fun onServiceDisconnected(name: ComponentName) { if (current.binder?.isBinderAlive == false) workerExited(current) }
|
||||
override fun onBindingDied(name: ComponentName) { if (current.binder?.isBinderAlive == false) workerExited(current) }
|
||||
override fun onNullBinding(name: ComponentName) { dispatch(suite.cancel(now())) }
|
||||
}
|
||||
current.bound = bindService(Intent(this, CameraProbeWorkerService::class.java), current.connection, Context.BIND_AUTO_CREATE)
|
||||
if (!current.bound) dispatch(suite.cancel(now()))
|
||||
}
|
||||
private fun ownedWorkerPid(): Int? {
|
||||
val processes = (getSystemService(ACTIVITY_SERVICE) as ActivityManager).runningAppProcesses ?: return null
|
||||
return processes.firstOrNull { it.uid == android.os.Process.myUid() && it.processName == packageName + CameraProbeWorkerService.PROCESS_SUFFIX && it.pid != android.os.Process.myPid() }?.pid
|
||||
}
|
||||
private fun terminate(current: WorkerLease) {
|
||||
unbind(current) // Remove AUTO_CREATE before killing, so Android cannot respawn this lease.
|
||||
if (current.binder?.isBinderAlive == false) { workerExited(current); return }
|
||||
val pid = ownedWorkerPid()
|
||||
if (pid != null && current.killedPid != pid) {
|
||||
current.killedPid = pid
|
||||
android.os.Process.killProcess(pid)
|
||||
} else if (current.binder == null && !current.startSent && workerAbsent()) {
|
||||
// No start message was sent; no camera owner existed. No native ACK is invented.
|
||||
workerExited(current)
|
||||
}
|
||||
}
|
||||
private fun workerAbsent(): Boolean {
|
||||
val processes = (getSystemService(ACTIVITY_SERVICE) as ActivityManager).runningAppProcesses ?: return false
|
||||
return processes.none { it.uid == android.os.Process.myUid() && it.processName == packageName + CameraProbeWorkerService.PROCESS_SUFFIX }
|
||||
}
|
||||
private fun unbind(current: WorkerLease) {
|
||||
if (current.bound) {
|
||||
current.bound = false
|
||||
try { unbindService(current.connection) } catch (_: IllegalArgumentException) {}
|
||||
}
|
||||
}
|
||||
private fun workerExited(current: WorkerLease) {
|
||||
if (lease !== current) return
|
||||
unbind(current)
|
||||
try { current.death?.let { current.binder?.unlinkToDeath(it, 0) } } catch (_: java.util.NoSuchElementException) {}
|
||||
lease = null
|
||||
dispatch(suite.exited(current.epoch, now()))
|
||||
}
|
||||
private fun sendEndSampling(token: Long) {
|
||||
val current = lease ?: return
|
||||
if (current.epoch != token) return
|
||||
try { current.messenger?.send(Message.obtain(null, CameraProbeWorkerService.END_SAMPLING).apply { data = Bundle().apply { putLong("epoch", token) } }) }
|
||||
catch (_: RemoteException) { workerExited(current) }
|
||||
}
|
||||
private fun sendReport() {
|
||||
if (sending) return
|
||||
sending = true; receipt = null
|
||||
val stage = if (suite.phase == ProbeIsolationPhase.BLOCKED) CameraProbeStage.BLOCKED else CameraProbeStage.DONE
|
||||
val info = DiagnosticReportInfo(appVersion = BuildConfig.VERSION_NAME, versionCode = BuildConfig.VERSION_CODE,
|
||||
device = "${Build.MANUFACTURER} ${Build.MODEL}", androidApi = Build.VERSION.SDK_INT,
|
||||
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())
|
||||
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) }
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import com.gorios.lanvoice.expression.*
|
||||
|
||||
enum class ProbeIsolationPhase { IDLE, STARTING, RUNNING, CLOSING, WAITING_EXIT, SETTLING, DONE, BLOCKED }
|
||||
sealed interface 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
|
||||
data object Report : 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) {
|
||||
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
|
||||
}
|
||||
var phase = ProbeIsolationPhase.IDLE; private set
|
||||
var epoch = seed; private set
|
||||
var results: List<CameraProbeResult> = emptyList(); private set
|
||||
val current get() = results.lastOrNull()
|
||||
private var since = 0L
|
||||
private var cancelled = false
|
||||
private var reported = false
|
||||
private fun update(change: (CameraProbeResult) -> CameraProbeResult) {
|
||||
results = results.dropLast(1) + change(checkNotNull(current))
|
||||
}
|
||||
fun start(now: Long): List<ProbeIsolationEffect> {
|
||||
if (phase != ProbeIsolationPhase.IDLE) return emptyList()
|
||||
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)
|
||||
return listOf(ProbeIsolationEffect.Start(epoch, mode))
|
||||
}
|
||||
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) }
|
||||
since = now; phase = ProbeIsolationPhase.RUNNING
|
||||
return emptyList()
|
||||
}
|
||||
fun snapshot(token: Long, row: CameraProbeResult, now: Long): List<ProbeIsolationEffect> {
|
||||
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) }
|
||||
if (row.closeStartedMs >= 0 && phase == ProbeIsolationPhase.RUNNING) {
|
||||
phase = ProbeIsolationPhase.CLOSING; since = row.closeStartedMs.coerceAtMost(now)
|
||||
}
|
||||
if (row.closeConfirmed) return retire(CameraProbeFailure.NONE, now)
|
||||
return emptyList()
|
||||
}
|
||||
fun completed(token: Long, now: Long): List<ProbeIsolationEffect> {
|
||||
if (token != epoch || phase !in setOf(ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING)) return emptyList()
|
||||
return retire(if (current?.closeConfirmed == true) CameraProbeFailure.NONE else CameraProbeFailure.CLOSE_TIMEOUT, now)
|
||||
}
|
||||
private fun retire(reason: CameraProbeFailure, now: Long): List<ProbeIsolationEffect> {
|
||||
update {
|
||||
it.copy(failure = if (reason != CameraProbeFailure.NONE) reason else it.failure,
|
||||
initialFailure = if (it.initialFailure == CameraProbeFailure.NONE) reason else it.initialFailure,
|
||||
finishedMs = if (it.finishedMs >= 0) it.finishedMs else now,
|
||||
processStopRequired = !it.closeConfirmed)
|
||||
}
|
||||
phase = ProbeIsolationPhase.WAITING_EXIT; since = now
|
||||
return listOf(ProbeIsolationEffect.Terminate(epoch, checkNotNull(current).workerPid))
|
||||
}
|
||||
/** Called only after Binder death or an OS-owned-process absence check before any start IPC. */
|
||||
fun exited(token: Long, now: Long): List<ProbeIsolationEffect> {
|
||||
if (token != epoch || phase !in setOf(ProbeIsolationPhase.WAITING_EXIT, ProbeIsolationPhase.STARTING,
|
||||
ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING)) return emptyList()
|
||||
if (phase != ProbeIsolationPhase.WAITING_EXIT) update {
|
||||
it.copy(failure = if (it.failure == CameraProbeFailure.NONE) CameraProbeFailure.WORKER_DIED else it.failure,
|
||||
initialFailure = if (it.initialFailure == CameraProbeFailure.NONE) CameraProbeFailure.WORKER_DIED else it.initialFailure,
|
||||
finishedMs = now, processStopRequired = !it.closeConfirmed)
|
||||
}
|
||||
update { it.copy(processExitConfirmed = true) }
|
||||
phase = ProbeIsolationPhase.SETTLING; since = now
|
||||
return emptyList()
|
||||
}
|
||||
fun tick(now: Long): List<ProbeIsolationEffect> = when (phase) {
|
||||
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
|
||||
listOf(ProbeIsolationEffect.EndSampling(epoch))
|
||||
} else emptyList()
|
||||
ProbeIsolationPhase.CLOSING -> if (now - since >= CLOSE_LIMIT_MS) retire(CameraProbeFailure.CLOSE_TIMEOUT, now) else emptyList()
|
||||
ProbeIsolationPhase.WAITING_EXIT -> if (now - since >= EXIT_LIMIT_MS) {
|
||||
update { it.copy(failure = CameraProbeFailure.PROCESS_EXIT_TIMEOUT) }; finish(true)
|
||||
} else emptyList()
|
||||
ProbeIsolationPhase.SETTLING -> if (now - since >= SETTLE_MS) next(now) else emptyList()
|
||||
else -> emptyList()
|
||||
}
|
||||
fun cancel(now: Long): List<ProbeIsolationEffect> {
|
||||
cancelled = true
|
||||
return when (phase) {
|
||||
ProbeIsolationPhase.STARTING, ProbeIsolationPhase.RUNNING, ProbeIsolationPhase.CLOSING -> retire(CameraProbeFailure.CANCELLED, now)
|
||||
ProbeIsolationPhase.SETTLING, ProbeIsolationPhase.IDLE -> finish(false)
|
||||
else -> emptyList()
|
||||
}
|
||||
}
|
||||
private fun finish(blocked: Boolean): List<ProbeIsolationEffect> {
|
||||
phase = if (blocked) ProbeIsolationPhase.BLOCKED else ProbeIsolationPhase.DONE
|
||||
if (reported) return emptyList()
|
||||
reported = true
|
||||
return listOf(ProbeIsolationEffect.Report)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user