Add Liam waiting poses with capture and playback fences

This commit is contained in:
zenord
2026-10-15 01:51:00 +08:00
parent 72e68a4166
commit 654630dea5
28 changed files with 1102 additions and 43 deletions
+2
View File
@@ -160,6 +160,7 @@ android {
else if (avatarEngineering) versionNameSuffix '-dev'
buildConfigField 'boolean', 'AVATAR_NETWORK_ACTIONS_ALLOWED', (!avatarUserAssetCandidate || avatarUserNetworkActions) ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_USER_ASSET_CANDIDATE', avatarUserAssetCandidate ? 'true' : 'false'
buildConfigField 'boolean', 'WAITING_POSES_ENABLED', characterMedia.waitingContract == true ? 'true' : 'false'
buildConfigField 'String', 'EMOTION_ASSET_ROOT', groovy.json.JsonOutput.toJson(characterMedia.assetRoot)
buildConfigField 'String', 'STARTUP_ASSET_ROOT', groovy.json.JsonOutput.toJson(characterMedia.bootstrapRoot)
buildConfigField 'String', 'STARTUP_MANIFEST_SHA', groovy.json.JsonOutput.toJson(characterMedia.bootstrapSha256)
@@ -177,6 +178,7 @@ android {
release {
buildConfigField 'boolean', 'AVATAR_NETWORK_ACTIONS_ALLOWED', 'false'
buildConfigField 'boolean', 'AVATAR_USER_ASSET_CANDIDATE', 'false'
buildConfigField 'boolean', 'WAITING_POSES_ENABLED', 'false'
buildConfigField 'String', 'EMOTION_ASSET_ROOT', '"avatar/a01-expression-action-v1/"'
buildConfigField 'String', 'STARTUP_ASSET_ROOT', '"avatar/startup-white-01/"'
buildConfigField 'String', 'STARTUP_MANIFEST_SHA', '"461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2"'
@@ -62,7 +62,7 @@ class MainActivity : ComponentActivity() {
private var loaderGeneration=0L
private var firstDrawReady=false
private var mediaReady=false
private val avatarMedia=com.gorios.lanvoice.avatar.AvatarMediaBinding()
private val avatarMedia=com.gorios.lanvoice.avatar.AvatarMediaBinding(BuildConfig.WAITING_POSES_ENABLED)
private var expressionState by mutableStateOf(ExpressionUiState())
private lateinit var expressions: ExpressionController
private var inForeground = false
@@ -224,7 +224,7 @@ class MainActivity : ComponentActivity() {
state = it
avatarMedia.beginTurn(it.turnId)
avatarMedia.intent(it.replyEmotion.takeIf { role->role.turnId!=null },
it.playbackActivity?.audible==true && !it.actionActive)
it.playbackActivity?.audible==true && !it.actionActive && !it.waitingPoseActive)
if (lostConnection && ::expressions.isInitialized) closeCamera()
entry.connection(it.connection == ConnectionStatus.CONNECTED, it.connection == ConnectionStatus.CONNECTING,
android.os.SystemClock.elapsedRealtime(), it.connection == ConnectionStatus.BUSY)
@@ -236,6 +236,7 @@ class MainActivity : ComponentActivity() {
reviewedActionPack = avatarPack?.emotionAction?.actionPack?.takeIf { BuildConfig.AVATAR_NETWORK_ACTIONS_ALLOWED && (!BuildConfig.AVATAR_STARTUP_FIX || mediaReady) },
pendingActionPackSha = { if(BuildConfig.AVATAR_STARTUP_FIX && BuildConfig.AVATAR_NETWORK_ACTIONS_ALLOWED) BuildConfig.EMOTION_MANIFEST_SHA else null },
actionPlayer = avatarMedia,
waitingPlayer = avatarMedia,
onPrepareExpression = avatarMedia::prepare,
persona = BuildConfig.DIALOGUE_PERSONA,
keepPermissionConnection = BuildConfig.PERMISSION_CONNECTION_RETENTION,
@@ -41,9 +41,10 @@ data class VoiceUiState(
val turnId: Long? = null,
val captureActive: Boolean = false,
val playbackRunning: Boolean = false,
val waitingPoseActive: Boolean = false,
) {
val voiceIndicator: VoiceIndicatorState get() = when {
!voiceActive || connection != ConnectionStatus.CONNECTED || actionActive -> VoiceIndicatorState.IDLE
!voiceActive || connection != ConnectionStatus.CONNECTED || actionActive || waitingPoseActive -> VoiceIndicatorState.IDLE
phase == VoicePhase.ANSWERING && playbackRunning -> VoiceIndicatorState.SPEAKING
phase == VoicePhase.LISTENING && captureActive && !microphoneMuted -> VoiceIndicatorState.LISTENING
else -> VoiceIndicatorState.IDLE
@@ -68,6 +69,7 @@ class VoiceSession(
private val pendingActionPackSha: ()->String? = { null },
persona: String = "default",
private val keepPermissionConnection: Boolean = true,
private val waitingPlayer: WaitingPosePlayer? = null,
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
@@ -85,6 +87,16 @@ class VoiceSession(
private var preparedPlaybackTurn: Long? = null
private var drainedTurn: Long? = null
private var emotionEndedTurn: Long? = null
private var poseEpoch=0L
private var poseActive=false
private var poseTimeout: Runnable?=null
private var talkEpoch=0L
private var talkPrepared: Long?=null
private var talkPreparing: Long?=null
private var talkTimeout: Runnable?=null
private val heldAudio=java.util.ArrayDeque<DownlinkFrame>()
private var heldBytes=0
private var heldEnd=false
private var faceSharing = false
private var faceSupported = false
private var faceCue = FaceCueObservation()
@@ -134,7 +146,7 @@ class VoiceSession(
private val playback: AudioPlayback = AudioPlayback(
onDrained = { turn, epoch ->
main.post {
if (isActive() && !actions.active && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
if (isActive() && !actions.active && !poseActive && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) {
drainedTurn=turn
@@ -162,6 +174,7 @@ class VoiceSession(
val reason=when {
!isActive()->"inactive"
actions.active->"action_owner"
poseActive->"pose_owner"
!playbackIsCurrent(activity.turnId,activity.generation)->"stale_generation"
currentTurn!=activity.turnId->"old_turn"
blockedTurn==activity.turnId->"blocked"
@@ -175,7 +188,7 @@ class VoiceSession(
},
onPlaying = { turn, epoch, playing ->
main.post {
if(isActive() && !actions.active && playbackIsCurrent(turn,epoch) &&
if(isActive() && !actions.active && !poseActive && playbackIsCurrent(turn,epoch) &&
currentTurn==turn && blockedTurn!=turn && emotionEndedTurn!=turn) {
update(state.copy(playbackRunning = playing))
}
@@ -195,6 +208,49 @@ class VoiceSession(
onConnectionLog = onConnectionLog,
)
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 fun offerPose(pose: WaitingPose) {
if(!waitingSafe()) { waitingPlayer?.cancelWaitingPose {};return }
if(!dialogue.listen(false)) { waitingPlayer?.cancelWaitingPose {};return }
poseActive=true;blockedTurn=currentTurn;val token=++poseEpoch
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")
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")
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")
if(dialogue.listen(true)) { update(state.copy(phase=VoicePhase.LISTENING));startCapture() }
else stopVoice(cancelReason="pose_resume_failed")
}
} },{ main.post { if(token==poseEpoch) stopVoice(cancelReason="pose_media_failed") } })
} }
}
private fun cancelPose() {
val token=++poseEpoch;poseTimeout?.let { main.removeCallbacks(it) };poseTimeout=null
waitingPlayer?.waitingEligible(false)
// Keep capture/TTS barred until real restore, including a quick foreground return.
waitingPlayer?.cancelWaitingPose { main.post {
if(token!=poseEpoch) return@post
poseActive=false;update(state.copy(waitingPoseActive=false))
if(isActive() && state.phase==VoicePhase.LISTENING) startCapture()
} }
}
fun foreground(connectAutomatically: Boolean = true) {
checkMainThread()
if (released) return
@@ -279,6 +335,7 @@ class VoiceSession(
fun stopVoice(sendControls: Boolean = true,cancelReason: String = "stop_voice") {
checkMainThread()
cancelPresence(reset=true)
cancelPose()
cancelActionFor(cancelReason)
resetReply("stop")
val wasActive = state.voiceActive
@@ -323,7 +380,7 @@ class VoiceSession(
fun interrupt() {
checkMainThread()
if (!isActive() || actions.active) return
if (!isActive() || actions.active || poseActive) return
resetReply("interrupt")
blockedTurn = currentTurn
playback.interrupt() // Silence locally before waiting for the server's abort event.
@@ -373,7 +430,7 @@ class VoiceSession(
presenceEnabled=enabled;presenceCamera=cameraActive
if(!enabled || !cameraActive) { lastPresenceObservedAt=null;presenceSampleRejected=false;cancelPresence(reset=true) }
}
private fun presenceEligible()=presenceEnabled && presenceCamera && presenceSupported && isActive() && !state.microphoneMuted
private fun presenceEligible()=!poseActive && presenceEnabled && presenceCamera && presenceSupported && isActive() && !state.microphoneMuted
fun presenceDiagnosticsSnapshot(): PresenceDiagnosticsSnapshot {
checkMainThread()
val now=SystemClock.elapsedRealtime()
@@ -493,6 +550,7 @@ class VoiceSession(
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
cancelPose()
clearPresenceRequest();presenceRules.reset();presenceSupported=false;presenceSpeech=false
lastPresenceObservedAt=null;presenceSampleRejected=false
cancelActionFor("disconnect")
@@ -524,7 +582,7 @@ class VoiceSession(
private fun startCapture() {
val active = isActive()
diagnostic("startCapture active=$active capturing=$capturing")
if (!active || capturing || state.microphoneMuted || actions.active) return
if (!active || capturing || state.microphoneMuted || actions.active || poseActive) return
capturing = true
val epoch = ++captureEpoch
val captureTurn = currentTurn
@@ -533,7 +591,8 @@ class VoiceSession(
capture.start(
onFrame = { pcm ->
main.post {
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive()) {
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive() && !poseActive) {
waitingPlayer?.waitingEligible(waitingSafe())
// 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)) {
@@ -566,6 +625,10 @@ class VoiceSession(
}
private fun onEvent(event: ServerEvent) {
if(poseActive && event.kind !in setOf(EventKind.HELLO,EventKind.ERROR,EventKind.CAPABILITIES)) {
com.gorios.lanvoice.diag.DiagnosticLog.state("waiting_late",event.kind.name,"reason=pose_owner event=${event.kind.name.lowercase()}")
return
}
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
if(event.kind==EventKind.PRESENCE) {
@@ -683,7 +746,9 @@ class VoiceSession(
when (action) {
"start" -> playback.beginTurn(currentTurn)
"stop", "done", "end" -> {
if (preparedPlaybackTurn == currentTurn) playback.endTurn(currentTurn)
if (preparedPlaybackTurn == currentTurn) {
if(talkPreparing==currentTurn) heldEnd=true else playback.endTurn(currentTurn)
}
else failAudio("本轮未收到可播放音频,请重新开始", IllegalStateException("TTS ended without accepted PCM"))
}
}
@@ -715,7 +780,7 @@ class VoiceSession(
private fun onFrame(frame: DownlinkFrame) {
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
if (!isActive() || actions.active || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
if (!isActive() || actions.active || poseActive || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
blockedTurn == frame.turnId) return
if (preparedPlaybackTurn != frame.turnId) {
drainedTurn=null
@@ -724,9 +789,27 @@ class VoiceSession(
preparedPlaybackTurn = frame.turnId
}
update(state.copy(phase = VoicePhase.ANSWERING))
if (!playback.enqueue(frame)) {
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
}
if(waitingPlayer?.waitingContract==true && talkPrepared!=frame.turnId) {
if(heldBytes+frame.pcm16.size>480_000) { failAudio("角色准备超时,请重新开始",IllegalStateException("talk_gate_bound"));return }
heldAudio.add(frame);heldBytes+=frame.pcm16.size
if(talkPreparing!=frame.turnId) {
talkPreparing=frame.turnId;val token=++talkEpoch;val turn=frame.turnId
talkTimeout=Runnable { if(token==talkEpoch && talkPreparing==turn) failAudio("角色准备超时,请重新开始",IllegalStateException("talk_gate_timeout")) }
.also { main.postDelayed(it,10_000) }
waitingPlayer.prepareTalk({ main.post {
if(token==talkEpoch && isActive() && !poseActive && currentTurn==turn && blockedTurn!=turn && talkPreparing==turn) {
talkTimeout?.let { main.removeCallbacks(it) };talkTimeout=null
talkPreparing=null;talkPrepared=turn
diagnostic("waiting state=talk_ready turn=$turn buffered_bytes=$heldBytes")
while(heldAudio.isNotEmpty()) if(!playback.enqueue(heldAudio.removeFirst())) {
failAudio("播放中断,请重新开始语音对话",IllegalStateException("talk_queue_rejected"));return@post
}
heldBytes=0
if(heldEnd) { heldEnd=false;playback.endTurn(turn) }
}
} },{ main.post { if(token==talkEpoch) failAudio("角色准备失败,请重新开始",IllegalStateException("talk_gate_failed")) } })
}
} else if(!playback.enqueue(frame)) failAudio("播放中断,请重新开始语音对话",IllegalStateException("Playback queue rejected frame"))
}
private fun acceptTurn(id: Long, logDecision: Boolean = true): Boolean {
@@ -787,6 +870,9 @@ class VoiceSession(
}
private fun resetReply(reason: String) {
talkEpoch++;talkTimeout?.let { main.removeCallbacks(it) };talkTimeout=null
heldAudio.clear();heldBytes=0;heldEnd=false;talkPrepared=null;talkPreparing=null
waitingPlayer?.finishTalk()
val expression = state.replyEmotion
val played = preparedPlaybackTurn == currentTurn && expression.turnId == currentTurn
if (expression.turnId != null) diagnostic("role reset reason=$reason turn=${expression.turnId} played=$played")
@@ -812,6 +898,7 @@ class VoiceSession(
val changed = state.replyEmotion != next.replyEmotion
state = next
onState(next)
waitingPlayer?.waitingEligible(waitingSafe())
if (changed) emotionObserver.onReplyEmotion(next.replyEmotion)
}
private fun checkMainThread() {
@@ -4,7 +4,23 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion
import com.gorios.lanvoice.diag.DiagnosticLog
/** One Activity-owned binding shared by VoiceSession and its persistent avatar view. */
class AvatarMediaBinding : ActionPlayer {
class AvatarMediaBinding(private val expectedWaitingContract: Boolean=false) : ActionPlayer,WaitingPosePlayer {
private var pendingTalk: Pair<()->Unit,()->Unit>?=null
private var waitingOffer: (WaitingPose)->Unit={}
private var waitingEnabled=false
override val waitingContract get()=expectedWaitingContract || driver?.waitingContract==true
override fun waitingListener(offer: (WaitingPose)->Unit) { waitingOffer=offer;driver?.waitingListener(offer) }
override fun waitingEligible(enabled: Boolean) { waitingEnabled=enabled;driver?.waitingEligible(enabled) }
override fun playWaitingPose(pose: WaitingPose,finished: ()->Unit,failed: ()->Unit) { driver?.playWaitingPose(pose,finished,failed) ?: failed() }
override fun cancelWaitingPose(restored: ()->Unit) { driver?.cancelWaitingPose(restored) ?: restored() }
override fun prepareTalk(ready: ()->Unit,failed: ()->Unit) {
val current=driver
if(current!=null) {
if(expectedWaitingContract && !current.waitingContract) failed() else current.prepareTalk(ready,failed)
} else if(expectedWaitingContract) { pendingTalk?.second?.invoke();pendingTalk=ready to failed }
else failed()
}
override fun finishTalk() { pendingTalk=null;driver?.finishTalk() }
val currentPackageId: String? get() = driver?.currentPackageId
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
val diagnosticState: String get() = (driver?.diagnosticState ?: "owner=stopped renderer=unavailable")+" $nativeMusic $mouthPresentation"
@@ -30,7 +46,10 @@ class AvatarMediaBinding : ActionPlayer {
fun attach(value: ConversationMediaDriver,onReleased: (()->Unit)?=null) {
check(driver==null || driver===value);driver=value
if(onReleased!=null) this.onReleased=onReleased
value.waitingListener(waitingOffer);value.waitingEligible(waitingEnabled)
value.beginTurn(turn);value.intent(reply,talking);value.prepareExpression(prepared)
val pending=pendingTalk;pendingTalk=null
pending?.let { prepareTalk(it.first,it.second) }
}
fun detach(value: ConversationMediaDriver) { if(driver===value) driver=null }
fun prepare(value: ReplyEmotion?) { prepared=value;driver?.prepareExpression(value) }
@@ -62,6 +62,12 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
check(total<=512_000_000)
}
stage="action_media_hash"
for(pose in index.waiting?.poses.orEmpty()) {
if(!immutableReceipt) {
val data=read(context,root+pose.clip.path,64_000_000)
check(sha(data)==pose.clip.sha256);total+=data.size;check(total<=512_000_000)
}
}
for(asset in index.actionPack?.assets.orEmpty()) {
val media=checkNotNull(asset.media)
if(!immutableReceipt) {
@@ -28,12 +28,51 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private val allowSilentEdges: Boolean=false,
private val chooseIdle: (Int)->Int = { kotlin.random.Random.nextInt(it) },
private val chooseIdleCycles: ()->Int = { kotlin.random.Random.nextInt(2,4) },
private val holdInitial: Boolean=false) : ActionPlayer {
private val holdInitial: Boolean=false) : ActionPlayer,WaitingPosePlayer {
override val waitingContract get()=index.waiting!=null
private var offerWaiting: (WaitingPose)->Unit={}
private var waitingEnabled=false
private var queuedPose: WaitingPose?=null
private var heldPose: WaitingPose?=null
private var pose: WaitingPose?=null
private var poseSlot: Slot?=null
private var poseSource: Slot?=null
private var poseStarted=false
private var poseReturning=false
private var poseCancelled=false
private var poseFinished: (()->Unit)?=null
private var poseFailed: (()->Unit)?=null
private var speechRequested=false
private var speechFinishing=false
private var speechReady: (()->Unit)?=null
private var speechFailed: (()->Unit)?=null
override fun waitingListener(offer: (WaitingPose)->Unit) { offerWaiting=offer }
override fun waitingEligible(enabled: Boolean) { waitingEnabled=enabled;if(!enabled) queuedPose=null }
override fun prepareTalk(ready: ()->Unit,failed: ()->Unit) {
if(index.waiting==null) { ready();return }
if(!active || speechReady!=null) { failed();return }
speechRequested=true;speechFinishing=false;speechReady=ready;speechFailed=failed
queuedPose=null;heldPose=null;idleTarget=null;talk=false;applyMouth();plan();talkReadyIfSafe()
}
override fun finishTalk() {
speechReady=null;speechFailed=null
if(index.waiting==null) return
talk=false;speechFinishing=true;applyMouth();talkReadyIfSafe()
}
private fun talkReadyIfSafe() {
val config=index.waiting ?: return
val current=visible ?: return
if(initialHeld || pose!=null || inBridge || revealing!=null || layerOwner!=LayerOwner.CONVERSATION || !current.closedMouth) return
if(speechFinishing) { speechFinishing=false;speechRequested=false;plan();return }
if(speechRequested && current.packageId==config.talkPackage && current.key!=null) {
val callback=speechReady;speechReady=null;speechFailed=null;callback?.invoke()
}
}
private var initialHeld=holdInitial
fun releaseInitial() {
if(!active || !initialHeld) return
initialHeld=false
plan()
plan();talkReadyIfSafe()
visible?.takeIf { !holdExit(it) }?.port?.advance()
}
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
@@ -51,9 +90,11 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private var idleCycleGoal=chooseIdleCycles().also { check(it in 2..3) }
private fun resetIdleCycles() { idleCycles=0;idleCycleGoal=chooseIdleCycles().also { check(it in 2..3) } }
var selection: RoleVisualSelection?=null;private set
val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId
val currentPackageId: String? get() = if(inBridge || actionStarted || poseStarted) null else visible?.packageId
val visualStatus: String get() = when {
!active -> "renderer_stopped"
poseStarted -> "waiting_pose_mouth_disabled"
index.waiting!=null && !inBridge && action==null -> if(speechRequested) "dedicated_talk_idle" else "waiting_idle"
actionStarted -> "action_mouth_disabled"
inBridge -> "bridge_own_mouth"
edge!=null || revealing!=null -> "queued_emotion_safe_exit_or_prepared_surface"
@@ -74,13 +115,13 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private var returning=false
private var actionFinished: ((ActionEnd)->Unit)?=null
private var actionFailed: (()->Unit)?=null
enum class LayerOwner { STOPPED, CONVERSATION, ACTION }
enum class LayerOwner { STOPPED, CONVERSATION, ACTION, POSE }
var layerOwner=LayerOwner.STOPPED;private set
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 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"
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"
private var musicEpoch=0L
private var closing=0
private val releaseWaiters=mutableListOf<()->Unit>()
@@ -92,7 +133,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
val current=visible?.packageId
selectedId=if(index.visuals.any { it.id==current && it.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL })
index.fallbackId else current ?: index.fallbackId
if(!inBridge && revealing==null) discardRoute()
if(!inBridge && revealing==null && pose==null) discardRoute()
applyMouth()
}
fun start() {
@@ -102,7 +143,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
// Ports must deliver callbacks asynchronously, like both Android ports.
}
fun prepareExpression(reply: ReplyEmotion?) {
if(!active || action!=null || inBridge || slots.size>=3) return
if(index.waiting!=null || !active || action!=null || pose!=null || inBridge || slots.size>=3) return
if(reply==null) { if(edge==null) discardTarget();return }
if(reply.turnId!=turn) return
val id=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId).packageId
@@ -120,12 +161,13 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
idleTarget=null
}
talk=talking && reply?.turnId==turn
if(index.waiting!=null && !speechRequested) talk=false
applyMouth()
if(active && !inBridge && !actionStarted) plan()
}
private fun applyMouth() {
val current=revealing ?: visible
current?.port?.mouth(talk && action==null && current.pack.apertureMode,generation,++revision)
current?.port?.mouth(talk && action==null && pose==null && current.pack.apertureMode,generation,++revision)
}
private fun loopEdge(id: String)=index.edges.first { it.from==id && it.to==id && (index.loopIds[id]==null || it.id==index.loopIds[id]) }
private fun prepare(id: String,frame: Int): Slot = prepare(index.packages.getValue(id),frame,true,loopEdge(id).nativeLoop,id)
@@ -142,6 +184,14 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
if(key.index !in pack.body.ptsUs.indices || kotlin.math.abs(key.ptsUs-pack.body.ptsUs[key.index])>2 ||
!sequential || previous==null && (key.index!=entry || key.loopOrdinal!=0L)) { fail();return@prepare }
slot.key=key;slot.closedMouth=closedMouth
if(poseStarted) {
if(slot===poseSlot && !poseReturning) {
if(!closedMouth) { fail();return@prepare }
reveal(slot.number);report("pose_${pose?.id}",key);slot.port.advance()
} else if(poseReturning && slot===target) restorePose(slot)
else ignoredCallbacks++
return@prepare
}
if(slot===visible && layerOwner==LayerOwner.ACTION) {
// Held compositors still tick every20ms. They cannot steal the
// movie's layer, relabel it, advance or plan during ACTION/return.
@@ -149,11 +199,22 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
}
if(slot===visible) {
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
if(!inBridge && !initialHeld) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
if(!inBridge && !initialHeld) {
talkReadyIfSafe();chooseIdleAtLoopEnd(slot,key,previous)
if(key.index==0 && slot.packageId==index.waiting?.idlePackage) {
val offered=queuedPose;queuedPose=null
if(offered!=null && waitingEnabled && pose==null && heldPose==null && !speechRequested) { heldPose=offered;offerWaiting(offered) }
}
applyMouth();plan()
}
if(slot===visible && !initialHeld && !actionStarted && !holdExit(slot)) slot.port.advance()
} else if(returning) restoreAction(slot) else plan()
}
},{
if(active && slot.live && poseStarted && !poseReturning && slot===poseSlot) {
if(slot.key?.index==slot.pack.body.frameCount-1 && slot.closedMouth) returnPose() else fail()
return@prepare
}
if(active && slot.live && visible===slot && inBridge && revealing==null) {
if(slot.key?.index==slot.pack.body.frameCount-1) finishBridge() else fail()
}
@@ -162,10 +223,24 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
}
private fun holdExit(slot: Slot): Boolean = !inBridge && (
slot.key?.index==edge?.fromFrame && edge!=null ||
action?.media?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true)
action?.media?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true ||
(pose ?: heldPose)?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true)
/** Only a completed neutral cycle may schedule variation. Speech/emotion/action
* remains authoritative, and every departure still goes through plan's own-mouth edge. */
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
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)
}
return
}
if(talk || action!=null || edge!=null || revealing!=null || target!=null || closing!=0 ||
key==previous || key.index!=slot.pack.body.frameCount-1 ||
selection?.visualEmotion?.let { it!=com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }==true ||
@@ -190,8 +265,19 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private fun plan() {
val source=visible ?: return
val key=source.key ?: return
if(initialHeld || inBridge || revealing!=null || !active || returning || actionStarted) return
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else idleTarget ?: selectedId
if(initialHeld || inBridge || revealing!=null || !active || returning || actionStarted || poseStarted) return
if(heldPose!=null && pose==null) return
if(pose!=null) {
val pending=checkNotNull(pose);val destination=poseSlot ?: return
if(source.packageId==pending.sourcePackage && source.key?.index==pending.sourceFrame && source.closedMouth && destination.closedMouth && destination.key?.index==0) {
poseStarted=true;layerOwner=LayerOwner.POSE;talk=false;applyMouth()
visible=destination;reveal(destination.number);report("pose_${pending.id}",destination.key);destination.port.advance()
}
return
}
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else index.waiting?.let {
if(speechRequested) it.talkPackage else it.idlePackage
} ?: idleTarget ?: selectedId
var reviewedLoop: ConversationEdge?=null
if(source.packageId==wanted) {
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
@@ -245,7 +331,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private fun activate(destination: Slot,ready: ()->Unit) {
if(revealing!=null) return
revealing=destination
destination.port.activateMouth(talk && action==null && destination.pack.apertureMode,generation,++revision) {
destination.port.activateMouth(talk && action==null && pose==null && destination.pack.apertureMode,generation,++revision) {
if(active && layerOwner==LayerOwner.CONVERSATION && destination.live && revealing===destination) {
revealing=null;ready()
}
@@ -253,14 +339,56 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
}
private fun discardTarget() { target?.let(::closeSlot);target=null }
private fun discardRoute() { bridge?.let(::closeSlot);bridge=null;edge=null;discardTarget() }
private fun closeSlot(slot: Slot) {
private fun closeSlot(slot: Slot,after: ()->Unit={}) {
if(!slot.live || slot !in slots) return
slot.live=false;closing++
slot.port.close { slots.remove(slot);closing--;releasedIfDone();if(active) plan() }
slot.port.close { slots.remove(slot);closing--;releasedIfDone();after();if(active) plan() }
}
override fun playWaitingPose(pose: WaitingPose,finished: ()->Unit,failed: ()->Unit) {
if(!active || this.pose!=null || action!=null || speechRequested || inBridge || revealing!=null ||
edge!=null || slots.size!=1 || index.waiting?.poses?.contains(pose)!=true ||
visible?.packageId!=pose.sourcePackage || visible?.key?.index!=pose.sourceFrame || visible?.closedMouth!=true) {
failed();return
}
heldPose=null;poseCancelled=false;poseSource=visible;this.pose=pose;poseFinished=finished;poseFailed=failed;talk=false;queuedPose=null;applyMouth()
val pack=ContinuousAvatarPack(pose.clip,emptyList(),emptyMap(),index.root,pose.clip.sha256)
poseSlot=prepare(pack,0,false,false,null);plan()
}
private fun returnPose() {
val current=pose ?: return
if(poseReturning) return
poseReturning=true
val old=poseSlot ?: return fail()
closeSlot(old) {
if(active && pose===current && poseReturning) {
// Held source really remains frame0. Recompose it after decoder release;
// only its new composed callback may restore A. Keep final pose texture
// visible meanwhile; no timer, recreated codec, or blank layer.
val source=poseSource ?: return@closeSlot fail()
target=source
source.port.activateMouth(false,generation,++revision) {}
}
}
}
private fun restorePose(slot: Slot) {
val current=pose ?: return
if(!poseReturning || slot!==target || slot.key?.index!=current.returnFrame || !slot.closedMouth) return
visible=slot;target=null;pose=null;poseSlot=null;poseSource=null;poseReturning=false;poseStarted=false;layerOwner=LayerOwner.CONVERSATION
reveal(slot.number);report("pose_return_a",slot.key)
val callback=poseFinished;poseFinished=null;poseFailed=null
applyMouth();talkReadyIfSafe();plan();slot.port.advance();callback?.invoke()
}
override fun cancelWaitingPose(restored: ()->Unit) {
if(index.waiting==null) { restored();return }
heldPose=null
if(pose==null) { visible?.takeIf { !holdExit(it) }?.port?.advance();restored();return }
poseCancelled=true;poseFinished=restored;poseFailed=null
if(!poseStarted) { poseStarted=true;layerOwner=LayerOwner.POSE }
returnPose()
}
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
val media=asset.media
if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
if(!active || action!=null || pose!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;musicPresented=false;talk=false;idleTarget=null;resetIdleCycles();applyMouth()
val epoch=++musicEpoch
music.prepare(media,{ if(active && epoch==musicEpoch && action===asset && !actionStarted && !returning) { musicReady=true;plan() } else ignoredCallbacks++ },
@@ -295,9 +423,12 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
musicEpoch++;layerOwner=LayerOwner.STOPPED;musicPresented=false;action=null;actionStarted=false;returning=false;musicReady=false;idleTarget=null
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
reveal(null);releaseWaiters.add(released)
if(poseCancelled) poseFinished?.let { releaseWaiters.add(it) };poseCancelled=false
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
pose=null;poseSlot=null;poseSource=null;poseStarted=false;poseReturning=false
queuedPose=null;heldPose=null;poseFinished=null;poseFailed=null;speechReady=null;speechFailed=null;speechRequested=false;speechFinishing=false
closing++ // Music barrier exists before any synchronous port release callback.
slots.toList().forEach(::closeSlot)
slots.toList().forEach { closeSlot(it) }
music.close { closing--;releasedIfDone() }
}
private fun releasedIfDone() {
@@ -306,6 +437,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private fun fail() {
report("media_failed",null)
val failed=actionFailed;actionFailed=null
stop {};failed?.invoke()
val waitingFailed=poseFailed;val talkFailed=speechFailed
stop {};failed?.invoke();waitingFailed?.invoke();talkFailed?.invoke()
}
}
@@ -4,7 +4,7 @@ import com.gorios.lanvoice.dialogue.RoleEmotion
data class EmotionActionIndex(val fallbackId: String, val packages: Map<String,ContinuousAvatarPack>,
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?, val edges: List<ConversationEdge> = emptyList(),val root: String="",
val loopIds: Map<String,String> = emptyMap())
val loopIds: Map<String,String> = emptyMap(),val waiting: WaitingMedia?=null)
data class ConversationEdge(val id: String,val from: String,val to: String,val fromFrame: Int,val toFrame: Int,
val clip: ContinuousBodyAsset,val nativeLoop: Boolean=false,val mouthRuntime: ContinuousAvatarPack?=null)
@@ -168,7 +168,38 @@ object EmotionActionManifest {
}
ReviewedActionPack(actualSha,assets)
}
EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges,pathRoot,rows.associate { it["id"] as String to it["loopEdge"] as String })
val waiting=root["waiting"]?.let { value ->
field="waiting.contract"
val config=obj(value)
require(config["schemaVersion"]==1L || config["schemaVersion"]==1)
require(config["microphoneAllowed"]==false && config["ttsAllowed"]==false && config["mouthAllowed"]==false)
val idle=config["idlePackageId"] as String;val talkId=config["talkPackageId"] as String
require(idle==fallback && talkId in packages)
val poses=config["poses"] as List<Map<String,Any?>>
require(poses.size in 1..8 && poses.map { it["id"] }.distinct().size==poses.size)
val parsed=poses.mapIndexed { i,pose ->
field="waiting.poses[$i]"
val id=pose["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}")))
require(pose["kind"]=="waiting_pose" && pose["mouthAllowed"]==false && pose["entryAnchor"]=="A" && pose["returnAnchor"]=="A")
require(pose["sourcePackageId"]==idle && pose["returnPackageId"]==idle)
// These clips were reviewed against neutral frame0, not the dance's last-frame exit.
require(integer(pose["sourceFrame"])==0L && integer(pose["returnFrame"])==0L &&
integer(pose["sourcePtsUs"])==packages.getValue(idle).body.ptsUs[0] &&
integer(pose["returnPtsUs"])==packages.getValue(idle).body.ptsUs[0])
val clip=obj(pose["clip"])
require(clip["hasAudio"]==false && "audioEndUs" !in pose && "mouthRuntimeManifest" !in pose)
val n=boundedInt(clip["frameCount"],BodyTimeline.MAX_TALK_FRAMES)
val pts=(clip["ptsUs"] as List<*>).map(::integer)
val duration=integer(clip["durationUs"])
val fps=boundedInt(clip["fpsNumerator"],120_000);val den=boundedInt(clip["fpsDenominator"],10_000)
require(integer(clip["width"])==shape.width.toLong() && integer(clip["height"])==shape.height.toLong() &&
BodyTimeline.valid(pts,n,duration,fps,den))
WaitingPose(id,ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),shape.width,shape.height,n,duration,pts,fps,den),idle,0,idle,0)
}
WaitingMedia(idle,talkId,parsed)
}
EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges,pathRoot,
rows.associate { it["id"] as String to it["loopEdge"] as String },waiting)
} catch(_: Exception) { onReject?.invoke(field);null }
}
}
@@ -16,7 +16,9 @@ data class StartupAssetKey(val versionCode: Long,val installedAt: Long,val pin:
root=="avatar/a01-black-tulle-roomy720-correct03/" &&
pin=="208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93" && validator>=3 ||
root=="avatar/char-expressions-r02/" &&
pin=="f8a69041da51e1a551c6991bfad6d7f034f0f320f726f58568afd43d81cb9604" && validator>=3) && validator>0) }
pin=="f8a69041da51e1a551c6991bfad6d7f034f0f320f726f58568afd43d81cb9604" && validator>=3 ||
root=="avatar/char-waiting-poses-r01/" &&
pin=="25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8" && validator>=3) && validator>0) }
val fingerprint: String get() = digest("$versionCode/$installedAt/$pin/$root/$validator")
}
private fun digest(value: String): String = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
@@ -0,0 +1,18 @@
package com.gorios.lanvoice.avatar
/** Local silent media, separate from server dance and from N×5 TALK runtimes. */
data class WaitingPose(val id: String,val clip: ContinuousBodyAsset,val sourcePackage: String,
val sourceFrame: Int,val returnPackage: String,val returnFrame: Int)
data class WaitingMedia(val idlePackage: String,val talkPackage: String,val poses: List<WaitingPose>)
/** A pose starts only after VoiceSession confirms recorder release. Completion means
* final indexed frame, decoder release, and actual restored idle frame, not a timer. */
interface WaitingPosePlayer {
fun waitingListener(offer: (WaitingPose)->Unit)
fun waitingEligible(enabled: Boolean)
fun playWaitingPose(pose: WaitingPose,finished: ()->Unit,failed: ()->Unit)
fun cancelWaitingPose(restored: ()->Unit)
fun prepareTalk(ready: ()->Unit,failed: ()->Unit)
fun finishTalk()
val waitingContract: Boolean
}