Expose face presence diagnostics and bound camera readiness recovery

This commit is contained in:
zenord
2026-10-13 17:14:37 +08:00
parent d0c1d7eb3d
commit 62dce32bb7
14 changed files with 348 additions and 44 deletions
+3 -1
View File
@@ -19,6 +19,7 @@ def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull ==
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true' def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true' def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true' def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true'
def faceDiagnosticsFix = providers.gradleProperty('faceDiagnosticsFix').orNull == 'true'
def presenceCandidate = providers.gradleProperty('presenceCandidate').orNull == 'true' def presenceCandidate = providers.gradleProperty('presenceCandidate').orNull == 'true'
def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true' def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true'
def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true' def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true'
@@ -39,6 +40,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA') if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17') if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18') if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
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') if (presenceCandidate && (!avatarStartupFix || actionVersionCode < 23)) throw new GradleException('Presence candidate requires startup fix and fresh code >=23')
if (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22') if (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22')
if (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21') if (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21')
@@ -93,7 +95,7 @@ android {
targetSdk 34 targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation' testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))) versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = 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 = 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' } ndk { abiFilters 'arm64-v8a' }
} }
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -199,6 +199,8 @@ class MainActivity : ComponentActivity() {
presenceEnabled=enabled;preferences().edit().putBoolean("presenceEnabled",enabled).apply() presenceEnabled=enabled;preferences().edit().putBoolean("presenceEnabled",enabled).apply()
if(::session.isInitialized) session.setPresence(enabled,expressionState.status==ExpressionStatus.ACTIVE) if(::session.isInitialized) session.setPresence(enabled,expressionState.status==ExpressionStatus.ACTIVE)
}, },
cameraDiagnostics={if(::expressions.isInitialized) expressions.diagnosticsSnapshot() else com.gorios.lanvoice.expression.CameraAnalysisSnapshot()},
presenceDiagnostics={if(::session.isInitialized) session.presenceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot()},
) )
} }
if(BuildConfig.AVATAR_STARTUP_FIX) startShell() if(BuildConfig.AVATAR_STARTUP_FIX) startShell()
@@ -302,6 +304,7 @@ class MainActivity : ComponentActivity() {
faceSharing = shareFace, faceSharing = shareFace,
cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else if(::expressions.isInitialized) expressions.diagnosticsSnapshot() else com.gorios.lanvoice.expression.CameraAnalysisSnapshot(), cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else if(::expressions.isInitialized) expressions.diagnosticsSnapshot() else com.gorios.lanvoice.expression.CameraAnalysisSnapshot(),
faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else if(::session.isInitialized) session.faceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.FaceTransmissionSnapshot(), faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else if(::session.isInitialized) session.faceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.FaceTransmissionSnapshot(),
presence = if(offlineAvatarPreview) com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot() else if(::session.isInitialized) session.presenceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot(),
rolePlaying = state.phase == VoicePhase.ANSWERING, rolePlaying = state.phase == VoicePhase.ANSWERING,
role = state.replyEmotion.takeIf { it.turnId != null }, role = state.replyEmotion.takeIf { it.turnId != null },
previousRole = state.previousReplyEmotion, previousRole = state.previousReplyEmotion,
@@ -18,6 +18,11 @@ import com.gorios.lanvoice.expression.FaceCueObservation
import com.gorios.lanvoice.expression.FaceCueReason import com.gorios.lanvoice.expression.FaceCueReason
import com.gorios.lanvoice.expression.FaceSendReason import com.gorios.lanvoice.expression.FaceSendReason
import com.gorios.lanvoice.expression.FaceTransmissionDiagnostics import com.gorios.lanvoice.expression.FaceTransmissionDiagnostics
import com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot
import com.gorios.lanvoice.expression.PresenceBlock
import com.gorios.lanvoice.expression.PresenceObservation
import com.gorios.lanvoice.expression.PresenceOutcome
import com.gorios.lanvoice.expression.PresenceServerReason
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING } enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
@@ -84,6 +89,10 @@ class VoiceSession(
var turn: Long?=null,var accepted: Boolean=false) var turn: Long?=null,var accepted: Boolean=false)
private var presenceRequest: PresenceRequest?=null private var presenceRequest: PresenceRequest?=null
private var presenceTimeout: Runnable?=null private var presenceTimeout: Runnable?=null
private var presenceStats=PresenceDiagnosticsSnapshot()
private var presenceSummaryAt: Long?=null
private var lastPresenceObservedAt: Long?=null
private var presenceSampleRejected=false
private val faceTick = object : Runnable { private val faceTick = object : Runnable {
override fun run() { override fun run() {
if (!faceSharing || released) return if (!faceSharing || released) return
@@ -117,7 +126,7 @@ class VoiceSession(
diagnostic("playback drained turn=$turn") diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) { if (dialogue.playbackDrained(turn)) {
drainedTurn=turn drainedTurn=turn
if(presenceRequest?.turn==turn) clearPresenceRequest() if(presenceRequest?.turn==turn) { presenceStats=presenceStats.copy(outcome=PresenceOutcome.COMPLETED);clearPresenceRequest() }
resetReply("drained") resetReply("drained")
emotionEndedTurn = turn emotionEndedTurn = turn
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
@@ -341,23 +350,67 @@ class VoiceSession(
fun setPresence(enabled: Boolean,cameraActive: Boolean) { fun setPresence(enabled: Boolean,cameraActive: Boolean) {
checkMainThread() checkMainThread()
presenceEnabled=enabled;presenceCamera=cameraActive presenceEnabled=enabled;presenceCamera=cameraActive
if(!enabled || !cameraActive) cancelPresence(reset=true) if(!enabled || !cameraActive) { lastPresenceObservedAt=null;presenceSampleRejected=false;cancelPresence(reset=true) }
} }
private fun presenceEligible()=presenceEnabled && presenceCamera && presenceSupported && isActive() && !state.microphoneMuted private fun presenceEligible()=presenceEnabled && presenceCamera && presenceSupported && isActive() && !state.microphoneMuted
fun presenceDiagnosticsSnapshot(): PresenceDiagnosticsSnapshot {
checkMainThread()
val now=SystemClock.elapsedRealtime()
val s=presenceRules.snapshot(now)
val cooldown=(appearedAllowed.get()-now).coerceAtLeast(0)
val block=when {
!presenceEnabled -> PresenceBlock.DISABLED
!presenceCamera -> PresenceBlock.CAMERA_INACTIVE
!foreground || released -> PresenceBlock.BACKGROUND
state.connection!=ConnectionStatus.CONNECTED -> PresenceBlock.NOT_CONNECTED
!state.voiceActive -> PresenceBlock.VOICE_INACTIVE
!presenceSupported -> PresenceBlock.UNSUPPORTED
state.microphoneMuted -> PresenceBlock.MUTED
actions.active -> PresenceBlock.ACTION_BUSY
presenceSpeech -> PresenceBlock.USER_SPEAKING
presenceRequest!=null -> PresenceBlock.REQUEST_ACTIVE
state.phase!=VoicePhase.LISTENING || !capturing -> PresenceBlock.TTS_BUSY
now-lastSpeechAt<800 -> PresenceBlock.QUIET_WINDOW
presenceSampleRejected -> PresenceBlock.STALE_SAMPLE
s.sampleAgeMs<0 -> PresenceBlock.WAITING_SAMPLE
s.sampleAgeMs>350 -> PresenceBlock.STALE_SAMPLE
s.pending!=null -> PresenceBlock.PENDING
s.observation==PresenceObservation.PRESENT && cooldown>0 -> PresenceBlock.COOLDOWN
s.observation==PresenceObservation.ABSENT && s.episodeConsumed -> PresenceBlock.EPISODE_CONSUMED
else -> PresenceBlock.CONFIRMING
}
return s.copy(enabled=presenceEnabled,cameraActive=presenceCamera,supported=presenceSupported,
sampleAgeMs=lastPresenceObservedAt?.let { (now-it).coerceAtLeast(0) } ?: s.sampleAgeMs,
cooldownMs=cooldown,block=block,active=presenceRequest?.kind,requestId=presenceStats.requestId,
outcome=presenceStats.outcome,serverReason=presenceStats.serverReason,
sent=presenceStats.sent,accepted=presenceStats.accepted,rejected=presenceStats.rejected,cancelled=presenceStats.cancelled)
}
private fun presenceSummary(now: Long) {
val last=presenceSummaryAt
if(last!=null && now-last<10_000) return
presenceSummaryAt=now
val s=presenceDiagnosticsSnapshot()
diagnostic("presence diagnostics observation=${s.observation.name.lowercase()} block=${s.block.name.lowercase()} sample_age_ms=${s.sampleAgeMs} absent_ms=${s.absentElapsedMs} present_ms=${s.presentElapsedMs} sent=${s.sent} accepted=${s.accepted} rejected=${s.rejected}")
}
fun observePresence(present: Boolean?,observedAt: Long) { fun observePresence(present: Boolean?,observedAt: Long) {
checkMainThread() checkMainThread()
if(!presenceEligible()) { presenceRules.reset();return }
val now=SystemClock.elapsedRealtime() val now=SystemClock.elapsedRealtime()
if(now-observedAt !in 0..350) { presenceRules.sample(null,now,currentTurn,false);return } if(!presenceEligible()) { presenceRules.reset();presenceSummary(now);return }
lastPresenceObservedAt=observedAt
presenceSampleRejected=now-observedAt !in 0..350
if(presenceSampleRejected) { presenceRules.sample(null,now,currentTurn,false);presenceSummary(now);return }
val idle=state.phase==VoicePhase.LISTENING && !actions.active && presenceRequest==null && val idle=state.phase==VoicePhase.LISTENING && !actions.active && presenceRequest==null &&
!presenceSpeech && now-lastSpeechAt>=800 && capturing !presenceSpeech && now-lastSpeechAt>=800 && capturing
val trigger=presenceRules.sample(present,observedAt,currentTurn,idle, val trigger=presenceRules.sample(present,observedAt,currentTurn,idle,
presenceRequest?.kind==com.gorios.lanvoice.expression.PresenceKind.ABSENT,appearedAllowed.get()) ?: return presenceRequest?.kind==com.gorios.lanvoice.expression.PresenceKind.ABSENT,appearedAllowed.get())
presenceSummary(now)
if(trigger==null) return
val id=presenceSerial.incrementAndGet() val id=presenceSerial.incrementAndGet()
if(id !in 1..UINT32_MASK) return if(id !in 1..UINT32_MASK) return
presenceRequest=PresenceRequest(id,trigger.kind) presenceRequest=PresenceRequest(id,trigger.kind)
presenceStats=presenceStats.copy(requestId=id,outcome=PresenceOutcome.SENT,serverReason=PresenceServerReason.NONE,sent=(presenceStats.sent+1).coerceAtMost(1_000_000))
diagnostic("presence state=sent kind=${trigger.kind.wire} request=$id turn=$currentTurn") diagnostic("presence state=sent kind=${trigger.kind.wire} request=$id turn=$currentTurn")
if(!dialogue.presence(id,trigger.turn,trigger.kind,now-observedAt)) { clearPresenceRequest();return } if(!dialogue.presence(id,trigger.turn,trigger.kind,now-observedAt)) { presenceStats=presenceStats.copy(outcome=PresenceOutcome.SEND_FAILED);clearPresenceRequest();return }
presenceTimeout=Runnable { cancelPresence(reset=false) }.also { main.postDelayed(it,5_000) } presenceTimeout=Runnable { cancelPresence(reset=false) }.also { main.postDelayed(it,5_000) }
} }
private fun clearPresenceRequest() { private fun clearPresenceRequest() {
@@ -368,6 +421,7 @@ class VoiceSession(
clearPresenceRequest() clearPresenceRequest()
if(reset) presenceRules.reset() else presenceRules.discardPending() if(reset) presenceRules.reset() else presenceRules.discardPending()
if(request!=null && state.connection==ConnectionStatus.CONNECTED) { if(request!=null && state.connection==ConnectionStatus.CONNECTED) {
presenceStats=presenceStats.copy(outcome=PresenceOutcome.CANCELLED,cancelled=(presenceStats.cancelled+1).coerceAtMost(1_000_000))
dialogue.presenceCancel(request.id) dialogue.presenceCancel(request.id)
if(request.turn==currentTurn) { if(request.turn==currentTurn) {
blockedTurn=currentTurn;playback.interrupt();onPrepareExpression(null);resetReply("presence_cancelled") blockedTurn=currentTurn;playback.interrupt();onPrepareExpression(null);resetReply("presence_cancelled")
@@ -419,6 +473,7 @@ class VoiceSession(
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect") diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) { if (connection != ConnectionStatus.CONNECTED) {
clearPresenceRequest();presenceRules.reset();presenceSupported=false;presenceSpeech=false clearPresenceRequest();presenceRules.reset();presenceSupported=false;presenceSpeech=false
lastPresenceObservedAt=null;presenceSampleRejected=false
cancelActionFor("disconnect") cancelActionFor("disconnect")
onPrepareExpression(null) onPrepareExpression(null)
resetReply("disconnect") resetReply("disconnect")
@@ -493,14 +548,19 @@ class VoiceSession(
val request=presenceRequest ?: return val request=presenceRequest ?: return
if((event.payload.opt("request_id") as? Number)?.toLong()!=request.id) return if((event.payload.opt("request_id") as? Number)?.toLong()!=request.id) return
val accepted=event.payload.optString("state")=="accepted" val accepted=event.payload.optString("state")=="accepted"
val serverReason=PresenceServerReason.entries.firstOrNull { it.name.lowercase()==event.payload.optString("reason") } ?: PresenceServerReason.UNKNOWN
presenceStats=presenceStats.copy(serverReason=serverReason)
if(accepted && request.turn==turn && presenceEligible()) { if(accepted && request.turn==turn && presenceEligible()) {
presenceTimeout?.let { main.removeCallbacks(it) };presenceTimeout=null presenceTimeout?.let { main.removeCallbacks(it) };presenceTimeout=null
if(!request.accepted && request.kind==com.gorios.lanvoice.expression.PresenceKind.APPEARED) if(!request.accepted && request.kind==com.gorios.lanvoice.expression.PresenceKind.APPEARED)
appearedAllowed.set(SystemClock.elapsedRealtime()+600_000) appearedAllowed.set(SystemClock.elapsedRealtime()+600_000)
if(!request.accepted) presenceStats=presenceStats.copy(outcome=PresenceOutcome.ACCEPTED,accepted=(presenceStats.accepted+1).coerceAtMost(1_000_000))
request.accepted=true request.accepted=true
} else if(!accepted) clearPresenceRequest() } else if(!accepted) {
presenceStats=presenceStats.copy(outcome=PresenceOutcome.REJECTED,rejected=(presenceStats.rejected+1).coerceAtMost(1_000_000));clearPresenceRequest()
}
else cancelPresence(reset=false) else cancelPresence(reset=false)
diagnostic("presence state=${if(accepted) "accepted" else "rejected_or_cancelled"} request=${request.id}") diagnostic("presence state=${if(accepted) "accepted" else "rejected_or_cancelled"} reason=${serverReason.name.lowercase()} request=${request.id}")
return return
} }
if(event.kind==EventKind.ABORT && event.payload.optString("reason")=="presence_greeting") { if(event.kind==EventKind.ABORT && event.payload.optString("reason")=="presence_greeting") {
@@ -97,6 +97,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
startupBase: ContinuousAvatarPack?=null,startupStage: String="ready", startupBase: ContinuousAvatarPack?=null,startupStage: String="ready",
onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction, onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,
presenceEnabled: Boolean=false,onPresenceEnabled: (Boolean)->Unit={}, 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()},
) { ) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive }) val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar) val latestAvatar by rememberUpdatedState(avatar)
@@ -151,6 +153,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
} }
} }
ExpressionControls(expression,onCamera,shareFace,onShare,controlsEnabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED) ExpressionControls(expression,onCamera,shareFace,onShare,controlsEnabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED)
com.gorios.lanvoice.expression.FaceDebugPanel(cameraDiagnostics,presenceDiagnostics)
HorizontalDivider(Modifier.padding(vertical=12.dp)) HorizontalDivider(Modifier.padding(vertical=12.dp))
Text("角色:${state.roleLabel}",fontSize=13.sp) 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) Text("请求表达:"+if(state.replyEmotion.turnId==null) "尚未收到" else "${state.replyEmotion.label} (${state.replyEmotion.emotion.wire}/${state.replyEmotion.intensity})",fontSize=12.sp)
@@ -4,6 +4,7 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion
import com.gorios.lanvoice.expression.ExpressionStatus import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.CameraAnalysisSnapshot import com.gorios.lanvoice.expression.CameraAnalysisSnapshot
import com.gorios.lanvoice.expression.FaceTransmissionSnapshot import com.gorios.lanvoice.expression.FaceTransmissionSnapshot
import com.gorios.lanvoice.expression.PresenceDiagnosticsSnapshot
import okhttp3.Call import okhttp3.Call
import okhttp3.Callback import okhttp3.Callback
import okhttp3.ConnectionPool import okhttp3.ConnectionPool
@@ -44,6 +45,7 @@ data class DiagnosticReportInfo(
val previousRole: ReplyEmotion? = null, val previousRole: ReplyEmotion? = null,
val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(), val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(),
val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(), val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(),
val presence: PresenceDiagnosticsSnapshot = PresenceDiagnosticsSnapshot(),
) )
/** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */ /** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */
@@ -110,7 +112,21 @@ object DiagnosticReportUpload {
.put("processed", info.cameraAnalysis.processed).put("failures", info.cameraAnalysis.failures) .put("processed", info.cameraAnalysis.processed).put("failures", info.cameraAnalysis.failures)
.put("faces", info.cameraAnalysis.faceCount).put("cue", info.cameraAnalysis.cue.wire) .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()) .put("reason", info.cameraAnalysis.reason.name.lowercase()).put("failure", info.cameraAnalysis.failure.name.lowercase())
.put("last_process_ms", info.cameraAnalysis.lastProcessMs)) .put("last_process_ms", info.cameraAnalysis.lastProcessMs).put("stage",info.cameraAnalysis.stage.name.lowercase())
.put("stage_elapsed_ms",(android.os.SystemClock.elapsedRealtime()-info.cameraAnalysis.stageSinceMs).coerceAtLeast(0))
.put("last_frame_age_ms",info.cameraAnalysis.lastFrameMs.takeIf { it>=0 }?.let { (android.os.SystemClock.elapsedRealtime()-it).coerceAtLeast(0) } ?: -1)
.put("last_result_age_ms",info.cameraAnalysis.lastResultMs.takeIf { it>=0 }?.let { (android.os.SystemClock.elapsedRealtime()-it).coerceAtLeast(0) } ?: -1)
.put("recoveries",info.cameraAnalysis.recoveries))
.put("presence", JSONObject().put("enabled",info.presence.enabled).put("camera_active",info.presence.cameraActive)
.put("supported",info.presence.supported).put("observation",info.presence.observation.name.lowercase())
.put("sample_age_ms",info.presence.sampleAgeMs).put("absent_elapsed_ms",info.presence.absentElapsedMs)
.put("present_elapsed_ms",info.presence.presentElapsedMs).put("pending_kind",info.presence.pending?.wire ?: "none")
.put("pending_ttl_ms",info.presence.pendingTtlMs).put("episode_consumed",info.presence.episodeConsumed)
.put("return_armed",info.presence.returnArmed).put("cooldown_ms",info.presence.cooldownMs)
.put("block",info.presence.block.name.lowercase()).put("active_kind",info.presence.active?.wire ?: "none")
.put("request_id",info.presence.requestId).put("outcome",info.presence.outcome.name.lowercase())
.put("server_reason",info.presence.serverReason.name.lowercase()).put("sent",info.presence.sent)
.put("accepted",info.presence.accepted).put("rejected",info.presence.rejected).put("cancelled",info.presence.cancelled))
.put("face_transmission", JSONObject().put("attempts", info.faceTransmission.attempts) .put("face_transmission", JSONObject().put("attempts", info.faceTransmission.attempts)
.put("sent", info.faceTransmission.sent).put("clears", info.faceTransmission.clears) .put("sent", info.faceTransmission.sent).put("clears", info.faceTransmission.clears)
.put("failures", info.faceTransmission.failures).put("reason", info.faceTransmission.reason.name.lowercase()) .put("failures", info.faceTransmission.failures).put("reason", info.faceTransmission.reason.name.lowercase())
@@ -43,6 +43,7 @@ class ExpressionController(
var analysis: ImageAnalysis? = null // Accessed only on main. var analysis: ImageAnalysis? = null // Accessed only on main.
var provider: ProcessCameraProvider? = null // Accessed only on main. var provider: ProcessCameraProvider? = null // Accessed only on main.
var firstReady=false var firstReady=false
val callbacks=CameraCallbackFence()
var lastSampleMs = Long.MIN_VALUE var lastSampleMs = Long.MIN_VALUE
var lastPublished: List<ExpressionCue>? = null var lastPublished: List<ExpressionCue>? = null
var lastStableCue = FaceCue.UNKNOWN var lastStableCue = FaceCue.UNKNOWN
@@ -57,8 +58,30 @@ class ExpressionController(
private val diagnosticTick = object : Runnable { private val diagnosticTick = object : Runnable {
override fun run() { override fun run() {
val run = current ?: return val run = current ?: return
run.diagnostics.summary(SystemClock.elapsedRealtime())?.let { DebugLogUpload.log("audio", it) } val now=SystemClock.elapsedRealtime()
main.postDelayed(this, 10_000) val snapshot=run.diagnostics.snapshot()
val failure=cameraTimeout(snapshot,now)
if(failure!=CameraFailure.NONE) {
if(canRecoverFirstFrame(snapshot,failure)) {
run.diagnostics.recovering()
DebugLogUpload.log("audio","camera recovery=first_frame_retry")
// Same model/run, at most one rebind; invalidate queued old analyzer/provider callbacks.
run.callbacks.invalidate()
try {
run.analysis?.clearAnalyzer()
run.analysis?.let { run.provider?.unbind(it) }
} catch (_: Exception) {
fail(run,"摄像头恢复失败,请重新开启。","camera_bind");return
}
run.analysis=null
bind(run)
} else {
fail(run,"摄像头未持续输出可用结果,请重新开启;语音功能不受影响。",failure.name.lowercase())
return
}
}
run.diagnostics.summary(now)?.let { DebugLogUpload.log("audio", it) }
main.postDelayed(this, 1_000)
} }
} }
@@ -75,6 +98,7 @@ class ExpressionController(
val run = Run() val run = Run()
current = run current = run
lastDiagnostics = run.diagnostics lastDiagnostics = run.diagnostics
run.diagnostics.stage(CameraStage.MODEL_LOADING,SystemClock.elapsedRealtime())
main.post(diagnosticTick) main.post(diagnosticTick)
onState(ExpressionUiState(ExpressionStatus.STARTING)) onState(ExpressionUiState(ExpressionStatus.STARTING))
// Model loading and all synchronous VIDEO inference stay off the UI/audio threads. // Model loading and all synchronous VIDEO inference stay off the UI/audio threads.
@@ -130,10 +154,12 @@ class ExpressionController(
@Suppress("DEPRECATION") // targetResolution keeps compatibility with stable CameraX APIs. @Suppress("DEPRECATION") // targetResolution keeps compatibility with stable CameraX APIs.
private fun bind(run: Run) { private fun bind(run: Run) {
val binding=run.callbacks.nextBinding()
run.diagnostics.stage(CameraStage.PROVIDER_WAIT,SystemClock.elapsedRealtime())
try { try {
val future = ProcessCameraProvider.getInstance(appContext) val future = ProcessCameraProvider.getInstance(appContext)
future.addListener({ future.addListener({
if (!isCurrent(run)) return@addListener if (!isCurrent(run) || !run.callbacks.accepts(binding)) return@addListener
try { try {
val provider = future.get() val provider = future.get()
if (!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) { if (!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {
@@ -149,12 +175,14 @@ class ExpressionController(
.build() .build()
run.provider = provider run.provider = provider
run.analysis = analysis run.analysis = analysis
analysis.setAnalyzer(run.executor) { image -> analyze(run, image) } analysis.setAnalyzer(run.executor) { image -> analyze(run, image,binding) }
// ImageAnalysis only: no Preview, capture, video recording or image persistence. // ImageAnalysis only: no Preview, capture, video recording or image persistence.
val bindStart=android.os.SystemClock.elapsedRealtime() val bindStart=android.os.SystemClock.elapsedRealtime()
run.diagnostics.stage(CameraStage.WAITING_FRAME,bindStart)
provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis) provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart) com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart)
onState(ExpressionUiState(ExpressionStatus.ACTIVE)) // Binding is not readiness. ACTIVE is published only after an actual inference result.
onState(ExpressionUiState(ExpressionStatus.STARTING))
} catch (_: Exception) { } catch (_: Exception) {
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind") fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
} }
@@ -164,11 +192,11 @@ class ExpressionController(
} }
} }
private fun analyze(run: Run, image: ImageProxy) { private fun analyze(run: Run, image: ImageProxy,binding: Long) {
var bitmap: Bitmap? = null var bitmap: Bitmap? = null
try { try {
if (!run.active) return if (!run.active || !run.callbacks.accepts(binding)) return
run.diagnostics.received() run.diagnostics.received(SystemClock.elapsedRealtime())
if(!run.firstReady) { run.firstReady=true;com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) } if(!run.firstReady) { run.firstReady=true;com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) }
val now = SystemClock.elapsedRealtime() val now = SystemClock.elapsedRealtime()
if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return
@@ -182,10 +210,10 @@ class ExpressionController(
mpImage.close() mpImage.close()
} ?: kotlin.run { } ?: kotlin.run {
run.diagnostics.failed(CameraFailure.NO_RESULT) run.diagnostics.failed(CameraFailure.NO_RESULT)
main.post { if(isCurrent(run)) onPresence(null,now) } main.post { if(isCurrent(run) && run.callbacks.accepts(binding)) onPresence(null,now) }
return return
} }
if (!run.active) return if (!run.active || !run.callbacks.accepts(binding)) return
val observation = if (result.faceLandmarks().isEmpty()) null else { val observation = if (result.faceLandmarks().isEmpty()) null else {
val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty() val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty()
val blendshapes = categories.associate { it.categoryName() to it.score() } val blendshapes = categories.associate { it.categoryName() to it.score() }
@@ -202,24 +230,24 @@ class ExpressionController(
(landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) * (landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) *
(landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f (landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f
val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now) val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now)
run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - now) run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - now,SystemClock.elapsedRealtime())
main.post { if (isCurrent(run)) onFaceCue(faceCue) } main.post { if (isCurrent(run) && run.callbacks.accepts(binding)) onFaceCue(faceCue) }
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient. // UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
val presence = if (result.faceLandmarks().isEmpty()) FacePresence.ABSENT else FacePresence.PRESENT val presence = if (result.faceLandmarks().isEmpty()) FacePresence.ABSENT else FacePresence.PRESENT
main.post { if(isCurrent(run)) onPresence(presence==FacePresence.PRESENT,now) } main.post { if(isCurrent(run) && run.callbacks.accepts(binding)) onPresence(presence==FacePresence.PRESENT,now) }
if (run.lastPublished != visible || run.lastStableCue != faceCue.cue || run.lastPresence != presence) { if (run.lastPublished != visible || run.lastStableCue != faceCue.cue || run.lastPresence != presence) {
run.lastPresence = presence run.lastPresence = presence
run.lastStableCue = faceCue.cue run.lastStableCue = faceCue.cue
run.lastPublished = visible run.lastPublished = visible
main.post { main.post {
if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue, facePresence = presence)) if (isCurrent(run) && run.callbacks.accepts(binding)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue, facePresence = presence))
} }
} }
} catch (_: Exception) { } catch (_: Exception) {
// Never log exceptions from inference, frames, coefficients or head pose. // Never log exceptions from inference, frames, coefficients or head pose.
fail(run, "表情分析已停止,请重新开启;语音功能不受影响。", "analysis") if(run.callbacks.accepts(binding)) fail(run, "表情分析已停止,请重新开启;语音功能不受影响。", "analysis")
} catch (_: LinkageError) { } catch (_: LinkageError) {
fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support") if(run.callbacks.accepts(binding)) fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support")
} finally { } finally {
bitmap?.recycle() bitmap?.recycle()
image.close() // Includes throttle/stop/error paths, so CameraX never retains the proxy. image.close() // Includes throttle/stop/error paths, so CameraX never retains the proxy.
@@ -243,8 +271,10 @@ class ExpressionController(
private fun stopCurrent() { private fun stopCurrent() {
val run = current ?: return val run = current ?: return
current = null // Invalidate every pending model/provider/result callback before unbinding. 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) main.removeCallbacks(diagnosticTick)
run.active = false run.active = false
run.callbacks.close()
try { try {
run.analysis?.clearAnalyzer() run.analysis?.clearAnalyzer()
} catch (_: Exception) { } } catch (_: Exception) { }
@@ -10,6 +10,13 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.mutableStateOf
import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
@@ -33,8 +40,8 @@ fun ExpressionControls(
state.status == ExpressionStatus.STARTING -> "启动中" state.status == ExpressionStatus.STARTING -> "启动中"
ExpressionCue.FACE_LOST in state.cues -> "无脸" ExpressionCue.FACE_LOST in state.cues -> "无脸"
state.facePresence == FacePresence.PRESENT -> "有人脸" state.facePresence == FacePresence.PRESENT -> "有人脸"
state.facePresence == FacePresence.ABSENT -> "尚无结果" state.facePresence == FacePresence.ABSENT -> "未检测到人脸"
else -> "尚无结果" else -> "等待分析结果"
}, fontSize = 12.sp, color = Color(0xFF385B46), }, fontSize = 12.sp, color = Color(0xFF385B46),
) )
TextButton(onClick = onToggle, enabled = controlsEnabled) { TextButton(onClick = onToggle, enabled = controlsEnabled) {
@@ -69,3 +76,28 @@ fun ExpressionControls(
} }
} }
} }
/** Poll only while the settings sheet is composed. No camera/image/renderer ownership. */
@Composable
fun FaceDebugPanel(camera: ()->CameraAnalysisSnapshot,presence: ()->PresenceDiagnosticsSnapshot) {
val cameraGetter by rememberUpdatedState(camera)
val presenceGetter by rememberUpdatedState(presence)
var c by remember { mutableStateOf(camera()) }
var p by remember { mutableStateOf(presence()) }
LaunchedEffect(Unit) {
while(true) { c=cameraGetter();p=presenceGetter();delay(1_000) }
}
Column {
Text("人脸检测调试",fontSize=13.sp)
Text("相机阶段:${when(c.stage) {
CameraStage.OFF->"关闭";CameraStage.MODEL_LOADING->"加载检测器";CameraStage.PROVIDER_WAIT->"等待相机服务"
CameraStage.WAITING_FRAME->"等待首帧";CameraStage.WAITING_RESULT->"等待首个分析结果"
CameraStage.READY->"结果就绪";CameraStage.FAILED->"失败"
}} · ${c.failure.name.lowercase()}",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)
Text("候选 ${p.pending?.wire ?: "none"} / ${p.pendingTtlMs}ms · 请求 ${p.active?.wire ?: "none"} · 本周期已消费 ${p.episodeConsumed}",fontSize=12.sp)
Text("发送 ${p.sent} · 接受 ${p.accepted} · 拒绝 ${p.rejected} · 取消 ${p.cancelled} · ${p.outcome.name.lowercase()}/${p.serverReason.name.lowercase()}",fontSize=12.sp)
}
}
@@ -1,32 +1,67 @@
package com.gorios.lanvoice.expression package com.gorios.lanvoice.expression
/** Fixed fields only. No image, coefficient, pose, free text, or user speech. */ /** Fixed fields only. No image, coefficient, pose, free text, or user speech. */
enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT } enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT,
MODEL_TIMEOUT, PROVIDER_TIMEOUT, FRAME_TIMEOUT, RESULT_TIMEOUT }
enum class CameraStage { OFF, MODEL_LOADING, PROVIDER_WAIT, WAITING_FRAME, WAITING_RESULT, READY, FAILED }
data class CameraAnalysisSnapshot( data class CameraAnalysisSnapshot(
val received: Int = 0, val processed: Int = 0, val failures: Int = 0, val received: Int = 0, val processed: Int = 0, val failures: Int = 0,
val faceCount: Int = 0, val cue: FaceCue = FaceCue.UNKNOWN, val faceCount: Int = 0, val cue: FaceCue = FaceCue.UNKNOWN,
val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE, val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE,
val lastProcessMs: Long = 0, val lastProcessMs: Long = 0,
val stage: CameraStage = CameraStage.OFF, val stageSinceMs: Long = 0,
val lastFrameMs: Long = -1, val lastResultMs: Long = -1, val recoveries: Int = 0,
) )
/** Deadlines use successful callbacks, never bind success as proof of a frame/result. */
fun cameraTimeout(s: CameraAnalysisSnapshot,now: Long): CameraFailure = when(s.stage) {
CameraStage.MODEL_LOADING -> if(now-s.stageSinceMs>=15_000) CameraFailure.MODEL_TIMEOUT else CameraFailure.NONE
CameraStage.PROVIDER_WAIT -> if(now-s.stageSinceMs>=8_000) CameraFailure.PROVIDER_TIMEOUT else CameraFailure.NONE
CameraStage.WAITING_FRAME -> if(now-s.stageSinceMs>=5_000) CameraFailure.FRAME_TIMEOUT else CameraFailure.NONE
CameraStage.WAITING_RESULT -> if(now-s.stageSinceMs>=5_000) CameraFailure.RESULT_TIMEOUT else CameraFailure.NONE
CameraStage.READY -> when {
now-s.lastFrameMs>=5_000 -> CameraFailure.FRAME_TIMEOUT
now-s.lastResultMs>=5_000 -> CameraFailure.RESULT_TIMEOUT
else -> CameraFailure.NONE
}
else -> CameraFailure.NONE
}
fun canRecoverFirstFrame(s: CameraAnalysisSnapshot,f: CameraFailure) =
f==CameraFailure.FRAME_TIMEOUT && s.received==0 && s.recoveries==0
/** Shared by actual provider/analyzer/result callbacks; a rebind or stop retires old callbacks. */
class CameraCallbackFence {
private val generation=java.util.concurrent.atomic.AtomicLong()
@Volatile private var alive=true
fun nextBinding(): Long { check(alive);return generation.incrementAndGet() }
fun invalidate() { generation.incrementAndGet() }
fun accepts(token: Long) = alive && token==generation.get()
fun close() { alive=false;invalidate() }
}
class CameraAnalysisDiagnostics { class CameraAnalysisDiagnostics {
private var state = CameraAnalysisSnapshot() private var state = CameraAnalysisSnapshot()
private var lastLogMs: Long? = null private var lastLogMs: Long? = null
@Synchronized fun received() { state = state.copy(received = (state.received + 1).coerceAtMost(1_000_000)) } @Synchronized fun stage(stage: CameraStage,now: Long) { state=state.copy(stage=stage,stageSinceMs=now) }
@Synchronized fun processed(count: Int, cue: FaceCueObservation, elapsedMs: Long) { @Synchronized fun recovering() { state=state.copy(recoveries=state.recoveries+1) }
@Synchronized fun received(now: Long=0) { state = state.copy(received = (state.received + 1).coerceAtMost(1_000_000),
lastFrameMs=now,stage=if(state.stage==CameraStage.WAITING_FRAME) CameraStage.WAITING_RESULT else state.stage,
stageSinceMs=if(state.stage==CameraStage.WAITING_FRAME) now else state.stageSinceMs) }
@Synchronized fun processed(count: Int, cue: FaceCueObservation, elapsedMs: Long,now: Long=0) {
state = state.copy(processed = (state.processed + 1).coerceAtMost(1_000_000), state = state.copy(processed = (state.processed + 1).coerceAtMost(1_000_000),
faceCount = count.coerceIn(0, 2), cue = cue.cue, reason = cue.reason, faceCount = count.coerceIn(0, 2), cue = cue.cue, reason = cue.reason,
lastProcessMs = elapsedMs.coerceIn(0, 60_000)) lastProcessMs = elapsedMs.coerceIn(0, 60_000),lastResultMs=now,stage=CameraStage.READY)
} }
@Synchronized fun failed(failure: CameraFailure) { @Synchronized fun failed(failure: CameraFailure) {
state = state.copy(failures = (state.failures + 1).coerceAtMost(1_000_000), failure = failure) state = state.copy(failures = (state.failures + 1).coerceAtMost(1_000_000), failure = failure,
stage=if(failure==CameraFailure.NO_RESULT) state.stage else CameraStage.FAILED)
} }
@Synchronized fun snapshot() = state @Synchronized fun snapshot() = state
@Synchronized fun summary(nowMs: Long, force: Boolean = false): String? { @Synchronized fun summary(nowMs: Long, force: Boolean = false): String? {
val last = lastLogMs val last = lastLogMs
if (!force && last != null && nowMs - last < 10_000) return null if (!force && last != null && nowMs - last < 10_000) return null
lastLogMs = nowMs lastLogMs = nowMs
return "camera analysis received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs}" return "camera analysis stage=${state.stage.name.lowercase()} received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs} recoveries=${state.recoveries}"
} }
} }
@@ -2,11 +2,29 @@ package com.gorios.lanvoice.expression
enum class PresenceKind(val wire: String) { ABSENT("absent"), APPEARED("appeared") } enum class PresenceKind(val wire: String) { ABSENT("absent"), APPEARED("appeared") }
data class PresenceTrigger(val kind: PresenceKind,val turn: Long,val ageMs: Long) data class PresenceTrigger(val kind: PresenceKind,val turn: Long,val ageMs: Long)
enum class PresenceObservation { UNKNOWN, PRESENT, ABSENT }
enum class PresenceBlock { DISABLED, CAMERA_INACTIVE, BACKGROUND, NOT_CONNECTED, VOICE_INACTIVE, UNSUPPORTED,
MUTED, WAITING_SAMPLE, STALE_SAMPLE, USER_SPEAKING, QUIET_WINDOW, TTS_BUSY, ACTION_BUSY, REQUEST_ACTIVE,
CONFIRMING, COOLDOWN, EPISODE_CONSUMED, PENDING, READY }
enum class PresenceOutcome { NONE, SENT, ACCEPTED, REJECTED, CANCELLED, COMPLETED, SEND_FAILED }
enum class PresenceServerReason { NONE, ACCEPTED, INVALID_FIELDS, OLD_ID, UNSUPPORTED, OLD_TURN,
NOT_LISTENING, BUSY, VOICE_OR_STALE_INPUT, COOLDOWN, CANCELLED, COMPLETED, FAILED, UNKNOWN_REQUEST, UNKNOWN }
data class PresenceDiagnosticsSnapshot(
val enabled: Boolean=false,val cameraActive: Boolean=false,val supported: Boolean=false,
val observation: PresenceObservation=PresenceObservation.UNKNOWN,val sampleAgeMs: Long=-1,
val absentElapsedMs: Long=0,val presentElapsedMs: Long=0,val pending: PresenceKind?=null,
val pendingTtlMs: Long=0,val episodeConsumed: Boolean=false,val returnArmed: Boolean=false,
val cooldownMs: Long=0,val block: PresenceBlock=PresenceBlock.DISABLED,
val active: PresenceKind?=null,val requestId: Long=0,val outcome: PresenceOutcome=PresenceOutcome.NONE,
val serverReason: PresenceServerReason=PresenceServerReason.NONE,
val sent: Int=0,val accepted: Int=0,val rejected: Int=0,val cancelled: Int=0,
)
/** Local booleans only; called on main with monotonic successful sample times. */ /** Local booleans only; called on main with monotonic successful sample times. */
class PresenceRules(private val absentMs: Long=20_000,private val confirmMs: Long=1_000) { class PresenceRules(private val absentMs: Long=20_000,private val confirmMs: Long=1_000) {
init { require(absentMs in 5_000..600_000 && confirmMs==1_000L) } init { require(absentMs in 5_000..600_000 && confirmMs==1_000L) }
private var last: Long?=null private var last: Long?=null
private var observation=PresenceObservation.UNKNOWN
private var absentSince: Long?=null private var absentSince: Long?=null
private var presentSince: Long?=null private var presentSince: Long?=null
private var absentAttempted=false private var absentAttempted=false
@@ -15,13 +33,22 @@ class PresenceRules(private val absentMs: Long=20_000,private val confirmMs: Lon
private var pending: Pending?=null private var pending: Pending?=null
fun discardPending() { pending=null } fun discardPending() { pending=null }
fun reset() { breakContinuity();absentAttempted=false } fun reset() { breakContinuity();absentAttempted=false }
private fun breakContinuity() { last=null;absentSince=null;presentSince=null;returnArmed=false;pending=null } private fun breakContinuity() { last=null;observation=PresenceObservation.UNKNOWN;absentSince=null;presentSince=null;returnArmed=false;pending=null }
fun snapshot(now: Long): PresenceDiagnosticsSnapshot {
val age=last?.let { (now-it).coerceAtLeast(0) } ?: -1
return PresenceDiagnosticsSnapshot(observation=if(age in 0..350) observation else PresenceObservation.UNKNOWN,
sampleAgeMs=age,absentElapsedMs=absentSince?.let { (last!!-it).coerceAtLeast(0) } ?: 0,
presentElapsedMs=presentSince?.let { (last!!-it).coerceAtLeast(0) } ?: 0,
pending=pending?.takeIf { now<it.until }?.kind,pendingTtlMs=pending?.let { (it.until-now).coerceAtLeast(0) } ?: 0,
episodeConsumed=absentAttempted,returnArmed=returnArmed)
}
fun sample(present: Boolean?,now: Long,turn: Long,idle: Boolean, fun sample(present: Boolean?,now: Long,turn: Long,idle: Boolean,
absentInFlight: Boolean=false,appearedAllowedAt: Long=0): PresenceTrigger? { absentInFlight: Boolean=false,appearedAllowedAt: Long=0): PresenceTrigger? {
val old=last val old=last
if(present==null || old!=null && now<=old) { breakContinuity();return null } if(present==null || old!=null && now<=old) { breakContinuity();return null }
if(old!=null && now-old>350) breakContinuity() if(old!=null && now-old>350) breakContinuity()
last=now last=now
observation=if(present) PresenceObservation.PRESENT else PresenceObservation.ABSENT
if(!present) { if(!present) {
presentSince=null presentSince=null
if(pending?.kind==PresenceKind.APPEARED) pending=null if(pending?.kind==PresenceKind.APPEARED) pending=null
+36
View File
@@ -0,0 +1,36 @@
# 0.7.6 人脸与 presence 诊断、相机就绪恢复
本轮针对用户0.7.5「以前人脸检测很敏感,现在看不到信息」反馈施工;不实施720×1280,不导入新素材。基线d0c1d7eb3d4ece9c8b8ad9dc5c66225244b54d39,旧pin987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887。
## 已知证据与未确定原因
原设置页只展示最后10条会话日志,相机分析摘要直接进入DiagnosticLog/上传,不在该列表。原报告已有camera_analysis和face_transmission;presence状态没有独立快照,门禁拒绝原因在客户端仅记录「rejected_or_cancelled」。UNKNOWN和部分ABSENT都显示「尚无结果」,CameraX bind成功即宣告ACTIVE,没有等首帧或首次推理结果。
2026-10-13上海16:48:02–16:49:42网关安全metadata窗口持续received=0/processed=0/failure=none,16:49:43相机关闭。该窗口表明某次相机没有帧进入analyzer,不证明FaceLandmarker检测阈值退化;/debug/report当时及本次施工前均count0,缺少当次versionCode映射。尚不能确认该设备零帧的CameraX/系统底层原因,不把宿主测试宣称成真机修复。
## 变更
- 设置页独立人脸调试面板,仅在sheet展开时每秒读取快照;不以事件是否发送、最近日志是否被覆盖作为有无检测的依据。不创建/重启相机、播放器或连接。显示阶段/帧数/分析次数/人脸数/耗时/恢复次数,presence本地有无脸、采样年龄、缺人/有人持续时间、冷却、候选TTL、active请求、计数及固定enum原因。
- 报告新增顶层presence结构,camera_analysis新增stage、阶段耗时、最后frame/result年龄及recoveries;字段为布尔/数字/固定enum,无照片、landmarks、脸系数、聊天、提示词、原始异常。presence摘要最多10s一次,保既有500ring;服务端拒绝reason以有限枚举保留,未知值归unknown。
- 明确「等待分析结果」与「未检测到人脸」。CameraX绑定成功仅进入等待首帧,真实detectForVideo返回有效结果(零脸也有效)才设ACTIVE。UNKNOWN/无返回不当作ABSENT。
- 有界看门:模型15s、provider8s、首帧5s、首结果5s;就绪后帧或结果连续5s停滞报告对应固定失败。只有首次收到0帧的frame_timeout可自动重绑一次,复用同一模型和executor,仅解绑本角色ImageAnalysis;再次失败显示不可用及手动重开提示,不无限循环。恢复/停止会退役旧provider/analyzer/result callback generation,旧ImageProxy仍finally关闭;后台/离线原停止规则保留。
- 检测器、CPU delegate、0.5阈值、100ms采样、640×480分析请求及表情判定未改。TTS/用户讲话/舞蹈期间继续检测与计时,但忙时不发起主动轮;5sTTL、跨轮丢弃、用户barge-in优先、absent期间出现不补招呼均原样。
- 此次仅Android,gateway0.8.1源码/配置/部署无变、不重启服务;时间/provider/TTS音色与参数不动,旧资产、嘴幅、APK保留。
## 验证和交付边界
生产相机诊断/期限函数测试覆盖deadline边界、无首帧和无结果区分、一次恢复上限、READY后停滞、OFF/FAILED不再恢复;实际callback fence测试覆盖重绑与停止后的旧epoch拒绝。生产VoiceSession回放验证默认off、相机未active、stale sample、发送/接受计数、重复accepted不重复计数、TTS/drain和VAD取消;采样快照只读,不消费episode。
发布前重跑9 JVM/UI、包装与gateway归档回归;保旧5包200项GLES(shader/harness未改),实际APK字节loader/媒体callback回放;Gradle编译instrumentation。全部是宿主或编译证据,CameraX出帧、相机恢复、真实检测灵敏度及手机GPU/耗电未测。新的APK目标0.7.6/code24,正式SHA及实际结果发布后追加;代码owner不安装、不开启手机mic/cam。
Coord有限验证:正常启动后展开gear设置,看相机阶段→帧数增长→分析次数增长;已授权但0帧应显示等待首帧,最多一次恢复后有明确失败,不再无限「尚无结果」。检测成功时分别观察有人/无脸及presence计时;TTS时帧数仍增长但门禁tts_busy/request_active,用户讲话门禁user_speaking;关开关、相机、后台/熄屏不发起主动轮。通过设置发送一份含code24的报告可区分model/provider/frame/result故障;无须读上传聊天、音脸原数据。
## 实际交付
- Android0.7.6/code24:http://192.168.31.124:8080/lan-voice-v076-face-diagnostics-code24-arm64-debug.apk
- APK SHA256:`d730084c0c86453b1a4eced83e1bb76e72b93b44e5aa5c9303f63607f93f36b7`,`.apk.sha256`同路径。HTTP字节已核;同debug证书`b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`,com.gorios.lanvoice、arm64、min26/target34。
- 全部3819个APK assets(包含检测模型及3818个avatar文件)与code23逐字节相同;3222runtime引用不变。无生成调用、无新模型或素材导入。
- 最终9 JVM/UI通过、1410presence采样断言及生产会话回调回放、34包装测试;gateway只读canonical源SHA一致并110 passed+1既有Silero模型归档排除skip,无部署/重启。五包200项旧离线GLES证据与未变shader/harness哈希一致。
- 新APK生产loader/媒体callback回放通过(Android/Surface/录音确认doubles);实际APK后台加载cold/receipt路径均main_asset_reads=0。Gradle assemble及instrumentation Kotlin编译通过,instrumentation运行及code24真机出帧/恢复/灵敏度/性能均未测。不能据此称手机零帧底层根因已修好。
- 忽略目录证据:logs/action-emotion/face-diagnostics-076/、face-diagnostics-076-release/,无日志/报告/密钥/图片视频入Git。代码提交作者zenord <zenord@email.com>,实际commit随最终回复并核main。
+10 -8
View File
@@ -302,7 +302,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)]) 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): 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):
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']), 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') 'live emotion release needs bridge-own TALK runtimes')
tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift') tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
@@ -310,6 +310,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
if requested is not None: if requested is not None:
require(requested>=version,'version code occupied');version=requested require(requested>=version,'version code occupied');version=requested
require(not full or version>=18,'full candidate needs code >=18') require(not full or version>=18,'full candidate needs code >=18')
require(not face_diagnostics_fix or presence_candidate and version>=24,'face diagnostics needs presence and fresh code >=24')
require(not presence_candidate or startup_fix and version>=23,'presence candidate needs startup and fresh code >=23') require(not presence_candidate or startup_fix and version>=23,'presence candidate needs startup and fresh code >=23')
require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape') require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape')
if startup_fix: if startup_fix:
@@ -319,9 +320,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') 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', subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN, '-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()],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()],check=True,cwd=ROOT)
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
version_name='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.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'"): 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(text in badge,'APK metadata: '+text)
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI') require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
@@ -341,8 +342,8 @@ 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') 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') 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') 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='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='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='v075' if presence_candidate else 'v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070' release='v076' if face_diagnostics_fix else 'v075' if presence_candidate else 'v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070'
artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk' 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) with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode() digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
@@ -356,7 +357,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'], '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, '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':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,'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,'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') (output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
return delivery return delivery
@@ -377,8 +378,9 @@ def main():
parser.add_argument('--playback-clock-fix',action='store_true',help='0.7.3 Android MediaPlayer-output clock fix; exact frozen avatar bytes') parser.add_argument('--playback-clock-fix',action='store_true',help='0.7.3 Android MediaPlayer-output clock fix; exact frozen avatar bytes')
parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap') parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap')
parser.add_argument('--presence-candidate',action='store_true',help='0.7.5 presence-triggered assistant turns, frozen runtime and startup assets') parser.add_argument('--presence-candidate',action='store_true',help='0.7.5 presence-triggered assistant turns, frozen runtime and startup assets')
parser.add_argument('--face-diagnostics-fix',action='store_true',help='0.7.6 local camera readiness/recovery and presence diagnostics; frozen assets')
args=parser.parse_args(); args=parser.parse_args();
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate))<=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))<=1,'choose one build purpose')
manifest=args.manifest.resolve(strict=True);output=args.output.resolve() 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') 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') 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')
@@ -395,7 +397,7 @@ def main():
require(not args.previous_pin and not args.backup,'previous import report required') require(not args.previous_pin and not args.backup,'previous import report required')
import_files(manifest.parent,report['files'],target) 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') (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,args.presence_candidate) 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,args.presence_candidate or args.face_diagnostics_fix,args.face_diagnostics_fix) if args.publish else {k:v for k,v in report.items() if k!='files'}
print(json.dumps(result,indent=2)) print(json.dumps(result,indent=2))
+32 -1
View File
@@ -1,6 +1,37 @@
import com.gorios.lanvoice.expression.* import com.gorios.lanvoice.expression.*
fun main() { fun main() {
val fence=CameraCallbackFence()
val initial=fence.nextBinding()
check(fence.accepts(initial))
fence.invalidate();check(!fence.accepts(initial))
val recovered=fence.nextBinding()
check(fence.accepts(recovered) && !fence.accepts(initial))
fence.close();check(!fence.accepts(recovered))
check(runCatching { fence.nextBinding() }.isFailure)
val boot=CameraAnalysisDiagnostics()
boot.stage(CameraStage.MODEL_LOADING,100)
check(cameraTimeout(boot.snapshot(),15099)==CameraFailure.NONE)
check(cameraTimeout(boot.snapshot(),15100)==CameraFailure.MODEL_TIMEOUT)
boot.stage(CameraStage.PROVIDER_WAIT,20000)
check(cameraTimeout(boot.snapshot(),28000)==CameraFailure.PROVIDER_TIMEOUT)
boot.stage(CameraStage.WAITING_FRAME,30000)
check(cameraTimeout(boot.snapshot(),34999)==CameraFailure.NONE)
check(canRecoverFirstFrame(boot.snapshot(),cameraTimeout(boot.snapshot(),35000)))
boot.recovering();boot.stage(CameraStage.WAITING_FRAME,35000)
check(!canRecoverFirstFrame(boot.snapshot(),cameraTimeout(boot.snapshot(),40000)))
boot.received(39000)
check(boot.snapshot().stage==CameraStage.WAITING_RESULT)
check(cameraTimeout(boot.snapshot(),44000)==CameraFailure.RESULT_TIMEOUT)
boot.processed(0,FaceCueObservation(reason=FaceCueReason.NO_FACE),10,40000)
check(boot.snapshot().stage==CameraStage.READY && boot.snapshot().processed==1)
check(cameraTimeout(boot.snapshot(),44000)==CameraFailure.FRAME_TIMEOUT)
boot.received(44500)
check(cameraTimeout(boot.snapshot(),45000)==CameraFailure.RESULT_TIMEOUT)
boot.stage(CameraStage.OFF,45000)
check(cameraTimeout(boot.snapshot(),100000)==CameraFailure.NONE)
boot.failed(CameraFailure.FRAME_TIMEOUT)
check(cameraTimeout(boot.snapshot(),100000)==CameraFailure.NONE)
val camera = CameraAnalysisDiagnostics() val camera = CameraAnalysisDiagnostics()
check(camera.snapshot().reason == FaceCueReason.NO_FRAME) check(camera.snapshot().reason == FaceCueReason.NO_FRAME)
var summaries = 0 var summaries = 0
@@ -29,5 +60,5 @@ fun main() {
send.record(FaceSendReason.STALE) send.record(FaceSendReason.STALE)
check(send.snapshot().attempts == 3 && send.snapshot().sent == 1 && send.snapshot().clears == 1 && send.snapshot().failures == 1) check(send.snapshot().attempts == 3 && send.snapshot().sent == 1 && send.snapshot().clears == 1 && send.snapshot().failures == 1)
check(send.summary(0) != null && send.summary(9999) == null && send.summary(10000) != null) check(send.summary(0) != null && send.summary(9999) == null && send.summary(10000) != null)
println("PASS: enum-only camera/frame/send snapshots, failure counters, 10s rate bound, no-face/stable/stale/clear accounting") println("PASS: production camera readiness deadlines/one bounded first-frame recovery/no-frame vs no-result/stale/stop; enum-only counters and 10s summaries")
} }
+11
View File
@@ -7,6 +7,17 @@ spec=importlib.util.spec_from_file_location('presence_package',ROOT/'scripts/pac
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack) pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
class PresencePackageTests(unittest.TestCase): class PresencePackageTests(unittest.TestCase):
def test_face_diagnostics_release_preserves_startup_and_presence_and_uses_new_code(self):
def stop_build(command,**kwargs):
if command[0]=='python3':return
self.assertIn('-PfaceDiagnosticsFix=true',command)
self.assertIn('-PpresenceCandidate=true',command)
self.assertIn('-PavatarStartupFix=true',command)
self.assertIn('-PactionVersionCode=24',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}]}),patch.object(pack,'next_version',return_value=24),patch.object(pack.subprocess,'run',side_effect=stop_build):
with self.assertRaises(ValueError):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,24,full=True,startup_fix=True,face_diagnostics_fix=True)
with self.assertRaisesRegex(RuntimeError,'build_sentinel'):pack.publish({'manifest_sha256':pack.RUNTIME_FIX_PIN},None,24,full=True,startup_fix=True,presence_candidate=True,face_diagnostics_fix=True)
def test_fresh_presence_version_requires_startup_and_frozen_pack(self): def test_fresh_presence_version_requires_startup_and_frozen_pack(self):
report={'manifest_sha256':pack.RUNTIME_FIX_PIN} report={'manifest_sha256':pack.RUNTIME_FIX_PIN}
def stop_build(command,**kwargs): def stop_build(command,**kwargs):
+16
View File
@@ -9,6 +9,10 @@ fun presenceCheck() {
val rules=PresenceRules() val rules=PresenceRules()
for(t in 0L..19_900L step 100) expect(rules.sample(false,t,1,true)==null) for(t in 0L..19_900L step 100) expect(rules.sample(false,t,1,true)==null)
expect(rules.sample(false,19_999,1,true)==null) expect(rules.sample(false,19_999,1,true)==null)
val before=rules.snapshot(19_999)
expect(before.observation==PresenceObservation.ABSENT && before.absentElapsedMs==19_999L)
expect(rules.snapshot(20_400).observation==PresenceObservation.UNKNOWN)
expect(rules.snapshot(19_999).absentElapsedMs==19_999L) // Snapshot never consumes an episode or changes clocks.
expect(rules.sample(false,20_000,1,true)?.kind==PresenceKind.ABSENT) expect(rules.sample(false,20_000,1,true)?.kind==PresenceKind.ABSENT)
for(t in 20_100L..45_000L step 100) expect(rules.sample(false,t,1,true)==null) for(t in 20_100L..45_000L step 100) expect(rules.sample(false,t,1,true)==null)
expect(rules.sample(true,45_100,1,true)==null) expect(rules.sample(true,45_100,1,true)==null)
@@ -53,7 +57,13 @@ private fun checkPresenceSessionCallbacks() {
eventMethod.invoke(session,ServerEvent(if(kind==EventKind.PRESENCE) "presence.status" else kind.name.lowercase(),kind,Payload(turn=turn,reason=reason,state=state,fields=fields))) eventMethod.invoke(session,ServerEvent(if(kind==EventKind.PRESENCE) "presence.status" else kind.name.lowercase(),kind,Payload(turn=turn,reason=reason,state=state,fields=fields)))
} }
session.startVoice();event(EventKind.HELLO,1,mapOf("presence_greeting_version" to 1)) session.startVoice();event(EventKind.HELLO,1,mapOf("presence_greeting_version" to 1))
check(session.presenceDiagnosticsSnapshot().block==PresenceBlock.DISABLED)
session.setPresence(true,false)
check(session.presenceDiagnosticsSnapshot().block==PresenceBlock.CAMERA_INACTIVE)
session.setPresence(true,true) session.setPresence(true,true)
field("lastSpeechAt",android.os.SystemClock.elapsedRealtime()-1000)
session.observePresence(false,android.os.SystemClock.elapsedRealtime()-500)
check(session.presenceDiagnosticsSnapshot().block==PresenceBlock.STALE_SAMPLE)
fun primeAndSend(): Long { fun primeAndSend(): Long {
val now=android.os.SystemClock.elapsedRealtime() val now=android.os.SystemClock.elapsedRealtime()
val rules=get("presenceRules") as PresenceRules val rules=get("presenceRules") as PresenceRules
@@ -65,16 +75,21 @@ private fun checkPresenceSessionCallbacks() {
return sent.split('/')[1].toLong() return sent.split('/')[1].toLong()
} }
val id=primeAndSend() val id=primeAndSend()
check(session.presenceDiagnosticsSnapshot().outcome==PresenceOutcome.SENT && session.presenceDiagnosticsSnapshot().sent==1)
event(EventKind.ABORT,2,mapOf("request_id" to id),reason="presence_greeting") event(EventKind.ABORT,2,mapOf("request_id" to id),reason="presence_greeting")
event(EventKind.PRESENCE,2,mapOf("request_id" to id),state="accepted") event(EventKind.PRESENCE,2,mapOf("request_id" to id),state="accepted")
event(EventKind.PRESENCE,2,mapOf("request_id" to id),state="accepted")
check(session.presenceDiagnosticsSnapshot().accepted==1)
check(states.last().turnId==2L && get("presenceRequest")!=null) check(states.last().turnId==2L && get("presenceRequest")!=null)
event(EventKind.TTS,2,state="start") event(EventKind.TTS,2,state="start")
val frames=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true } val frames=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
frames.invoke(session,DownlinkFrame(2)) frames.invoke(session,DownlinkFrame(2))
check(states.last().phase==VoicePhase.ANSWERING) check(states.last().phase==VoicePhase.ANSWERING)
check(session.presenceDiagnosticsSnapshot().block==PresenceBlock.REQUEST_ACTIVE)
checkNotNull(AudioPlayback.lastDrained)(2,0);Handler.drain();check(get("presenceRequest")==null) checkNotNull(AudioPlayback.lastDrained)(2,0);Handler.drain();check(get("presenceRequest")==null)
val id2=primeAndSend();session.setPresence(false,true) val id2=primeAndSend();session.setPresence(false,true)
check(socket.sent.count { it=="presence_cancel/$id2" }==1) check(socket.sent.count { it=="presence_cancel/$id2" }==1)
check(session.presenceDiagnosticsSnapshot().cancelled==1)
val before=AudioPlayback.enqueued val before=AudioPlayback.enqueued
event(EventKind.ABORT,3,mapOf("request_id" to id2),reason="presence_greeting") event(EventKind.ABORT,3,mapOf("request_id" to id2),reason="presence_greeting")
frames.invoke(session,DownlinkFrame(3));check(AudioPlayback.enqueued==before) frames.invoke(session,DownlinkFrame(3));check(AudioPlayback.enqueued==before)
@@ -83,5 +98,6 @@ private fun checkPresenceSessionCallbacks() {
session.setPresence(true,true);val id3=primeAndSend() session.setPresence(true,true);val id3=primeAndSend()
event(EventKind.VAD,4,mapOf("event" to Payload(fields=mapOf("type" to "speech.start")))) event(EventKind.VAD,4,mapOf("event" to Payload(fields=mapOf("type" to "speech.start"))))
check(get("presenceRequest")==null && socket.sent.any { it=="presence_cancel/$id3" }) check(get("presenceRequest")==null && socket.sent.any { it=="presence_cancel/$id3" })
check(session.presenceDiagnosticsSnapshot().block==PresenceBlock.USER_SPEAKING)
session.background();session.release();Handler.drain() session.background();session.release();Handler.drain()
} }