From 654630dea51af6fce86a0d2a168c442eea16ba86 Mon Sep 17 00:00:00 2001 From: zenord Date: Thu, 15 Oct 2026 01:51:00 +0800 Subject: [PATCH] Add Liam waiting poses with capture and playback fences --- app/build.gradle | 2 + .../java/com/gorios/lanvoice/MainActivity.kt | 5 +- .../com/gorios/lanvoice/audio/VoiceSession.kt | 111 ++++++++++-- .../lanvoice/avatar/AvatarMediaBinding.kt | 21 ++- .../com/gorios/lanvoice/avatar/AvatarPack.kt | 6 + .../avatar/ConversationMediaDriver.kt | 170 ++++++++++++++++-- .../lanvoice/avatar/EmotionActionManifest.kt | 35 +++- .../lanvoice/avatar/StartupLoadCache.kt | 4 +- .../com/gorios/lanvoice/avatar/WaitingPose.kt | 18 ++ docs/AVATAR_PACK_V2_CONTRACT.md | 21 +++ docs/LIAM_CODE40_WAITING_POSES.md | 79 ++++++++ manifests/character-build-profiles.json | 19 +- .../liam-waiting-poses-r01-provenance.json | 40 +++++ manifests/startup-char-waiting-poses-r01.json | 166 +++++++++++++++++ scripts/check-avatar-apk-runtime.py | 28 +++ scripts/check-reply-regressions.py | 4 +- scripts/check-waiting-pose-shader.py | 46 +++++ scripts/derive-liam-waiting-pack.py | 90 ++++++++++ scripts/package-avatar-emotion.py | 10 +- scripts/package-character-test.py | 3 + scripts/select-character-assets.py | 3 + tests/avatar/AvatarCheck.kt | 1 + tests/avatar/EmotionActionCheck.kt | 15 ++ tests/avatar/WaitingPoseMediaCheck.kt | 108 +++++++++++ tests/packaging/test_character_profiles.py | 52 ++++++ tests/session/AudioDoubles.kt | 4 +- tests/session/CallCheck.kt | 1 + tests/session/WaitingPoseSessionCheck.kt | 83 +++++++++ 28 files changed, 1102 insertions(+), 43 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/WaitingPose.kt create mode 100644 docs/LIAM_CODE40_WAITING_POSES.md create mode 100644 manifests/liam-waiting-poses-r01-provenance.json create mode 100644 manifests/startup-char-waiting-poses-r01.json create mode 100644 scripts/check-waiting-pose-shader.py create mode 100644 scripts/derive-liam-waiting-pack.py create mode 100644 tests/avatar/WaitingPoseMediaCheck.kt create mode 100644 tests/session/WaitingPoseSessionCheck.kt diff --git a/app/build.gradle b/app/build.gradle index ae61562..bc644a8 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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"' diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index 8fe3c80..d07140a 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -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, diff --git a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt index 75e9497..8fbed49 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -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() + 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() { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt index 797e6d0..be85ed9 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt @@ -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) } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt index cbd12f4..c4ec8aa 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt @@ -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) { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt index b65ceda..9fe1f09 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt @@ -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() } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt index 9ebfbf3..29c6cde 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt @@ -4,7 +4,7 @@ import com.gorios.lanvoice.dialogue.RoleEmotion data class EmotionActionIndex(val fallbackId: String, val packages: Map, val visuals: List, val actionPack: ReviewedActionPack?, val edges: List = emptyList(),val root: String="", - val loopIds: Map = emptyMap()) + val loopIds: Map = 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> + 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 } } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt b/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt index b4ed4f9..d17544b 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt @@ -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()) diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/WaitingPose.kt b/app/src/main/java/com/gorios/lanvoice/avatar/WaitingPose.kt new file mode 100644 index 0000000..b366b95 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/WaitingPose.kt @@ -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) + +/** 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 +} diff --git a/docs/AVATAR_PACK_V2_CONTRACT.md b/docs/AVATAR_PACK_V2_CONTRACT.md index 5d598bd..45f2c19 100644 --- a/docs/AVATAR_PACK_V2_CONTRACT.md +++ b/docs/AVATAR_PACK_V2_CONTRACT.md @@ -233,3 +233,24 @@ omitted; if supplied they must both match levels[4]. All five levels/own-body/N/ shape/hash/cache checks remain mandatory. This path admits local media only, never network dance capability. Current exact revision and restoration instructions: `docs/BLACK_TULLE_CORRECT03_INTEGRATION.md`. Source pack bytes stay immutable. + +## Optional local waiting poses (Liam code40) + +The additive `waiting` object is now supported for a trusted selected bundle only: +`schemaVersion:1`, `idlePackageId`, `talkPackageId`, `microphoneAllowed:false`, +`ttsAllowed:false`, `mouthAllowed:false`, and 1–8 unique `poses`. Each pose has +`kind:waiting_pose`, `mouthAllowed:false`, source/return package=the idle fallback, +source/return frame0 with their exact indexed PTS, anchors A, and an exact hashed +silent H264 clip with actual N/PTS/shape/FPS/duration. No audioEndUs or +mouthRuntimeManifest is allowed. Every clip must appear in files with actual SHA/bytes. +The receiver probes the actual streams; a metadata hasAudio=false flag alone is insufficient. + +These are local waiting behaviors, distinct from the two registered server music dances. +The production session must await actual recorder-stop ACK before playback, prohibit +capture/TTS/mouth overlays through decoder release and actual restored idle evidence, +and fence late turns/callbacks. TALK prepares the dedicated talk package before +AudioTrack enqueue and closes the mouth on real drain. This contract is not the +transparent-expression-patch semantics where TTS continues. See +[code40 implementation and evidence](LIAM_CODE40_WAITING_POSES.md). New silent server +commands such as arbitrary turn-around still require their own protocol/authorization work; +local pose admission does not add them to the gateway allowlist. diff --git a/docs/LIAM_CODE40_WAITING_POSES.md b/docs/LIAM_CODE40_WAITING_POSES.md new file mode 100644 index 0000000..ec7ed00 --- /dev/null +++ b/docs/LIAM_CODE40_WAITING_POSES.md @@ -0,0 +1,79 @@ +# Liam code40:无声等待 pose + +基线 main `72e68a41665ccaf0e88336efccaff04a71afad02`,开始时工作树干净、remote main 相同。本次只交付 Liam 测试包;没有安装设备、部署/改动 gateway、素材生成、推理调用、改变时间/provider/TTS/相机实现或覆盖旧 APK。 + +## 精确取件与独立封装 + +收件 tar SHA256 `8abef3ee4df55c5539452b59067525c12ecdc562f7626069ce151654002836e9`。核验后解压到 `/home/ubuntu/asset-inbox/liam-poses-r02-intake-20261015-8abef3ee/`,不覆盖旧收件包。基础 index 实际 SHA256 `1f7b33e145e68476f3a9b1f15a3380d56cef3040fcd798a4ca19d027ea4c5ad9`;四 body 是 neutral/happy/sad/neutral-v03,neutral145 及自身 N×5 嘴层按用户确认指定为专用 talk-idle。 + +生产封装由 `scripts/derive-liam-waiting-pack.py` 在独立 `.runtime/avatar-imports/char-waiting-poses-r01-verified/` 派生。新 index SHA256: + +`25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8` + +未修改源视频、源 PNG、源 runtime manifest 或任何 `runtimeReady:false`。确证并修正的是新 revision 的以下元数据: + +- HANDOFF.md 的 files 行 SHA/bytes 过期;重新写明当前等待合同并记录实际字节。 +- files 清单漏列七份已有 runtime:`conversation/{neutral,happy,sad}/manifest.json`、`bridges/{neutral-to-happy,happy-to-neutral,neutral-to-sad,sad-to-neutral}/manifest.json`。逐份核验其引用 SHA 后补入。 +- asset_02 声明 audioEndUs=8,000,000,实际 MP4 AAC presentation end=7,940,998µs;沿用实测纠正,媒体字节不变。 +- 添加真正的 `waiting.poses`、两段无声 MP4、封装 provenance 和新外置 checksum;没有伪造 dance 或透明 N×5 pose 嘴层。 + +来源与补项记录见 `manifests/liam-waiting-poses-r01-provenance.json`。以上清单问题同时作为资产侧修正待办;App 封装不替代资产侧修订原包。 + +| 本地 pose | bytes | SHA256 | 解码事实 | +| --- | ---: | --- | --- | +| suit-adjust | 1,914,915 | d849ca16945d951821d315f5c76f2a6466656d8093584b2004eb0ae794bf1fb9 | 720×1280 H264@24,193帧,8,041,667µs,仅视频 | +| knuckle-check | 1,525,851 | c88655e370ad164cb028d1e11f4f6b5ae7aff695f26f9ecf7068349a3f25f761 | 同上 | + +用户拒绝的掸灰 pose 未纳入。两段舞蹈与 code38 原媒体字节完全一致:asset_01 SHA `c13a4c037d89a9a8a43f4fcf22d0acb001e58f3557dcfe1e80a7cd7e9f8a4fb0`,asset_02 SHA `b0d752bc12a94be4d89a39fbeb2343dece90adfad220dc1e0a9e647eaf4aca98`。 + +## 生产状态互斥 + +仅 `char-waiting-poses-r01` / Liam 的可信构建配置启用 `WAITING_POSES_ENABLED`。杨密、吕布和旧 Liam bundle 沿原路径,旧资产/pin 不改。 + +在前台、连接和语音活动成立、LISTENING 且真实采音、用户未讲话/主动轮未占用时,每完成2–3个 neutral 自然循环,从普通 idle、suit-adjust、knuckle-check 等概率选择。普通 idle 继续播放;pose 候选等到 actual neutral frame0、closed-mouth 合成后保留该入口。 + +`VoiceSession` 发送现有 auto listen(false),使本地 capture epoch 失效,阻挡旧轮并调用生产 `AudioCapture.stopAndConfirm`。只有实际录音工作线程完成清理的确认才调用 pose player;失败或5秒确认超时停止语音,不伪造已停采。入口在确认期间保持 actual frame0。 + +pose 使用生产 `ContinuousBodyRenderer` 的 body-only 模式(mouthEnabled=false、无 patches/curves、无音轨),显示 owner=POSE。原 body、旧轮、late ASR/TTS/listen/播放活动不能抢层或重启采音。下行 PCM 直接丢弃,不排成 pose 后的迟到发言;旧轮在恢复后仍 blocked,直到正常新轮宣告。pose 自然完成必须含 actual final indexed frame → decoder release ACK → held neutral actual frame0重新合成 → owner归还。取消、失败、设置停止和后台有独立 epoch;后台断 WS 并停止语音,旧完成回调不会重新开始。 + +TTS 只使用 neutral 自身嘴层。第一段 PCM 先进入有界准备队列(≤480,000B、10秒),等待 full renderer、bootstrap正式交接及 talk-idle实际闭嘴帧;之后才交给 AudioPlayback。TTS end 在准备期间暂存,随音频一起交付;取消/新轮/后台丢弃该队列与过期 ready 回调。真实 playback.drained 后关闭嘴意图,等 actual closed-mouth 状态再回等待。模型 emotion 标签保留;这个等待合同下显示目标始终为 neutral talk-idle,不把模型标签伪称为 happy/sad 已显示。 + +右上语音状态保留实际录音帧/AudioTrack播放头依据;pose、生成和舞蹈隐藏。pose 的8秒内用户语音不会录入,这是此次用户要求。自动等待 pose 运行于正常活动会话;离线舞蹈检查仍复用已有设置入口。 + +## 已完成验证与边界 + +- 严格生产 Kotlin index/runtime parser;整包 files/SHA/bytes、十套 runtime 独立 N×5/尺寸/绑定、全部视频完整解码/N/PTS、AAC presentation end、两 pose 仅视频,均通过。十套 RGBA合计27,632,640B,单包≤8MB、总计≤32MB;APK仅打实际引用、bootstrap和既有594文件回退清单,共3,192资产文件。 +- 全量11 JVM/UI入口通过,包括757旧报告时钟、103 native失败/取消断言;新增830生产 driver/View/renderer回调断言、38生产 VoiceSession断言及19严格 waiting parser断言。 +- VoiceSession回放故意延迟/拒绝真实 stop-confirm边界,确认前player调用=0;pose期间反复400次晚到采音/PCM:新增上行=0、AudioPlayback.enqueue=0;晚到TTS/listen不能建立新轮。退出、失败、超时、后台、双完成、旧准备回调、TTS end排队、实际状态指示均覆盖。设备 API为测试 doubles,未宣称实体录音器或手机 GPU已通过。 +- 83包装回归全通过,覆盖默认/吕布不混新包、新pin、两 pose SHA、防串包与旧dance媒体一致。Gradle assembleDebug及compileDebugAndroidTestKotlin通过;instrumentation仅编译,未运行。 +- 十套 runtime 的400个真实离屏GLES像素比较通过;两 pose首/中/末帧×三视口共18个body-only比较通过,native形状下输出RGB与解码原生帧逐像素相同。OES用CPU解码2D纹理替代,不能当手机GPU/真实Surface显示证明。 +- 最终APK实际loader/startup/production View重放:两 pose各193 composed callbacks、音乐播放器创建=0、neutral恢复;TALK requested=happy但actual=neutral own-mouth;两dance各193帧独占且释放回A。冷加载2570嘴层读取在worker,receipt模式0、同process重复0;真机启动性能未测。 +- 既有只读canonical gateway snapshot上的隔离握手:9个Android AUTH/HELLO回放、11个ASGI WS握手通过,Liam=en、服务器锁定声音、fresh CID、旧socket fence、断连busy释放;新pin ready/pending均拒绝,0 ASR/LLM/TTS调用。未改或重启 live gateway。 + +证据保存于忽略目录 `logs/liam-code40/`、现有 `logs/avatar-safe-061/` 和构建日志;不提交媒体、报告或敏感日志。 + +## APK与回退 + +- `lan-voice-v0714-liam-test-code40-arm64-debug.apk` +- URL:`http://192.168.31.124:8080/lan-voice-v0714-liam-test-code40-arm64-debug.apk` +- SHA256:`5aa64ca37aac218ab10d9b41b832d7574f9aa1b399c455ddf744d80c138ff644` +- applicationId:`com.gorios.lanvoice.liamtest`,versionName:`0.7.14-liam-test`,versionCode:40。 +- arm64-v8a,min26/target34;既有debug证书 SHA256 `b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`。 +- main code39与Liam code38文件/SHA复核相同;全部旧APK及camera-probe保留。回退可由协调者按既有USB流程选择旧Liam code38;本轮没有安装/降级/清数据。 + +正常launcher在既有用户授权/权限允许时会自动开始语音/相机;本轮没有执行。协调者安装后只需保持正常会话安静等待12–18秒左右,再观察随机 pose:标记应隐藏、此时语音不被录入;完成后 actual LISTENING恢复。讲话应只显示neutral自身嘴动画,drain后收口;后台返回不能出现旧音频/旧pose回调。随机可能选择继续idle,不保证每一个等待周期必出pose。 + +## 交给 gateway owner 的未执行登记清单 + +新精确 index key:`25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8`。 + +```json +{ + "25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8": { + "asset_01": 8042, + "asset_02": 8042 + } +} +``` + +两action仍kind=dance、193帧、8,041,667µs、entry/return A、neutral frame144进/frame0回、disallowTALK=true;上述媒体SHA保持不变。pose是本地等待行为,不登记成server dance/新action种类。本APK `networkActionsAllowed=false`、HELLO不宣称新pin的联网dance;正常Liam对话可用,离线dance检查保留。gateway审核登记后,按现有机制还需明确打开构建开关、交付新的不可覆盖版本;不能冒用旧pin或宣称仅登记即自动打开code40。音乐听审、舞蹈接缝与真实设备验收仍未测。 diff --git a/manifests/character-build-profiles.json b/manifests/character-build-profiles.json index 9a4c7a8..e522aa1 100644 --- a/manifests/character-build-profiles.json +++ b/manifests/character-build-profiles.json @@ -34,7 +34,8 @@ "versionBase": "0.7.14", "minimumVersionCode": 35, "additionalMediaSelections": [ - "char-expressions-r02" + "char-expressions-r02", + "char-waiting-poses-r01" ], "settingsNote": "Liam 英语人设与服务端绑定音色测试;外观仍为黑裙角色,媒体身份为 a01。" } @@ -74,6 +75,22 @@ "resourceDirectory": "app/src/characterAssets/char-expressions-r02/res", "posterResource": "startup_char_expressions_r02_poster", "settingsNote": "Liam 英语人设与服务端绑定音色测试;char 多表情素材候选,联网舞蹈已授权登记,音乐听审与真机自然度待验。" + }, + "char-waiting-poses-r01": { + "identityId": "a01", + "packId": "a01-expression-action-v1", + "assetRoot": "avatar/char-waiting-poses-r01/", + "indexSha256": "25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8", + "userAuthorizedDebug": true, + "networkActionsAllowed": false, + "minimumVersionCode": 40, + "bootstrapRoot": "avatar/startup-char-waiting-poses-r01/", + "bootstrapSha256": "097113985ee279f0360fe4817dd91f4aabea6a5bf32a6fd86e290dc8c381a941", + "bootstrapMetadata": "manifests/startup-char-waiting-poses-r01.json", + "resourceDirectory": "app/src/characterAssets/char-waiting-poses-r01/res", + "posterResource": "startup_char_waiting_poses_r01_poster", + "settingsNote": "Liam 英语人设;neutral 专用 TALK、两段本地无声等待 pose(停采音、不讲、不叠嘴)。新 pin 联网舞蹈待登记;两段舞蹈字节保留。", + "waitingContract": true } }, "commonAssets": { diff --git a/manifests/liam-waiting-poses-r01-provenance.json b/manifests/liam-waiting-poses-r01-provenance.json new file mode 100644 index 0000000..3eee7ea --- /dev/null +++ b/manifests/liam-waiting-poses-r01-provenance.json @@ -0,0 +1,40 @@ +{ + "sourceIndexSha256": "1f7b33e145e68476f3a9b1f15a3380d56cef3040fcd798a4ca19d027ea4c5ad9", + "revision": "char-waiting-poses-r01", + "authorization": "user_20261015_liam_local_waiting_poses", + "sourceInventoryMismatches": [ + "HANDOFF.md" + ], + "metadataCorrections": [ + { + "field": "asset_02.audioEndUs", + "source": 8000000, + "measured": 7940998 + } + ], + "runtimeReadyOverridden": false, + "talkIdle": "existing neutral145 with its own five-level patches", + "gatewayAdmission": "pending_new_exact_pin", + "poseMedia": { + "suit-adjust": { + "sha256": "d849ca16945d951821d315f5c76f2a6466656d8093584b2004eb0ae794bf1fb9", + "bytes": 1914915 + }, + "knuckle-check": { + "sha256": "c88655e370ad164cb028d1e11f4f6b5ae7aff695f26f9ecf7068349a3f25f761", + "bytes": 1525851 + } + }, + "generationCalls": 0, + "sourceInventoryOmissions": [ + "conversation/neutral/manifest.json", + "conversation/happy/manifest.json", + "conversation/sad/manifest.json", + "bridges/neutral-to-happy/manifest.json", + "bridges/happy-to-neutral/manifest.json", + "bridges/neutral-to-sad/manifest.json", + "bridges/sad-to-neutral/manifest.json" + ], + "indexSha256": "25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8", + "files": 2596 +} diff --git a/manifests/startup-char-waiting-poses-r01.json b/manifests/startup-char-waiting-poses-r01.json new file mode 100644 index 0000000..6f444dd --- /dev/null +++ b/manifests/startup-char-waiting-poses-r01.json @@ -0,0 +1,166 @@ +{ + "schemaVersion": 1, + "sourceIndexSha256": "25de3d199ad6122bf7840005d581b3ae2b4a1ffc10ceecd95793f636e3fd4ed8", + "posterSha256": "c9dea401f80273a6ddf6d8b33673ee2c5968a5d4e2123080aee37a18c164f0a6", + "posterWidth": 180, + "posterHeight": 320, + "provenance": "Exact decoded neutral source frame0; CPU downsample, no generated media; user-authorized debug integration, not Pi certification", + "body": { + "path": "avatar/char-waiting-poses-r01/conversation/neutral/body/neutral-idle.mp4", + "sha256": "731b2444d00d307816b7edc9a11437f2780255b279506547a4caad13ef3fc23c", + "width": 720, + "height": 1280, + "frameCount": 145, + "ptsUs": [ + 0, + 41667, + 83333, + 125000, + 166667, + 208333, + 250000, + 291667, + 333333, + 375000, + 416667, + 458333, + 500000, + 541667, + 583333, + 625000, + 666667, + 708333, + 750000, + 791667, + 833333, + 875000, + 916667, + 958333, + 1000000, + 1041667, + 1083333, + 1125000, + 1166667, + 1208333, + 1250000, + 1291667, + 1333333, + 1375000, + 1416667, + 1458333, + 1500000, + 1541667, + 1583333, + 1625000, + 1666667, + 1708333, + 1750000, + 1791667, + 1833333, + 1875000, + 1916667, + 1958333, + 2000000, + 2041667, + 2083333, + 2125000, + 2166667, + 2208333, + 2250000, + 2291667, + 2333333, + 2375000, + 2416667, + 2458333, + 2500000, + 2541667, + 2583333, + 2625000, + 2666667, + 2708333, + 2750000, + 2791667, + 2833333, + 2875000, + 2916667, + 2958333, + 3000000, + 3041667, + 3083333, + 3125000, + 3166667, + 3208333, + 3250000, + 3291667, + 3333333, + 3375000, + 3416667, + 3458333, + 3500000, + 3541667, + 3583333, + 3625000, + 3666667, + 3708333, + 3750000, + 3791667, + 3833333, + 3875000, + 3916667, + 3958333, + 4000000, + 4041667, + 4083333, + 4125000, + 4166667, + 4208333, + 4250000, + 4291667, + 4333333, + 4375000, + 4416667, + 4458333, + 4500000, + 4541667, + 4583333, + 4625000, + 4666667, + 4708333, + 4750000, + 4791667, + 4833333, + 4875000, + 4916667, + 4958333, + 5000000, + 5041667, + 5083333, + 5125000, + 5166667, + 5208333, + 5250000, + 5291667, + 5333333, + 5375000, + 5416667, + 5458333, + 5500000, + 5541667, + 5583333, + 5625000, + 5666667, + 5708333, + 5750000, + 5791667, + 5833333, + 5875000, + 5916667, + 5958333, + 6000000 + ], + "durationUs": 6041667, + "fpsNumerator": 24, + "fpsDenominator": 1, + "hasAudio": false + } +} diff --git a/scripts/check-avatar-apk-runtime.py b/scripts/check-avatar-apk-runtime.py index 2437b8a..ad55e4b 100644 --- a/scripts/check-avatar-apk-runtime.py +++ b/scripts/check-avatar-apk-runtime.py @@ -266,6 +266,34 @@ if args.user_asset_candidate: startup_main=startup_main.replace('packages.size==5','packages.size=='+str(len(index['conversationPackages']))) startup_main=startup_main.replace('packages=5|bridge_mouths=8','packages='+str(len(index['conversationPackages']))+ '|bridge_mouths='+str(sum('mouthRuntimeManifest' in e for e in index['edges']))) +if args.user_asset_candidate and index.get('waiting'): + # Use the actual APK's local waiting contract, not the old emotion-idle policy. + header=main[:main.index(' run {')] + dance=main[main.index(' for(initial in listOf('):main.index(' println("HOST_REPLAY|')] + main=header+r''' + for(pose in index.waiting!!.poses) { + val(view,binding,trace)=rig();var finished=0;var failed=0 + binding.waitingListener { binding.waitingEligible(false);binding.playWaitingPose(it,{finished++},{failed++}) } + binding.waitingEligible(true) + val driver=view.javaClass.getDeclaredField("driver").apply { isAccessible=true }.get(view) as ConversationMediaDriver + driver.javaClass.getDeclaredField("queuedPose").apply { isAccessible=true }.set(driver,pose) + TestScheduler.until(15_000) { trace.lastOrNull()?.second?.actual=="pose_${pose.id}" } + TestScheduler.until(15_000) { finished==1 || failed>0 } + check(failed==0 && finished==1 && trace.none { it.second.actual=="media_failed" }) + val frames=trace.count { it.second.actual=="pose_${pose.id}" } + check(frames==pose.clip.frameCount && MediaPlayer.created.isEmpty() && binding.currentPackageId==index.waiting!!.idlePackage) + println("WAITING_POSE|id=${pose.id}|actual_composed_frames=$frames|music_players=0|return=${binding.currentPackageId}|owner=${driver.layerOwner}|device=false") + var ready=0;binding.prepareTalk({ready++},{failed++});TestScheduler.advanceBy(50) + check(ready==1 && failed==0) + binding.intent(mediaReply(RoleEmotion.HAPPY),true);TestScheduler.advanceBy(1500) + check(binding.currentPackageId==index.waiting!!.talkPackage && binding.selection?.selectedEmotion==RoleEmotion.HAPPY) + binding.intent(null,false);binding.finishTalk();TestScheduler.advanceBy(1000) + check(binding.currentPackageId==index.waiting!!.idlePackage) + println("TALK_IDLE|requested=happy|actual=${binding.currentPackageId}|own_mouth=true|closed_to_wait=true|device=false") + view.dispose();TestScheduler.advanceBy(100) + } +'''+dance+' println("HOST_REPLAY|waiting_contract=true|both_poses=true|actual_apk_bytes=true|native_device=false|record_stop_mock=true")\n}\n' + main=main.replace(' index.actionPack?.assets?', ' index.waiting?.poses?.forEach { CodecFixture.timelines[index.root+it.clip.path]=it.clip.ptsUs }\n index.actionPack?.assets?') with tempfile.TemporaryDirectory(prefix='baji-runtime-audit-') as td: tmp=Path(td);files=[] for path in (ROOT/'tests/avatar').glob('*.kt'): diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index 0438f45..7880d54 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -27,7 +27,7 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice' suites = [ ('session','ConnectionCheckKt', [source/'diag/DiagnosticLog.kt',source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']), - ('avatar','AvatarCheckKt', [source/'diag/DiagnosticLog.kt',source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/OfflineDancePreview.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), + ('avatar','AvatarCheckKt', [source/'avatar/WaitingPose.kt',source/'diag/DiagnosticLog.kt',source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/OfflineDancePreview.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), ('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ] @@ -50,7 +50,7 @@ for name, main, real in suites: if args.suite and name != args.suite: continue with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out: files = list((ROOT/'tests'/name).glob('*.kt')) + real - if name in ('session','avatar'): files.append(source/'diag/StartupTrace.kt') + if name in ('session','avatar'): files += [source/'diag/StartupTrace.kt',source/'avatar/WaitingPose.kt',source/'avatar/ContinuousAvatarManifest.kt',source/'avatar/ContinuousMouth.kt'] if name=='session' else [source/'diag/StartupTrace.kt'] if name in ('session','protocol'): files.append(source/'expression/PresenceRules.kt') if name=='avatar': files += [source/'avatar/StartupAvatarView.kt',source/'avatar/StartupLoadCache.kt'] if name == 'avatar' and (args.runtime_manifest or args.index_manifest): diff --git a/scripts/check-waiting-pose-shader.py b/scripts/check-waiting-pose-shader.py new file mode 100644 index 0000000..1081f90 --- /dev/null +++ b/scripts/check-waiting-pose-shader.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Real offscreen production GLES fragment shader, decoded silent pose frames. +OES is replaced with a 2D decoded surrogate; no Android GPU/performance claim. +The one-pixel test texture verifies opacity=0 body bypass, not a runtime mouth pack. +""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import numpy as np +ROOT=Path(__file__).resolve().parents[1] + +def check(index,output): + m=json.loads(index.read_bytes());source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text() + vertex=re.search(r'const val VERTEX="""([\s\S]*?)"""',source)[1] + fragment=re.search(r'const val FRAGMENT="""([\s\S]*?)"""',source)[1].replace('#extension GL_OES_EGL_image_external : require','').replace('samplerExternalOES','sampler2D') + spec=importlib.util.spec_from_file_location('golden',ROOT/'scripts/check-avatar-shader.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + rows=[] + with tempfile.TemporaryDirectory(prefix='waiting-pose-gles-') as td: + tmp=Path(td);(tmp/'vertex').write_text(vertex);(tmp/'fragment').write_text(fragment) + subprocess.run(['cc','-O2',str(ROOT/'tests/avatar-pixels/gles-golden.c'),'-lEGL','-lGLESv2','-lm','-o',str(tmp/'golden')],check=True) + env=dict(os.environ,EGL_PLATFORM='surfaceless',LIBGL_ALWAYS_SOFTWARE='1') + for pose in m['waiting']['poses']: + clip=pose['clip'];w,h=clip['width'],clip['height'];frames=[0,clip['frameCount']//2,clip['frameCount']-1] + raw=subprocess.check_output(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(index.parent/clip['path']),'-vf','select='+ '+'.join(f'eq(n\\,{i})' for i in frames),'-fps_mode','vfr','-f','rawvideo','-pix_fmt','rgba','-'],timeout=60) + assert len(raw)==len(frames)*w*h*4 + # Deliberately opaque bright test patch: body-only must bypass even this texture. + patch=np.array([[[255,0,255,255]]],dtype=np.uint8);(tmp/'patch.rgba').write_bytes(patch.tobytes()) + for j,i in enumerate(frames): + body=np.frombuffer(raw[j*w*h*4:(j+1)*w*h*4],np.uint8).reshape(h,w,4);(tmp/'body.rgba').write_bytes(body.tobytes()) + for vw,vh in [(w,h),(360,800),(800,480)]: + r=subprocess.run([str(tmp/'golden'),str(tmp/'vertex'),str(tmp/'fragment'),str(tmp/'body.rgba'),str(tmp/'patch.rgba'),str(tmp/'out.rgba'),'1','1','0','0','0',str(vw),str(vh),'0',str(w),str(h),'1','.5'],env=env,capture_output=True,text=True,check=True) + actual=np.frombuffer((tmp/'out.rgba').read_bytes(),np.uint8).reshape(vh,vw,4)[::-1,:,:3] + expected=module.golden(body,patch,0,0,0,vw,vh,0) + diff=np.abs(actual.astype(int)-expected.astype(int));assert diff.max()<=2 + if (vw,vh)==(w,h):assert np.array_equal(actual,body[:,:,:3]),'native smile/body must be pixel exact' + rows.append({'pose':pose['id'],'frame':i,'viewport':[vw,vh],'mouthOpacity':0,'maxAbsRGB':int(diff.max()),'gl':r.stdout.strip()}) + output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps({'status':'passed','cases':rows,'device':'not_run','runtimeMouthTextures':0},indent=2)+'\n') + print(f'PASS: {len(rows)} real GLES decoded pose/no-mouth/native-face/Fit pixel comparisons; Android GPU not_run') + +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--index',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();check(a.index,a.output) diff --git a/scripts/derive-liam-waiting-pack.py b/scripts/derive-liam-waiting-pack.py new file mode 100644 index 0000000..268c2ee --- /dev/null +++ b/scripts/derive-liam-waiting-pack.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Freeze the exact authorized Liam intake as a new revision; never edit owner input. +Only HANDOFF inventory, measured dance AAC presentation end, and local pose metadata +are corrected. No synthesis, video re-encode, runtimeReady override or gateway admission. +""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil + +ROOT=Path(__file__).resolve().parents[1] +SOURCE_PIN='1f7b33e145e68476f3a9b1f15a3380d56cef3040fcd798a4ca19d027ea4c5ad9' +POSES={ + 'suit-adjust':('pose-source/revisions/poses-r02/media/suit-adjust.mp4',1914915,'d849ca16945d951821d315f5c76f2a6466656d8093584b2004eb0ae794bf1fb9'), + 'knuckle-check':('pose-source/revisions/poses-r01/media/knuckle-check.mp4',1525851,'c88655e370ad164cb028d1e11f4f6b5ae7aff695f26f9ecf7068349a3f25f761')} + +def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest() +def write(p,data):p.write_text(json.dumps(data,indent=2,ensure_ascii=False)+'\n') +def derive(intake,output): + source=intake/'expressions-r02';manifest=source/'manifest.json' + assert digest(manifest)==SOURCE_PIN,'wrong intake index' + assert not output.exists() and not output.resolve().is_relative_to(intake.resolve()),'new external revision required' + assert not any(p.is_symlink() for p in intake.rglob('*')),'symlink input' + m=json.loads(manifest.read_bytes());bad=[] + for r in m['files']: + p=source/r['path'];assert p.resolve().is_relative_to(source.resolve()) and p.is_file() + if digest(p)!=r['sha256'] or p.stat().st_size!=r['bytes']:bad.append(r['path']) + assert bad==['HANDOFF.md'],'unexpected inventory mismatch' + spec=importlib.util.spec_from_file_location('gate',ROOT/'scripts/package-avatar-emotion.py') + gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(gate) + measurements={key:gate.probe_clip(intake/row[0]) for key,row in POSES.items()} + for key,(name,size,sha) in POSES.items(): + p=intake/name;v=measurements[key] + assert p.stat().st_size==size and digest(p)==sha + assert v['shape']==(720,1280) and len(v['ptsUs'])==193 and v['fps']==24 and abs(v['durationUs']-8041667)<=2 + shutil.copytree(source,output) + corrections=[] + for a in m['actions']: + clip=a['clip'];actual=gate.probe_music_clip(source/clip['path']) + if actual['audioEndUs']!=a['audioEndUs']: + corrections.append({'field':a['id']+'.audioEndUs','source':a['audioEndUs'],'measured':actual['audioEndUs']}) + a['audioEndUs']=actual['audioEndUs'] + poses=[] + for key,(name,size,sha) in POSES.items(): + v=measurements[key];path='waiting-poses/'+key+'.mp4';dest=output/path;dest.parent.mkdir(exist_ok=True);shutil.copyfile(intake/name,dest) + poses.append({'id':key,'kind':'waiting_pose','mouthAllowed':False,'entryAnchor':'A','returnAnchor':'A', + 'sourcePackageId':'neutral','sourceFrame':0,'sourcePtsUs':0,'returnPackageId':'neutral','returnFrame':0,'returnPtsUs':0, + 'clip':{'path':path,'sha256':sha,'width':720,'height':1280,'frameCount':193,'durationUs':v['durationUs'], + 'fpsNumerator':24,'fpsDenominator':1,'ptsUs':v['ptsUs'],'hasAudio':False}}) + m['revision']='char-waiting-poses-r01' + m['waiting']={'schemaVersion':1,'idlePackageId':'neutral','talkPackageId':'neutral', + 'microphoneAllowed':False,'ttsAllowed':False,'mouthAllowed':False,'poses':poses} + provenance={'sourceIndexSha256':SOURCE_PIN,'revision':m['revision'],'authorization':'user_20261015_liam_local_waiting_poses', + 'sourceInventoryMismatches':bad,'metadataCorrections':corrections,'runtimeReadyOverridden':False, + 'talkIdle':'existing neutral145 with its own five-level patches','gatewayAdmission':'pending_new_exact_pin', + 'poseMedia':{k:{'sha256':v[2],'bytes':v[1]} for k,v in POSES.items()},'generationCalls':0} + write(output/'PACKAGING_REVISION.json',provenance) + (output/'HANDOFF.md').write_text('# Liam waiting poses: immutable application revision\n\n' + 'Source index: '+SOURCE_PIN+'\n\n' + 'The source HANDOFF inventory was stale. This revision corrects that row and ' + 'measures AAC presentation ends without changing media bytes. All original runtimeReady ' + 'flags remain unchanged; exact user-authorized debug admission requires the production checker.\n\n' + 'neutral (145 frames, own N×5 patches) is the dedicated TALK idle. During silent waiting, ' + 'rotate ordinary idle and two local waiting poses. Before a pose, confirm actual AudioRecord ' + 'stop. No ASR input, TTS, audio track or mouth patches during pose. Return only after actual ' + 'final video frame, decoder release and actual composed neutral frame0. ' + 'This is separate from transparent expression patch intervals, where TTS may continue.\n\n' + 'Both original dance videos are byte-identical. New exact index gateway registration is pending; ' + 'this packaging does not authorize network dance, installation or production deployment.\n') + table={r['path']:r for r in m['files']} + refs=[r['runtimeManifest'] for r in m['conversationPackages']]+[e['mouthRuntimeManifest'] for e in m['edges'] if 'mouthRuntimeManifest' in e] + omitted=[] + for ref in refs: + p=source/ref['path'];assert digest(p)==ref['sha256'],'runtime reference hash drift' + if ref['path'] not in table: + omitted.append(ref['path']);table[ref['path']]={'path':ref['path'],'sha256':digest(p),'bytes':p.stat().st_size} + provenance['sourceInventoryOmissions']=omitted + write(output/'PACKAGING_REVISION.json',provenance) + for name in ['HANDOFF.md','PACKAGING_REVISION.json',*[p['clip']['path'] for p in poses]]: + p=output/name;table[name]={'path':name,'sha256':digest(p),'bytes':p.stat().st_size} + m['files']=[table[k] for k in sorted(table)];write(output/'manifest.json',m) + assert 'manifest.sha256' not in table,'self-pin must be external to index files' + (output/'manifest.sha256').write_text(digest(output/'manifest.json')+' manifest.json\n') + return {**provenance,'indexSha256':digest(output/'manifest.json'),'files':len(m['files'])} + +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--intake',type=Path,required=True);p.add_argument('--output',type=Path,required=True) + a=p.parse_args();print(json.dumps(derive(a.intake,a.output),indent=2)) diff --git a/scripts/package-avatar-emotion.py b/scripts/package-avatar-emotion.py index 166a7bf..ef5ee4e 100644 --- a/scripts/package-avatar-emotion.py +++ b/scripts/package-avatar-emotion.py @@ -153,6 +153,14 @@ def check_bundle(manifest,expected,output,user_authorized_debug=False): require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name) require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name) require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name) + pose_measurements=[] + for pose in index.get('waiting',{}).get('poses',[]): + clip=pose['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],64_000_000) + require(pose['kind']=='waiting_pose' and clip['hasAudio'] is False and pose['mouthAllowed'] is False,'silent waiting pose contract') + measured=probe_clip(path) + require(measured['shape']==(clip['width'],clip['height']) and len(measured['ptsUs'])==clip['frameCount']==len(clip['ptsUs']),'pose decoded shape/N') + require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])) and abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'pose decoded PTS/timing') + pose_measurements.append({'id':pose['id'],**{k:v for k,v in measured.items() if k!='fps'}}) action_measurements=[] for action in actions: clip=action['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],128_000_000) @@ -185,7 +193,7 @@ def check_bundle(manifest,expected,output,user_authorized_debug=False): for name,row in files.items(): require(file_sha(locate(root,name))==row['sha256'],'bundle changed during gate') report={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':expected, 'user_authorized_debug':user_authorized_debug,'runtime_packages':runtimes,'combined_rgba_bytes':rgba,'referenced_files':len(files),'preview_files_not_packaged':len(table.keys()-files.keys()), - 'edge_count':len(index['edges']),'action_count':len(actions),'dance_available':False, + 'pose_measurements':pose_measurements,'edge_count':len(index['edges']),'action_count':len(actions),'dance_available':False, 'candidate_dance_validated':bool(actions),'action_measurements':action_measurements,'production_kotlin_index':'passed', 'naturalness':'not_certified','real_device':'not_run','files':files} (output/'bundle-gate.json').write_text(json.dumps(report,indent=2)+'\n') diff --git a/scripts/package-character-test.py b/scripts/package-character-test.py index 0528374..2dd19d7 100644 --- a/scripts/package-character-test.py +++ b/scripts/package-character-test.py @@ -99,6 +99,8 @@ def verify(apk, profile, version, media_bundle='black-correct03',frame_zoom=1,fr for field, value in {'AVATAR_NETWORK_ACTIONS_ALLOWED': media.get('networkActionsAllowed',False), 'AVATAR_USER_ASSET_CANDIDATE': True, 'PERMISSION_CONNECTION_RETENTION': role['permissionConnectionRetention']}.items(): require(dex_values.get(field) == str(value).lower(), 'APK DEX boolean mismatch: '+field) + if 'WAITING_POSES_ENABLED' in dex_values or version>=40: + require(dex_values.get('WAITING_POSES_ENABLED') == str(media.get('waitingContract',False)).lower(), 'APK DEX waiting gate mismatch') require(dex_values.get('VERSION_CODE') == str(version) and dex_values.get('VERSION_NAME') == '"0.7.14'+role['versionSuffix']+'"', 'APK DEX version mismatch') for field,value in [('AVATAR_FRAME_ZOOM',frame_zoom),('AVATAR_FRAME_CENTER_Y',frame_center_y)]: @@ -126,6 +128,7 @@ def verify(apk, profile, version, media_bundle='black-correct03',frame_zoom=1,fr 'index_sha256': media['indexSha256'], 'media_bundle':media_bundle, 'asset_files_verified':len(selected['files']), 'assets_unchanged': len(selected['files']) if media_bundle=='black-correct03' else None, 'network_actions_allowed':media.get('networkActionsAllowed',False), + 'waiting_contract_enabled':media.get('waitingContract',False), 'framing_zoom':frame_zoom,'framing_center_y':frame_center_y, 'poster_resources_unchanged': 2, 'provider_authorities': authorities, 'actual_dex_verified': True, 'device': 'not_run', 'gateway_changed': False} diff --git a/scripts/select-character-assets.py b/scripts/select-character-assets.py index a0c3179..65bd143 100644 --- a/scripts/select-character-assets.py +++ b/scripts/select-character-assets.py @@ -89,6 +89,7 @@ def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mout base = bundle['assetRoot'] index = json.loads(add(base + 'manifest.json', emotion_sha)) require(index['identityId'] == bundle['identityId'] and index['packId'] == bundle['packId'], 'media identity mismatch') + require(bool(index.get('waiting')) == bundle.get('waitingContract',False), 'waiting contract/catalog mismatch') declared = {relative(r['path']): r for r in index['files']} def payload(name, sha): @@ -112,6 +113,8 @@ def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mout payload(edge['clip']['path'], edge['clip']['sha256']) if edge.get('mouthRuntimeManifest'): runtime(edge['mouthRuntimeManifest']) + for pose in index.get('waiting',{}).get('poses',[]): + payload(pose['clip']['path'],pose['clip']['sha256']) for action in index['actions']: payload(action['clip']['path'], action['clip']['sha256']) if startup: diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index bdf2cd1..3b2a04f 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -6,6 +6,7 @@ import android.media.MediaPlayer import android.view.TextureView fun main() { + waitingPoseMediaCheck() startupCacheCheck() startupViewCheck() reportedActionClockCheck() diff --git a/tests/avatar/EmotionActionCheck.kt b/tests/avatar/EmotionActionCheck.kt index 99f4b86..14d2555 100644 --- a/tests/avatar/EmotionActionCheck.kt +++ b/tests/avatar/EmotionActionCheck.kt @@ -34,5 +34,20 @@ fun emotionActionCheck() { mapOf("audioEndUs" to 2_000_001L),mapOf("clip" to clip(false)),mapOf("clip" to clip(true)+("path" to "../escape.mp4")))) { check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null) } + val pose=mapOf("id" to "suit-adjust","kind" to "waiting_pose","mouthAllowed" to false, + "entryAnchor" to "A","returnAnchor" to "A","sourcePackageId" to "neutral","returnPackageId" to "neutral", + "sourceFrame" to 0,"returnFrame" to 0,"sourcePtsUs" to 0L,"returnPtsUs" to 0L,"clip" to clip(false)) + val waiting=mapOf("schemaVersion" to 1,"microphoneAllowed" to false,"ttsAllowed" to false,"mouthAllowed" to false, + "idlePackageId" to "neutral","talkPackageId" to "neutral","poses" to listOf(pose)) + check(read(root+("waiting" to waiting))?.waiting?.poses?.single()?.id=="suit-adjust") + for(change in listOf(mapOf("microphoneAllowed" to true),mapOf("ttsAllowed" to true),mapOf("mouthAllowed" to true), + mapOf("talkPackageId" to "missing"),mapOf("idlePackageId" to "happy"),mapOf("poses" to listOf(pose,pose)),mapOf("poses" to emptyList()))) + check(read(root+("waiting" to waiting+change))==null) + for(change in listOf(mapOf("sourceFrame" to 1),mapOf("returnPtsUs" to 1),mapOf("sourcePackageId" to "happy"),mapOf("mouthAllowed" to true), + mapOf("audioEndUs" to 1900000),mapOf("kind" to "dance"),mapOf("mouthRuntimeManifest" to mapOf("path" to "x")), + mapOf("clip" to clip(true)),mapOf("clip" to clip(false)+("width" to 720)),mapOf("clip" to clip(false)+("path" to "../wrong.mp4")), + mapOf("clip" to clip(false)+("ptsUs" to listOf(0L,0L))))) + check(read(root+("waiting" to waiting+("poses" to listOf(pose+change))))==null) + println("PASS: 19 production waiting contract admission/rejection assertions: silent body-only, strict pin/source-return0/PTS/shape/paths/unique IDs, no dance or fake mouths") println("PASS: production v2 index exact external pin/own body-mouth SHA/runtime04/complete bridges/music bounds/no TALK, synthetic metadata only") } diff --git a/tests/avatar/WaitingPoseMediaCheck.kt b/tests/avatar/WaitingPoseMediaCheck.kt new file mode 100644 index 0000000..82300c5 --- /dev/null +++ b/tests/avatar/WaitingPoseMediaCheck.kt @@ -0,0 +1,108 @@ +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.dialogue.* +import android.os.TestScheduler +import android.media.CodecFixture +import android.media.MediaPlayer +import android.opengl.GLFixture +import android.graphics.BitmapFactory + +fun waitingFixture(): EmotionActionIndex { + val base=mediaFixtureIndex(720,1280) + val poses=listOf("suit-adjust","knuckle-check").map { id->WaitingPose(id, + ContinuousBodyAsset("waiting-poses/$id.mp4","b".repeat(64),720,1280,193,8_041_667,List(193) { (it*1_000_000.0/24).toLong() }), + "neutral",0,"neutral",0) } + return base.copy(waiting=WaitingMedia("neutral","neutral",poses)) +} + +/** Production layer driver with deliberately delayed recorder admission / decoder release. */ +fun waitingPoseMediaCheck() { + var cases=0 + class Port: CompositeMediaPort { + lateinit var pack: ContinuousAvatarPack;lateinit var frame: (BodyFrameKey,Boolean)->Unit + lateinit var end: ()->Unit;lateinit var fail: ()->Unit + var mouthEnabled=true;var looping=false;var talk=false;var advances=0;var key: BodyFrameKey?=null + var release: (()->Unit)?=null;var activation: (()->Unit)?=null + override fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean, + frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) { + this.pack=pack;this.frame=frame;end=ended;fail=failed;mouthEnabled=mouth;looping=loop + } + fun emit(i: Int,loop: Long=0,closed: Boolean=true) { key=BodyFrameKey(i,loop,pack.body.ptsUs[i]);frame(key!!,closed) } + override fun advance() { advances++ } + override fun mouth(talk: Boolean,generation: Long,revision: Long) { this.talk=talk } + override fun activateMouth(talk: Boolean,generation: Long,revision: Long,ready: ()->Unit) { + this.talk=talk;activation={ key?.let { frame(it,!talk) };ready() } + } + override fun close(released: ()->Unit) { release=released } + } + val music=object: MusicMediaPort { + override fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit)=error("pose must not use dance/audio") + override fun start()=error("pose must not start music") + override fun close(released: ()->Unit)=released() + } + for(choice in 0..2) for(cancel in listOf(false,true)) { + val index=waitingFixture();val ports=mutableListOf();val trace=mutableListOf();val layers=mutableListOf() + val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,layers::add,{ e,_->trace.add(e) },chooseIdle={choice},chooseIdleCycles={2}) + var offered: WaitingPose?=null;var done=0;var failed=0 + driver.waitingListener { offered=it };driver.waitingEligible(true);driver.beginTurn(7);driver.start() + val source=ports[0];source.emit(0) + for(loop in 0L..1L) { if(loop>0) source.emit(0,loop);for(i in 1..96) source.emit(i,loop) } + source.emit(0,2) + if(choice==0) { check(offered==null && ports.size==1);cases++;driver.stop {};continue } + check(offered==index.waiting!!.poses[choice-1]);cases++ + val held=source.advances;source.emit(0,2);check(source.advances==held);cases++ + // No pose renderer exists before the real capture-stop acknowledgment calls play. + check(ports.size==1 && driver.layerOwner==ConversationMediaDriver.LayerOwner.CONVERSATION);cases++ + driver.playWaitingPose(offered!!,{done++},{failed++});val pose=ports[1] + check(!pose.mouthEnabled && !pose.looping && pose.pack.patches.isEmpty() && pose.pack.curves.isEmpty());cases++ + pose.emit(0);check(driver.layerOwner==ConversationMediaDriver.LayerOwner.POSE);cases++ + driver.beginTurn(8);driver.intent(mediaReply(RoleEmotion.HAPPY,turn=8),true) + var ready=0;driver.prepareTalk({ready++},{failed++}) + val layer=layers.last();source.emit(0,2);check(layers.last()==layer && !pose.talk && ready==0);cases++ + for(i in 1..192) { pose.emit(i);check(!pose.talk && layers.last()==layer);cases++ } + if(cancel) driver.cancelWaitingPose { done++ } else pose.end() + check(done==0 && ready==0 && driver.layerOwner==ConversationMediaDriver.LayerOwner.POSE && pose.release!=null);cases++ + source.emit(0,2);check(done==0);cases++ // Still barred before decoder close acknowledgment. + pose.release!!();check(done==0 && source.activation!=null);cases++ + source.activation!!();check(done==1 && failed==0 && ready==1 && layers.last()==0 && driver.layerOwner==ConversationMediaDriver.LayerOwner.CONVERSATION);cases++ + val before=trace.size;pose.emit(192);pose.end();check(trace.size==before && done==1);cases++ + driver.finishTalk();driver.stop {};source.emit(0,2);check(driver.layerOwner==ConversationMediaDriver.LayerOwner.STOPPED);cases++ + ports.forEach { it.release?.invoke() } + } + // Real native renderer + actual view/binding, deterministic Android MediaCodec/EGL doubles. + for(picked in 0..1) { + TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false;MediaPlayer.created.clear() + CodecFixture.emitNativeSurface=true;CodecFixture.width=720;CodecFixture.height=1280 + val index=waitingFixture() + index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } + index.waiting!!.poses.forEach { CodecFixture.timelines[index.root+it.clip.path]=it.clip.ptsUs } + val binding=AvatarMediaBinding();var finish=0;var failure=0 + val reports=mutableListOf() + val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,reports::add) + binding.waitingListener { binding.waitingEligible(false);binding.playWaitingPose(it,{finish++},{failure++}) } + binding.waitingEligible(true);view.render(true) + val driver=view.javaClass.getDeclaredField("driver").apply { isAccessible=true }.get(view) as ConversationMediaDriver + driver.javaClass.getDeclaredField("queuedPose").apply { isAccessible=true }.set(driver,index.waiting.poses[picked]) + TestScheduler.advanceBy(1) + TestScheduler.until { finish==1 || failure>0 || reports.any { it.actual=="media_failed" } } + check(finish==1 && failure==0 && reports.none { it.actual=="media_failed" });cases++ + check(reports.count { it.actual=="pose_${index.waiting.poses[picked].id}" }==193);cases++ + check(reports.any { it.actual=="pose_return_a" } && MediaPlayer.created.isEmpty());cases++ + val before=reports.size;view.dispose();TestScheduler.advanceBy(1000) + check(reports.size==before);cases++ + } + run { + val early=AvatarMediaBinding(true);var ready=0;var failure=0 + early.prepareTalk({ready++},{failure++});check(ready==0 && failure==0);cases++ + val index=waitingFixture();val ports=mutableListOf() + val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{},holdInitial=true) + driver.start();early.attach(driver);ports.single().emit(0) + check(ready==0);cases++ // Actual frame is ready but bootstrap still owns the visible layer. + driver.releaseInitial();check(ready==1 && failure==0);cases++ + early.finishTalk();driver.stop {};ports.forEach { it.release?.invoke() };early.detach(driver) + early.prepareTalk({ready++},{failure++});early.finishTalk() + val next=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}) + next.start();early.attach(next);ports.last().emit(0);check(ready==1);cases++ + next.stop {};ports.forEach { it.release?.invoke() } + } + println("PASS: $cases production waiting-pose owner/held-frame0/random-idle/both193-frame-body-only clips/mouth-off/late-turn/release-ack/restored-actual-A/cancel/old-callback assertions; real view+renderer callbacks with Android doubles, hardware not_run") +} diff --git a/tests/packaging/test_character_profiles.py b/tests/packaging/test_character_profiles.py index f79467e..75a789e 100644 --- a/tests/packaging/test_character_profiles.py +++ b/tests/packaging/test_character_profiles.py @@ -168,3 +168,55 @@ class CharacterProfilesTests(unittest.TestCase): self.assertIn('-PcharacterMediaBundle=char-expressions-r02',flags) self.assertTrue(select.catalog()['mediaBundles']['char-expressions-r02']['networkActionsAllowed']) self.assertIn('Network dance requires separate reviewed media registration',(ROOT/'app/build.gradle').read_text()) + + +class WaitingPackTests(unittest.TestCase): + def selected(self,profile='liam-test'): + row=select.catalog()['mediaBundles']['char-waiting-poses-r01'] + return select.selection(ASSETS,profile,emotion_sha=row['indexSha256'],user_assets=True,mouth=True,startup=True,media_bundle='char-waiting-poses-r01') + + def test_new_pack_is_liam_only_with_two_real_body_only_poses(self): + row=select.catalog()['mediaBundles']['char-waiting-poses-r01'] + selected=self.selected();root=ASSETS/row['assetRoot'] + index=json.loads((root/'manifest.json').read_bytes()) + self.assertEqual(selected['persona'],'liam') + self.assertEqual(index['waiting']['talkPackageId'],'neutral') + self.assertEqual([p['id'] for p in index['waiting']['poses']],['suit-adjust','knuckle-check']) + for pose in index['waiting']['poses']: + self.assertIn(row['assetRoot']+pose['clip']['path'],selected['files']) + self.assertIs(pose['clip']['hasAudio'],False) + self.assertNotIn('mouthRuntimeManifest',pose) + self.assertFalse(any('char-expressions-r02/' in p or 'black-tulle' in p for p in selected['files'])) + for profile in ('main','lvbu-test'): + with self.assertRaises(ValueError):self.selected(profile) + + def test_frozen_media_and_candidate_flags_are_preserved(self): + new=select.catalog()['mediaBundles']['char-waiting-poses-r01'] + old=select.catalog()['mediaBundles']['char-expressions-r02'] + a=ASSETS/new['assetRoot'];b=ASSETS/old['assetRoot'] + m=json.loads((a/'manifest.json').read_bytes()) + for action in m['actions']: + name=action['clip']['path'] + self.assertEqual((a/name).read_bytes(),(b/name).read_bytes()) + for r in m['conversationPackages']: + runtime=json.loads((a/r['runtimeManifest']['path']).read_bytes()) + self.assertIs(runtime['runtimeReady'],False) + self.assertFalse(new['networkActionsAllowed']) + self.assertTrue(old['networkActionsAllowed']) + self.assertEqual(new['minimumVersionCode'],40) + + def test_pose_corruption_is_rejected(self): + row=select.catalog()['mediaBundles']['char-waiting-poses-r01'] + target=ASSETS/row['assetRoot']/'waiting-poses/suit-adjust.mp4';original=Path.read_bytes + with patch.object(Path,'read_bytes',lambda p:b'bad' if p==target else original(p)),self.assertRaises(ValueError):self.selected() + + def test_inventory_receipt_records_actual_source_gaps(self): + row=select.catalog()['mediaBundles']['char-waiting-poses-r01'] + root=ASSETS/row['assetRoot'];m=json.loads((root/'manifest.json').read_bytes()) + table={r['path']:r for r in m['files']} + refs=[r['runtimeManifest'] for r in m['conversationPackages']]+[r['mouthRuntimeManifest'] for r in m['edges'] if 'mouthRuntimeManifest' in r] + self.assertTrue(all(ref['path'] in table and table[ref['path']]['sha256']==ref['sha256'] for ref in refs)) + provenance=json.loads((ROOT/'manifests/liam-waiting-poses-r01-provenance.json').read_bytes()) + self.assertEqual(provenance['sourceInventoryMismatches'],['HANDOFF.md']) + self.assertEqual(len(provenance['sourceInventoryOmissions']),7) + self.assertFalse(provenance['runtimeReadyOverridden']) diff --git a/tests/session/AudioDoubles.kt b/tests/session/AudioDoubles.kt index 02e6cb7..16a56a0 100644 --- a/tests/session/AudioDoubles.kt +++ b/tests/session/AudioDoubles.kt @@ -14,13 +14,13 @@ class AudioCapture { fun release() {} } class AudioPlayback(onDrained: (Long, Long) -> Unit, onError: (Long, Exception) -> Unit, onProgress: (Long, Long, String) -> Unit = { _, _, _ -> }, onActivity: (PlaybackActivity) -> Unit = {}, onPlaying: (Long,Long,Boolean)->Unit={_,_,_->}) { - companion object { var interrupts = 0; var enqueued = 0; var lastDrained: ((Long, Long) -> Unit)? = null + companion object { val endedTurns=mutableListOf(); var interrupts = 0; var enqueued = 0; var lastDrained: ((Long, Long) -> Unit)? = null var lastActivity: ((PlaybackActivity) -> Unit)? = null var lastPlaying: ((Long,Long,Boolean)->Unit)? = null var activityFence: ((Long,Long)->Boolean)? = null } init { lastDrained = onDrained; lastActivity = onActivity; lastPlaying = onPlaying } fun beginTurn(turn: Long) {} - fun endTurn(turn: Long) {} + fun endTurn(turn: Long) { endedTurns.add(turn) } fun enqueue(frame: DownlinkFrame): Boolean { enqueued++; return true } fun isCurrent(turn: Long, epoch: Long) = activityFence?.invoke(turn,epoch) ?: true fun isCurrent(epoch: Long) = true diff --git a/tests/session/CallCheck.kt b/tests/session/CallCheck.kt index b450d9d..0031997 100644 --- a/tests/session/CallCheck.kt +++ b/tests/session/CallCheck.kt @@ -3,6 +3,7 @@ import com.gorios.lanvoice.audio.* import com.gorios.lanvoice.net.* fun checkCallControls() { + checkWaitingPoseSession() checkActionSession() val states = mutableListOf() val session = VoiceSession("localhost",5011,states::add) diff --git a/tests/session/WaitingPoseSessionCheck.kt b/tests/session/WaitingPoseSessionCheck.kt new file mode 100644 index 0000000..24c1ee9 --- /dev/null +++ b/tests/session/WaitingPoseSessionCheck.kt @@ -0,0 +1,83 @@ +import android.os.Handler +import com.gorios.lanvoice.audio.* +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.net.* + +fun checkWaitingPoseSession() { + class Player: WaitingPosePlayer { + override val waitingContract=true + lateinit var offer: (WaitingPose)->Unit + var eligible=false;var plays=0;var finishes=0 + var done: (()->Unit)?=null;var failure: (()->Unit)?=null + var ready: (()->Unit)?=null;var restored: (()->Unit)?=null + override fun waitingListener(offer: (WaitingPose)->Unit) { this.offer=offer } + override fun waitingEligible(enabled: Boolean) { eligible=enabled } + override fun playWaitingPose(pose: WaitingPose,finished: ()->Unit,failed: ()->Unit) { plays++;done=finished;failure=failed } + override fun cancelWaitingPose(restored: ()->Unit) { this.restored=restored;if(plays==0) restored() } + override fun prepareTalk(ready: ()->Unit,failed: ()->Unit) { this.ready=ready } + override fun finishTalk() { finishes++ } + } + val pose=WaitingPose("suit-adjust",ContinuousBodyAsset("poses/suit.mp4","b".repeat(64),720,1280,193,8041667),"neutral",0,"neutral",0) + var assertions=0 + for(exit in listOf("complete","background","failed","stop_failed","timeout")) { + val player=Player();val states=mutableListOf() + val session=VoiceSession("localhost",5011,states::add,waitingPlayer=player,persona="liam",keepPermissionConnection=false) + fun field(n:String)=session.javaClass.getDeclaredField(n).apply { isAccessible=true } + val client=field("dialogue").get(session) as DialogueClient + val socket=FakeSocket();client.setField("socket",socket);client.setField("ready",true) + field("foreground").set(session,true);field("state").set(session,VoiceUiState(connection=ConnectionStatus.CONNECTED)) + val ev=session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true } + fun event(kind:EventKind,action:String,turn:Long=7)=ev.invoke(session,ServerEvent(kind.name.lowercase(),kind,Payload(turn=turn,state=action,reason=if(kind==EventKind.ABORT) "listen_start" else ""))) + val fm=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true } + session.startVoice();event(EventKind.LISTEN,"start") + field("lastSpeechAt").setLong(session,0) + checkNotNull(AudioCapture.lastFrame)(ByteArray(640));Handler.drain() + check(player.eligible);assertions++ + AudioCapture.confirmStopsAutomatically=false + val lateMic=checkNotNull(AudioCapture.lastFrame);val beforeUp=DialogueProtocol.uplinks.size;val beforeAudio=AudioPlayback.enqueued + player.offer(pose) + val ack=checkNotNull(AudioCapture.lastStopped) + check(player.plays==0 && states.last().waitingPoseActive && states.last().voiceIndicator==VoiceIndicatorState.IDLE);assertions++ + lateMic(ByteArray(640));fm.invoke(session,DownlinkFrame(7));event(EventKind.TTS,"start");event(EventKind.TTS,"done");event(EventKind.LISTEN,"start",8);Handler.drain() + check(DialogueProtocol.uplinks.size==beforeUp && AudioPlayback.enqueued==beforeAudio && states.last().turnId==7L);assertions++ + if(exit=="timeout") { + val deadline=field("poseTimeout").get(session) as Runnable;deadline.run();ack(true);Handler.drain() + check(player.plays==0 && !states.last().voiceActive);assertions++ + } else if(exit=="stop_failed") { + ack(false);Handler.drain();check(player.plays==0 && !states.last().voiceActive);assertions++ + } else { + ack(true);Handler.drain();check(player.plays==1);assertions++ + val starts=AudioCapture.starts;val complete=checkNotNull(player.done) + session.setMicrophoneMuted(true);session.setMicrophoneMuted(false);session.interrupt() + check(AudioCapture.starts==starts);assertions++ + repeat(400) { lateMic(ByteArray(640));fm.invoke(session,DownlinkFrame(7)) } + checkNotNull(AudioPlayback.lastPlaying)(7,0,true);checkNotNull(AudioPlayback.lastActivity)(PlaybackActivity(7,0,true,960,1920));Handler.drain() + check(AudioPlayback.enqueued==beforeAudio && DialogueProtocol.uplinks.size==beforeUp && states.last().voiceIndicator==VoiceIndicatorState.IDLE);assertions++ + when(exit) { + "complete"->{ + complete();Handler.drain();check(!states.last().waitingPoseActive && states.last().voiceActive && AudioCapture.starts==starts+1);assertions++ + val sent=socket.sent.size;complete();Handler.drain();check(socket.sent.size==sent);assertions++ + fm.invoke(session,DownlinkFrame(7));check(AudioPlayback.enqueued==beforeAudio);assertions++ // old turn remains fenced after pose + event(EventKind.ABORT,"",8);event(EventKind.LISTEN,"start",8);event(EventKind.TTS,"start",8) + val endCount=AudioPlayback.endedTurns.size + fm.invoke(session,DownlinkFrame(8));event(EventKind.TTS,"done",8) + check(AudioPlayback.endedTurns.size==endCount);assertions++ + check(AudioPlayback.enqueued==beforeAudio && player.ready!=null && states.last().phase==VoicePhase.ANSWERING);assertions++ + player.ready!!();Handler.drain();check(AudioPlayback.enqueued==beforeAudio+1 && AudioPlayback.endedTurns.size==endCount+1);assertions++ + checkNotNull(AudioPlayback.lastPlaying)(8,0,true);Handler.drain();check(states.last().voiceIndicator==VoiceIndicatorState.SPEAKING);assertions++ + checkNotNull(AudioPlayback.lastDrained)(8,0);Handler.drain();check(player.finishes>0 && states.last().phase==VoicePhase.LISTENING);assertions++ + event(EventKind.ABORT,"",9);event(EventKind.LISTEN,"start",9);fm.invoke(session,DownlinkFrame(9)) + val lateReady=player.ready!!;val count=AudioPlayback.enqueued + session.interrupt();lateReady();Handler.drain();check(AudioPlayback.enqueued==count);assertions++ + event(EventKind.ABORT,"",10);event(EventKind.LISTEN,"start",10);fm.invoke(session,DownlinkFrame(10)) + val backgroundReady=player.ready!!;session.background();backgroundReady();Handler.drain() + check(AudioPlayback.enqueued==count && !states.last().voiceActive);assertions++ + } + "background"->{session.background();complete();player.restored?.invoke();ack(true);Handler.drain();check(!states.last().voiceActive && socket.cancelled && AudioCapture.starts==starts);assertions++} + "failed"->{player.failure!!();Handler.drain();player.restored?.invoke();complete();Handler.drain();check(!states.last().voiceActive && AudioCapture.starts==starts);assertions++} + } + } + session.release();player.restored?.invoke();Handler.drain();AudioCapture.confirmStopsAutomatically=true + } + println("PASS: $assertions production VoiceSession pose capture-stop-ACK/timeout/failure/400 late PCM+mic callbacks/old-turn/listen/TTS gate/cancel/background/native-indicator/drain-to-wait assertions; audio devices doubled, phone not_run") +}