fix(camera): isolate stalled diagnostic modes and gate preview surfaces
This commit is contained in:
@@ -44,9 +44,11 @@ class CameraDiagnosticsActivity: ComponentActivity() {
|
||||
AndroidView(factory={context->SurfaceView(context).apply {
|
||||
holder.addCallback(object: SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
readyHolder=holder;startIfReady()
|
||||
readyHolder=holder
|
||||
}
|
||||
override fun surfaceChanged(holder: SurfaceHolder,format: Int,width: Int,height: Int) {
|
||||
if(width>0 && height>0) window.decorView.post {startIfReady()}
|
||||
}
|
||||
override fun surfaceChanged(holder: SurfaceHolder,format: Int,width: Int,height: Int) {}
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {runner?.cancel()}
|
||||
})
|
||||
}},modifier=Modifier.fillMaxWidth().height(220.dp))
|
||||
@@ -82,8 +84,9 @@ class CameraDiagnosticsActivity: ComponentActivity() {
|
||||
}
|
||||
private fun startIfReady() {
|
||||
val holder=readyHolder ?: return
|
||||
if(!holder.surface.isValid || holder.isCreating || holder.surfaceFrame.width()<=0 || holder.surfaceFrame.height()<=0) return
|
||||
if(runner==null && foreground) {
|
||||
runner=CameraProbeController(this,this,holder,::sendReport);runner!!.start()
|
||||
runner=CameraProbeController(this,this,holder,done=::sendReport);runner!!.start()
|
||||
}
|
||||
}
|
||||
override fun onResume() {super.onResume();hideSystemBars(window);foreground=true;startIfReady()}
|
||||
|
||||
@@ -48,6 +48,9 @@ data class DiagnosticReportInfo(
|
||||
val cameraProbeStage: CameraProbeStage=CameraProbeStage.IDLE,
|
||||
val cameraProbeEntryFailure: CameraProbeFailure=CameraProbeFailure.NONE,
|
||||
val cameraProbes: List<CameraProbeResult> = emptyList(),
|
||||
val cameraProbeIsolated: Boolean=false,
|
||||
val cameraProbeRunLimitMs: Int=8000,val cameraProbeCloseLimitMs: Int=8000,
|
||||
val cameraProbeExitLimitMs: Int=0,
|
||||
val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(),
|
||||
val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(),
|
||||
val presence: PresenceDiagnosticsSnapshot = PresenceDiagnosticsSnapshot(),
|
||||
@@ -91,6 +94,10 @@ object DiagnosticReportUpload {
|
||||
.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("worker_pid",r.workerPid).put("process_stop_required",r.processStopRequired)
|
||||
.put("process_exit_confirmed",r.processExitConfirmed)
|
||||
.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")
|
||||
.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)
|
||||
@@ -106,7 +113,9 @@ object DiagnosticReportUpload {
|
||||
.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",CameraProbeMode.entries.size)
|
||||
.put("run_limit_ms",8000).put("close_limit_ms",8000).put("results",rows)
|
||||
.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)
|
||||
}
|
||||
|
||||
/** Result arrives on an OkHttp worker (or immediately if setup fails). */
|
||||
|
||||
@@ -29,7 +29,8 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
@androidx.annotation.OptIn(markerClass=[androidx.camera.camera2.interop.ExperimentalCamera2Interop::class])
|
||||
@Suppress("DEPRECATION")
|
||||
class CameraProbeController(private val context: Context,private val owner: LifecycleOwner,
|
||||
private val holder: SurfaceHolder,private val done: ()->Unit) {
|
||||
private val holder: SurfaceHolder,private val config: CameraProbeConfig=CameraProbeConfig(),
|
||||
private val onSnapshot: (CameraProbeResult)->Unit={},private val done: ()->Unit) {
|
||||
private val main=Handler(Looper.getMainLooper())
|
||||
private var generation=0L
|
||||
@Volatile private var active: Run?=null
|
||||
@@ -42,10 +43,10 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
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) {
|
||||
if(run!=null && !run.retired && SystemClock.elapsedRealtime()-run.result.startedMs>=config.runLimitMs) {
|
||||
finishRun(run)
|
||||
}
|
||||
if(run!=null && run.retired && closeAt>=0 && SystemClock.elapsedRealtime()-closeAt>=8_000) {
|
||||
if(run!=null && run.retired && closeAt>=0 && SystemClock.elapsedRealtime()-closeAt>=config.closeLimitMs) {
|
||||
// Still works if CameraX unbind or the camera worker is 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_watchdog_blocked");finish(true)
|
||||
@@ -82,10 +83,10 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
if(context.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
|
||||
CameraProbeStore.entryFailure=CameraProbeFailure.PERMISSION;finish(false);return
|
||||
}
|
||||
if(cancelled || nextIndex>=CameraProbeMode.entries.size) {finish(false);return}
|
||||
if(cancelled || nextIndex>=config.modes.size) {finish(false);return}
|
||||
val run=synchronized(progressLock) {
|
||||
if(notified.get() || cancelled) return
|
||||
Run(++generation,CameraProbeMode.entries[nextIndex++]).also {
|
||||
Run(++generation,config.modes[nextIndex++]).also {
|
||||
active=it;closeAt=-1;CameraProbeStore.stage=CameraProbeStage.RUNNING
|
||||
}
|
||||
}
|
||||
@@ -106,6 +107,9 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
private fun startLegacy(run: Run) {
|
||||
run.worker.post {
|
||||
if(run.retired) return@post
|
||||
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 {
|
||||
@@ -134,6 +138,10 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
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
|
||||
@@ -150,6 +158,8 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
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()
|
||||
@@ -272,7 +282,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
if(!run.retired && context.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
|
||||
cancelled=true;close(run,CameraProbeFailure.PERMISSION)
|
||||
}
|
||||
if(!run.retired && now-run.result.startedMs>=8_000) finishRun(run)
|
||||
if(!run.retired && now-run.result.startedMs>=config.runLimitMs) finishRun(run)
|
||||
if(run.retired) {
|
||||
val safe=probeCloseSafe(run.mode.legacy,run.result.boundMs>=0,
|
||||
run.result.nativeState==CameraNativeState.CLOSED,run.result.surfaceCreated,
|
||||
@@ -282,7 +292,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
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) {
|
||||
if(now-closeAt>=config.closeLimitMs) {
|
||||
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)}
|
||||
@@ -341,6 +351,7 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
frameHeight=if(run.height>0) run.height else it.frameHeight,callbackBytes=run.bytes,
|
||||
previewTrace=run.sink?.trace() ?: it.previewTrace)}
|
||||
CameraProbeStore.put(run.result)
|
||||
onSnapshot(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()} operation=${run.result.nativeOperation.name.lowercase()} call_state=${run.result.nativeCallState.name.lowercase()}"
|
||||
@@ -355,6 +366,9 @@ class CameraProbeController(private val context: Context,private val owner: Life
|
||||
main.removeCallbacks(tick);watchdog.removeCallbacks(watchTick);watchThread.quitSafely()
|
||||
done()
|
||||
}
|
||||
fun endSampling() {
|
||||
active?.let { if(!it.retired && !notified.get()) finishRun(it) }
|
||||
}
|
||||
fun cancel() {
|
||||
cancelled=true
|
||||
val run=active
|
||||
|
||||
@@ -14,7 +14,17 @@ enum class CameraNativeOperation { NONE, ENUMERATE, OPEN, GET_PARAMETERS, SET_PA
|
||||
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, NATIVE_TIMEOUT, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED }
|
||||
START, CAMERA_ERROR, SURFACE, NATIVE_TIMEOUT, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED,
|
||||
WORKER_START_TIMEOUT, WORKER_DIED, PROCESS_EXIT_TIMEOUT }
|
||||
data class CameraProbeConfig(
|
||||
val modes: List<CameraProbeMode> = CameraProbeMode.entries.toList(),
|
||||
val runLimitMs: Long = 8_000, val closeLimitMs: Long = 8_000,
|
||||
) {
|
||||
init {
|
||||
require(modes.isNotEmpty() && modes.size <= 7 && modes.distinct().size == modes.size)
|
||||
require(runLimitMs in 1_000..8_000 && closeLimitMs in 500..8_000)
|
||||
}
|
||||
}
|
||||
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,
|
||||
@@ -30,7 +40,11 @@ data class CameraProbeResult(val mode: CameraProbeMode,val startedMs: Long,
|
||||
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)
|
||||
val previewTrace: CameraPreviewTrace=CameraPreviewTrace(),val failure: CameraProbeFailure=CameraProbeFailure.NONE,
|
||||
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,
|
||||
) : java.io.Serializable
|
||||
|
||||
/** One foreground suite per process at a time. A timed-out close keeps normal camera inhibited. */
|
||||
object CameraProbeStore {
|
||||
|
||||
@@ -114,7 +114,7 @@ class FaceTransmissionDiagnostics {
|
||||
/** Counters are recorded before potentially blocking GL calls, sampled by a separate watchdog. */
|
||||
data class CameraPreviewTrace(val available: Int=0,val latchStarted: Int=0,val latchCompleted: Int=0,
|
||||
val firstAvailableMs: Long=-1,val latchStartedMs: Long=-1,val latchCompletedMs: Long=-1,
|
||||
val heartbeatMs: Long=-1,val resultAcks: Int=0,val resultCode: Int=-1,val closed: Boolean=false)
|
||||
val heartbeatMs: Long=-1,val resultAcks: Int=0,val resultCode: Int=-1,val closed: Boolean=false) : java.io.Serializable
|
||||
class CameraPreviewMetrics {
|
||||
private var value=CameraPreviewTrace()
|
||||
@Synchronized fun available(now: Long): Boolean { val first=value.available==0
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# 相机诊断进程隔离 — camera-probe-0.1.2 / code3
|
||||
|
||||
本阶段修复独立诊断包首项关闭超时导致整轮停止的问题,并增加 Surface 就绪检查。角色主包仍为0.7.14/code33;其已发布 APK、角色 index、时间、provider、TTS、gateway 部署均未改动。没有素材或模型生成调用。
|
||||
|
||||
## 用户设备证据与结论边界
|
||||
|
||||
用户提供的设备时间标记:03:21:50.981 默认 Camera1 预览 opened;03:21:58.797 请求关闭;03:22:06.808 关闭 watchdog 报 `close_timeout / stop_preview / pending`。另有 ISP `viewfinder is not opened yet` 和 DMA/RRZO wait fail 信息。
|
||||
|
||||
这些证据支持原生预览流异常及 `stopPreview()` 未返回。源码原先已经先执行 `setPreviewDisplay(holder)`,再执行 `startPreview()`,所以不能由 ISP 消息直接认定漏调附加 Surface。原先 Camera1 缺少有效性/创建中/尺寸就绪校验,可能存在时序缺口;此次补上,但是否解释此 MTK 设备的全部 ISP 异常仍需真机验证。
|
||||
|
||||
首项 `camera1_default_preview` 刻意不注册图像回调,`frames=0` / `frame_observation=not_sampled` 不能作为“8秒没有任何显示帧”的独立证据。其他分析/缓冲回调和 capture/GL 锁存计数各自保留,不能混算。
|
||||
|
||||
## 实现
|
||||
|
||||
- 独立包的新检查页只负责显示、父进程 watchdog 和报告。七种配置依次运行,每项都由未导出的 `CameraProbeWorkerService` 在私有 `:camera_probe_worker` 进程内调用同一生产 `CameraProbeController`,每进程只运行一种配置。
|
||||
- 开始阶段最长4秒,采样5秒,关闭等待2秒,进程退出等待最长4秒;退出确认后留500ms间隔再启动下一项。所有时间使用 elapsedRealtime。Surface 未就绪不会调用 start;界面显示当前阶段,不假装已测试或通过。
|
||||
- 可见 Surface 由前台父进程创建,等待 surfaceChanged 后检查有效性、非 creating、正尺寸,并按目标预览尺寸准备;仅通过应用内部 Binder 传 Surface handle。Camera1 在打开前、附加前、启动前再次检查。CameraX GL 项继续使用已有 SurfaceTexture/EGL 路径,此次没有盲换整套相机 API。
|
||||
- 旧实现已在工作线程执行 Camera1 关闭,但超时后整轮停止;仅新增另一个线程不能收回仍占用的 HAL。新父进程取消 AUTO_CREATE 绑定,再结束**本应用指定私有工作进程**,等待 Binder death。只有退出确认后才继续;不重启系统相机服务、不强抢别的应用、不清数据。
|
||||
- 原生 close ACK 与进程退出是独立字段。强制结束进程后仍保留 `close_timeout` 和原生 `close_confirmed=false`,只记录 `process_exit_confirmed=true`,不把失败变成通过。后台、权限撤销、Surface 销毁或用户停止取消当前轮,不自动补跑后续;旧 epoch 回调不影响新项。
|
||||
- 若操作系统本身未确认工作进程退出,4秒后仍会终止本轮并自动发报告,剩余配置标为未运行;不会为“完成七项”重叠打开相机。应用不能保证绕过整个 vendor HAL/内核永久阻塞。
|
||||
- 报告上传保留在父进程,正常结束、取消结束或退出未确认均自动上传一次。网络失败可重发。只发送固定枚举、时间、尺寸、计数和进程状态,不复制/保存/上传图像、脸、声音、聊天或原始异常。独立包仍没有麦克风权限、MediaPipe、角色素材或模型调用。
|
||||
|
||||
新增报告字段:`process_isolated`、实际 run/close/process_exit budgets;每项的 `worker_pid`、`process_stop_required`、`process_exit_confirmed`、`surface_valid_before_attach`、`surface_valid_before_start`、`surface_creating_at_attach`、`surface_width/height`。有界读取脚本 `scripts/collect-camera-probe-metadata.py` 已支持这些字段。
|
||||
|
||||
## 交付
|
||||
|
||||
[lan-voice-camera-probe-v012-code3-debug.apk](http://192.168.31.124:8080/lan-voice-camera-probe-v012-code3-debug.apk)
|
||||
|
||||
[SHA256 校验文件](http://192.168.31.124:8080/lan-voice-camera-probe-v012-code3-debug.apk.sha256)
|
||||
|
||||
SHA256:`f37bdeecbb1ce36e46ef45f349ec500e988013edb842c82ed4ab36f8142c328d`;11,248,878 bytes。包名 `com.gorios.lanvoice.cameraprobe`,camera-probe-0.1.2/code3,arm64-v8a,min26 / target34。同 debug certificate:`b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`。
|
||||
|
||||
可覆盖旧相机检查包,不需要卸载或清数据。打开后点击一次“一键诊断并发送”,授权相机并保持页面前台即可;不需逐项点击。新包保持全屏。
|
||||
|
||||
## 验证
|
||||
|
||||
- 11 JVM/UI 回归入口通过。既有相机生产回放121断言通过;新增120断言覆盖七项顺序、5秒/2秒/4秒边界、停止挂起时必须等待退出、迟到 ACK 不改失败、取消/权限/Surface 门禁、只报告一次、metadata 序列化及实际生产 CameraProbeController 关闭挂起回放。
|
||||
- 57包装测试通过。独立 APK assembleDebug 通过,共享主包源和主包 instrumentation Kotlin 编译通过;相机模块没有已执行的设备 instrumentation 测试。
|
||||
- 实际 APK badging、同证书、arm64、仅 CAMERA/INTERNET 权限、零 assets/无 face model,以及未导出的私有进程 Service 均核验;共享生成源逐文件一致,HTTP APK/checksum bytes 验证通过。旧主包 code33 和相机 code2 的 APK hash 保持一致。
|
||||
- Binder death、进程终止后 vendor HAL 释放、预览是否可见和此设备七项实际完成尚未真机验证。回放使用 API doubles,不能声称已修好设备驱动。
|
||||
|
||||
构建、回放、交付和 source fingerprints 位于 ignored `logs/camera-isolation-012/`,不提交 APK、素材、诊断原报告或日志。
|
||||
@@ -11,9 +11,11 @@ for node in ast.parse(script.read_text()).body:
|
||||
ns={'__file__':str(script)};exec(compile(ast.Module(body=nodes,type_ignores=[]),str(script),'exec'),ns)
|
||||
real=[ROOT/'app/src/main/java/com/gorios/lanvoice/expression'/name for name in
|
||||
('ExpressionController.kt','ExpressionState.kt','ExpressionRules.kt','FaceCueRules.kt','FaceDiagnostics.kt','CameraPixelConverter.kt','CameraPreviewSurface.kt','CameraProbeState.kt','CameraProbeController.kt')]
|
||||
real.append(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/IsolatedProbeSuite.kt')
|
||||
with tempfile.TemporaryDirectory(prefix='camera-controller-check-') as folder:
|
||||
subprocess.run([ns['JAVA'],'-cp',ns['compiler'],'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
|
||||
'-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'],'-d',folder,
|
||||
*map(str,list((ROOT/'tests/camera').glob('*.kt'))+real)],check=True,cwd=ROOT)
|
||||
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)
|
||||
|
||||
@@ -16,13 +16,13 @@ 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'}
|
||||
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'}
|
||||
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'):
|
||||
for k in ('stage','entry_failure','max_tests','run_limit_ms','close_limit_ms','process_isolated','process_exit_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):
|
||||
|
||||
@@ -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='2'",
|
||||
"versionName='camera-probe-0.1.1'", "sdkVersion:'26'", "targetSdkVersion:'34'"):
|
||||
for value in ("name='com.gorios.lanvoice.cameraprobe'", "versionCode='3'",
|
||||
"versionName='camera-probe-0.1.2'", "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',
|
||||
@@ -41,6 +41,11 @@ def verify(apk):
|
||||
'unexpected permissions')
|
||||
native = re.search(r'^native-code: (.+)$', badge, re.M)
|
||||
require(native is not None and native[1].strip() == "'arm64-v8a'", 'unexpected native ABI')
|
||||
manifest = subprocess.check_output([str(TOOLS/'aapt'), 'dump', 'xmltree', str(apk), 'AndroidManifest.xml'], text=True)
|
||||
services = re.findall(r'^ E: service .*?(?=^ E:|\Z)', manifest, re.M | re.S)
|
||||
worker = next((s for s in services if '"com.gorios.lanvoice.CameraProbeWorkerService"' in s), '')
|
||||
require('android:exported(0x01010010)=(type 0x12)0x0' in worker and
|
||||
'android:process(0x01010011)=":camera_probe_worker"' in worker, 'worker not privately process-isolated in actual APK')
|
||||
cert = subprocess.check_output([str(TOOLS/'apksigner'), 'verify', '--verbose', '--print-certs', str(apk)], text=True)
|
||||
require(re.search(r'Signer #1 certificate SHA-256 digest: (\w+)', cert)[1] == CERT, 'debug certificate drift')
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
@@ -60,6 +65,9 @@ def verify(apk):
|
||||
require(b'Lcom/google/mediapipe/' not in dex, 'face model dependency included')
|
||||
for klass in ('Lcom/gorios/lanvoice/CameraDiagnosticsActivity;',
|
||||
'Lcom/gorios/lanvoice/CameraProbeLauncherActivity;',
|
||||
'Lcom/gorios/lanvoice/IsolatedCameraDiagnosticsActivity;',
|
||||
'Lcom/gorios/lanvoice/CameraProbeWorkerService;',
|
||||
'Lcom/gorios/lanvoice/IsolatedProbeSuite;',
|
||||
'Lcom/gorios/lanvoice/expression/CameraProbeController;',
|
||||
'Lcom/gorios/lanvoice/diag/DiagnosticReportUpload;'):
|
||||
require(klass.encode() in dex, 'missing production diagnostic component: '+klass)
|
||||
@@ -72,10 +80,13 @@ def verify(apk):
|
||||
sources[name] = digest(source)
|
||||
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')
|
||||
return {'package': 'com.gorios.lanvoice.cameraprobe', 'version_name': 'camera-probe-0.1.1',
|
||||
'version_code': 2, 'min_sdk': 26, 'target_sdk': 34, 'certificate_sha256': CERT,
|
||||
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,
|
||||
'abi': 'arm64-v8a', 'assets': 0, 'microphone_permission': False,
|
||||
'shared_production_sources': sources, 'camera_tests': 7, 'device': 'not_run'}
|
||||
'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'}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
@@ -88,7 +99,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-v011-code2-debug.apk'
|
||||
artifact = ROOT/'artifacts/lan-voice-camera-probe-v012-code3-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)
|
||||
@@ -106,7 +117,7 @@ def main():
|
||||
http_bytes_verified=True, paid_calls=0, model_calls=0)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k!='shared_production_sources'}, indent=2))
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('shared_production_sources','camera_application_sources')}, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import com.gorios.lanvoice.*
|
||||
import com.gorios.lanvoice.expression.*
|
||||
import android.os.CameraClock
|
||||
import android.hardware.Camera
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
|
||||
fun main() {
|
||||
var checks = 0
|
||||
fun verify(value: Boolean) { checks++; check(value) { "isolated check $checks" } }
|
||||
// A blocked native close continues only AFTER a real process-death signal.
|
||||
val suite = IsolatedProbeSuite()
|
||||
var now = 0L
|
||||
var start = suite.start(now).single() as ProbeIsolationEffect.Start
|
||||
for (index in 0 until 7) {
|
||||
val token = start.epoch
|
||||
suite.ready(token, 100 + index, now)
|
||||
verify(suite.phase == ProbeIsolationPhase.RUNNING)
|
||||
verify(suite.tick(now + 4999).isEmpty())
|
||||
verify(suite.tick(now + 5000).single() == ProbeIsolationEffect.EndSampling(token))
|
||||
val stalled = index == 0 || index == 4
|
||||
suite.snapshot(token, CameraProbeResult(start.mode, now,
|
||||
frames = if (index == 0) 0 else 3, finishedMs = now + 5000, closeStartedMs = now + 5000,
|
||||
nativeOperation = CameraNativeOperation.STOP_PREVIEW,
|
||||
nativeCallState = if (stalled) CameraNativeCallState.PENDING else CameraNativeCallState.RETURNED,
|
||||
closeConfirmed = !stalled), now + 5000).also {
|
||||
if (!stalled) verify(it.single() is ProbeIsolationEffect.Terminate)
|
||||
}
|
||||
if (stalled) {
|
||||
verify(suite.tick(now + 6999).isEmpty())
|
||||
verify(suite.tick(now + 7000).single() is ProbeIsolationEffect.Terminate)
|
||||
verify(suite.current!!.failure == CameraProbeFailure.CLOSE_TIMEOUT)
|
||||
verify(!suite.current!!.closeConfirmed && suite.current!!.processStopRequired)
|
||||
}
|
||||
verify(suite.phase == ProbeIsolationPhase.WAITING_EXIT)
|
||||
verify(suite.tick(now + 7499).isEmpty() && suite.results.size == index + 1)
|
||||
verify(suite.snapshot(token, CameraProbeResult(start.mode, now, closeConfirmed = true), now + 7500).isEmpty())
|
||||
verify(suite.current!!.closeConfirmed == !stalled) // Late native ACK cannot rewrite killed-owner facts.
|
||||
suite.exited(token, now + 7500)
|
||||
verify(suite.current!!.processExitConfirmed && suite.phase == ProbeIsolationPhase.SETTLING)
|
||||
verify(suite.tick(now + 7999).isEmpty())
|
||||
val effects = suite.tick(now + 8000)
|
||||
now += 8000
|
||||
if (index < 6) {
|
||||
start = effects.single() as ProbeIsolationEffect.Start
|
||||
verify(start.mode == CameraProbeMode.entries[index + 1])
|
||||
verify(suite.exited(token, now).isEmpty())
|
||||
} else verify(effects.single() == ProbeIsolationEffect.Report)
|
||||
}
|
||||
verify(suite.results.size == 7 && suite.results.all { it.processExitConfirmed })
|
||||
verify(suite.results.count { !it.closeConfirmed } == 2)
|
||||
verify(suite.phase == ProbeIsolationPhase.DONE && suite.tick(now + 100000).isEmpty())
|
||||
verify(suite.cancel(now).isEmpty())
|
||||
|
||||
// No death/absence confirmation: bounded BLOCKED report, never overlap owners or fake a pass.
|
||||
val blocked = IsolatedProbeSuite(); val lease = blocked.start(0).single() as ProbeIsolationEffect.Start
|
||||
verify(blocked.tick(3999).isEmpty())
|
||||
verify(blocked.tick(4000).single() is ProbeIsolationEffect.Terminate)
|
||||
verify(blocked.current!!.failure == CameraProbeFailure.WORKER_START_TIMEOUT)
|
||||
verify(blocked.tick(7999).isEmpty())
|
||||
verify(blocked.tick(8000).single() == ProbeIsolationEffect.Report)
|
||||
verify(blocked.phase == ProbeIsolationPhase.BLOCKED && blocked.results.size == 1)
|
||||
verify(!blocked.current!!.processExitConfirmed && blocked.current!!.failure == CameraProbeFailure.PROCESS_EXIT_TIMEOUT)
|
||||
verify(blocked.exited(lease.epoch, 9000).isEmpty() && blocked.tick(10000).isEmpty())
|
||||
|
||||
// Repeated background/permission/surface cancellation reports exactly once after owner exit.
|
||||
val cancel = IsolatedProbeSuite(); val c = cancel.start(0).single() as ProbeIsolationEffect.Start
|
||||
cancel.ready(c.epoch, 42, 0)
|
||||
verify(cancel.cancel(10).single() is ProbeIsolationEffect.Terminate)
|
||||
verify(cancel.cancel(11).isEmpty() && cancel.current!!.failure == CameraProbeFailure.CANCELLED)
|
||||
cancel.exited(c.epoch, 12)
|
||||
verify(cancel.tick(512).single() == ProbeIsolationEffect.Report && cancel.results.size == 1)
|
||||
verify(cancel.cancel(600).isEmpty())
|
||||
|
||||
// Actual production runner with new one-mode/5s/2s configuration, not a copied camera FSM.
|
||||
fun reset() { CameraClock.reset(); Camera.opened.clear(); Camera.failOpen=false; Camera.onOpen=null; ProcessCameraProvider.instance = ProcessCameraProvider(); CameraProbeStore.inhibitNormal=false; CameraProbeStore.stage=CameraProbeStage.IDLE; CameraProbeStore.results=emptyList(); android.os.HandlerThread.threads.clear() }
|
||||
val owner = object : androidx.lifecycle.LifecycleOwner {}
|
||||
reset(); CameraProbeStore.begin(); var done = 0
|
||||
CameraProbeController(android.content.Context(), owner, android.view.SurfaceHolder(),
|
||||
config = CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_640), 5000, 2000)) { done++ }.start()
|
||||
CameraClock.advance(4999); verify(done == 0 && Camera.opened.size == 1)
|
||||
CameraClock.advance(500); verify(done == 1 && Camera.opened.size == 1)
|
||||
verify(CameraProbeStore.results.single().failure == CameraProbeFailure.FRAME_TIMEOUT)
|
||||
verify(CameraProbeStore.results.single().closeConfirmed)
|
||||
verify(CameraProbeStore.results.single().surfaceValidBeforeAttach && CameraProbeStore.results.single().surfaceValidBeforeStart)
|
||||
|
||||
// Capture a native stopPreview pending snapshot, then feed its actual callback into the parent.
|
||||
reset(); CameraProbeStore.begin()
|
||||
val replay = IsolatedProbeSuite(); val r = replay.start(0).single() as ProbeIsolationEffect.Start
|
||||
replay.ready(r.epoch, 99, 0); var terminate: ProbeIsolationEffect.Terminate? = null
|
||||
fun consume(effects: List<ProbeIsolationEffect>) { effects.forEach { if (it is ProbeIsolationEffect.Terminate) terminate = it } }
|
||||
CameraProbeController(android.content.Context(), owner, android.view.SurfaceHolder(),
|
||||
config = CameraProbeConfig(listOf(r.mode), 5000, 2000),
|
||||
onSnapshot = { consume(replay.snapshot(r.epoch, it, CameraClock.now)) },
|
||||
done = { consume(replay.completed(r.epoch, CameraClock.now)) }).start()
|
||||
CameraClock.advance()
|
||||
Camera.opened.single().second.onStop = { CameraClock.advance(2250) }
|
||||
CameraClock.advance(5000)
|
||||
verify(terminate?.epoch == r.epoch && replay.phase == ProbeIsolationPhase.WAITING_EXIT)
|
||||
verify(replay.current!!.nativeOperation == CameraNativeOperation.STOP_PREVIEW)
|
||||
verify(replay.current!!.nativeCallState == CameraNativeCallState.PENDING)
|
||||
verify(!replay.current!!.closeConfirmed && replay.current!!.failure == CameraProbeFailure.CLOSE_TIMEOUT)
|
||||
replay.exited(r.epoch, CameraClock.now)
|
||||
verify(replay.tick(CameraClock.now + 500).single() is ProbeIsolationEffect.Start)
|
||||
verify(replay.results.first().processExitConfirmed && !replay.results.first().closeConfirmed)
|
||||
|
||||
// Invalid/uncreated surface is rejected before opening a camera.
|
||||
reset(); CameraProbeStore.begin()
|
||||
val invalid = android.view.SurfaceHolder().apply { surface.release() }
|
||||
CameraProbeController(android.content.Context(), owner, invalid,
|
||||
config = CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_DEFAULT_PREVIEW), 5000, 2000)) {}.start()
|
||||
CameraClock.advance(10000)
|
||||
verify(Camera.opened.isEmpty() && CameraProbeStore.results.single().initialFailure == CameraProbeFailure.SURFACE)
|
||||
reset(); CameraProbeStore.begin()
|
||||
CameraProbeController(android.content.Context(), owner, android.view.SurfaceHolder().apply { isCreating=true },
|
||||
config = CameraProbeConfig(listOf(CameraProbeMode.CAMERA1_DEFAULT_PREVIEW), 5000, 2000)) {}.start()
|
||||
CameraClock.advance(10000); verify(Camera.opened.isEmpty())
|
||||
|
||||
// IPC serialization is a bounded metadata graph, including the nested GL trace.
|
||||
val row = CameraProbeResult(CameraProbeMode.CAMERAX_GL_DUAL, 1, previewTrace=CameraPreviewTrace(available=2, closed=true))
|
||||
val bytes = java.io.ByteArrayOutputStream().also { java.io.ObjectOutputStream(it).use { stream -> stream.writeObject(row) } }.toByteArray()
|
||||
verify(bytes.size < 10000)
|
||||
verify(java.io.ObjectInputStream(java.io.ByteArrayInputStream(bytes)).use { it.readObject() } == row)
|
||||
println("PASS: $checks production isolated-suite deadlines/death-only continuation/late-callback/cancel/once-report + actual camera pending-stop/surface guards/metadata IPC checks; Binder, HAL and GPU device not_run")
|
||||
}
|
||||
@@ -6,6 +6,8 @@ class Surface(val texture: android.graphics.SurfaceTexture) {
|
||||
}
|
||||
|
||||
class SurfaceHolder {
|
||||
var isCreating=false
|
||||
var surfaceFrame=android.graphics.Rect(0,0,640,480)
|
||||
val surface=Surface(android.graphics.SurfaceTexture(run {
|
||||
val ids=IntArray(1);android.opengl.GLES20.glGenTextures(1,ids,0);ids[0]
|
||||
}))
|
||||
|
||||
@@ -17,6 +17,7 @@ class CameraStandaloneTests(unittest.TestCase):
|
||||
self.assertIn('putExtra("camera_probe_admitted",true)',entry)
|
||||
self.assertIn('registerForActivityResult',entry);self.assertIn('一键诊断并发送',entry)
|
||||
self.assertNotIn('VoiceSession(',entry);self.assertNotIn('AudioRecord(',entry)
|
||||
self.assertIn('IsolatedCameraDiagnosticsActivity::class.java',entry)
|
||||
def test_same_certificate_trust_and_native_bounded_diagnostics(self):
|
||||
build=(ROOT/'camera-probe/build.gradle').read_text()
|
||||
for name in ('gateway_cert.pem','network_security_config.xml','config.xml'):self.assertIn(name,build)
|
||||
@@ -24,3 +25,22 @@ class CameraStandaloneTests(unittest.TestCase):
|
||||
self.assertIn('CameraProbeStore.finish',runner)
|
||||
report=(ROOT/'app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt').read_text()
|
||||
for field in ('native_operation','native_call_state','preview_trace','camera_probe'):self.assertIn(field,report)
|
||||
def test_native_calls_are_in_a_private_disposable_process(self):
|
||||
import xml.etree.ElementTree as ET
|
||||
manifest=ET.parse(ROOT/'camera-probe/src/main/AndroidManifest.xml')
|
||||
a='{http://schemas.android.com/apk/res/android}'
|
||||
services=manifest.findall('./application/service')
|
||||
self.assertEqual(len(services),1)
|
||||
self.assertEqual(services[0].get(a+'exported'),'false')
|
||||
self.assertEqual(services[0].get(a+'process'),':camera_probe_worker')
|
||||
self.assertEqual(services[0].get(a+'name'),'com.gorios.lanvoice.CameraProbeWorkerService')
|
||||
owner=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/IsolatedCameraDiagnosticsActivity.kt').read_text()
|
||||
worker=(ROOT/'camera-probe/src/main/java/com/gorios/lanvoice/CameraProbeWorkerService.kt').read_text()
|
||||
self.assertNotIn('CameraProbeController(',owner)
|
||||
self.assertIn('binder.linkToDeath',owner);self.assertIn('unbind(current)',owner)
|
||||
self.assertIn('Process.killProcess(pid)',owner)
|
||||
self.assertIn('it.uid == android.os.Process.myUid()',owner)
|
||||
self.assertIn('surfaceChanged',owner);self.assertIn('viewHolder.surface.isValid',owner)
|
||||
self.assertIn('CameraProbeController(',worker);self.assertIn('listOf(mode)',worker)
|
||||
self.assertIn('message.sendingUid != android.os.Process.myUid()',worker)
|
||||
self.assertNotIn('DiagnosticReportUpload',worker)
|
||||
|
||||
Reference in New Issue
Block a user