feat: add single-call action protocol and Android stage interfaces

This commit is contained in:
zenord
2026-10-13 00:41:55 +08:00
parent dfd1372ba2
commit e91354c9e8
41 changed files with 1438 additions and 70 deletions
+9 -3
View File
@@ -17,6 +17,11 @@ def avatarEngineering = providers.gradleProperty('avatarEngineering').orNull ==
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 actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16')
}
if (avatarMouthCandidate && (!avatarNatural || avatarUiCandidate)) {
throw new GradleException('Mouth candidate requires natural runtime and a distinct version from UI-only')
}
@@ -70,8 +75,8 @@ android {
minSdk 26
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))
versionName = (avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = 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 }
@@ -79,7 +84,8 @@ android {
buildFeatures { compose true; buildConfig true }
buildTypes {
debug {
if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
if (avatarActionCandidate) versionNameSuffix '-stage-dev'
else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
else if (avatarNatural) versionNameSuffix '-natural-dev'
else if (avatarEngineering) versionNameSuffix '-dev'
@@ -193,6 +193,7 @@ class MainActivity : ComponentActivity() {
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
micGranted,cameraGranted,permissionPending,::authorizeCamera,
onCancelAction = session::cancelAction,
)
}
}
@@ -22,6 +22,7 @@ class AudioCapture {
}
private val lock = Any()
private var current: Run? = null
@Volatile private var stopConfirmed = true
fun aecAvailability(): AecAvailability = try {
if (AcousticEchoCanceler.isAvailable()) AecAvailability.AVAILABLE else AecAvailability.UNAVAILABLE
@@ -36,8 +37,9 @@ class AudioCapture {
) {
stop()
val run = Run()
stopConfirmed = false
synchronized(lock) { current = run }
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) }
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) else stopConfirmed = true }
}
fun stop() {
@@ -55,6 +57,14 @@ class AudioCapture {
worker.shutdown()
}
/** Queue after worker cleanup; stopped intent alone is not a recording-state proof. */
fun stopAndConfirm(onStopped: (Boolean) -> Unit) {
stop()
try {
worker.execute { onStopped(synchronized(lock) { current == null && stopConfirmed }) }
} catch (_: java.util.concurrent.RejectedExecutionException) { onStopped(false) }
}
private fun record(
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
onDiagnostic: (String) -> Unit,
@@ -129,8 +139,10 @@ class AudioCapture {
aec?.release()
recorder?.let {
try { it.stop() } catch (_: IllegalStateException) { }
stopConfirmed = it.recordingState != AudioRecord.RECORDSTATE_RECORDING
it.release()
}
if (recorder == null) stopConfirmed = true
}
}
@@ -1,5 +1,6 @@
package com.gorios.lanvoice.audio
import com.gorios.lanvoice.avatar.*
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
@@ -30,6 +31,7 @@ data class VoiceUiState(
val previousReplyEmotion: ReplyEmotion? = null,
val playbackActivity: PlaybackActivity? = null,
val microphoneMuted: Boolean = false,
val actionActive: Boolean = false,
) {
val roleLabel: String get() = when {
phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label
@@ -44,6 +46,9 @@ class VoiceSession(
private val onConnectionLog: (String) -> Unit = {},
private val onPreparePlayback: () -> String? = { null },
private val onVoiceStopped: () -> Unit = {},
private val reviewedActionPack: ReviewedActionPack? = null,
private val actionPlayer: ActionPlayer = UnavailableActionPlayer,
private val onPrepareExpression: (ReplyEmotion?) -> Unit = {},
private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {},
) {
private val main = Handler(Looper.getMainLooper())
@@ -51,6 +56,7 @@ class VoiceSession(
private var foreground = false
private var released = false
private var backgroundTimeout: Runnable? = null
private var actionTimeout: Runnable? = null
private var captureEpoch = 0L
private var capturing = false
private var currentTurn = 0L
@@ -73,10 +79,21 @@ class VoiceSession(
}
}
private val capture = AudioCapture()
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) },
changed = { active ->
if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null }
if (active) { playback.interrupt(); resetReply("action") }
update(state.copy(actionActive = active, playbackActivity = null))
if (!active && isActive() && state.phase == VoicePhase.LISTENING) startCapture()
})
private val playback: AudioPlayback = AudioPlayback(
onDrained = { turn, epoch ->
main.post {
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
if (isActive() && !actions.active && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) {
resetReply("drained")
@@ -99,7 +116,7 @@ class VoiceSession(
},
onActivity = { activity ->
main.post {
if (isActive() && playbackIsCurrent(activity.turnId, activity.generation) &&
if (isActive() && !actions.active && playbackIsCurrent(activity.turnId, activity.generation) &&
currentTurn == activity.turnId && blockedTurn != activity.turnId && emotionEndedTurn != activity.turnId) {
update(state.copy(playbackActivity = activity))
}
@@ -110,6 +127,7 @@ class VoiceSession(
host, port,
onStatus = {},
onStatusReason = ::onConnection,
actionPackSha = { actions.capability?.manifestSha },
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
@@ -179,6 +197,7 @@ class VoiceSession(
fun stopVoice(sendControls: Boolean = true) {
checkMainThread()
actions.cancel()
resetReply("stop")
val wasActive = state.voiceActive
stopCapture()
@@ -222,7 +241,7 @@ class VoiceSession(
fun interrupt() {
checkMainThread()
if (!isActive()) return
if (!isActive() || actions.active) return
resetReply("interrupt")
blockedTurn = currentTurn
playback.interrupt() // Silence locally before waiting for the server's abort event.
@@ -232,6 +251,8 @@ class VoiceSession(
}
}
fun cancelAction() { checkMainThread(); actions.cancel() }
fun permissionDenied() {
checkMainThread()
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
@@ -302,6 +323,8 @@ class VoiceSession(
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
actions.cancel()
onPrepareExpression(null)
resetReply("disconnect")
faceSupported = false
faceSent = false
@@ -328,7 +351,7 @@ class VoiceSession(
private fun startCapture() {
val active = isActive()
diagnostic("startCapture active=$active capturing=$capturing")
if (!active || capturing || state.microphoneMuted) return
if (!active || capturing || state.microphoneMuted || actions.active) return
capturing = true
val epoch = ++captureEpoch
val captureTurn = currentTurn
@@ -369,6 +392,29 @@ class VoiceSession(
private fun onEvent(event: ServerEvent) {
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
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"))
}
return
}
if (event.kind == EventKind.ACTION) {
if (!isActive() || !hasTurn || turn != currentTurn) 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 (!actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl)))
dialogue.actionStatus(ActionStatus(id,currentTurn,"failed"))
else if(actions.active) {
actionTimeout?.let { main.removeCallbacks(it) }
actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) }
}
}
return
}
if (event.kind == EventKind.REPLY_EMOTION) { receiveReply(event, turn); return }
if (released || state.connection != ConnectionStatus.CONNECTED) {
diagnostic("event ignored: connection=${state.connection.name} released=$released")
@@ -433,7 +479,7 @@ class VoiceSession(
// The server's following LISTEN start and TTS belong to that new turn.
val reason = event.payload.optString("reason")
val listenReset = reason == "listen_start"
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort")
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort", "action_followup", "action_cancelled", "action_timeout")
blockedTurn = if (announcesNewTurn) null else oldTurn
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
playback.interrupt()
@@ -442,6 +488,7 @@ class VoiceSession(
startCapture()
}
}
EventKind.SPEECH -> if (isActive()) { preparedPlaybackTurn = null; emotionEndedTurn = null }
EventKind.ERROR -> if (state.voiceActive) {
stopVoice()
update(state.copy(guidance = "服务端处理失败,请重新开始语音对话"))
@@ -452,7 +499,7 @@ class VoiceSession(
private fun onFrame(frame: DownlinkFrame) {
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
if (!isActive() || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
if (!isActive() || actions.active || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
blockedTurn == frame.turnId) return
if (preparedPlaybackTurn != frame.turnId) {
val failure = onPreparePlayback()
@@ -473,6 +520,8 @@ class VoiceSession(
}
// IDs identify turns; do not assume the server allocates them in numeric order.
if (!hasTurn || id != currentTurn) {
actions.cancel()
onPrepareExpression(null)
resetReply("new_turn")
val resumeCapture = capturing
if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq.
@@ -499,11 +548,13 @@ class VoiceSession(
turn in retiredTurns -> "old_turn"
turn != currentTurn -> "unannounced_turn"
!isActive() -> "inactive"
actions.active -> "action"
blockedTurn == currentTurn -> "blocked_turn"
emotionEndedTurn == currentTurn -> "drained"
else -> null
}
if (reason != null) { diagnostic("role ignore reason=$reason turn=$turn"); return }
onPrepareExpression(null)
val expression = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"),
event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source"),
event.payload.opt("reason"), event.payload.opt("parse_branch"), event.payload.opt("finish_reason"))
@@ -0,0 +1,81 @@
package com.gorios.lanvoice.avatar
data class ActionAsset(val id: String, val durationMs: Long)
data class ReviewedActionPack(val manifestSha: String, val assets: List<ActionAsset>)
data class ActionPlan(val id: String, val turn: Long, val packSha: String, val ttlMs: Long)
data class ActionStatus(val id: String, val turn: Long, val status: String, val asset: String? = null,
val micStopped: Boolean = false, val videoEnded: Boolean = false,
val audioStopped: Boolean = false, val idleRestored: Boolean = false)
data class ActionEnd(val videoEnded: Boolean, val audioStopped: Boolean, val idleRestored: Boolean)
/** An implementation must complete only AFTER decoder/music stop AND reviewed return A.
* stop's callback is a release fence, never an arbitrary fixed tail timer. */
interface ActionPlayer {
fun play(asset: ActionAsset, finished: (ActionEnd) -> Unit, failed: () -> Unit)
fun stop(released: () -> Unit)
}
/** Main-thread state machine. No pack is installed until an external exact-SHA review.
* No microphone data is stored here, and no model URL can reach the player. */
class ActionController(
private val pack: ReviewedActionPack?, private val player: ActionPlayer,
private val clock: () -> Long, private val stopCapture: ((Boolean) -> Unit) -> Unit,
private val status: (ActionStatus) -> Unit, private val changed: (Boolean) -> Unit = {},
private val choose: (Int) -> Int = { kotlin.random.Random.nextInt(it) },
) {
private var generation = 0L
private var plan: ActionPlan? = null
private var previous: String? = null
private var stopping = false
val active get() = plan != null || stopping
private var deadline = 0L
private var started = 0L
val capability: ReviewedActionPack? get() = pack?.takeIf {
it.manifestSha.matches(Regex("[0-9a-f]{64}")) &&
it.assets.map { a -> a.id }.toSet() == setOf("asset_01", "asset_02") &&
it.assets.size == 2 && it.assets.all { a -> a.durationMs in 1_000..90_000 }
}
fun offer(next: ActionPlan): Boolean {
val valid = capability
if (active || valid == null || next.packSha != valid.manifestSha || next.id.length !in 16..64 ||
next.turn !in 0..0xffff_ffffL || next.ttlMs !in 1..120_000) return false
val candidates = valid.assets.filter { it.id != previous }
val asset = candidates[choose(candidates.size)]
val fence = ++generation
plan = next; deadline = clock()+next.ttlMs; changed(true)
stopCapture { confirmed ->
if (fence != generation || plan != next) return@stopCapture
if (!confirmed || clock() >= deadline) { cancel("failed"); return@stopCapture }
started = clock(); previous = asset.id
status(ActionStatus(next.id,next.turn,"started",asset.id,micStopped=true))
player.play(asset, { end ->
if (fence == generation && plan == next) {
if (clock() >= deadline || clock()-started < asset.durationMs ||
!end.videoEnded || !end.audioStopped || !end.idleRestored) cancel("failed")
else {
plan = null; generation++
status(ActionStatus(next.id,next.turn,"completed",asset.id,true,true,true,true))
changed(false)
}
}
}, { if (fence == generation && plan == next) cancel("failed") })
}
return true
}
fun tick() { if (plan != null && clock() >= deadline) cancel("failed") }
fun cancel(reason: String = "cancelled") {
val old = plan ?: return
generation++; plan = null; stopping = true
player.stop {
stopping = false
status(ActionStatus(old.id,old.turn,if (reason == "failed") "failed" else "cancelled"))
changed(false)
}
}
}
/** Production default while no independently approved dance pack exists. */
object UnavailableActionPlayer : ActionPlayer {
override fun play(asset: ActionAsset, finished: (ActionEnd) -> Unit, failed: () -> Unit) = failed()
override fun stop(released: () -> Unit) = released()
}
@@ -77,8 +77,9 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
expression: ExpressionUiState,shareFace: Boolean,onShare: (Boolean)->Unit,
logs: List<String>,onReport: ()->Unit,reportSending: Boolean,reportResult: String?,onInterrupt: ()->Unit,
micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit,
onCancelAction: ()->Unit,
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity)
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar)
var video by remember(pack) { mutableStateOf(VideoPresentation()) }
val latestVideo by rememberUpdatedState(video)
@@ -105,13 +106,14 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
}
}
Text(status,style=MaterialTheme.typography.titleMedium)
Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp)
Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && !state.actionActive && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp)
if(state.actionActive) Button(onClick=onCancelAction) { Text("结束表演") }
TextButton(onClick=onRetry) { Text("重试连接") }
permissionMessage?.let { Text(it,fontSize=13.sp) }
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
state.guidance?.let { Text(it,fontSize=13.sp) }
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
Button(onClick=onMute,enabled=state.voiceActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Button(onClick=onMute,enabled=state.voiceActive && !state.actionActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Text(if(state.microphoneMuted) "恢复收音" else "暂停收音")
}
OutlinedButton(onClick=onCamera,
@@ -128,7 +130,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
Row {
TextButton(onClick=onInterrupt,enabled=state.voiceActive) { Text("打断回答") }
TextButton(onClick=onInterrupt,enabled=state.voiceActive && !state.actionActive) { Text("打断回答") }
TextButton(onClick=onReport,enabled=!reportSending) { Text(if(reportSending) "发送中…" else "发送诊断报告") }
}
reportResult?.let { Text(it,fontSize=12.sp) }
@@ -23,7 +23,8 @@ object ContinuousAvatarManifest {
fun smallInt(v: Any?): Int { val n=integer(v);require(n in 0..1_000_000);return n.toInt() }
fun finite(v: Any?): Float { val f=(v as Number).toFloat(); require(f.isFinite()); return f }
fun hash(v: Any?)=(v as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04"
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" ||
(root["packId"] as? String)?.matches(Regex("a01-expression-action-v1-[a-z0-9_-]+-runtime-04"))==true
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" &&
(apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03"))
require(root["publishApproval"]==false && root["runtimeReady"]==true)
@@ -0,0 +1,85 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.dialogue.RoleEmotion
data class EmotionActionIndex(val fallbackId: String, val packages: Map<String,ContinuousAvatarPack>,
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?)
/** Exact external manifest pin admits the whole graph. Self-approval fields have no effect.
* loadRuntime must hash-check exact bytes and all body/patch files before returning a pack.
* An admitted index is data; playback still needs reviewed bridge execution by its driver. */
object EmotionActionManifest {
@Suppress("UNCHECKED_CAST")
fun read(root: Map<String,Any?>, actualSha: String, piPinnedSha: String,
loadRuntime: (String,String)->ContinuousAvatarPack?): EmotionActionIndex? = try {
require(piPinnedSha.matches(Regex("[0-9a-f]{64}")) && actualSha==piPinnedSha)
require(root["schemaVersion"]==2L || root["schemaVersion"]==2)
require(root["identityId"]=="a01" && root["packId"]=="a01-expression-action-v1")
fun obj(value: Any?)=value as Map<String,Any?>
fun path(value: Any?)=(value as String).also {
require(it.matches(Regex("[A-Za-z0-9_./-]+")) && !it.startsWith('/') && it.split('/').none { p -> p in setOf("..", ".", "") })
}
fun hash(value: Any?)=(value as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
fun integer(value: Any?): Long { val n=value as Number;require(n.toDouble()==n.toLong().toDouble());return n.toLong() }
val fallback=root["fallbackPackageId"] as String
val rows=root["conversationPackages"] as List<Map<String,Any?>>
require(rows.isNotEmpty() && rows.size<=12 && rows.map { it["id"] }.distinct().size==rows.size)
val packages=linkedMapOf<String,ContinuousAvatarPack>()
val visuals=rows.map { row ->
val id=row["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}")))
val emotion=RoleEmotion.entries.single { it.wire==row["emotion"] }
require(emotion!=RoleEmotion.ANGRY && integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L)
val reference=obj(row["runtimeManifest"])
val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"])))
require(runtime.apertureMode && runtime.body.sha256==hash(row["mouthBodySha256"]))
require(runtime.patches.size==runtime.body.frameCount && runtime.patches.all { it.levels.size==5 })
packages[id]=runtime
val pts=runtime.patches.map { it.ptsUs }
TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),pts,pts,false)
}
require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL)
val edges=root["edges"] as List<Map<String,Any?>>
require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size)
edges.forEach { edge ->
require(edge["from"] in packages && edge["to"] in packages)
val from=checkNotNull(packages[edge["from"]]);val to=checkNotNull(packages[edge["to"]])
require(integer(edge["fromFrame"]) in 0 until from.body.frameCount.toLong())
require(integer(edge["toFrame"]) in 0 until to.body.frameCount.toLong())
require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A")
val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"])
require(clip["hasAudio"]==false && integer(clip["frameCount"])>0 && integer(clip["durationUs"])>0)
val pts=(clip["ptsUs"] as List<*>).map(::integer)
require(pts.size==integer(clip["frameCount"]).toInt() && pts.first()==0L && pts.zipWithNext().all { (a,b)->a<b })
}
val admitted=visuals.map { visual ->
val row=rows.single { it["id"]==visual.id }
require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A")
val loop=row["loopEdge"] as String
require(edges.any { it["id"]==loop && it["from"]==visual.id && it["to"]==visual.id })
val exits=(row["legalExitFrames"] as List<*>).map(::integer)
require(exits.isNotEmpty() && exits.all { it in 0 until packages.getValue(visual.id).body.frameCount.toLong() })
if(visual.id!=fallback) {
require(edges.any { it["from"]==fallback && it["to"]==visual.id })
require(edges.any { it["from"]==visual.id && it["to"]==fallback })
}
visual.copy(approvedEdges=true)
}
val actions=root["actions"] as List<Map<String,Any?>>
val actionPack=if(actions.isEmpty()) null else {
require(actions.size==2 && actions.map { it["id"] }.toSet()==setOf("asset_01","asset_02"))
val assets=actions.map { action ->
require(action["kind"]=="dance" && action["mouthAllowed"]==false && action["disallowTALK"]==true)
require(action["entryAnchor"]=="A" && action["returnAnchor"]=="A")
val clip=obj(action["clip"]);path(clip["path"]);hash(clip["sha256"])
val duration=integer(clip["durationUs"])
require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration)
val pts=(clip["ptsUs"] as List<*>).map(::integer)
require(pts.isNotEmpty() && pts.size==integer(clip["frameCount"]).toInt() && pts.zipWithNext().all { (a,b)->a<b })
require(duration in 1_000_000..90_000_000)
ActionAsset(action["id"] as String,(duration+999)/1000)
}
ReviewedActionPack(actualSha,assets)
}
EmotionActionIndex(fallback,packages,admitted,actionPack)
} catch(_: Exception) { null }
}
@@ -0,0 +1,26 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.dialogue.RoleEmotion
/** Selected model intent remains separate from the actually admitted visual package. */
data class RoleVisualSelection(val selectedEmotion: RoleEmotion, val selectedIntensity: Int,
val visualEmotion: RoleEmotion, val visualIntensity: Int, val packageId: String,
val degraded: Boolean, val reason: String)
data class TalkPackage(val id: String, val emotion: RoleEmotion, val bodySha: String,
val mouthBodySha: String?, val framePtsUs: List<Long>, val mouthPtsUs: List<Long>,
val approvedEdges: Boolean)
object RoleVisualSelector {
fun select(emotion: RoleEmotion, intensity: Int, packages: List<TalkPackage>, fallbackId: String): RoleVisualSelection {
fun valid(p: TalkPackage) = p.bodySha.matches(Regex("[0-9a-f]{64}")) &&
p.mouthBodySha == p.bodySha && p.framePtsUs.size == 97 &&
p.framePtsUs == p.mouthPtsUs && p.framePtsUs.zipWithNext().all { (a,b) -> a < b } && p.approvedEdges
val usable = packages.filter(::valid)
val same = usable.firstOrNull { it.emotion == emotion && emotion != RoleEmotion.ANGRY }
val chosen = same ?: usable.firstOrNull { it.id == fallbackId }
?: error("No reviewed complete fallback TALK package")
val visualIntensity = if (chosen.emotion == RoleEmotion.NEUTRAL) 0 else 1
val reason = when { same == null -> "whole_package_fallback"; intensity > visualIntensity -> "slight_only"; else -> "none" }
return RoleVisualSelection(emotion,intensity,chosen.emotion,visualIntensity,chosen.id,reason != "none",reason)
}
}
@@ -42,6 +42,7 @@ class DialogueClient(
private val onFrame: (DownlinkFrame) -> Unit = {},
private val onProtocolError: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
private val actionPackSha: () -> String? = { null },
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
) {
private val main = Handler(Looper.getMainLooper())
@@ -216,6 +217,8 @@ class DialogueClient(
fun playbackDrained(turnId: Long): Boolean = send(DialogueProtocol.playbackDrained(turnId))
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus): Boolean = send(DialogueProtocol.actionStatus(value))
/** Optional context is best effort and never tears down the audio connection. */
fun sendFaceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): Boolean {
checkMainThread()
@@ -287,7 +290,7 @@ class DialogueClient(
if (authReceived) return@dispatch
authReceived = true
connectionLog("auth ok", "auth")
if (webSocket.send(DialogueProtocol.hello())) {
if (webSocket.send(DialogueProtocol.hello(actionPackSha()))) {
helloSent = true
connectionLog("hello sent", "auth")
} else {
@@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
enum class EventKind {
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
}
/** Header integers are unsigned, network byte order; PCM samples are signed little endian. */
@@ -26,13 +26,17 @@ object DialogueProtocol {
const val UPLINK_PCM_BYTES = 640
const val DOWNLINK_PCM_BYTES = 1_920
fun hello(): String = JSONObject()
fun hello(actionPackSha: String? = null): String = JSONObject()
.put("type", "hello")
.put("codec", "pcm16")
.put("sample_rate", 16_000)
.put("frame_duration", 20)
.put("persona", "default")
.put("voice_mode", "continuous_voice")
.apply { if (actionPackSha?.matches(Regex("[0-9a-f]{64}")) == true) {
put("action_protocol", 1); put("action_pack_sha256", actionPackSha)
put("action_kinds", org.json.JSONArray().put("dance"))
} }
.toString()
fun listen(start: Boolean): String = JSONObject()
@@ -51,6 +55,12 @@ object DialogueProtocol {
fun playbackDrained(turnId: Long): String = JSONObject()
.put("type", "playback.drained").put("turn_id", turnId).toString()
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus): String = JSONObject()
.put("type", "action.status").put("turn_id", value.turn).put("action_id", value.id)
.put("status", value.status).put("asset_id", value.asset ?: "")
.put("mic_stopped", value.micStopped).put("video_ended", value.videoEnded)
.put("audio_stopped", value.audioStopped).put("idle_restored", value.idleRestored).toString()
fun faceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): String {
require(turnId in 0..0xffff_ffffL)
val valid = observation.cue != FaceCue.UNKNOWN && ageMs in 0..3_000 &&
@@ -77,7 +87,7 @@ object DialogueProtocol {
val payload = JSONObject(text)
val type = payload.opt("type") as? String
require(!type.isNullOrBlank()) { "Event is missing a string type" }
val kind = if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
val kind = if (type.startsWith("reply.emotion.prepare")) EventKind.EXPRESSION_PREPARE else if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
"auth" -> EventKind.AUTH
"hello" -> EventKind.HELLO
"history" -> EventKind.HISTORY
@@ -86,6 +96,8 @@ object DialogueProtocol {
"stt" -> EventKind.STT
"llm" -> EventKind.LLM
"tts" -> EventKind.TTS
"action" -> EventKind.ACTION
"speech" -> EventKind.SPEECH
"error" -> EventKind.ERROR
"abort" -> EventKind.ABORT
"metrics" -> EventKind.METRICS