Fix Liam waiting rotation and capability ready acknowledgement

This commit is contained in:
zenord
2026-10-15 10:41:23 +08:00
parent 654630dea5
commit f705c27eee
13 changed files with 426 additions and 34 deletions
@@ -209,10 +209,49 @@ class VoiceSession(
)
init { waitingPlayer?.waitingListener(::offerPose) }
private fun waitingSafe()=isActive() && hasTurn && blockedTurn!=currentTurn && !poseActive && !actions.active && !presenceSpeech &&
presenceRequest==null && state.phase==VoicePhase.LISTENING && capturing && !state.microphoneMuted &&
preparedPlaybackTurn?.let { drainedTurn!=it }!=true && talkPreparing==null &&
SystemClock.elapsedRealtime()-lastSpeechAt>=800
private enum class WaitingBlock {
DISABLED, RELEASED, BACKGROUND, DISCONNECTED, VOICE_INACTIVE, NO_TURN, BLOCKED_TURN,
POSE_OWNER, ACTION_OWNER, USER_SPEAKING, PRESENCE_REQUEST, NOT_LISTENING, MUTED,
CAPTURE_INACTIVE, PLAYBACK_PENDING, TALK_PREPARING, QUIET_WINDOW, READY
}
private var waitingLogged: WaitingBlock?=null
private var waitingLoggedAt=Long.MIN_VALUE
private fun waitingBlock(): WaitingBlock = when {
waitingPlayer?.waitingContract!=true -> WaitingBlock.DISABLED
released -> WaitingBlock.RELEASED
!foreground -> WaitingBlock.BACKGROUND
state.connection!=ConnectionStatus.CONNECTED -> WaitingBlock.DISCONNECTED
!state.voiceActive -> WaitingBlock.VOICE_INACTIVE
!hasTurn -> WaitingBlock.NO_TURN
blockedTurn==currentTurn -> WaitingBlock.BLOCKED_TURN
poseActive -> WaitingBlock.POSE_OWNER
actions.active -> WaitingBlock.ACTION_OWNER
presenceSpeech -> WaitingBlock.USER_SPEAKING
presenceRequest!=null -> WaitingBlock.PRESENCE_REQUEST
state.phase!=VoicePhase.LISTENING -> WaitingBlock.NOT_LISTENING
state.microphoneMuted -> WaitingBlock.MUTED
!capturing -> WaitingBlock.CAPTURE_INACTIVE
preparedPlaybackTurn?.let { drainedTurn!=it }==true -> WaitingBlock.PLAYBACK_PENDING
talkPreparing!=null -> WaitingBlock.TALK_PREPARING
SystemClock.elapsedRealtime()-lastSpeechAt<800 -> WaitingBlock.QUIET_WINDOW
else -> WaitingBlock.READY
}
private fun waitingSafe()=waitingBlock()==WaitingBlock.READY
private fun refreshWaitingEligibility() {
val block=waitingBlock();waitingPlayer?.waitingEligible(block==WaitingBlock.READY)
if(waitingPlayer?.waitingContract!=true) return
val now=SystemClock.elapsedRealtime()
if(block!=waitingLogged || now-waitingLoggedAt>=10_000) {
waitingLogged=block;waitingLoggedAt=now
val message="enabled=true eligible=${block==WaitingBlock.READY} block=${block.name.lowercase()} turn=$currentTurn has_turn=$hasTurn phase=${state.phase.name.lowercase()} capture=$capturing capture_frame=${state.captureActive} muted=${state.microphoneMuted} quiet_ms=${(now-lastSpeechAt).coerceIn(0,600_000)}"
com.gorios.lanvoice.diag.DiagnosticLog.record("waiting_gate",message)
Log.i("LanVoiceWaiting",message)
}
}
private fun waitingDiagnostic(message: String) {
diagnostic(message)
Log.i("LanVoiceWaiting",message)
}
private fun offerPose(pose: WaitingPose) {
if(!waitingSafe()) { waitingPlayer?.cancelWaitingPose {};return }
@@ -221,19 +260,19 @@ class VoiceSession(
cancelPresence(reset=true);captureEpoch++;capturing=false
playback.interrupt()
update(state.copy(waitingPoseActive=true,captureActive=false,playbackActivity=null,playbackRunning=false))
diagnostic("waiting state=capture_stop_pending pose=${pose.id} epoch=$token")
waitingDiagnostic("waiting state=capture_stop_pending pose=${pose.id} epoch=$token")
poseTimeout=Runnable { if(token==poseEpoch && poseActive) stopVoice(cancelReason="pose_capture_timeout") }
.also { main.postDelayed(it,5_000) }
capture.stopAndConfirm { stopped -> main.post {
if(token!=poseEpoch || !poseActive || !isActive()) return@post
poseTimeout?.let { main.removeCallbacks(it) };poseTimeout=null
diagnostic("waiting state=${if(stopped) "capture_stopped" else "capture_failed"} pose=${pose.id} epoch=$token")
waitingDiagnostic("waiting state=${if(stopped) "capture_stopped" else "capture_failed"} pose=${pose.id} epoch=$token")
if(!stopped) { stopVoice(cancelReason="pose_capture_failed");return@post }
waitingPlayer?.playWaitingPose(pose,{ main.post {
if(token==poseEpoch && poseActive && isActive()) {
poseEpoch++;poseActive=false
update(state.copy(waitingPoseActive=false))
diagnostic("waiting state=restored_idle pose=${pose.id} epoch=$token")
waitingDiagnostic("waiting state=restored_idle pose=${pose.id} epoch=$token")
if(dialogue.listen(true)) { update(state.copy(phase=VoicePhase.LISTENING));startCapture() }
else stopVoice(cancelReason="pose_resume_failed")
}
@@ -517,7 +556,7 @@ class VoiceSession(
if (clearObservation) faceCue = FaceCueObservation()
}
val runtimeProtocolState: String get() = "hello=${dialogue.actionNegotiation} connection=${state.connection.name.lowercase()} turn=$currentTurn drained=$drainedTurn action=${actions.active} capture=$capturing capture_epoch=$captureEpoch presence=$presenceEnabled/$presenceCamera/$presenceSupported/${presenceRequest?.kind?.wire ?: "none"}"
val runtimeProtocolState: String get() = "hello=${dialogue.actionNegotiation} connection=${state.connection.name.lowercase()} turn=$currentTurn drained=$drainedTurn action=${actions.active} capture=$capturing capture_epoch=$captureEpoch presence=$presenceEnabled/$presenceCamera/$presenceSupported/${presenceRequest?.kind?.wire ?: "none"} waiting_enabled=${waitingPlayer?.waitingContract==true} waiting_block=${waitingBlock().name.lowercase()}"
fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot()
private fun sendFaceContext() {
@@ -592,7 +631,7 @@ class VoiceSession(
onFrame = { pcm ->
main.post {
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive() && !poseActive) {
waitingPlayer?.waitingEligible(waitingSafe())
refreshWaitingEligibility()
// First real recorder frame, rather than a listen command or permission.
if(!state.captureActive) update(state.copy(captureActive = true))
if (dialogue.sendAudio(pcm, captureTurn, sequence)) {
@@ -898,7 +937,7 @@ class VoiceSession(
val changed = state.replyEmotion != next.replyEmotion
state = next
onState(next)
waitingPlayer?.waitingEligible(waitingSafe())
refreshWaitingEligibility()
if (changed) emotionObserver.onReplyEmotion(next.replyEmotion)
}
private fun checkMainThread() {
@@ -32,6 +32,17 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
override val waitingContract get()=index.waiting!=null
private var offerWaiting: (WaitingPose)->Unit={}
private var waitingEnabled=false
private var waitingChoiceKind="none"
private var waitingChoiceId="none"
// Derive only existing neutral packages with reviewed own-mouth routes both ways.
// The index/pin and all media bytes remain unchanged.
private val waitingIdlePackages=index.waiting?.let { config ->
listOf(config.idlePackage)+index.visuals.filter { p ->
p.id!=config.idlePackage && p.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL && p.approvedEdges &&
index.edges.any { it.from==config.idlePackage && it.to==p.id && it.mouthRuntime!=null } &&
index.edges.any { it.from==p.id && it.to==config.idlePackage && it.mouthRuntime!=null }
}.map { it.id }
}.orEmpty()
private var queuedPose: WaitingPose?=null
private var heldPose: WaitingPose?=null
private var pose: WaitingPose?=null
@@ -120,8 +131,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private var musicPresented=false
private var ignoredCallbacks=0L
/** Fixed metadata only; frames are sampled in reports, never logged per callback. */
val diagnosticState: String get() = "owner=${layerOwner.name.lowercase()} turn=$turn seq=$seq gen=$generation epoch=$musicEpoch requested=${selection?.selectedEmotion?.wire ?: "unset"} selected=$selectedId visual=${currentPackageId ?: "none"} edge=${edge?.id ?: "none"} idle_goal=${idleTarget ?: "none"} cycles=$idleCycles/$idleCycleGoal talk=$talk pose=${pose?.id ?: heldPose?.id ?: "none"} pose_stage=${if(poseReturning) "restoring" else if(poseStarted) "playing" else if(pose!=null) "preparing" else if(heldPose!=null) "capture_barrier" else "none"} speech_gate=$speechRequested action=${when { returning -> "returning";musicPresented -> "presented";actionStarted -> "await_frame";action!=null -> "routing";else -> "none" }} ignored=$ignoredCallbacks frame=${visible?.key?.index ?: -1} loop=${visible?.key?.loopOrdinal ?: -1} pts=${visible?.key?.ptsUs ?: -1}"
val diagnosticSignature: String get() = "$layerOwner/$turn/$seq/$generation/$selectedId/${visible?.packageId}/${edge?.id}/$idleTarget/$talk/$actionStarted/$returning/$musicPresented/$active/${pose?.id}/$poseReturning/$speechRequested"
val diagnosticState: String get() = "owner=${layerOwner.name.lowercase()} turn=$turn seq=$seq gen=$generation epoch=$musicEpoch requested=${selection?.selectedEmotion?.wire ?: "unset"} selected=$selectedId visual=${currentPackageId ?: "none"} edge=${edge?.id ?: "none"} idle_goal=${idleTarget ?: "none"} cycles=$idleCycles/$idleCycleGoal talk=$talk pose=${pose?.id ?: heldPose?.id ?: "none"} pose_stage=${if(poseReturning) "restoring" else if(poseStarted) "playing" else if(pose!=null) "preparing" else if(heldPose!=null) "capture_barrier" else "none"} speech_gate=$speechRequested action=${when { returning -> "returning";musicPresented -> "presented";actionStarted -> "await_frame";action!=null -> "routing";else -> "none" }} waiting_policy=${index.waiting!=null} waiting_enabled=$waitingEnabled choice_kind=$waitingChoiceKind choice_id=$waitingChoiceId ignored=$ignoredCallbacks frame=${visible?.key?.index ?: -1} loop=${visible?.key?.loopOrdinal ?: -1} pts=${visible?.key?.ptsUs ?: -1}"
val diagnosticSignature: String get() = "$layerOwner/$turn/$seq/$generation/$selectedId/${visible?.packageId}/${edge?.id}/$idleTarget/$talk/$actionStarted/$returning/$musicPresented/$active/${pose?.id}/$poseReturning/$speechRequested/$waitingEnabled/$waitingChoiceKind/$waitingChoiceId"
private var musicEpoch=0L
private var closing=0
private val releaseWaiters=mutableListOf<()->Unit>()
@@ -230,14 +241,25 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private fun chooseIdleAtLoopEnd(slot: Slot,key: BodyFrameKey,previous: BodyFrameKey?) {
if(index.waiting!=null) {
if(!waitingEnabled || pose!=null || action!=null || speechRequested || talk || inBridge || edge!=null ||
revealing!=null || key==previous || key.index!=slot.pack.body.frameCount-1 || slot.packageId!=index.waiting.idlePackage) return
revealing!=null || queuedPose!=null || idleTarget?.let { it!=slot.packageId }==true ||
key==previous || key.index!=slot.pack.body.frameCount-1 || slot.packageId !in waitingIdlePackages) return
idleCycles++
if(idleCycles>=idleCycleGoal) {
resetIdleCycles()
val picked=chooseIdle(index.waiting.poses.size+1)
check(picked in 0..index.waiting.poses.size)
queuedPose=if(picked==0) null else index.waiting.poses[picked-1]
report("waiting_choice_${queuedPose?.id ?: "idle"}",key)
val count=waitingIdlePackages.size+index.waiting.poses.size
val picked=chooseIdle(count);check(picked in 0 until count)
if(picked<waitingIdlePackages.size) {
queuedPose=null;idleTarget=waitingIdlePackages[picked]
waitingChoiceKind=if(idleTarget==index.waiting.idlePackage) "idle" else "variant"
waitingChoiceId=checkNotNull(idleTarget)
} else {
queuedPose=index.waiting.poses[picked-waitingIdlePackages.size]
// A pose is authored against idle frame0. A variant must first
// finish its real return bridge, never jump directly into the pose.
idleTarget=index.waiting.idlePackage
waitingChoiceKind="pose";waitingChoiceId=checkNotNull(queuedPose).id
}
report("waiting_choice_$waitingChoiceId",key)
}
return
}
@@ -276,7 +298,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
return
}
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else index.waiting?.let {
if(speechRequested) it.talkPackage else it.idlePackage
if(speechRequested) it.talkPackage else idleTarget ?: it.idlePackage
} ?: idleTarget ?: selectedId
var reviewedLoop: ConversationEdge?=null
if(source.packageId==wanted) {
@@ -86,7 +86,10 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
}
},{ phase,key ->
driver?.let { value -> DiagnosticLog.state("avatar_media", value.diagnosticSignature,
"event=$phase layer=${visibleLayer ?: -1} ${value.diagnosticState}") }
"event=$phase layer=${visibleLayer ?: -1} ${value.diagnosticState}")
if(phase.startsWith("waiting_choice_") || phase.startsWith("pose_") && key?.index==0)
android.util.Log.i("LanVoiceWaiting","event=$phase ${value.diagnosticState}")
}
report(VideoPresentation(actual=phase,reason="reviewed_media_path",
clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) },holdInitial=startupHold)
driver=current;main.removeCallbacks(summary);main.postDelayed(summary,10_000);current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie()
@@ -110,10 +110,9 @@ object DialogueProtocol {
val payload = JSONObject(text)
val type = payload.opt("type") as? String
require(!type.isNullOrBlank()) { "Event is missing a string type" }
val kind = if (type.startsWith("reply.emotion.prepare")) EventKind.EXPRESSION_PREPARE else if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
val kind = if (type=="client.capabilities") EventKind.CAPABILITIES else if (type.startsWith("reply.emotion.prepare")) EventKind.EXPRESSION_PREPARE else if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
"auth" -> EventKind.AUTH
"hello" -> EventKind.HELLO
"client.capabilities" -> EventKind.CAPABILITIES
"history" -> EventKind.HISTORY
"listen" -> EventKind.LISTEN
"vad" -> EventKind.VAD