Add one-button bounded front-camera diagnostics and automatic report
This commit is contained in:
+5
-1
@@ -21,6 +21,7 @@ def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').or
|
||||
def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true'
|
||||
def cameraCompatibilityFix = providers.gradleProperty('cameraCompatibilityFix').orNull == 'true'
|
||||
def cameraDirectYuv = providers.gradleProperty('cameraDirectYuv').orNull == 'true'
|
||||
def cameraProbeDiagnostic = providers.gradleProperty('cameraProbeDiagnostic').orNull == 'true'
|
||||
def cameraPreviewStream = providers.gradleProperty('cameraPreviewStream').orNull == 'true'
|
||||
def faceDiagnosticsFix = providers.gradleProperty('faceDiagnosticsFix').orNull == 'true'
|
||||
def presenceCandidate = providers.gradleProperty('presenceCandidate').orNull == 'true'
|
||||
@@ -45,6 +46,7 @@ if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !a
|
||||
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
|
||||
if (cameraCompatibilityFix && (!faceDiagnosticsFix || actionVersionCode < 25)) throw new GradleException('Camera compatibility requires face diagnostics and fresh code >=25')
|
||||
if (cameraDirectYuv && (!cameraCompatibilityFix || actionVersionCode < 26)) throw new GradleException('Direct YUV validation requires camera diagnostics and fresh code >=26')
|
||||
if (cameraProbeDiagnostic && (!cameraPreviewStream || actionVersionCode < 28)) throw new GradleException('Camera probe diagnostics requires fresh code >=28')
|
||||
if (cameraPreviewStream && (!cameraDirectYuv || actionVersionCode < 27)) throw new GradleException('Preview stream validation requires camera diagnostics and fresh code >=27')
|
||||
if (faceDiagnosticsFix && (!presenceCandidate || actionVersionCode < 24)) throw new GradleException('Face diagnostics fix requires presence and fresh code >=24')
|
||||
if (presenceCandidate && (!avatarStartupFix || actionVersionCode < 23)) throw new GradleException('Presence candidate requires startup fix and fresh code >=23')
|
||||
@@ -101,7 +103,7 @@ android {
|
||||
targetSdk 34
|
||||
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
||||
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
|
||||
versionName = cameraPreviewStream ? '0.7.9' : cameraDirectYuv ? '0.7.8' : cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
|
||||
versionName = cameraProbeDiagnostic ? '0.7.10' : cameraPreviewStream ? '0.7.9' : cameraDirectYuv ? '0.7.8' : cameraCompatibilityFix ? '0.7.7' : faceDiagnosticsFix ? '0.7.6' : presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
@@ -116,6 +118,7 @@ android {
|
||||
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
|
||||
else if (avatarNatural) versionNameSuffix '-natural-dev'
|
||||
else if (avatarEngineering) versionNameSuffix '-dev'
|
||||
buildConfigField 'boolean', 'CAMERA_PROBE_DIAGNOSTIC', cameraProbeDiagnostic ? 'true' : 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', avatarStartupFix ? 'true' : 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false'
|
||||
@@ -124,6 +127,7 @@ android {
|
||||
buildConfigField 'String', 'EMOTION_MANIFEST_SHA', '"' + emotionManifestSha + '"'
|
||||
}
|
||||
release {
|
||||
buildConfigField 'boolean', 'CAMERA_PROBE_DIAGNOSTIC', 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false'
|
||||
buildConfigField 'boolean', 'AVATAR_NATURAL', 'false'
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
android:supportsRtl="true"
|
||||
android:usesCleartextTraffic="false"
|
||||
android:networkSecurityConfig="@xml/network_security_config">
|
||||
<activity android:name=".CameraDiagnosticsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.gorios.lanvoice
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
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.expression.*
|
||||
import com.gorios.lanvoice.diag.DiagnosticReportInfo
|
||||
import com.gorios.lanvoice.diag.DiagnosticReportUpload
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** Local front-camera test screen. No VoiceSession, model, microphone or face upload. */
|
||||
class CameraDiagnosticsActivity: ComponentActivity() {
|
||||
private var readyHolder: SurfaceHolder?=null
|
||||
private var runner: CameraProbeController?=null
|
||||
@Volatile private var foreground=false
|
||||
private var sending by mutableStateOf(false)
|
||||
private var receipt by mutableStateOf<String?>(null)
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// Internal entry requires the previous production camera's CLOSED/released acknowledgement.
|
||||
if(!BuildConfig.DEBUG || !intent.getBooleanExtra("camera_probe_admitted",false) ||
|
||||
CameraProbeStore.stage!=CameraProbeStage.RUNNING || runner!=null) {finish();return}
|
||||
setContent {
|
||||
var stage by remember {mutableStateOf(CameraProbeStore.stage)}
|
||||
var rows by remember {mutableStateOf(CameraProbeStore.results)}
|
||||
LaunchedEffect(Unit) {while(true) {stage=CameraProbeStore.stage;rows=CameraProbeStore.results;delay(500)}}
|
||||
MaterialTheme {Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()
|
||||
.verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
Text("前置相机一键诊断",style=MaterialTheme.typography.titleLarge)
|
||||
Text("自动检查六条路径,结束后发送状态报告。约一分钟;此页不收音、不运行模型、不保存或上传画面。")
|
||||
AndroidView(factory={context->SurfaceView(context).apply {
|
||||
holder.addCallback(object: SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
readyHolder=holder;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))
|
||||
Text("${stage.name.lowercase()} · 已开始 ${rows.size}/6")
|
||||
rows.forEach {r->
|
||||
Text("${r.mode.name.lowercase()} · 回调 ${r.frames} / capture ${r.captureCompleted} · ${r.frameWidth}×${r.frameHeight} · ${r.failure.name.lowercase()} · 关闭${if(r.closeConfirmed) "已确认" else "待确认"}")
|
||||
}
|
||||
if(stage==CameraProbeStage.BLOCKED) Text("关闭未确认,后续测试已停止。报告会标明卡点;不会强抢相机。")
|
||||
Text(if(sending) "正在发送报告…" else receipt ?: "诊断进行中…")
|
||||
if(receipt=="发送失败") TextButton(onClick=::sendReport) {Text("重发报告")}
|
||||
TextButton(onClick={runner?.cancel()}) {Text("停止诊断并发送")}
|
||||
TextButton(onClick={runner?.cancel();finish()}) {Text("返回")}
|
||||
Text("CameraX Preview 单路的 capture 计数表示原生捕获完成,不能证明显示首帧;实际分析回调与 EGL 锁存分开记录。")
|
||||
}}
|
||||
}
|
||||
}
|
||||
private fun sendReport() {
|
||||
// Can be called by the independent close watchdog if main/native close is stalled.
|
||||
val info=DiagnosticReportInfo(appVersion=BuildConfig.VERSION_NAME,versionCode=BuildConfig.VERSION_CODE,
|
||||
device="${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}",androidApi=android.os.Build.VERSION.SDK_INT,
|
||||
connection="LOCAL_CAMERA_PROBE",voiceActive=false,phase="IDLE",aec="NOT_RUNNING",
|
||||
avatarMode="camera_probe",avatarPin=BuildConfig.EMOTION_MANIFEST_SHA,
|
||||
cameraGranted=checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED,
|
||||
cameraProbeStage=CameraProbeStore.stage,cameraProbeEntryFailure=CameraProbeStore.entryFailure,
|
||||
cameraProbes=CameraProbeStore.results)
|
||||
runOnUiThread {sending=true;receipt=null}
|
||||
DiagnosticReportUpload.send(info) {ok->runOnUiThread {sending=false;receipt=if(ok) "已自动发送" else "发送失败"}}
|
||||
}
|
||||
private fun startIfReady() {
|
||||
val holder=readyHolder ?: return
|
||||
if(runner==null && foreground) {
|
||||
runner=CameraProbeController(this,this,holder,::sendReport);runner!!.start()
|
||||
}
|
||||
}
|
||||
override fun onResume() {super.onResume();foreground=true;startIfReady()}
|
||||
override fun onPause() {foreground=false;runner?.cancel();super.onPause()}
|
||||
override fun onDestroy() {runner?.cancel();super.onDestroy()}
|
||||
}
|
||||
@@ -68,6 +68,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var inForeground = false
|
||||
private var offlineAvatarPreview = false
|
||||
private var openingOffline = false
|
||||
private var openingCameraProbe=false
|
||||
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
permissionResult(EntryPermission.CAMERA, granted)
|
||||
}
|
||||
@@ -92,7 +93,7 @@ class MainActivity : ComponentActivity() {
|
||||
if (!isDestroyed) main.post(pump)
|
||||
}
|
||||
private fun advanceEntry() {
|
||||
if (!::entry.isInitialized || isDestroyed) return
|
||||
if (!::entry.isInitialized || isDestroyed || openingCameraProbe || com.gorios.lanvoice.expression.CameraProbeStore.stage in setOf(com.gorios.lanvoice.expression.CameraProbeStage.RUNNING,com.gorios.lanvoice.expression.CameraProbeStage.CLOSING)) return
|
||||
if(BuildConfig.AVATAR_STARTUP_FIX && (!firstDrawReady || !offlineAvatarPreview && !::session.isInitialized)) return
|
||||
// First consent is after the foreground Compose host has a stable layout,
|
||||
// independent of health/WS/HELLO. No request originates from recomposition.
|
||||
@@ -120,7 +121,7 @@ class MainActivity : ComponentActivity() {
|
||||
for (action in actions) when (action) {
|
||||
EntryEffect.Connect -> if(!offlineAvatarPreview && inForeground) session.dial()
|
||||
EntryEffect.StartVoice -> if(!offlineAvatarPreview && inForeground && micGranted && state.connection==ConnectionStatus.CONNECTED) session.startVoice(microphoneMuted = preferences().getBoolean("microphoneMuted", false))
|
||||
EntryEffect.StartCamera -> if (!offlineAvatarPreview && inForeground && cameraGranted) expressions.start()
|
||||
EntryEffect.StartCamera -> if (!offlineAvatarPreview && inForeground && cameraGranted && !BuildConfig.CAMERA_PROBE_DIAGNOSTIC && !com.gorios.lanvoice.expression.CameraProbeStore.inhibitNormal) expressions.start()
|
||||
is EntryEffect.RequestPermission -> {
|
||||
val mic = action.permission == EntryPermission.MICROPHONE
|
||||
preferences().edit().putBoolean(if (mic) "micAsked" else "camAsked", true).apply()
|
||||
@@ -195,6 +196,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
},
|
||||
onCameraProbe=::openCameraProbe,
|
||||
presenceEnabled = presenceEnabled,onPresenceEnabled = { enabled ->
|
||||
presenceEnabled=enabled;preferences().edit().putBoolean("presenceEnabled",enabled).apply()
|
||||
if(::session.isInitialized) session.setPresence(enabled,expressionState.status==ExpressionStatus.ACTIVE)
|
||||
@@ -298,6 +300,9 @@ class MainActivity : ComponentActivity() {
|
||||
avatarAdmission = avatarPack?.emotionAdmission ?: if(BuildConfig.AVATAR_STARTUP_FIX) "startup_$startupStage" else "static_identity_rejected",
|
||||
avatarRuntime = avatarMedia.diagnosticState,
|
||||
actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else if(::session.isInitialized) session.runtimeProtocolState else "startup_no_session",
|
||||
cameraProbeStage=com.gorios.lanvoice.expression.CameraProbeStore.stage,
|
||||
cameraProbeEntryFailure=com.gorios.lanvoice.expression.CameraProbeStore.entryFailure,
|
||||
cameraProbes=com.gorios.lanvoice.expression.CameraProbeStore.results,
|
||||
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
|
||||
cameraStatus = expressionState.status,
|
||||
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
|
||||
@@ -325,7 +330,42 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun openCameraProbe() {
|
||||
if(openingCameraProbe || !inForeground || !::session.isInitialized ||
|
||||
!granted(Manifest.permission.CAMERA)) return
|
||||
if(!com.gorios.lanvoice.expression.CameraProbeStore.begin()) {
|
||||
reportResult="前次相机关闭未确认,不能启动新的相机检查";sendDiagnosticReport();return
|
||||
}
|
||||
openingCameraProbe=true;entry.cameraOff();closeCamera()
|
||||
// Actual capture-stop confirmation, rather than merely muting a flag.
|
||||
session.suspendForLocalPreview { safe ->
|
||||
if(!safe || !inForeground || isDestroyed) {
|
||||
openingCameraProbe=false
|
||||
com.gorios.lanvoice.expression.CameraProbeStore.entryFailure=com.gorios.lanvoice.expression.CameraProbeFailure.CANCELLED
|
||||
com.gorios.lanvoice.expression.CameraProbeStore.finish(false);sendDiagnosticReport()
|
||||
} else {
|
||||
val deadline=android.os.SystemClock.elapsedRealtime()+8_000
|
||||
val check=object: Runnable {override fun run() {
|
||||
if(!inForeground || isDestroyed) {
|
||||
openingCameraProbe=false;com.gorios.lanvoice.expression.CameraProbeStore.finish(false);return
|
||||
}
|
||||
if(expressions.closeConfirmed()) {
|
||||
openingCameraProbe=false
|
||||
startActivity(android.content.Intent(this@MainActivity,CameraDiagnosticsActivity::class.java)
|
||||
.putExtra("camera_probe_admitted",true))
|
||||
} else if(android.os.SystemClock.elapsedRealtime()>=deadline) {
|
||||
openingCameraProbe=false
|
||||
com.gorios.lanvoice.expression.CameraProbeStore.entryFailure=com.gorios.lanvoice.expression.CameraProbeFailure.CLOSE_TIMEOUT
|
||||
com.gorios.lanvoice.expression.CameraProbeStore.finish(true);sendDiagnosticReport()
|
||||
} else main.postDelayed(this,100)
|
||||
}}
|
||||
main.post(check)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun toggleExpressions() {
|
||||
if(BuildConfig.CAMERA_PROBE_DIAGNOSTIC) {openCameraProbe();return}
|
||||
if (!inForeground || entry.permissionPending != null) return
|
||||
val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE)
|
||||
if (running) { preferences().edit().putBoolean("cameraWanted", false).apply(); entry.cameraOff(); closeCamera() }
|
||||
|
||||
@@ -96,6 +96,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
onOfflinePreview: ()->Unit=NoUiAction,
|
||||
startupBase: ContinuousAvatarPack?=null,startupStage: String="ready",
|
||||
onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,
|
||||
onCameraProbe: ()->Unit=NoUiAction,
|
||||
presenceEnabled: Boolean=false,onPresenceEnabled: (Boolean)->Unit={},
|
||||
cameraDiagnostics: ()->com.gorios.lanvoice.expression.CameraAnalysisSnapshot={com.gorios.lanvoice.expression.CameraAnalysisSnapshot()},
|
||||
presenceDiagnostics: ()->com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot={com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot()},
|
||||
@@ -154,6 +155,10 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
||||
}
|
||||
ExpressionControls(expression,onCamera,shareFace,onShare,controlsEnabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED)
|
||||
com.gorios.lanvoice.expression.FaceDebugPanel(cameraDiagnostics,presenceDiagnostics)
|
||||
if(BuildConfig.CAMERA_PROBE_DIAGNOSTIC) {
|
||||
Text("相机诊断候选:常规相机暂缓启动,避免与检查抢占;角色与语音沿用现配置。",fontSize=12.sp)
|
||||
Button(onClick=onCameraProbe,enabled=cameraGranted && permissionPending==null) {Text("相机一键诊断并发送")}
|
||||
}
|
||||
HorizontalDivider(Modifier.padding(vertical=12.dp))
|
||||
Text("角色:${state.roleLabel}",fontSize=13.sp)
|
||||
Text("请求表达:"+if(state.replyEmotion.turnId==null) "尚未收到" else "${state.replyEmotion.label} (${state.replyEmotion.emotion.wire}/${state.replyEmotion.intensity})",fontSize=12.sp)
|
||||
|
||||
@@ -22,6 +22,8 @@ import java.net.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
import com.gorios.lanvoice.expression.*
|
||||
|
||||
data class DiagnosticReportInfo(
|
||||
val appVersion: String,
|
||||
val device: String,
|
||||
@@ -43,6 +45,9 @@ data class DiagnosticReportInfo(
|
||||
val rolePlaying: Boolean = false,
|
||||
val role: ReplyEmotion? = null,
|
||||
val previousRole: ReplyEmotion? = null,
|
||||
val cameraProbeStage: CameraProbeStage=CameraProbeStage.IDLE,
|
||||
val cameraProbeEntryFailure: CameraProbeFailure=CameraProbeFailure.NONE,
|
||||
val cameraProbes: List<CameraProbeResult> = emptyList(),
|
||||
val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(),
|
||||
val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(),
|
||||
val presence: PresenceDiagnosticsSnapshot = PresenceDiagnosticsSnapshot(),
|
||||
@@ -75,6 +80,31 @@ object DiagnosticReportUpload {
|
||||
.put("parse_branch", it.parseBranch.wire).put("finish_reason", it.finishReason.wire)
|
||||
} ?: JSONObject.NULL
|
||||
|
||||
private fun previewTrace(t: CameraPreviewTrace)=JSONObject()
|
||||
.put("available",t.available).put("latch_started",t.latchStarted).put("latch_completed",t.latchCompleted)
|
||||
.put("first_available_ms",t.firstAvailableMs).put("latch_started_ms",t.latchStartedMs)
|
||||
.put("latch_completed_ms",t.latchCompletedMs).put("worker_heartbeat_ms",t.heartbeatMs)
|
||||
.put("result_acks",t.resultAcks).put("result_code",t.resultCode).put("consumer_closed",t.closed)
|
||||
private fun probeReport(info: DiagnosticReportInfo): JSONObject {
|
||||
val rows=JSONArray()
|
||||
info.cameraProbes.take(6).forEach {r->rows.put(JSONObject()
|
||||
.put("mode",r.mode.name.lowercase()).put("failure",r.failure.name.lowercase())
|
||||
.put("started_ms",r.startedMs).put("finished_ms",r.finishedMs).put("bound_ms",r.boundMs)
|
||||
.put("open_ms",r.openMs).put("surface_provided_ms",r.surfaceProvidedMs)
|
||||
.put("provided_surfaces",r.providedSurfaces).put("acknowledged_surfaces",r.acknowledgedSurfaces)
|
||||
.put("surface_ack_ms",r.surfaceAckMs).put("surface_result_code",r.surfaceResult)
|
||||
.put("surface_created",r.surfaceCreated).put("surface_released",r.surfaceReleased)
|
||||
.put("first_frame_ms",r.firstFrameMs).put("frames",r.frames).put("analysis_returned",r.analysisReturned)
|
||||
.put("capture_completed",r.captureCompleted).put("capture_failed",r.captureFailed)
|
||||
.put("width",r.frameWidth).put("height",r.frameHeight).put("callback_bytes",r.callbackBytes)
|
||||
.put("native_state",r.nativeState.name.lowercase()).put("session_failure",r.sessionFailure.name.lowercase())
|
||||
.put("close_started_ms",r.closeStartedMs).put("close_returned_ms",r.closeReturnedMs)
|
||||
.put("closed_ms",r.closedMs).put("close_confirmed",r.closeConfirmed).put("preview_trace",previewTrace(r.previewTrace)))}
|
||||
return JSONObject().put("stage",info.cameraProbeStage.name.lowercase())
|
||||
.put("entry_failure",info.cameraProbeEntryFailure.name.lowercase()).put("max_tests",6)
|
||||
.put("run_limit_ms",8000).put("close_limit_ms",8000).put("results",rows)
|
||||
}
|
||||
|
||||
/** Result arrives on an OkHttp worker (or immediately if setup fails). */
|
||||
fun send(info: DiagnosticReportInfo, onResult: (Boolean) -> Unit) {
|
||||
if (!sending.compareAndSet(false, true)) {
|
||||
@@ -108,7 +138,8 @@ object DiagnosticReportUpload {
|
||||
.put("role_playing", info.rolePlaying)
|
||||
.put("role_active", roleMetadata(info.role))
|
||||
.put("role_previous", roleMetadata(info.previousRole))
|
||||
.put("camera_analysis", JSONObject().put("received", info.cameraAnalysis.received)
|
||||
.put("camera_probe",probeReport(info))
|
||||
.put("camera_analysis", JSONObject().put("preview_trace",previewTrace(info.cameraAnalysis.previewTrace)).put("received", info.cameraAnalysis.received)
|
||||
.put("processed", info.cameraAnalysis.processed).put("failures", info.cameraAnalysis.failures)
|
||||
.put("faces", info.cameraAnalysis.faceCount).put("cue", info.cameraAnalysis.cue.wire)
|
||||
.put("reason", info.cameraAnalysis.reason.name.lowercase()).put("failure", info.cameraAnalysis.failure.name.lowercase())
|
||||
|
||||
@@ -22,7 +22,17 @@ class CameraPreviewSurface(
|
||||
) : Preview.SurfaceProvider, AutoCloseable {
|
||||
private val thread=HandlerThread("lan-voice-camera-preview").apply { start() }
|
||||
private val worker=Handler(thread.looper)
|
||||
private val executor=Executor { task -> worker.post(task) }
|
||||
// Frame notification and producer release acknowledgement cannot sit behind updateTexImage.
|
||||
private val signalsThread=HandlerThread("lan-voice-camera-signals").apply { start() }
|
||||
private val signals=Handler(signalsThread.looper)
|
||||
private val executor=Executor { task -> signals.post(task) }
|
||||
private val metrics=CameraPreviewMetrics()
|
||||
fun trace()=metrics.snapshot()
|
||||
private val heartbeat=object: Runnable { override fun run() {
|
||||
metrics.heartbeat(android.os.SystemClock.elapsedRealtime())
|
||||
if(!metrics.snapshot().closed) worker.postDelayed(this,500)
|
||||
} }
|
||||
init {worker.post(heartbeat)}
|
||||
private val accepting=AtomicBoolean(true)
|
||||
private var display=EGL14.EGL_NO_DISPLAY
|
||||
private var context=EGL14.EGL_NO_CONTEXT
|
||||
@@ -33,7 +43,9 @@ class CameraPreviewSurface(
|
||||
|
||||
private class Lease(val textureId: Int,val texture: SurfaceTexture,val surface: Surface,
|
||||
val width: Int,val height: Int) {
|
||||
var released=false
|
||||
@Volatile var released=false
|
||||
val pending=AtomicBoolean()
|
||||
val acknowledged=AtomicBoolean()
|
||||
var first=false
|
||||
}
|
||||
|
||||
@@ -68,18 +80,32 @@ class CameraPreviewSurface(
|
||||
lease=provided;surfaces+=provided
|
||||
texture.setOnFrameAvailableListener({
|
||||
if(!provided.released) {
|
||||
try {
|
||||
// Latch/release buffers even after stop until CameraX releases its producer.
|
||||
// No draw/readback, camera View, Bitmap, timestamp, face geometry or upload.
|
||||
provided.texture.updateTexImage()
|
||||
if(!provided.first) {
|
||||
provided.first=true
|
||||
event(CameraPreviewEvent.FIRST_FRAME,provided.width,provided.height)
|
||||
}
|
||||
} catch(_: Exception) { fail() }
|
||||
if(metrics.available(android.os.SystemClock.elapsedRealtime()))
|
||||
event(CameraPreviewEvent.FRAME_AVAILABLE,provided.width,provided.height)
|
||||
// One pending latch; coalesce callbacks while the GL worker is stalled.
|
||||
if(provided.pending.compareAndSet(false,true)) worker.post {
|
||||
try {
|
||||
if(!provided.released) {
|
||||
if(metrics.latchStart(android.os.SystemClock.elapsedRealtime()))
|
||||
event(CameraPreviewEvent.LATCH_STARTED,provided.width,provided.height)
|
||||
provided.texture.updateTexImage()
|
||||
metrics.latchEnd(android.os.SystemClock.elapsedRealtime())
|
||||
if(!provided.first) {
|
||||
provided.first=true
|
||||
event(CameraPreviewEvent.FIRST_FRAME,provided.width,provided.height)
|
||||
}
|
||||
}
|
||||
} catch(_: Exception) { fail() }
|
||||
finally {provided.pending.set(false)}
|
||||
}
|
||||
}
|
||||
},worker)
|
||||
request.provideSurface(surface,executor) { release(provided) }
|
||||
},signals)
|
||||
request.provideSurface(surface,executor) { result ->
|
||||
if(!provided.acknowledged.compareAndSet(false,true)) return@provideSurface
|
||||
metrics.ack(result.resultCode)
|
||||
event(CameraPreviewEvent.RESULT_ACK,provided.width,provided.height)
|
||||
worker.post {release(provided)}
|
||||
}
|
||||
event(CameraPreviewEvent.PROVIDED,size.width,size.height)
|
||||
} catch(_: Exception) {
|
||||
request.willNotProvideSurface()
|
||||
@@ -138,6 +164,9 @@ class CameraPreviewSurface(
|
||||
EGL14.eglReleaseThread()
|
||||
}
|
||||
context=EGL14.EGL_NO_CONTEXT;pbuffer=EGL14.EGL_NO_SURFACE;display=EGL14.EGL_NO_DISPLAY
|
||||
metrics.closed()
|
||||
worker.removeCallbacks(heartbeat)
|
||||
signalsThread.quitSafely()
|
||||
thread.quitSafely()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.ImageFormat
|
||||
import android.hardware.Camera
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Size
|
||||
import android.view.SurfaceHolder
|
||||
import androidx.camera.core.*
|
||||
import androidx.camera.core.resolutionselector.ResolutionSelector
|
||||
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.lifecycle.LiveData
|
||||
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** Finite, foreground-only diagnostic runner. No model, microphone, network inference or image copy.
|
||||
* Camera1 uses the visible SurfaceHolder rather than the suspect EGL/Camera2 path.
|
||||
* Native camera calls may block; the main watchdog still reports that branch and NEVER opens another API.
|
||||
*/
|
||||
@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 main=Handler(Looper.getMainLooper())
|
||||
private var generation=0L
|
||||
@Volatile private var active: Run?=null
|
||||
private var cancelled=false
|
||||
private val notified=java.util.concurrent.atomic.AtomicBoolean()
|
||||
private var nextIndex=0
|
||||
private val watchThread=HandlerThread("lan-voice-camera-watchdog").apply {start()}
|
||||
private val watchdog=Handler(watchThread.looper)
|
||||
private val watchTick=object: Runnable { override fun run() {
|
||||
if(notified.get()) return
|
||||
val run=active
|
||||
if(run!=null && run.retired && closeAt>=0 && SystemClock.elapsedRealtime()-closeAt>=8_000) {
|
||||
// Still works if CameraX unbind or the camera worker is blocked.
|
||||
run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT)
|
||||
publish(run);event(run,"close_watchdog_blocked");finish(true)
|
||||
main.post {run.observer?.let {run.states?.removeObserver(it)}}
|
||||
} else watchdog.postDelayed(this,500)
|
||||
} }
|
||||
@Volatile private var closeAt=-1L
|
||||
private class Run(val token: Long,val mode: CameraProbeMode) {
|
||||
val workerThread=HandlerThread("lan-voice-camera-probe").apply {start()}
|
||||
val worker=Handler(workerThread.looper)
|
||||
val provided=AtomicInteger();val acks=AtomicInteger()
|
||||
val captures=AtomicInteger();val captureFailures=AtomicInteger()
|
||||
val frames=AtomicInteger();val returned=AtomicInteger();val first=AtomicLong(-1)
|
||||
@Volatile var width=0;@Volatile var height=0;@Volatile var bytes=0
|
||||
@Volatile var retired=false
|
||||
@Volatile var legacy: Camera?=null
|
||||
var provider: ProcessCameraProvider?=null
|
||||
var analysis: ImageAnalysis?=null;var preview: Preview?=null
|
||||
var sink: CameraPreviewSurface?=null
|
||||
var states: LiveData<CameraState>?=null;var observer: Observer<CameraState>?=null
|
||||
@Volatile var result=CameraProbeResult(mode,SystemClock.elapsedRealtime())
|
||||
}
|
||||
fun start() {
|
||||
if(active!=null || notified.get() || CameraProbeStore.stage!=CameraProbeStage.RUNNING) return
|
||||
if(context.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
|
||||
CameraProbeStore.entryFailure=CameraProbeFailure.PERMISSION;finish(false);return
|
||||
}
|
||||
watchdog.post(watchTick)
|
||||
next()
|
||||
}
|
||||
private fun next() {
|
||||
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}
|
||||
val run=Run(++generation,CameraProbeMode.entries[nextIndex++]);active=run
|
||||
closeAt=-1;CameraProbeStore.stage=CameraProbeStage.RUNNING;publish(run);event(run,"start")
|
||||
main.post(tick)
|
||||
if(run.mode.legacy) startLegacy(run) else startCameraX(run)
|
||||
}
|
||||
private fun valid(run: Run)=active===run && !run.retired && !cancelled && run.token==generation
|
||||
private fun error(run: Run,reason: CameraProbeFailure) {
|
||||
main.post { if(valid(run)) {run.result=run.result.copy(failure=reason);close(run)} }
|
||||
}
|
||||
private fun frame(run: Run,width: Int,height: Int,bytes: Int=0) {
|
||||
if(run.retired) return
|
||||
val now=SystemClock.elapsedRealtime();run.first.compareAndSet(-1,now)
|
||||
run.width=width;run.height=height;run.bytes=bytes
|
||||
run.frames.updateAndGet { (it+1).coerceAtMost(1_000_000) }
|
||||
}
|
||||
private fun startLegacy(run: Run) {
|
||||
run.worker.post {
|
||||
if(run.retired) return@post
|
||||
var camera: Camera?=null
|
||||
var failure=CameraProbeFailure.OPEN
|
||||
try {
|
||||
val info=Camera.CameraInfo()
|
||||
val id=(0 until Camera.getNumberOfCameras()).firstOrNull {
|
||||
Camera.getCameraInfo(it,info);info.facing==Camera.CameraInfo.CAMERA_FACING_FRONT
|
||||
}
|
||||
if(id==null) {error(run,CameraProbeFailure.NO_FRONT);return@post}
|
||||
camera=Camera.open(id);run.legacy=camera
|
||||
if(run.retired) return@post
|
||||
failure=CameraProbeFailure.UNSUPPORTED_SIZE
|
||||
val params=camera.parameters
|
||||
check(params.supportedPreviewSizes.any {it.width==run.mode.width && it.height==run.mode.height})
|
||||
check(ImageFormat.NV21 in params.supportedPreviewFormats)
|
||||
params.setPreviewSize(run.mode.width,run.mode.height);params.previewFormat=ImageFormat.NV21
|
||||
failure=CameraProbeFailure.START
|
||||
camera.parameters=params
|
||||
val actual=camera.parameters.previewSize
|
||||
run.width=actual.width;run.height=actual.height
|
||||
val expected=actual.width*actual.height*3/2
|
||||
camera.setErrorCallback {_,_->error(run,CameraProbeFailure.CAMERA_ERROR)}
|
||||
camera.setPreviewDisplay(holder)
|
||||
camera.setPreviewCallbackWithBuffer {data,c ->
|
||||
if(!run.retired) {
|
||||
if(data!=null && data.size==expected) frame(run,actual.width,actual.height,data.size)
|
||||
else error(run,CameraProbeFailure.CAMERA_ERROR)
|
||||
}
|
||||
if(!run.retired && data!=null) try {c.addCallbackBuffer(data)}
|
||||
catch(_: Exception) {error(run,CameraProbeFailure.CAMERA_ERROR)}
|
||||
}
|
||||
repeat(3) {camera.addCallbackBuffer(ByteArray(expected))}
|
||||
if(run.retired) return@post
|
||||
camera.startPreview()
|
||||
main.post {if(valid(run)) {
|
||||
val now=SystemClock.elapsedRealtime()
|
||||
run.result=run.result.copy(boundMs=now,openMs=now,surfaceProvidedMs=now,
|
||||
nativeState=CameraNativeState.OPEN,surfaceCreated=true)
|
||||
event(run,"opened");publish(run)
|
||||
}}
|
||||
} catch(_: Exception) {error(run,failure)}
|
||||
|
||||
}
|
||||
}
|
||||
private fun releaseLegacy(run: Run,camera: Camera?) {
|
||||
try {
|
||||
camera?.setPreviewCallbackWithBuffer(null);camera?.setErrorCallback(null)
|
||||
camera?.stopPreview();camera?.release();run.legacy=null
|
||||
main.post {
|
||||
val now=SystemClock.elapsedRealtime()
|
||||
run.result=run.result.copy(closeReturnedMs=now,nativeState=CameraNativeState.CLOSED,
|
||||
surfaceAckMs=now,surfaceReleased=true)
|
||||
publish(run);event(run,"release_returned")
|
||||
if(notified.get()) run.workerThread.quitSafely()
|
||||
}
|
||||
} catch(_: Exception) {main.post {run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run)}}
|
||||
}
|
||||
private fun startCameraX(run: Run) {
|
||||
try {
|
||||
val future=ProcessCameraProvider.getInstance(context)
|
||||
future.addListener({
|
||||
if(!valid(run)) return@addListener
|
||||
try {
|
||||
val provider=future.get();run.provider=provider
|
||||
if(!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {error(run,CameraProbeFailure.NO_FRONT);return@addListener}
|
||||
val resolution=ResolutionSelector.Builder().setResolutionStrategy(
|
||||
ResolutionStrategy(Size(run.mode.width,run.mode.height),ResolutionStrategy.FALLBACK_RULE_NONE)).build()
|
||||
val cases=mutableListOf<UseCase>()
|
||||
if(run.mode.analysis) {
|
||||
val analysis=ImageAnalysis.Builder().setResolutionSelector(resolution)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888).build()
|
||||
run.analysis=analysis;cases+=analysis
|
||||
analysis.setAnalyzer({task->run.worker.post(task)}) {image ->
|
||||
try {if(!run.retired) frame(run,image.width,image.height)}
|
||||
finally {image.close();run.returned.updateAndGet {(it+1).coerceAtMost(1_000_000)}}
|
||||
}
|
||||
}
|
||||
if(run.mode!=CameraProbeMode.CAMERAX_ANALYSIS) {
|
||||
val previewBuilder=Preview.Builder().setResolutionSelector(resolution)
|
||||
androidx.camera.camera2.interop.Camera2Interop.Extender(previewBuilder)
|
||||
.setSessionCaptureCallback(object: android.hardware.camera2.CameraCaptureSession.CaptureCallback() {
|
||||
override fun onCaptureCompleted(session: android.hardware.camera2.CameraCaptureSession,
|
||||
request: android.hardware.camera2.CaptureRequest,result: android.hardware.camera2.TotalCaptureResult) {
|
||||
if(!run.retired) run.captures.updateAndGet {(it+1).coerceAtMost(1_000_000)}
|
||||
}
|
||||
override fun onCaptureFailed(session: android.hardware.camera2.CameraCaptureSession,
|
||||
request: android.hardware.camera2.CaptureRequest,failure: android.hardware.camera2.CaptureFailure) {
|
||||
if(!run.retired) run.captureFailures.updateAndGet {(it+1).coerceAtMost(1_000_000)}
|
||||
}
|
||||
})
|
||||
val preview=previewBuilder.build()
|
||||
run.preview=preview;cases.add(0,preview)
|
||||
if(run.mode==CameraProbeMode.CAMERAX_GL_DUAL) {
|
||||
val sink=CameraPreviewSurface({e,w,h->main.post {
|
||||
if(active!==run) return@post
|
||||
if(e==CameraPreviewEvent.PROVIDED) {run.provided.incrementAndGet();run.result=run.result.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime())}
|
||||
if(e==CameraPreviewEvent.RESULT_ACK) {run.acks.incrementAndGet();run.result=run.result.copy(surfaceAckMs=SystemClock.elapsedRealtime(),surfaceResult=run.sink?.trace()?.resultCode ?: -1)}
|
||||
if(e==CameraPreviewEvent.RELEASED) run.result=run.result.copy(surfaceReleased=true)
|
||||
publish(run);event(run,"gl_${e.name.lowercase()}")
|
||||
}},{error(run,CameraProbeFailure.SURFACE)})
|
||||
run.sink=sink;preview.setSurfaceProvider(sink)
|
||||
} else preview.setSurfaceProvider {request ->
|
||||
try {
|
||||
if(!valid(run) || !holder.surface.isValid) {request.willNotProvideSurface();return@setSurfaceProvider}
|
||||
if(run.provided.get()-run.acks.get()>=2) {request.willNotProvideSurface();error(run,CameraProbeFailure.SURFACE);return@setSurfaceProvider}
|
||||
val ack=java.util.concurrent.atomic.AtomicBoolean()
|
||||
run.provided.incrementAndGet()
|
||||
holder.setFixedSize(request.resolution.width,request.resolution.height)
|
||||
run.result=run.result.copy(surfaceCreated=true,surfaceProvidedMs=SystemClock.elapsedRealtime(),
|
||||
frameWidth=request.resolution.width,frameHeight=request.resolution.height)
|
||||
request.provideSurface(holder.surface,{task->main.post(task)}) {result->
|
||||
if(!ack.compareAndSet(false,true)) return@provideSurface
|
||||
run.acks.incrementAndGet()
|
||||
run.result=run.result.copy(surfaceAckMs=SystemClock.elapsedRealtime(),
|
||||
surfaceResult=result.resultCode,surfaceReleased=true)
|
||||
publish(run);event(run,"surface_ack")
|
||||
}
|
||||
event(run,"surface_provided")
|
||||
} catch(_: Exception) {
|
||||
request.willNotProvideSurface();error(run,CameraProbeFailure.SURFACE)
|
||||
}
|
||||
}
|
||||
}
|
||||
val camera=provider.bindToLifecycle(owner,CameraSelector.DEFAULT_FRONT_CAMERA,*cases.toTypedArray())
|
||||
run.result=run.result.copy(boundMs=SystemClock.elapsedRealtime())
|
||||
val states=camera.cameraInfo.cameraState
|
||||
val observer=Observer<CameraState> {state ->
|
||||
val native=CameraNativeState.entries.firstOrNull {it.name==state.type.name} ?: CameraNativeState.UNKNOWN
|
||||
val changed=run.result.nativeState!=native || state.error!=null
|
||||
run.result=run.result.copy(nativeState=native,
|
||||
openMs=if(native==CameraNativeState.OPEN && run.result.openMs<0) SystemClock.elapsedRealtime() else run.result.openMs)
|
||||
if(state.error!=null) run.result=run.result.copy(sessionFailure=when(state.error!!.code) {
|
||||
CameraState.ERROR_STREAM_CONFIG->CameraSessionFailure.STREAM_CONFIG
|
||||
CameraState.ERROR_CAMERA_IN_USE->CameraSessionFailure.IN_USE
|
||||
CameraState.ERROR_CAMERA_FATAL_ERROR->CameraSessionFailure.FATAL
|
||||
else->CameraSessionFailure.OTHER})
|
||||
publish(run);if(changed) event(run,"native_${native.name.lowercase()}")
|
||||
}
|
||||
run.states=states;run.observer=observer;states.observeForever(observer)
|
||||
event(run,"bound");publish(run)
|
||||
} catch(_: Exception) {error(run,CameraProbeFailure.BIND)}
|
||||
},{task->main.post(task)})
|
||||
} catch(_: Exception) {error(run,CameraProbeFailure.PROVIDER)}
|
||||
}
|
||||
private val tick=object: Runnable {override fun run() {
|
||||
if(notified.get()) return
|
||||
val run=active ?: return
|
||||
val now=SystemClock.elapsedRealtime();publish(run)
|
||||
if(!run.retired && context.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) {
|
||||
cancelled=true;run.result=run.result.copy(failure=CameraProbeFailure.PERMISSION);close(run)
|
||||
}
|
||||
if(!run.retired && now-run.result.startedMs>=8_000) {
|
||||
// Visible Preview alone has no software frame callback: do not claim frames from OPEN.
|
||||
val got=run.frames.get()>0 || (run.mode==CameraProbeMode.CAMERAX_PREVIEW && run.captures.get()>0) || (run.sink?.trace()?.latchCompleted ?: 0)>0
|
||||
if(!got) run.result=run.result.copy(failure=CameraProbeFailure.FRAME_TIMEOUT)
|
||||
close(run)
|
||||
}
|
||||
if(run.retired) {
|
||||
val safe=probeCloseSafe(run.mode.legacy,run.result.boundMs>=0,
|
||||
run.result.nativeState==CameraNativeState.CLOSED,run.result.surfaceCreated,
|
||||
(run.result.surfaceAckMs>=0 && run.provided.get()==run.acks.get()),if(run.sink!=null) run.sink!!.trace().closed else run.result.surfaceReleased,
|
||||
run.result.closeReturnedMs>=0)
|
||||
if(safe) {
|
||||
run.result=run.result.copy(closedMs=now,closeConfirmed=true);publish(run);event(run,"close_confirmed")
|
||||
detach(run);active=null;main.removeCallbacks(this);next();return
|
||||
}
|
||||
if(now-closeAt>=8_000) {
|
||||
run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run);event(run,"close_blocked")
|
||||
// Retain producer-owned Surface/blocked worker; never force release or start next API.
|
||||
run.observer?.let {run.states?.removeObserver(it)}
|
||||
finish(true);return
|
||||
}
|
||||
}
|
||||
main.postDelayed(this,250)
|
||||
}}
|
||||
private fun close(run: Run) {
|
||||
if(run.retired) return
|
||||
run.retired=true;closeAt=SystemClock.elapsedRealtime()
|
||||
run.result=run.result.copy(finishedMs=closeAt,closeStartedMs=closeAt)
|
||||
CameraProbeStore.stage=CameraProbeStage.CLOSING;publish(run);event(run,"close_requested")
|
||||
if(run.mode.legacy) run.worker.post {releaseLegacy(run,run.legacy)}
|
||||
else {
|
||||
run.analysis?.clearAnalyzer();run.sink?.close()
|
||||
try {
|
||||
val cases=listOfNotNull(run.preview,run.analysis)
|
||||
if(cases.isNotEmpty()) run.provider?.unbind(*cases.toTypedArray())
|
||||
run.result=run.result.copy(closeReturnedMs=SystemClock.elapsedRealtime())
|
||||
publish(run);event(run,"unbind_returned")
|
||||
} catch(_: Exception) {run.result=run.result.copy(failure=CameraProbeFailure.CLOSE_TIMEOUT);publish(run)}
|
||||
}
|
||||
}
|
||||
private fun publish(run: Run) {
|
||||
run.result=run.result.copy(providedSurfaces=run.provided.get(),acknowledgedSurfaces=run.acks.get(),captureCompleted=run.captures.get(),captureFailed=run.captureFailures.get(),frames=run.frames.get(),analysisReturned=run.returned.get(),
|
||||
firstFrameMs=run.first.get(),frameWidth=if(run.width>0) run.width else run.result.frameWidth,
|
||||
frameHeight=if(run.height>0) run.height else run.result.frameHeight,callbackBytes=run.bytes,
|
||||
previewTrace=run.sink?.trace() ?: run.result.previewTrace)
|
||||
CameraProbeStore.put(run.result)
|
||||
}
|
||||
private fun event(run: Run,event: String) {
|
||||
val msg="camera_probe event=$event mode=${run.mode.name.lowercase()} elapsed_ms=${SystemClock.elapsedRealtime()-run.result.startedMs} frames=${run.frames.get()} native=${run.result.nativeState.name.lowercase()} failure=${run.result.failure.name.lowercase()}"
|
||||
android.util.Log.i("LanVoiceCameraProbe",msg);DiagnosticLog.record("camera_probe",msg)
|
||||
}
|
||||
private fun detach(run: Run) {run.observer?.let {run.states?.removeObserver(it)};run.workerThread.quitSafely()}
|
||||
private fun finish(blocked: Boolean) {
|
||||
if(!notified.compareAndSet(false,true)) return
|
||||
main.removeCallbacks(tick);watchdog.removeCallbacks(watchTick);watchThread.quitSafely()
|
||||
CameraProbeStore.finish(blocked);done()
|
||||
}
|
||||
fun cancel() {
|
||||
cancelled=true
|
||||
val run=active
|
||||
if(run!=null && !notified.get()) {
|
||||
if(!run.retired) {run.result=run.result.copy(failure=CameraProbeFailure.CANCELLED);close(run)}
|
||||
} else if(!notified.get()) finish(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
/** Fixed bounded metadata; this object never receives pixel contents, face geometry or voice. */
|
||||
enum class CameraProbeMode(val width: Int,val height: Int) {
|
||||
CAMERA1_640(640,480), CAMERA1_320(320,240), CAMERAX_PREVIEW(640,480),
|
||||
CAMERAX_VISIBLE_DUAL(640,480), CAMERAX_ANALYSIS(640,480), CAMERAX_GL_DUAL(640,480);
|
||||
val legacy get()=this==CAMERA1_640 || this==CAMERA1_320
|
||||
val analysis get()=this==CAMERAX_VISIBLE_DUAL || this==CAMERAX_ANALYSIS || this==CAMERAX_GL_DUAL
|
||||
val visible get()=legacy || this==CAMERAX_PREVIEW || this==CAMERAX_VISIBLE_DUAL
|
||||
}
|
||||
enum class CameraProbeStage { IDLE, RUNNING, CLOSING, DONE, BLOCKED }
|
||||
enum class CameraProbeFailure { NONE, PERMISSION, NO_FRONT, UNSUPPORTED_SIZE, PROVIDER, BIND, OPEN,
|
||||
START, CAMERA_ERROR, SURFACE, FRAME_TIMEOUT, CLOSE_TIMEOUT, CANCELLED }
|
||||
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,
|
||||
val captureCompleted: Int=0,val captureFailed: Int=0,
|
||||
val frameWidth: Int=0,val frameHeight: Int=0,val callbackBytes: Int=0,
|
||||
val nativeState: CameraNativeState=CameraNativeState.UNKNOWN,
|
||||
val sessionFailure: CameraSessionFailure=CameraSessionFailure.NONE,
|
||||
val boundMs: Long=-1,val openMs: Long=-1,val surfaceProvidedMs: Long=-1,
|
||||
val providedSurfaces: Int=0,val acknowledgedSurfaces: Int=0,
|
||||
val surfaceAckMs: Long=-1,val surfaceResult: Int=-1,val surfaceReleased: Boolean=false,
|
||||
val surfaceCreated: Boolean=false,val closeConfirmed: Boolean=false,
|
||||
val previewTrace: CameraPreviewTrace=CameraPreviewTrace(),val failure: CameraProbeFailure=CameraProbeFailure.NONE)
|
||||
|
||||
/** One foreground suite per process at a time. A timed-out close keeps normal camera inhibited. */
|
||||
object CameraProbeStore {
|
||||
@Volatile var inhibitNormal=false
|
||||
@Volatile var stage=CameraProbeStage.IDLE
|
||||
@Volatile var entryFailure=CameraProbeFailure.NONE
|
||||
@Volatile var results: List<CameraProbeResult> = emptyList()
|
||||
@Synchronized fun begin(): Boolean {
|
||||
if(inhibitNormal || stage==CameraProbeStage.RUNNING || stage==CameraProbeStage.CLOSING) return false
|
||||
inhibitNormal=true;stage=CameraProbeStage.RUNNING;entryFailure=CameraProbeFailure.NONE;results=emptyList();return true
|
||||
}
|
||||
@Synchronized fun put(result: CameraProbeResult) {
|
||||
val rows=results.toMutableList();val index=rows.indexOfFirst {it.mode==result.mode}
|
||||
if(index<0) {if(rows.size<6) rows+=result} else rows[index]=result
|
||||
results=rows.toList()
|
||||
}
|
||||
@Synchronized fun finish(blocked: Boolean) {
|
||||
stage=if(blocked) CameraProbeStage.BLOCKED else CameraProbeStage.DONE
|
||||
inhibitNormal=blocked
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared by the production diagnostic runner: no next API until all close acknowledgements. */
|
||||
fun probeCloseSafe(legacy: Boolean,bound: Boolean,nativeClosed: Boolean,surfaceCreated: Boolean,
|
||||
producerAck: Boolean,consumerReleased: Boolean,releaseReturned: Boolean): Boolean =
|
||||
releaseReturned && (!bound || legacy || nativeClosed) &&
|
||||
(!surfaceCreated || producerAck && consumerReleased)
|
||||
@@ -52,6 +52,8 @@ class ExpressionController(
|
||||
var previewSurface: CameraPreviewSurface? = null
|
||||
var provider: ProcessCameraProvider? = null // Accessed only on main.
|
||||
var firstReady=false
|
||||
var bindingReturned=false
|
||||
var closeAck=false
|
||||
var states: LiveData<CameraState>?=null
|
||||
var stateObserver: Observer<CameraState>?=null
|
||||
val callbacks=CameraCallbackFence()
|
||||
@@ -65,6 +67,8 @@ class ExpressionController(
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var current: Run? = null
|
||||
private var released = false
|
||||
private var retired: Run?=null
|
||||
private var lastPreview: CameraPreviewSurface?=null
|
||||
private var lastDiagnostics = CameraAnalysisDiagnostics()
|
||||
private val diagnosticTick = object : Runnable {
|
||||
override fun run() {
|
||||
@@ -81,12 +85,19 @@ class ExpressionController(
|
||||
}
|
||||
}
|
||||
|
||||
fun diagnosticsSnapshot(): CameraAnalysisSnapshot = lastDiagnostics.snapshot()
|
||||
fun diagnosticsSnapshot(): CameraAnalysisSnapshot = lastDiagnostics.snapshot().copy(
|
||||
previewTrace=lastPreview?.trace() ?: CameraPreviewTrace())
|
||||
/** A new camera owner requires native CLOSED plus all provided preview resources released. */
|
||||
fun closeConfirmed(): Boolean {
|
||||
val run=retired ?: return current==null
|
||||
return current==null && (!run.bindingReturned || run.closeAck) &&
|
||||
(run.previewSurface?.trace()?.closed!=false)
|
||||
}
|
||||
|
||||
/** Called only after an explicit user toggle and CAMERA permission approval. */
|
||||
fun start() {
|
||||
checkMainThread()
|
||||
if (released || current != null) return
|
||||
if (released || current != null || !closeConfirmed() || CameraProbeStore.inhibitNormal) return
|
||||
if (appContext.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
|
||||
permissionDenied()
|
||||
return
|
||||
@@ -94,6 +105,7 @@ class ExpressionController(
|
||||
val run = Run()
|
||||
current = run
|
||||
lastDiagnostics = run.diagnostics
|
||||
lastPreview=null
|
||||
run.diagnostics.stage(CameraStage.MODEL_LOADING,SystemClock.elapsedRealtime())
|
||||
cameraEvent(run,"model_loading")
|
||||
main.post(diagnosticTick)
|
||||
@@ -187,7 +199,7 @@ class ExpressionController(
|
||||
},failure={ main.post {
|
||||
if(isCurrent(run) && run.callbacks.accepts(binding)) failCamera(run,CameraFailure.PREVIEW_SURFACE)
|
||||
} })
|
||||
run.previewSurface=sink
|
||||
run.previewSurface=sink;lastPreview=sink
|
||||
preview.setSurfaceProvider(sink)
|
||||
// Preview is locally drained on its own GL worker, never attached to UI.
|
||||
val bindStart=android.os.SystemClock.elapsedRealtime()
|
||||
@@ -195,11 +207,18 @@ class ExpressionController(
|
||||
run.diagnostics.stage(CameraStage.WAITING_FRAME,bindStart)
|
||||
cameraEvent(run,"bind_requested")
|
||||
val camera=provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, preview,analysis)
|
||||
run.bindingReturned=true
|
||||
cameraEvent(run,"bound")
|
||||
val states=camera.cameraInfo.cameraState
|
||||
var firstState=true
|
||||
val observer=Observer<CameraState> { state ->
|
||||
val initial=firstState;firstState=false
|
||||
if(!isCurrent(run) && state.type==CameraState.Type.CLOSED) {
|
||||
run.closeAck=true
|
||||
run.diagnostics.nativeState(CameraNativeState.CLOSED,SystemClock.elapsedRealtime())
|
||||
cameraEvent(run,"close_ack")
|
||||
run.stateObserver?.let { run.states?.removeObserver(it) }
|
||||
}
|
||||
if(isCurrent(run) && run.callbacks.accepts(binding)) {
|
||||
val native=CameraNativeState.entries.firstOrNull { it.name==state.type.name } ?: CameraNativeState.UNKNOWN
|
||||
if(run.diagnostics.snapshot().nativeState!=native) {
|
||||
@@ -227,7 +246,7 @@ class ExpressionController(
|
||||
}
|
||||
}
|
||||
}
|
||||
run.states=states;run.stateObserver=observer;states.observe(lifecycleOwner,observer)
|
||||
run.states=states;run.stateObserver=observer;states.observeForever(observer)
|
||||
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart)
|
||||
// Binding is not readiness. ACTIVE is published only after an actual inference result.
|
||||
onState(ExpressionUiState(ExpressionStatus.STARTING))
|
||||
@@ -314,17 +333,18 @@ class ExpressionController(
|
||||
}
|
||||
|
||||
private fun unbind(run: Run) {
|
||||
run.stateObserver?.let { run.states?.removeObserver(it) }
|
||||
run.stateObserver=null;run.states=null
|
||||
// Keep an enum-only close observer briefly after invalidating analysis/UI callbacks.
|
||||
main.postDelayed({run.stateObserver?.let {run.states?.removeObserver(it)}},8_000)
|
||||
run.analysis?.clearAnalyzer()
|
||||
run.previewSurface?.close() // Stop new requests; provided surfaces await CameraX Result before release.
|
||||
val analysis=run.analysis;val preview=run.preview
|
||||
if(analysis!=null && preview!=null) {
|
||||
cameraEvent(run,"unbind_requested") // Request only: this is not a native CLOSED acknowledgement.
|
||||
cameraEvent(run,"unbind_requested")
|
||||
run.provider?.unbind(preview,analysis)
|
||||
cameraEvent(run,"unbind_returned")
|
||||
} else analysis?.let { run.provider?.unbind(it) }
|
||||
run.analysis=null
|
||||
run.preview=null;run.previewSurface=null
|
||||
run.preview=null
|
||||
}
|
||||
|
||||
/** Single-profile validation: fail visibly without automatic close/rebind races. */
|
||||
@@ -353,6 +373,7 @@ class ExpressionController(
|
||||
|
||||
private fun stopCurrent() {
|
||||
val run = current ?: return
|
||||
retired=run
|
||||
current = null // Invalidate every pending model/provider/result callback before unbinding.
|
||||
if(run.diagnostics.snapshot().stage!=CameraStage.FAILED) run.diagnostics.stage(CameraStage.OFF,SystemClock.elapsedRealtime())
|
||||
main.removeCallbacks(diagnosticTick)
|
||||
|
||||
@@ -97,6 +97,7 @@ fun FaceDebugPanel(camera: ()->CameraAnalysisSnapshot,presence: ()->PresenceDiag
|
||||
Text("配置 ${c.profile.name.lowercase()} · 最近会话 ${c.sessionFailure.name.lowercase()} · 帧尺寸 ${c.frameWidth}×${c.frameHeight}",fontSize=12.sp)
|
||||
Text("原生状态 ${c.nativeState.name.lowercase()} · 首帧 ${if(c.firstFrameMs>=0 && c.bindStartedMs>=0) "${c.firstFrameMs-c.bindStartedMs}ms" else "未收到"}",fontSize=12.sp)
|
||||
Text("预览流 ${c.previewWidth}×${c.previewHeight} · Surface ${when { c.previewReleased->"已释放";c.previewProvided->"已提供";c.previewRequested->"已请求";else->"未请求" }} · 首帧 ${if(c.previewFirstFrameMs>=0 && c.bindStartedMs>=0) "${c.previewFirstFrameMs-c.bindStartedMs}ms" else "未收到"}",fontSize=12.sp)
|
||||
Text("预览通知 ${c.previewTrace.available} · 锁存 ${c.previewTrace.latchStarted}/${c.previewTrace.latchCompleted} · 释放回执 ${c.previewTrace.resultAcks} · worker已关闭 ${c.previewTrace.closed}",fontSize=12.sp)
|
||||
Text("帧 ${c.received} · 分析 ${c.processed} · 人脸 ${c.faceCount} · 耗时 ${c.lastProcessMs}ms · 恢复 ${c.recoveries}",fontSize=12.sp)
|
||||
Text("主动发言:${p.observation.name.lowercase()} · 门禁 ${p.block.name.lowercase()} · 采样年龄 ${p.sampleAgeMs}ms",fontSize=12.sp)
|
||||
Text("缺人 ${p.absentElapsedMs/1000.0}/20s · 有人 ${p.presentElapsedMs/1000.0}/1s · 冷却 ${p.cooldownMs/1000}s",fontSize=12.sp)
|
||||
|
||||
@@ -4,11 +4,12 @@ package com.gorios.lanvoice.expression
|
||||
enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT,
|
||||
MODEL_TIMEOUT, PROVIDER_TIMEOUT, FRAME_TIMEOUT, RESULT_TIMEOUT, STREAM_CONFIG, PREVIEW_SURFACE }
|
||||
enum class CameraProfile { PREVIEW_YUV_640 }
|
||||
enum class CameraPreviewEvent { REQUESTED, PROVIDED, FIRST_FRAME, RELEASED }
|
||||
enum class CameraPreviewEvent { REQUESTED, PROVIDED, FRAME_AVAILABLE, LATCH_STARTED, FIRST_FRAME, RESULT_ACK, RELEASED }
|
||||
enum class CameraNativeState { UNKNOWN, PENDING_OPEN, OPENING, OPEN, CLOSING, CLOSED }
|
||||
enum class CameraSessionFailure { NONE, STREAM_CONFIG, IN_USE, LIMIT, DISABLED, FATAL, OTHER }
|
||||
enum class CameraStage { OFF, MODEL_LOADING, PROVIDER_WAIT, WAITING_FRAME, WAITING_RESULT, READY, FAILED }
|
||||
data class CameraAnalysisSnapshot(
|
||||
val previewTrace: CameraPreviewTrace = CameraPreviewTrace(),
|
||||
val received: Int = 0, val processed: Int = 0, val failures: Int = 0,
|
||||
val faceCount: Int = 0, val cue: FaceCue = FaceCue.UNKNOWN,
|
||||
val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE,
|
||||
@@ -57,6 +58,7 @@ class CameraAnalysisDiagnostics {
|
||||
CameraPreviewEvent.REQUESTED -> state.copy(previewRequested=true)
|
||||
CameraPreviewEvent.PROVIDED -> state.copy(previewProvided=true,previewReleased=false,previewSurfaceCount=(state.previewSurfaceCount+1).coerceAtMost(2))
|
||||
CameraPreviewEvent.FIRST_FRAME -> state.copy(previewFirstFrameMs=if(state.previewFirstFrameMs<0) now else state.previewFirstFrameMs)
|
||||
CameraPreviewEvent.FRAME_AVAILABLE, CameraPreviewEvent.LATCH_STARTED, CameraPreviewEvent.RESULT_ACK -> state
|
||||
CameraPreviewEvent.RELEASED -> state.copy(previewReleased=state.previewSurfaceCount<=1,previewSurfaceCount=(state.previewSurfaceCount-1).coerceAtLeast(0))
|
||||
}.copy(previewWidth=width.coerceIn(0,1920),previewHeight=height.coerceIn(0,1920))
|
||||
}
|
||||
@@ -108,3 +110,20 @@ class FaceTransmissionDiagnostics {
|
||||
return "face transmission attempts=${state.attempts} sent=${state.sent} clears=${state.clears} failures=${state.failures} reason=${state.reason.name.lowercase()} cue=${state.cue.wire}"
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
class CameraPreviewMetrics {
|
||||
private var value=CameraPreviewTrace()
|
||||
@Synchronized fun available(now: Long): Boolean { val first=value.available==0
|
||||
value=value.copy(available=(value.available+1).coerceAtMost(1_000_000),firstAvailableMs=if(first) now else value.firstAvailableMs);return first }
|
||||
@Synchronized fun latchStart(now: Long): Boolean {val first=value.latchStarted==0
|
||||
value=value.copy(latchStarted=(value.latchStarted+1).coerceAtMost(1_000_000),latchStartedMs=now);return first }
|
||||
@Synchronized fun latchEnd(now: Long) {value=value.copy(latchCompleted=(value.latchCompleted+1).coerceAtMost(1_000_000),latchCompletedMs=now)}
|
||||
@Synchronized fun heartbeat(now: Long) {value=value.copy(heartbeatMs=now)}
|
||||
@Synchronized fun ack(code: Int) {value=value.copy(resultAcks=(value.resultAcks+1).coerceAtMost(2),resultCode=code)}
|
||||
@Synchronized fun closed() {value=value.copy(closed=true)}
|
||||
@Synchronized fun snapshot()=value
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# 0.7.10 / code28:前置相机一键诊断
|
||||
|
||||
本版是诊断候选,不宣称 MTK 相机问题已修复。基线 code27、旧角色 pin
|
||||
`987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887` 保留。
|
||||
不改网关、时间、模型、TTS、ASR/VAD、角色素材或嘴幅;不产生付费推理/媒体调用。
|
||||
|
||||
## 使用
|
||||
|
||||
coord 安装同签名 code28 后,正常打开 App → 齿轮 → **相机一键诊断并发送**。
|
||||
只需点一次,不逐项选配置。六项自动运行,完成、取消或关闭超时后自动发送一份汇总报告。
|
||||
网络发送失败才显示“重发报告”;它重发保留的结果,不重新运行测试。
|
||||
|
||||
本诊断候选暂缓常规人脸相机自动启动,避免先发生零帧/关闭卡住而无法进行对照。
|
||||
正常启动的语音连接/已授权录音仍沿用原设置;点诊断后先退出会话并确认真实录音停止,
|
||||
再进入独立检查页面。页面没有 VoiceSession、FaceLandmarker、LLM、TTS 或 presence 触发器。
|
||||
其前置预览仅本地显示,不保存、不截帧、不上传人脸/照片/landmarks/音频。
|
||||
返回正常页面可恢复既有会话;常规人脸管线在本诊断候选中保持暂缓。
|
||||
相机未授权不开始;检查中撤销权限、后台或离开页面会取消当前检查。
|
||||
|
||||
## 有界自动对照
|
||||
|
||||
依次 Camera1 NV21 640×480、Camera1 NV21 320×240、CameraX 可见 Preview 单路、
|
||||
CameraX 可见 Preview+YUV640、CameraX YUV640 单路、CameraX 原 EGL 消费 Preview+YUV640。
|
||||
全部只选择前置相机,Camera1 仅使用设备明确支持的预览大小/格式。
|
||||
Camera1 用 SurfaceHolder 消费预览,并以三个回收缓冲接收 NV21;只统计回调/尺寸/字节长度。
|
||||
CameraX 分析对照只计回调并归还 ImageProxy,不复制或分析图像。
|
||||
CameraX 可见 Preview 的 Camera2 capture 完成计数只是原生捕获完成,**不是显示帧证明**。
|
||||
|
||||
每项运行上限8秒,关闭确认上限8秒,通常约一分钟;不是性能承诺。
|
||||
错误可以结束当前项,但只有确认关闭后才继续。Camera1 要 release 返回;CameraX 要原生 CLOSED,
|
||||
已提供的每个 Surface 都收到 Result 回执;EGL 消费者还必须完成本地资源释放。
|
||||
缺任何回执则停组、自动发送已有结果,不强制释放生产者仍持有的 Surface,不自动重绑/强抢另一 API。
|
||||
关闭阻塞后的迟到回执不会开启下一项。此时同进程禁止再开检查,报告会显示 close_timeout;
|
||||
若需新一轮,由 coord 正常冷启同一 APK,不能以未确认关闭时立即强抢来复测。
|
||||
|
||||
## 为什么补这些断点
|
||||
|
||||
code27 最近实际报告(上海 2026-10-13 19:00:43)显示两次 Preview+YUV640尝试,
|
||||
模型创建/绑定/Surface提供/OPEN 均曾成功,但 received=processed=0,无 preview_first_frame;
|
||||
提交时 Surface 未释放。用户已确认系统前置预览流畅,所以不能说设备相机整体坏。
|
||||
旧消费者先调用 updateTexImage,返回后才报告首帧;无法区别未收到 FrameAvailable 与锁存阻塞。
|
||||
Result 回执也与 GL 锁存共用执行队列,未释放不能单独证明 HAL 永久死锁。
|
||||
|
||||
现在 FrameAvailable 和 Result 回执使用独立信号线程,先计数再排 GL 操作。
|
||||
GL 只保留一个待锁存任务;记录 latch_started/latch_completed、独立采样的 GL heartbeat、
|
||||
回执 result_code/计数及 consumer_closed;只记录首个阶段事件,不逐帧刷日志。
|
||||
关闭还有独立 watchdog,可在 GL/camera worker 或主线程解绑等待时发送有界结果。
|
||||
|
||||
## 报告与判断
|
||||
|
||||
新增 `camera_probe`:stage、entry_failure、最多六条 results;每条只包含固定枚举、
|
||||
帧/capture/归还计数、尺寸/缓冲长度、单调阶段时间、Surface 提供/回执数、关闭确认和 preview_trace。
|
||||
常规 `camera_analysis.preview_trace` 也包含通知/锁存/回执断点。TAG 为 LanVoiceCameraProbe / LanVoiceCamera。
|
||||
诊断 ring 上限500,阶段改变/摘要日志,不包含原异常文本、聊天、密钥或图像。
|
||||
|
||||
| 结果 | 可支持的定位方向 |
|
||||
| --- | --- |
|
||||
| Camera1 有帧,CameraX 无帧 | 优先 CameraX/Camera2/用例配置兼容路径;Camera1 尚未接入生产人脸检测 |
|
||||
| Preview capture 有计数,分析无回调 | 捕获与分析交付分离;不能以 capture 计数说脸检测可用 |
|
||||
| 单路有帧、双路无帧 | 双流组合值得定位,仍需结合会话错误/关闭结果 |
|
||||
| available>0,latch_started>latch_completed,heartbeat停滞 | EGL 锁存/worker 等待分支,不能笼统归“相机没出帧” |
|
||||
| 回执已到、本地资源未释放 | 消费者清理/GL 队列分支,与未收到生产者回执区分 |
|
||||
| unbind返回,但没有 CLOSED 或 Surface回执 | 原生关闭未确认,停组,不能继续抢占 |
|
||||
|
||||
任何一条出帧不等于 production presence 已修好,也不证明自然度/真机 GPU 或整个系统相机健康。
|
||||
手机结果必须按 code28、camera_probe 模式和报告接收时间对齐。
|
||||
|
||||
## 验证与边界
|
||||
|
||||
生产 CameraProbeController/CameraPreviewSurface/ExpressionController 与 Android API doubles 重放,
|
||||
覆盖六条实际配置、前置 ID、帧与 capture 区分、归还、权限撤销、取消、超时停组、迟到回执与一次完成。
|
||||
JVM/UI、严格包装、网关回归及 Android instrumentation 编译;具体数量见本轮交付记录。
|
||||
这些是宿主回放和编译,不是 MTK 真机出帧、EGL 性能或 Camera1 推理验证;设备测试待 coord。
|
||||
APK 打包继续严格验证冻结 pin、3222运行文件、同签名/min26/target34/arm64 与 HTTP 字节。
|
||||
|
||||
## 本轮交付核验
|
||||
|
||||
- 0.7.10/code28,APK SHA256 `0246b84f3675f43630e1c40f620971fce5f7e62045f9358d9dda9c6ec0236017`。
|
||||
- 同既有 debug 证书:`b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`;arm64/min26/target34;HTTP字节及 checksum通过。
|
||||
- 与 code27 比对全部3819 assets逐文件字节完全相同;严格生产导入仍为3222运行引用文件。
|
||||
- 11 JVM/UI入口;相机生产类回放105断言(22消费者+48现有分析器+35诊断组)。
|
||||
- 包装48通过;网关110通过+1既有 Silero skip;instrumentation仅编译未运行。
|
||||
- 包内生产 loader/renderer/action宿主回放通过,startup冷读/receipt均 main_asset_reads=0;它们不能证明手机性能。
|
||||
- 200既有离线GLES断言按完全相同 renderer/测试源hash继承,未追加手机GPU证据。
|
||||
- 未安装/未运行真机;本轮0付费调用,未部署/重启网关或模型。
|
||||
@@ -14,8 +14,8 @@ root=Path.cwd()
|
||||
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'app/src/androidTest').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
|
||||
paths += list((root/'tests/avatar-pixels').glob('*.c'))
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/check-camera-controller.py','scripts/check-avatar-shader.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py','scripts/package-avatar-mouth.py')]
|
||||
result={'status':'passed','jvm_entry_points':10,'camera_callback_replay':True,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
result={'status':'passed','jvm_entry_points':11,'camera_callback_replay':True,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
'hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(paths)}}
|
||||
(root/'logs/avatar-safe-061/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('PASS: ten JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
|
||||
print('PASS: eleven JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
|
||||
PY
|
||||
|
||||
@@ -10,9 +10,10 @@ for node in ast.parse(script.read_text()).body:
|
||||
nodes.append(node)
|
||||
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')]
|
||||
('ExpressionController.kt','ExpressionState.kt','ExpressionRules.kt','FaceCueRules.kt','FaceDiagnostics.kt','CameraPixelConverter.kt','CameraPreviewSurface.kt','CameraProbeState.kt','CameraProbeController.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)
|
||||
|
||||
@@ -269,7 +269,7 @@ def reviewed_actions(index,pin,registry):
|
||||
|
||||
def tested_source(full=False):
|
||||
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||
require(client['status']=='passed' and client['jvm_entry_points'] in (9,10),'client regression evidence')
|
||||
require(client['status']=='passed' and client['jvm_entry_points'] in (9,10,11),'client regression evidence')
|
||||
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
|
||||
if full:
|
||||
evidence=read_json(ROOT/'logs/action-emotion/full-release/checks.json')
|
||||
@@ -304,7 +304,7 @@ def verify_runtime_fix_assets(built,pin,startup_fix=False):
|
||||
return len([p for p in paths(new) if p.startswith('assets/'+ASSET_ROOT)])
|
||||
|
||||
|
||||
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False,face_diagnostics_fix=False,camera_compatibility_fix=False,camera_direct_yuv=False,camera_preview_stream=False):
|
||||
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False,face_diagnostics_fix=False,camera_compatibility_fix=False,camera_direct_yuv=False,camera_preview_stream=False,camera_probe_diagnostic=False):
|
||||
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
|
||||
'live emotion release needs bridge-own TALK runtimes')
|
||||
tested_source(full);packaging_tests_current();
|
||||
@@ -316,6 +316,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
if requested is not None:
|
||||
require(requested>=version,'version code occupied');version=requested
|
||||
require(not full or version>=18,'full candidate needs code >=18')
|
||||
require(not camera_probe_diagnostic or camera_preview_stream and version>=28,'camera probe needs preview diagnostics and fresh code >=28')
|
||||
require(not camera_preview_stream or camera_direct_yuv and version>=27,'preview stream needs camera diagnostics and fresh code >=27')
|
||||
require(not camera_direct_yuv or camera_compatibility_fix and version>=26,'direct YUV needs camera diagnostics and fresh code >=26')
|
||||
require(not camera_compatibility_fix or face_diagnostics_fix and version>=25,'camera compatibility needs diagnostics and fresh code >=25')
|
||||
@@ -329,9 +330,9 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
require(not runtime_fix or full and version>=19 and report['manifest_sha256']==RUNTIME_FIX_PIN,'runtime fix release shape')
|
||||
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
|
||||
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower(),'-PfaceDiagnosticsFix='+str(face_diagnostics_fix).lower(),'-PcameraCompatibilityFix='+str(camera_compatibility_fix).lower(),'-PcameraDirectYuv='+str(camera_direct_yuv).lower(),'-PcameraPreviewStream='+str(camera_preview_stream).lower()],check=True,cwd=ROOT)
|
||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower(),'-PfaceDiagnosticsFix='+str(face_diagnostics_fix).lower(),'-PcameraCompatibilityFix='+str(camera_compatibility_fix).lower(),'-PcameraDirectYuv='+str(camera_direct_yuv).lower(),'-PcameraPreviewStream='+str(camera_preview_stream).lower(),'-PcameraProbeDiagnostic='+str(camera_probe_diagnostic).lower()],check=True,cwd=ROOT)
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
|
||||
version_name='0.7.9' if camera_preview_stream else '0.7.8' if camera_direct_yuv else '0.7.7' if camera_compatibility_fix else '0.7.6' if face_diagnostics_fix else '0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
|
||||
version_name='0.7.10' if camera_probe_diagnostic else '0.7.9' if camera_preview_stream else '0.7.8' if camera_direct_yuv else '0.7.7' if camera_compatibility_fix else '0.7.6' if face_diagnostics_fix else '0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
|
||||
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
require(text in badge,'APK metadata: '+text)
|
||||
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
||||
@@ -351,7 +352,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
if startup_fix: require('AVATAR_STARTUP_FIX = true' in config.read_text(),'compiled startup flag mismatch')
|
||||
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
|
||||
if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'],startup_fix)==len(report['files']),'runtime fix file count')
|
||||
stem='front-preview' if camera_preview_stream else 'front-yuv' if camera_direct_yuv else 'camera-compat' if camera_compatibility_fix else 'face-diagnostics' if face_diagnostics_fix else 'presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
|
||||
stem='camera-matrix' if camera_probe_diagnostic else 'front-preview' if camera_preview_stream else 'front-yuv' if camera_direct_yuv else 'camera-compat' if camera_compatibility_fix else 'face-diagnostics' if face_diagnostics_fix else 'presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
|
||||
release='v'+version_name.split('-')[0].replace('.','')
|
||||
artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk'
|
||||
with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
|
||||
@@ -366,7 +367,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
|
||||
'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'],
|
||||
'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,
|
||||
'gateway_deployed':bool(full and read_json(ROOT/'logs/action-emotion/full-release/checks.json').get('gateway_deployed',False)),
|
||||
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'face_diagnostics_fix':face_diagnostics_fix,'camera_compatibility_fix':camera_compatibility_fix,'camera_direct_yuv':camera_direct_yuv,'camera_preview_stream':camera_preview_stream,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
|
||||
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'face_diagnostics_fix':face_diagnostics_fix,'camera_compatibility_fix':camera_compatibility_fix,'camera_direct_yuv':camera_direct_yuv,'camera_preview_stream':camera_preview_stream,'camera_probe_diagnostic':camera_probe_diagnostic,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
|
||||
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
|
||||
return delivery
|
||||
|
||||
@@ -391,8 +392,9 @@ def main():
|
||||
parser.add_argument('--camera-compatibility-fix',action='store_true',help='0.7.7 bounded low-resolution native YUV camera session recovery; frozen assets')
|
||||
parser.add_argument('--camera-direct-yuv',action='store_true',help='0.7.8 single fresh front YUV640 session, no automatic rebind, frozen assets')
|
||||
parser.add_argument('--camera-preview-stream',action='store_true',help='0.7.9 front Preview+YUV640 single-session compatibility candidate, local undisplayed surface')
|
||||
parser.add_argument('--camera-probe-diagnostic',action='store_true',help='0.7.10 one-button finite front-camera suite and automatic metadata report; frozen assets')
|
||||
args=parser.parse_args();
|
||||
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate,args.face_diagnostics_fix,args.camera_compatibility_fix,args.camera_direct_yuv,args.camera_preview_stream))<=1,'choose one build purpose')
|
||||
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate,args.face_diagnostics_fix,args.camera_compatibility_fix,args.camera_direct_yuv,args.camera_preview_stream,args.camera_probe_diagnostic))<=1,'choose one build purpose')
|
||||
manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
||||
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
||||
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
|
||||
@@ -409,7 +411,7 @@ def main():
|
||||
require(not args.previous_pin and not args.backup,'previous import report required')
|
||||
import_files(manifest.parent,report['files'],target)
|
||||
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
|
||||
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream,args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream,args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream,args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream,args.camera_direct_yuv or args.camera_preview_stream,args.camera_preview_stream) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream or args.camera_probe_diagnostic,args.presence_candidate or args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream or args.camera_probe_diagnostic,args.face_diagnostics_fix or args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream or args.camera_probe_diagnostic,args.camera_compatibility_fix or args.camera_direct_yuv or args.camera_preview_stream or args.camera_probe_diagnostic,args.camera_direct_yuv or args.camera_preview_stream or args.camera_probe_diagnostic,args.camera_preview_stream or args.camera_probe_diagnostic,args.camera_probe_diagnostic) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||
print(json.dumps(result,indent=2))
|
||||
|
||||
|
||||
|
||||
@@ -61,8 +61,10 @@ fun main() {
|
||||
repeat(100) {p3.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.OPEN))}
|
||||
verify(android.util.Log.lines.size==logsBefore)
|
||||
ready.stop();CameraClock.advance();val count=presence.size
|
||||
verify(!ready.closeConfirmed())
|
||||
verify(p3.unboundPreviews.size==1 && !request.surface!!.released)
|
||||
request.complete();CameraClock.advance();verify(ready.diagnosticsSnapshot().previewReleased && request.surface!!.released)
|
||||
request.complete();CameraClock.advance();p3.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.CLOSED))
|
||||
verify(ready.closeConfirmed());verify(ready.diagnosticsSnapshot().previewReleased && request.surface!!.released)
|
||||
val retired=ImageProxy();previousAnalyzer(retired)
|
||||
CameraClock.advance(30000);verify(retired.closed && p3.bindings.size==1 && presence.size==count && p3.camera.cameraInfo.cameraState.observers.isEmpty())
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import com.gorios.lanvoice.expression.*
|
||||
import android.os.CameraClock
|
||||
import android.hardware.Camera
|
||||
import androidx.camera.core.*
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
|
||||
fun main() {
|
||||
var count=0
|
||||
fun verify(value: Boolean) {check(value);count++}
|
||||
val owner=object: androidx.lifecycle.LifecycleOwner {}
|
||||
fun reset() {
|
||||
CameraClock.reset();Camera.opened.clear();Camera.failOpen=false
|
||||
ProcessCameraProvider.instance=ProcessCameraProvider().apply {autoClose=true}
|
||||
CameraProbeStore.finish(false)
|
||||
}
|
||||
// One finite suite: both Camera1 APIs/front IDs, all CameraX combinations, GL ack and exact close.
|
||||
reset();verify(CameraProbeStore.begin());verify(!CameraProbeStore.begin())
|
||||
val holder=android.view.SurfaceHolder();var done=0
|
||||
val runner=CameraProbeController(android.content.Context(),owner,holder) {done++}
|
||||
runner.start();CameraClock.advance()
|
||||
verify(Camera.opened.single().first==1)
|
||||
repeat(5) {Camera.opened.last().second.frame()};CameraClock.advance(8250)
|
||||
verify(CameraProbeStore.results.first().frames==5 && CameraProbeStore.results.first().callbackBytes==640*480*3/2)
|
||||
verify(CameraProbeStore.results.first().closeConfirmed && Camera.opened.first().second.released)
|
||||
verify(CameraProbeStore.results.last().mode==CameraProbeMode.CAMERA1_320)
|
||||
Camera.opened.last().second.frame();CameraClock.advance(8250)
|
||||
verify(CameraProbeStore.results[1].frames==1 && CameraProbeStore.results[1].frameWidth==320)
|
||||
val provider=ProcessCameraProvider.instance
|
||||
verify(provider.previews.size==1 && provider.bindings.isEmpty())
|
||||
val previewOnly=provider.previews.last();val request=previewOnly.request();CameraClock.advance()
|
||||
previewOnly.capture!!.onCaptureCompleted(android.hardware.camera2.CameraCaptureSession(),android.hardware.camera2.CaptureRequest(),android.hardware.camera2.TotalCaptureResult())
|
||||
request.complete();CameraClock.advance(8250)
|
||||
verify(CameraProbeStore.results[2].captureCompleted==1 && CameraProbeStore.results[2].frames==0 && CameraProbeStore.results[2].closeConfirmed)
|
||||
verify(provider.bindings.size==1 && provider.previews.size==2)
|
||||
val dual=provider.bindings.last();val image=ImageProxy();dual.frame(image);CameraClock.advance()
|
||||
val vr=provider.previews.last().request();CameraClock.advance();vr.complete();CameraClock.advance(8250)
|
||||
verify(image.closed && CameraProbeStore.results[3].analysisReturned==1 && CameraProbeStore.results[3].frames==1)
|
||||
verify(provider.bindings.size==2 && provider.previews.size==2) // analysis-only really omits Preview.
|
||||
val analysis=provider.bindings.last();val a=ImageProxy();analysis.frame(a);CameraClock.advance();CameraClock.advance(8250)
|
||||
verify(CameraProbeStore.results[4].frames==1 && !CameraProbeStore.results[4].surfaceCreated && a.closed)
|
||||
val gl=provider.previews.last().request();CameraClock.advance()
|
||||
val surface=gl.surface!!;surface.texture.frame();CameraClock.advance()
|
||||
verify(CameraProbeStore.results.last().previewTrace.available==1 && CameraProbeStore.results.last().previewTrace.latchCompleted==1)
|
||||
// Producer ack can arrive after stop; no early GL release.
|
||||
CameraClock.advance(8000);verify(!surface.released && CameraProbeStore.stage==CameraProbeStage.CLOSING && done==0)
|
||||
gl.complete();CameraClock.advance(250)
|
||||
verify(done==1 && CameraProbeStore.stage==CameraProbeStage.DONE && !CameraProbeStore.inhibitNormal)
|
||||
verify(CameraProbeStore.results.size==6 && CameraProbeStore.results.all {it.closeConfirmed})
|
||||
runner.cancel();CameraClock.advance(30000);verify(done==1 && Camera.opened.size==2 && provider.bindings.size==3)
|
||||
verify(provider.camera.cameraInfo.cameraState.observers.isEmpty())
|
||||
|
||||
// Close timeout blocks the suite, does not try the next camera owner, and reports once.
|
||||
reset();CameraProbeStore.begin();var blocked=0
|
||||
val second=CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder()) {blocked++}
|
||||
second.start();CameraClock.advance(16500) // both legacy tests close safely, Preview now runs.
|
||||
val p2=ProcessCameraProvider.instance;p2.autoClose=false
|
||||
p2.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.OPEN))
|
||||
val blockedRequest=p2.previews.last().request();CameraClock.advance()
|
||||
CameraClock.advance(16000)
|
||||
verify(CameraProbeStore.stage==CameraProbeStage.BLOCKED && blocked==1 && CameraProbeStore.inhibitNormal)
|
||||
verify(CameraProbeStore.results.size==3 && CameraProbeStore.results.last().failure==CameraProbeFailure.CLOSE_TIMEOUT)
|
||||
verify(!CameraProbeStore.begin() && !blockedRequest.surface!!.released)
|
||||
blockedRequest.complete();p2.camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.CLOSED));CameraClock.advance(30000)
|
||||
verify(blocked==1 && p2.bindings.isEmpty()) // Late ack is metadata, never launches the next test.
|
||||
second.cancel();verify(blocked==1)
|
||||
|
||||
// No camera permission: zero native opens, no probes/models/audio/network, exactly one completion.
|
||||
reset();CameraProbeStore.begin();var denied=0
|
||||
CameraProbeController(android.content.Context().apply {permission=false},owner,android.view.SurfaceHolder()) {denied++}.start()
|
||||
CameraClock.advance(30000)
|
||||
verify(denied==1 && Camera.opened.isEmpty() && ProcessCameraProvider.instance.previews.isEmpty())
|
||||
verify(CameraProbeStore.entryFailure==CameraProbeFailure.PERMISSION && !CameraProbeStore.inhibitNormal)
|
||||
|
||||
// Cancellation during a run closes that owner and cannot proceed to another mode.
|
||||
reset();CameraProbeStore.begin();var cancelled=0
|
||||
val stop=CameraProbeController(android.content.Context(),owner,android.view.SurfaceHolder()) {cancelled++}
|
||||
stop.start();CameraClock.advance();stop.cancel();stop.cancel();CameraClock.advance(30000)
|
||||
verify(cancelled==1 && Camera.opened.size==1 && Camera.opened.single().second.released)
|
||||
verify(CameraProbeStore.results.single().failure==CameraProbeFailure.CANCELLED && CameraProbeStore.results.single().closeConfirmed)
|
||||
// Permission revocation during capture closes the active front camera without starting the next.
|
||||
reset();CameraProbeStore.begin();var revokedDone=0
|
||||
val revokedContext=android.content.Context()
|
||||
val revoked=CameraProbeController(revokedContext,owner,android.view.SurfaceHolder()) {revokedDone++}
|
||||
revoked.start();CameraClock.advance();revokedContext.permission=false;CameraClock.advance(30000)
|
||||
verify(revokedDone==1 && Camera.opened.size==1 && Camera.opened.single().second.released)
|
||||
verify(CameraProbeStore.results.single().failure==CameraProbeFailure.PERMISSION)
|
||||
verify(!probeCloseSafe(false,true,false,true,true,true,true))
|
||||
verify(!probeCloseSafe(false,true,true,true,false,true,true))
|
||||
verify(!probeCloseSafe(false,true,true,true,true,false,true))
|
||||
verify(!probeCloseSafe(true,true,true,true,true,true,false))
|
||||
verify(probeCloseSafe(true,true,true,true,true,true,true))
|
||||
println("PASS: $count actual finite CameraProbeController front-only six-mode callback/zero-frame/native-vs-analysis/close-fences/stale-ack/cancel/permission/once-report assertions; API doubles, device not_run")
|
||||
}
|
||||
@@ -2,16 +2,17 @@ package android.graphics
|
||||
class SurfaceTexture(val texture: Int) {
|
||||
fun interface OnFrameAvailableListener {fun onFrameAvailable(surface: SurfaceTexture)}
|
||||
var released=false;var updates=0;var throwUpdate=false
|
||||
var onUpdate: (()->Unit)?=null
|
||||
var width=0;var height=0
|
||||
private var listener: OnFrameAvailableListener?=null;private var handler: android.os.Handler?=null
|
||||
init {check(texture in android.opengl.GLES20.liveTextures)}
|
||||
fun setDefaultBufferSize(w: Int,h: Int) {width=w;height=h}
|
||||
fun setOnFrameAvailableListener(l: OnFrameAvailableListener?,h: android.os.Handler?=null) {listener=l;handler=h}
|
||||
fun frame() {val cb=listener ?: return;handler!!.post {cb.onFrameAvailable(this)}}
|
||||
fun updateTexImage() {check(!released);if(throwUpdate) error("synthetic_update_failure");updates++}
|
||||
fun updateTexImage() {onUpdate?.invoke();check(!released);if(throwUpdate) error("synthetic_update_failure");updates++}
|
||||
fun release() {check(!released);released=true}
|
||||
}
|
||||
object ImageFormat {const val YUV_420_888=35}
|
||||
object ImageFormat {const val YUV_420_888=35;const val NV21=17}
|
||||
class Matrix {fun postRotate(f: Float) {}}
|
||||
class Rect(val left: Int,val top: Int,val right: Int,val bottom: Int) {fun width()=right-left;fun height()=bottom-top}
|
||||
class Bitmap(val width: Int,val height: Int) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package android.hardware
|
||||
import android.view.SurfaceHolder
|
||||
class Camera {
|
||||
class CameraInfo {var facing=0;companion object {const val CAMERA_FACING_FRONT=1}}
|
||||
class Size(val width: Int,val height: Int)
|
||||
class Parameters {
|
||||
var previewFormat=17;var previewSize=Size(640,480)
|
||||
val supportedPreviewSizes=listOf(Size(640,480),Size(320,240))
|
||||
val supportedPreviewFormats=listOf(17)
|
||||
fun setPreviewSize(w: Int,h: Int) {previewSize=Size(w,h)}
|
||||
}
|
||||
var parameters=Parameters();var started=false;var released=false
|
||||
var callback: ((ByteArray?,Camera)->Unit)?=null
|
||||
var error: ((Int,Camera)->Unit)?=null
|
||||
private var buffers=mutableListOf<ByteArray>()
|
||||
fun setErrorCallback(cb: ((Int,Camera)->Unit)?) {error=cb}
|
||||
fun setPreviewDisplay(holder: SurfaceHolder) {check(holder.surface.isValid)}
|
||||
fun setPreviewCallbackWithBuffer(cb: ((ByteArray?,Camera)->Unit)?) {callback=cb}
|
||||
fun addCallbackBuffer(data: ByteArray) {buffers+=data}
|
||||
fun startPreview() {started=true}
|
||||
fun stopPreview() {started=false}
|
||||
fun release() {check(!released);released=true}
|
||||
fun frame() {if(started) callback?.invoke(buffers.removeAt(0),this)}
|
||||
companion object {
|
||||
var opened=mutableListOf<Pair<Int,Camera>>()
|
||||
var failOpen=false
|
||||
fun getNumberOfCameras()=2
|
||||
fun getCameraInfo(id: Int,info: CameraInfo) {info.facing=id}
|
||||
fun open(id: Int): Camera {if(failOpen) error("synthetic");val c=Camera();opened+=id to c;return c}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ fun interface Observer<T> {fun onChanged(value: T)}
|
||||
class LiveData<T>(var current: T) {
|
||||
val observers=mutableListOf<Observer<T>>()
|
||||
fun observe(owner: LifecycleOwner,o: Observer<T>) {observers+=o;o.onChanged(current)}
|
||||
fun observeForever(o: Observer<T>) {observers+=o;o.onChanged(current)}
|
||||
fun removeObserver(o: Observer<T>) {observers.remove(o)}
|
||||
fun emit(value: T) {current=value;observers.toList().forEach {it.onChanged(value)}}
|
||||
}
|
||||
|
||||
@@ -2,22 +2,23 @@ package androidx.camera.core
|
||||
import android.util.Size
|
||||
import android.view.Surface
|
||||
import java.util.concurrent.Executor
|
||||
class Preview(val size: Size,val fallback: Int) : UseCase() {
|
||||
interface SurfaceProvider {fun onSurfaceRequested(request: SurfaceRequest)}
|
||||
class Preview(val size: Size,val fallback: Int,val capture: android.hardware.camera2.CameraCaptureSession.CaptureCallback?=null) : UseCase() {
|
||||
fun interface SurfaceProvider {fun onSurfaceRequested(request: SurfaceRequest)}
|
||||
var provider: SurfaceProvider?=null
|
||||
fun setSurfaceProvider(p: SurfaceProvider) {provider=p}
|
||||
fun request(r: SurfaceRequest=SurfaceRequest(size)): SurfaceRequest {provider!!.onSurfaceRequested(r);return r}
|
||||
class Builder {
|
||||
var capture: android.hardware.camera2.CameraCaptureSession.CaptureCallback?=null
|
||||
var size=Size(640,480);var fallback=0
|
||||
fun setTargetRotation(r: Int)=this
|
||||
fun setResolutionSelector(r: androidx.camera.core.resolutionselector.ResolutionSelector)=apply {size=r.strategy.size;fallback=r.strategy.fallback}
|
||||
fun build()=Preview(size,fallback)
|
||||
fun build()=Preview(size,fallback,capture)
|
||||
}
|
||||
}
|
||||
class SurfaceRequest(val resolution: Size) {
|
||||
var rejected=0;var surface: Surface?=null;var provided=0;var throwProvide=false
|
||||
private var executor: Executor?=null;private var result: ((Result)->Unit)?=null
|
||||
class Result
|
||||
class Result(val resultCode: Int=0)
|
||||
fun willNotProvideSurface(): Boolean {rejected++;return surface==null}
|
||||
fun provideSurface(s: Surface,e: Executor,r: (Result)->Unit) {
|
||||
if(throwProvide) error("synthetic_surface_failure")
|
||||
|
||||
@@ -13,19 +13,25 @@ fun cameraPreviewSurfaceCheck(): Int {
|
||||
val events=mutableListOf<CameraPreviewEvent>();var errors=0
|
||||
val sink=CameraPreviewSurface({e,_,_->events+=e},{errors++})
|
||||
val r=request();sink.onSurfaceRequested(r);CameraClock.advance()
|
||||
val surface=checkNotNull(r.surface);val thread=HandlerThread.threads.last()
|
||||
val surface=checkNotNull(r.surface);val thread=HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}
|
||||
verify(r.provided==1 && events==listOf(CameraPreviewEvent.REQUESTED,CameraPreviewEvent.PROVIDED))
|
||||
verify(surface.texture.width==640 && surface.texture.height==480 && !thread.quit)
|
||||
surface.texture.onUpdate={
|
||||
verify(sink.trace().available==3 && sink.trace().latchStarted==1 && sink.trace().latchCompleted==0)
|
||||
verify(CameraPreviewEvent.FRAME_AVAILABLE in events && CameraPreviewEvent.LATCH_STARTED in events)
|
||||
}
|
||||
repeat(3) {surface.texture.frame()};CameraClock.advance()
|
||||
verify(surface.texture.updates==3 && events.count {it==CameraPreviewEvent.FIRST_FRAME}==1)
|
||||
verify(surface.texture.updates==1 && events.count {it==CameraPreviewEvent.FIRST_FRAME}==1)
|
||||
surface.texture.onUpdate=null
|
||||
sink.close();sink.close();CameraClock.advance()
|
||||
verify(!surface.released && !surface.texture.released && !thread.quit) // Camera still owns producer.
|
||||
surface.texture.frame();CameraClock.advance()
|
||||
verify(surface.texture.updates==4 && errors==0) // Drain while CameraX asynchronously closes.
|
||||
verify(surface.texture.updates==2 && errors==0) // Drain while CameraX asynchronously closes.
|
||||
val rejected=request();sink.onSurfaceRequested(rejected);CameraClock.advance()
|
||||
verify(rejected.rejected==1 && rejected.provided==0)
|
||||
r.complete();r.complete();CameraClock.advance()
|
||||
verify(surface.released && surface.texture.released && thread.quit)
|
||||
verify(sink.trace().resultAcks==1 && sink.trace().closed)
|
||||
verify(events.count {it==CameraPreviewEvent.RELEASED}==1 && GLES20.liveTextures.isEmpty())
|
||||
verify(EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
|
||||
|
||||
@@ -39,36 +45,36 @@ fun cameraPreviewSurfaceCheck(): Int {
|
||||
// Stop before queued request executes never allocates/returns a Surface.
|
||||
val stopped=CameraPreviewSurface({_,_,_->},{errors++});val sr=request()
|
||||
stopped.onSurfaceRequested(sr);stopped.close();CameraClock.advance()
|
||||
verify(sr.rejected==1 && sr.provided==0 && HandlerThread.threads.last().quit)
|
||||
verify(sr.rejected==1 && sr.provided==0 && HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit)
|
||||
|
||||
// Actual worker initialization failure is one enum-only failure, not fallback/retry.
|
||||
EGL14.failInitialize=true
|
||||
val failing=CameraPreviewSurface({_,_,_->},{errors++});val fr=request()
|
||||
failing.onSurfaceRequested(fr);CameraClock.advance();EGL14.failInitialize=false
|
||||
verify(fr.rejected==1 && errors==1 && HandlerThread.threads.last().quit)
|
||||
verify(fr.rejected==1 && errors==1 && HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit)
|
||||
|
||||
// Surface rejected before transfer releases locally, with no leaked GPU/camera ownership.
|
||||
val broken=CameraPreviewSurface({_,_,_->},{errors++});val br=request().apply {throwProvide=true}
|
||||
broken.onSurfaceRequested(br);CameraClock.advance()
|
||||
verify(br.provided==0 && br.rejected==1 && errors==2 && HandlerThread.threads.last().quit)
|
||||
verify(br.provided==0 && br.rejected==1 && errors==2 && HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit)
|
||||
verify(GLES20.liveTextures.isEmpty() && EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
|
||||
|
||||
// Runtime latch failure requests teardown, but must wait for the camera's release callback.
|
||||
val update=CameraPreviewSurface({_,_,_->},{errors++});val ur=request()
|
||||
update.onSurfaceRequested(ur);CameraClock.advance();val us=checkNotNull(ur.surface)
|
||||
us.texture.throwUpdate=true;us.texture.frame();us.texture.frame();CameraClock.advance()
|
||||
verify(errors==3 && !us.released && !HandlerThread.threads.last().quit)
|
||||
verify(errors==3 && !us.released && !HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit)
|
||||
ur.complete();CameraClock.advance()
|
||||
verify(us.released && HandlerThread.threads.last().quit && GLES20.liveTextures.isEmpty())
|
||||
verify(us.released && HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit && GLES20.liveTextures.isEmpty())
|
||||
|
||||
// CameraX can replace a request; at most two in-flight surfaces, all release once.
|
||||
val bounded=CameraPreviewSurface({_,_,_->},{errors++})
|
||||
val one=request();val two=request();val three=request()
|
||||
bounded.onSurfaceRequested(one);bounded.onSurfaceRequested(two);bounded.onSurfaceRequested(three);CameraClock.advance()
|
||||
verify(one.provided==1 && two.provided==1 && three.rejected==1 && errors==4)
|
||||
one.complete();CameraClock.advance();verify(!HandlerThread.threads.last().quit)
|
||||
one.complete();CameraClock.advance();verify(!HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit)
|
||||
two.complete();CameraClock.advance()
|
||||
verify(HandlerThread.threads.last().quit && GLES20.liveTextures.isEmpty() && EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
|
||||
verify(HandlerThread.threads.last {it.name=="lan-voice-camera-preview"}.quit && GLES20.liveTextures.isEmpty() && EGL14.liveContexts.isEmpty() && EGL14.liveSurfaces.isEmpty())
|
||||
println("PASS: $cases production camera Preview consumer lifetime/frame-drain/stop-before-provide/stale-frame/once-release/GL-failure/bounded-surfaces assertions; EGL/SurfaceTexture doubles, device not_run")
|
||||
return cases
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
package android.view
|
||||
class Surface(val texture: android.graphics.SurfaceTexture) {
|
||||
val isValid get()=!released
|
||||
var released=false
|
||||
fun release() {check(!released);released=true}
|
||||
}
|
||||
|
||||
class SurfaceHolder {
|
||||
val surface=Surface(android.graphics.SurfaceTexture(run {
|
||||
val ids=IntArray(1);android.opengl.GLES20.glGenTextures(1,ids,0);ids[0]
|
||||
}))
|
||||
fun setFixedSize(width: Int,height: Int) {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
package androidx.annotation
|
||||
annotation class OptIn(val markerClass: Array<kotlin.reflect.KClass<*>>)
|
||||
@@ -0,0 +1,10 @@
|
||||
package android.hardware.camera2
|
||||
class CameraCaptureSession {
|
||||
open class CaptureCallback {
|
||||
open fun onCaptureCompleted(session: CameraCaptureSession,request: CaptureRequest,result: TotalCaptureResult) {}
|
||||
open fun onCaptureFailed(session: CameraCaptureSession,request: CaptureRequest,failure: CaptureFailure) {}
|
||||
}
|
||||
}
|
||||
class CaptureRequest
|
||||
class TotalCaptureResult
|
||||
class CaptureFailure
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.gorios.lanvoice.diag
|
||||
object DiagnosticLog {
|
||||
val messages=mutableListOf<String>()
|
||||
fun record(tag: String,message: String) {messages+=message}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package androidx.camera.camera2.interop
|
||||
annotation class ExperimentalCamera2Interop
|
||||
object Camera2Interop {
|
||||
class Extender(builder: androidx.camera.core.Preview.Builder) {
|
||||
private val builder=builder
|
||||
fun setSessionCaptureCallback(cb: android.hardware.camera2.CameraCaptureSession.CaptureCallback)=apply {builder.capture=cb}
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,15 @@ import androidx.camera.core.*
|
||||
class ProcessCameraProvider {
|
||||
val camera=Camera();val bindings=mutableListOf<ImageAnalysis>();val unbound=mutableListOf<ImageAnalysis>()
|
||||
val previews=mutableListOf<Preview>();val unboundPreviews=mutableListOf<Preview>()
|
||||
var autoClose=false
|
||||
var throwBind=false
|
||||
fun hasCamera(s: CameraSelector)=true
|
||||
fun bindToLifecycle(l: androidx.lifecycle.LifecycleOwner,s: CameraSelector,vararg cases: UseCase): Camera {
|
||||
if(throwBind) {throwBind=false;error("synthetic_bind_error")}
|
||||
check(cases.size==2 && cases[0] is Preview && cases[1] is ImageAnalysis)
|
||||
check(cases.isNotEmpty() && cases.size<=2)
|
||||
bindings+=cases.filterIsInstance<ImageAnalysis>();previews+=cases.filterIsInstance<Preview>();return camera
|
||||
}
|
||||
fun unbind(vararg cases: UseCase) {unbound+=cases.filterIsInstance<ImageAnalysis>();unboundPreviews+=cases.filterIsInstance<Preview>()}
|
||||
fun unbind(vararg cases: UseCase) {if(autoClose) camera.cameraInfo.cameraState.emit(CameraState(type=CameraState.Type.CLOSED));unbound+=cases.filterIsInstance<ImageAnalysis>();unboundPreviews+=cases.filterIsInstance<Preview>()}
|
||||
class Future(val provider: ProcessCameraProvider) {
|
||||
fun get()=provider
|
||||
fun addListener(r: Runnable,e: java.util.concurrent.Executor) {e.execute(r)}
|
||||
|
||||
@@ -8,6 +8,27 @@ spec=importlib.util.spec_from_file_location('presence_package',ROOT/'scripts/pac
|
||||
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
|
||||
|
||||
class PresencePackageTests(unittest.TestCase):
|
||||
def test_camera_matrix_release_requires_code28_and_preview_guards(self):
|
||||
def stop_build(command,**kwargs):
|
||||
if command[0]=='python3': return
|
||||
for flag in ('-PcameraProbeDiagnostic=true','-PcameraPreviewStream=true','-PactionVersionCode=28'):
|
||||
self.assertIn(flag,command)
|
||||
raise RuntimeError('build_sentinel')
|
||||
with patch.object(pack,'tested_source'),patch.object(pack,'packaging_tests_current'),patch.object(pack,'read_json',
|
||||
return_value={'edges':[{'nativeLoop':True}],'camera_callback_replay':True}),patch.object(pack,'next_version',return_value=28),patch.object(pack.subprocess,'run',side_effect=stop_build):
|
||||
flags=dict(full=True,startup_fix=True,presence_candidate=True,face_diagnostics_fix=True,camera_compatibility_fix=True,camera_direct_yuv=True,camera_probe_diagnostic=True)
|
||||
with self.assertRaises(ValueError):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,28,**flags)
|
||||
with self.assertRaisesRegex(RuntimeError,'build_sentinel'):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,28,camera_preview_stream=True,**flags)
|
||||
|
||||
def test_camera_matrix_cli_is_one_purpose(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
args=['package-avatar-emotion.py','--manifest',str(ROOT/'app/src/main/assets'/pack.ASSET_ROOT/'manifest.json'),
|
||||
'--sha256',pack.RUNTIME_FIX_PIN,'--output',str(Path(folder)/'evidence'),'--camera-probe-diagnostic']
|
||||
with patch.object(sys,'argv',args),patch.object(pack,'check_bundle',side_effect=RuntimeError('gate_sentinel')):
|
||||
with self.assertRaisesRegex(RuntimeError,'gate_sentinel'):pack.main()
|
||||
with patch.object(sys,'argv',args+['--camera-preview-stream']):
|
||||
with self.assertRaisesRegex(ValueError,'choose one build purpose'):pack.main()
|
||||
|
||||
def test_preview_stream_release_requires_prior_guards_and_code27(self):
|
||||
def stop_build(command,**kwargs):
|
||||
if command[0]=='python3': return
|
||||
|
||||
Reference in New Issue
Block a user