fix(android): retain action layer and idle rotation across turns

This commit is contained in:
zenord
2026-10-13 09:36:29 +08:00
parent 24ec3ab044
commit a68988e0ba
21 changed files with 554 additions and 58 deletions
+3 -1
View File
@@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
@@ -34,6 +35,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
if (avatarRuntimeFix && (!avatarFullActionCandidate || actionVersionCode < 19)) throw new GradleException('Runtime fix requires full pinned graph and fresh code >=19')
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
}
@@ -82,7 +84,7 @@ android {
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1')
versionName = avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -215,6 +215,11 @@ class MainActivity : ComponentActivity() {
DiagnosticReportInfo(
appVersion = appVersion,
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode,
avatarMode = if(offlineAvatarPreview) "offline_preview" else "normal",
avatarPin = BuildConfig.EMOTION_MANIFEST_SHA,
avatarAdmission = avatarPack?.emotionAdmission ?: "static_identity_rejected",
avatarRuntime = avatarMedia.diagnosticState,
actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else session.runtimeProtocolState,
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
cameraStatus = expressionState.status,
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
@@ -84,8 +84,15 @@ class VoiceSession(
private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime,
stopCapture = { confirmed ->
captureEpoch++; capturing = false
capture.stopAndConfirm { stopped -> main.post { confirmed(stopped) } }
}, status = { status -> if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status) },
diagnostic("action_capture state=stop_pending turn=$currentTurn epoch=$captureEpoch")
capture.stopAndConfirm { stopped -> main.post {
diagnostic("action_capture state=${if(stopped) "stop_confirmed" else "stop_failed"} turn=$currentTurn epoch=$captureEpoch")
confirmed(stopped)
} }
}, status = { status ->
diagnostic("action_status state=${status.status} turn=${status.turn} mic_stopped=${status.micStopped} video_ended=${status.videoEnded} audio_stopped=${status.audioStopped} restored_a=${status.idleRestored}")
if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status)
},
changed = { active ->
if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null }
if (active) { playback.interrupt(); resetReply("action") }
@@ -294,6 +301,7 @@ class VoiceSession(
if (clearObservation) faceCue = FaceCueObservation()
}
val runtimeProtocolState: String get() = "hello=${dialogue.actionNegotiation} connection=${state.connection.name.lowercase()} turn=$currentTurn drained=$drainedTurn action=${actions.active} capture=$capturing capture_epoch=$captureEpoch"
fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot()
private fun sendFaceContext() {
@@ -398,21 +406,26 @@ class VoiceSession(
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
if (event.kind == EventKind.EXPRESSION_PREPARE) {
if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) {
if (event.type.endsWith(".cancel")) onPrepareExpression(null)
else onPrepareExpression(ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"),
event.payload.opt("intensity"),"model"))
if (event.type.endsWith(".cancel")) { diagnostic("emotion_prepare state=cancelled turn=$turn");onPrepareExpression(null) }
else {
val header=ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"),event.payload.opt("intensity"),"model")
diagnostic("emotion_prepare state=${if(header==null) "invalid" else "received"} turn=$turn seq=${header?.sequence} emotion=${header?.emotion?.wire ?: "unset"} intensity=${header?.intensity}")
onPrepareExpression(header)
}
}
return
}
if (event.kind == EventKind.ACTION) {
if (!isActive() || !hasTurn || turn != currentTurn) return
if (!isActive() || !hasTurn || turn != currentTurn) { diagnostic("action_plan state=ignored_turn_or_inactive turn=$turn");return }
if (event.type == "action.cancel") actions.cancel()
else if (event.type == "action.plan") {
val id = event.payload.optString("action_id")
val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L
if (drainedTurn!=currentTurn || !actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl)))
diagnostic("action_plan state=received turn=$turn pre_tts_drained=${drainedTurn==currentTurn}")
if (drainedTurn!=currentTurn || !actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl))) {
diagnostic("action_plan state=rejected_drain_or_capability turn=$turn")
dialogue.actionStatus(ActionStatus(id,currentTurn,"failed"))
else if(actions.active) {
} else if(actions.active) {
actionTimeout?.let { main.removeCallbacks(it) }
actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) }
}
@@ -6,6 +6,7 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion
class AvatarMediaBinding : ActionPlayer {
val currentPackageId: String? get() = driver?.currentPackageId
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
val diagnosticState: String get() = driver?.diagnosticState ?: "owner=stopped renderer=unavailable"
val selection: RoleVisualSelection? get() = driver?.selection
private var driver: ConversationMediaDriver?=null
private var prepared: ReplyEmotion?=null
@@ -1,5 +1,6 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.diag.DiagnosticLog
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
@@ -9,7 +10,8 @@ import com.gorios.lanvoice.BuildConfig
/** Static identity approval and motion approval are independent. No metadata self-approval. */
data class AvatarPack(val idle: String = "", val talk: String = "", val fallback: String, val waiting: String = fallback,
val safeGraph: SafeAvatarGraph? = null, val pathRoot: String = "", val motionStatus: String = "anchor_review_pending",
val continuous: ContinuousAvatarPack? = null,val emotionAction: EmotionActionIndex?=null) {
val continuous: ContinuousAvatarPack? = null,val emotionAction: EmotionActionIndex?=null,
val emotionAdmission: String="not_requested") {
companion object {
const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2"
private const val STATIC_ROOT = "avatar/a01-standing-arms-reference/"
@@ -19,32 +21,47 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
fun load(context: Context): AvatarPack? {
val fallback = STATIC_ROOT + "frames/reference.png"
try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) }
catch (_: Exception) { return null }
val static = AvatarPack(fallback=fallback)
catch (_: Exception) { DiagnosticLog.record("avatar_loader","result=static_identity_rejected");return null }
var static = AvatarPack(fallback=fallback)
if(BuildConfig.DEBUG && BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) {
var stage="index_read_or_hash"
val admitted=try {
val root="avatar/a01-expression-action-v1/"
val raw=read(context,root+"manifest.json",2_000_000)
check(sha(raw)==BuildConfig.EMOTION_MANIFEST_SHA)
stage="index_schema_or_binding"
val index=checkNotNull(EmotionActionManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw),
BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash ->
val runtimeRoot=root+path.substringBeforeLast('/')+"/"
stage="runtime_read_or_hash"
val bytes=read(context,root+path,2_000_000)
check(sha(bytes)==hash)
stage="runtime_schema"
val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot))
verifyRuntime(context,runtime);runtime
stage="runtime_body_patch_hash_or_shape"
verifyRuntime(context,runtime);stage="index_schema_or_binding";runtime
})
var total=0L
stage="edge_media_hash"
for(clip in index.edges.map { it.clip }) {
val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size
check(total<=512_000_000)
}
stage="action_media_hash"
for(asset in index.actionPack?.assets.orEmpty()) {
val media=checkNotNull(asset.media);val data=read(context,media.root+media.path,128_000_000)
check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000)
}
static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph")
} catch(_: Exception) { null }
if(admitted!=null) return admitted
static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph",emotionAdmission="accepted")
} catch(_: Exception) {
static=static.copy(emotionAdmission=stage)
DiagnosticLog.record("avatar_loader","result=rejected reason=$stage pin=${BuildConfig.EMOTION_MANIFEST_SHA.take(12)}")
null
}
if(admitted!=null) {
DiagnosticLog.record("avatar_loader","result=accepted pin=${BuildConfig.EMOTION_MANIFEST_SHA.take(12)} packages=${admitted.emotionAction?.packages?.size} actions=${admitted.emotionAction?.actionPack?.assets?.size ?: 0}")
return admitted
}
// Continue into independently pinned neutral admission as a whole pack.
}
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
@@ -87,8 +87,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
LaunchedEffect(state.voiceActive,pack) {
if(state.voiceActive) while(true) {
val selected=latestAvatar
DiagnosticLog.record("avatar","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} current_visual=${mediaBinding?.currentPackageId ?: "unavailable"} visual_status=${mediaBinding?.visualStatus ?: "legacy_neutral"}")
delay(1_000)
DiagnosticLog.state("avatar", "${selected.desiredMode}/${selected.requestedEmotion.emotion}/${selected.requestedEmotion.intensity}/${mediaBinding?.visualStatus}/${mediaBinding?.currentPackageId}","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} current_visual=${mediaBinding?.currentPackageId ?: "unavailable"} visual_status=${mediaBinding?.visualStatus ?: "legacy_neutral"}")
delay(10_000)
}
}
CleanAvatarScaffold(avatar={
@@ -132,6 +132,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
Text("当前画面:${visualEmotion?.label ?: if(pack?.emotionAction!=null) "过渡或未呈现" else "中立"} · ${video.actual}",fontSize=12.sp)
Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
Text("版本 ${com.gorios.lanvoice.BuildConfig.VERSION_NAME} · code ${com.gorios.lanvoice.BuildConfig.VERSION_CODE} · pin ${com.gorios.lanvoice.BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp)
Text("素材准入:${pack?.emotionAdmission ?: "unavailable"} · ${mediaBinding?.diagnosticState ?: "legacy_neutral"}",fontSize=11.sp)
AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
Row {
@@ -66,19 +66,30 @@ 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 }
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"
private var musicEpoch=0L
private var closing=0
private val releaseWaiters=mutableListOf<()->Unit>()
fun beginTurn(id: Long?) {
if(id==turn) return
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null;resetIdleCycles()
selectedId=visible?.packageId ?: index.fallbackId
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null
// A neutral idle variant is a displayed body, never the model's retained goal.
// Preserve its rotation and completed cycles across new user turns.
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()
applyMouth()
}
fun start() {
if(active || closing!=0) return
active=true;generation++;revision=0;resetIdleCycles()
active=true;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles()
val slot=prepare(index.fallbackId,0);visible=slot
// Ports must deliver callbacks asynchronously, like both Android ports.
}
@@ -98,10 +109,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
seq=reply.sequence
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
selectedId=checkNotNull(selection).packageId
idleTarget=null;resetIdleCycles()
idleTarget=null
}
talk=talking && reply?.turnId==turn
if(talk) { idleTarget=null;idleCycles=0 }
applyMouth()
if(active && !inBridge && !actionStarted) plan()
}
@@ -124,6 +134,11 @@ 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(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.
ignoredCallbacks++;return@prepare
}
if(slot===visible) {
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
@@ -150,7 +165,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
idleCycles++
if(idleCycles<idleCycleGoal) return
resetIdleCycles()
if(idleTarget!=null && slot.packageId==idleTarget && slot.packageId!=index.fallbackId) {
if(slot.packageId!=index.fallbackId) {
idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return
}
if(slot.packageId!=index.fallbackId || selectedId!=index.fallbackId) return
@@ -173,7 +188,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
if(source.packageId==wanted) {
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
if(action!=null && musicReady && source.closedMouth && key.index==action?.media?.sourceFrame) {
actionStarted=true;talk=false;applyMouth();report("action",key)
actionStarted=true;layerOwner=LayerOwner.ACTION;talk=false;applyMouth();report("action",key)
music.start()
return
}
@@ -214,7 +229,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
val current=edge ?: return fail()
if(destination.key?.index!=current.toFrame) return fail()
activate(destination) {
visible=destination;target=null;bridge=null;edge=null;inBridge=false
visible=destination;target=null;bridge=null;edge=null;inBridge=false;resetIdleCycles()
closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key)
applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance()
}
@@ -223,7 +238,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
if(revealing!=null) return
revealing=destination
destination.port.activateMouth(talk && action==null && destination.pack.apertureMode,generation,++revision) {
if(active && destination.live && revealing===destination) {
if(active && layerOwner==LayerOwner.CONVERSATION && destination.live && revealing===destination) {
revealing=null;ready()
}
}
@@ -238,35 +253,38 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
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 }
action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;idleTarget=null;resetIdleCycles();applyMouth()
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) { musicReady=true;plan() } },
{ if(active && epoch==musicEpoch && actionStarted) reveal(3) },{
if(active && epoch==musicEpoch && action==asset && actionStarted) {
music.prepare(media,{ if(active && epoch==musicEpoch && action===asset && !actionStarted && !returning) { musicReady=true;plan() } else ignoredCallbacks++ },
{ if(active && epoch==musicEpoch && action===asset && layerOwner==LayerOwner.ACTION && actionStarted && !returning && !musicPresented) {
musicPresented=true;reveal(3);report("action_first_frame",null)
} else ignoredCallbacks++ },{
if(active && epoch==musicEpoch && action===asset && actionStarted && !returning) {
returning=true;closing++
// onCompletion alone is not audio-release evidence.
music.close {
closing--;releasedIfDone()
if(active && epoch==musicEpoch && action==asset) {
visible?.let(::closeSlot);visible=null;discardRoute()
musicPresented=false;report("action_audio_released",null)
target=prepare(media.returnPackage,media.returnFrame)
// Target's first composed frame is the restored idle evidence.
}
}
}
},{ if(active && epoch==musicEpoch) fail() })
} else ignoredCallbacks++
},{ if(active && epoch==musicEpoch && action===asset) fail() else ignoredCallbacks++ })
}
private fun restoreAction(slot: Slot) {
val media=action?.media ?: return
if(!returning || slot!==target || slot.key?.index!=media.returnFrame) return
visible=slot;target=null;returning=false;actionStarted=false;action=null
visible=slot;target=null;returning=false;actionStarted=false;action=null;layerOwner=LayerOwner.CONVERSATION
reveal(slot.number);report("body_${slot.packageId}",slot.key)
val completed=actionFinished;actionFinished=null;actionFailed=null
selectedId=slot.packageId ?: index.fallbackId;applyMouth();slot.port.advance()
completed?.invoke(ActionEnd(true,true,true))
}
override fun stop(released: ()->Unit) {
musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false;idleTarget=null
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)
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
@@ -1,5 +1,6 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.diag.DiagnosticLog
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Matrix
@@ -23,6 +24,14 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
private var active=false
private var released=false
private var movie: AndroidMusicPort?=null
private val summary=object: Runnable {
override fun run() {
val current=driver ?: return
DiagnosticLog.state("avatar_media",current.diagnosticSignature,"layer=${visibleLayer ?: -1} ${current.diagnosticState}")
if(active && !released) main.postDelayed(this,10_000)
}
}
private var visibleLayer: Int?=null
private val renderers=arrayOfNulls<ContinuousBodyRenderer>(3)
init {
addView(still,LayoutParams(-1,-1))
@@ -41,6 +50,8 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
}
fun render(foreground: Boolean) { active=foreground;if(active) start() else suspend() }
private fun start() {
DiagnosticLog.state("avatar_surface", "$active/$released/${textures.map { it.isAvailable }}",
"foreground=$active disposed=$released ready_mask=${textures.joinToString("") { if(it.isAvailable) "1" else "0" }}")
if(!active || released || driver!=null || textures.any { !it.isAvailable }) return
val index=checkNotNull(pack.emotionAction)
val mouthClock=ConversationMouthClock()
@@ -67,10 +78,16 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
}
}
},music,{ slot ->
textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f
},{ phase,key -> report(VideoPresentation(actual=phase,reason="reviewed_media_path",
clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) })
driver=current;current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie()
if(visibleLayer!=slot) {
visibleLayer=slot
textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f
}
},{ phase,key ->
driver?.let { value -> DiagnosticLog.state("avatar_media", value.diagnosticSignature,
"event=$phase layer=${visibleLayer ?: -1} ${value.diagnosticState}") }
report(VideoPresentation(actual=phase,reason="reviewed_media_path",
clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) })
driver=current;main.removeCallbacks(summary);main.postDelayed(summary,10_000);current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie()
}
private fun fitMovie() {
val view=textures[3];if(view.width<=0 || view.height<=0) return
@@ -78,6 +95,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
view.setTransform(Matrix().apply { setScale(fit.scaleX,fit.scaleY,view.width/2f,view.height/2f) })
}
private fun suspend() {
main.removeCallbacks(summary)
val old=driver ?: return
old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() }
}
@@ -18,6 +18,18 @@ object DiagnosticLog {
private val lock = Any()
private val entries = ArrayDeque<Entry>()
private var nextId = 0L
private val states = LinkedHashMap<String, Pair<String, Long>>()
/** State changes + one monotonic ten-second summary. Frame/PTS/counters belong
* in the sampled message, never the signature, so held ticks cannot flood500. */
fun state(tag: String, signature: String, message: String, nowMs: Long = System.nanoTime()/1_000_000) = synchronized(lock) {
val previous=states[tag]
if(previous==null || previous.first!=signature || nowMs-previous.second>=10_000) {
if(tag !in states && states.size>=32) states.remove(states.keys.first())
states[tag]=signature.take(500) to nowMs
record(tag,message)
}
}
fun record(
tag: String, message: String,
@@ -30,6 +30,11 @@ data class DiagnosticReportInfo(
val phase: String,
val aec: String,
val versionCode: Int = 0,
val avatarMode: String = "unknown",
val avatarPin: String = "",
val avatarAdmission: String = "unknown",
val avatarRuntime: String = "unavailable",
val actionProtocolState: String = "unknown",
val cameraGranted: Boolean = false,
val cameraStatus: ExpressionStatus = ExpressionStatus.OFF,
val cameraPermissionPending: Boolean = false,
@@ -93,6 +98,9 @@ object DiagnosticReportUpload {
.put("phase", info.phase)
.put("aec", info.aec)
.put("version_code", info.versionCode)
.put("avatar_runtime", JSONObject().put("mode",info.avatarMode).put("expected_pin",info.avatarPin)
.put("admission",info.avatarAdmission).put("state",info.avatarRuntime.take(1000))
.put("action_protocol",info.actionProtocolState.take(500)))
.put("camera", JSONObject().put("granted", info.cameraGranted).put("status", info.cameraStatus.name.lowercase())
.put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing))
.put("role_playing", info.rolePlaying)
@@ -75,6 +75,7 @@ class DialogueClient(
private var ready = false
private var wsOpened = false
private var authReceived = false
var actionNegotiation: String = "disconnected";private set
private var helloSent = false
private var loggedAudioTurn: Long? = null
private var handshakeTimeout: Runnable? = null
@@ -93,6 +94,7 @@ class DialogueClient(
wsOpened = false
authReceived = false
helloSent = false
actionNegotiation = "pending"
loggedAudioTurn = null
healthCall?.cancel()
healthCall = null
@@ -187,6 +189,7 @@ class DialogueClient(
generation++ // Invalidate before cancellation can trigger onFailure.
cancelHandshakeTimeout()
ready = false
actionNegotiation = "disconnected"
val previousHealth = healthCall
healthCall = null
previousHealth?.cancel()
@@ -290,9 +293,10 @@ class DialogueClient(
if (authReceived) return@dispatch
authReceived = true
connectionLog("auth ok", "auth")
if (webSocket.send(DialogueProtocol.hello(actionPackSha()))) {
val offeredPack=actionPackSha()
if (webSocket.send(DialogueProtocol.hello(offeredPack))) {
helloSent = true
connectionLog("hello sent", "auth")
connectionLog("hello sent action_offer=${offeredPack?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }?.take(12) ?: "none"} generation=$attempt", "auth")
} else {
connectionLog("hello send failed", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure")
@@ -306,7 +310,12 @@ class DialogueClient(
}
ready = true
cancelHandshakeTimeout()
connectionLog("hello received", "auth")
actionNegotiation=when {
event.payload.opt("action_available") !is Boolean -> "unknown"
event.payload.opt("action_available")==true -> "accepted"
else -> "unavailable"
}
connectionLog("hello received action_pack=$actionNegotiation generation=$attempt", "auth")
updateStatus(ConnectionStatus.CONNECTED, "server_hello_received")
}
if (event.kind == EventKind.ERROR && !ready) {
@@ -391,6 +400,7 @@ class DialogueClient(
previousHealth?.cancel()
socket = null
ready = false
actionNegotiation = "disconnected"
webSocket?.cancel()
updateStatus(status, reason)
}