Show startup shell before background avatar admission and update reviewed capabilities

This commit is contained in:
zenord
2026-10-13 14:57:13 +08:00
parent 345e26e245
commit 40abf3a14e
41 changed files with 1113 additions and 124 deletions
+6 -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 avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true'
def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true'
def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true'
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
@@ -37,6 +38,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 (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22')
if (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21')
if (avatarPlaybackDiagnostic && (!avatarFullActionCandidate || actionVersionCode < 20 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback diagnostic requires frozen full graph and fresh code >=20')
if (avatarRuntimeFix && (!avatarFullActionCandidate || actionVersionCode < 19)) throw new GradleException('Runtime fix requires full pinned graph and fresh code >=19')
@@ -75,6 +77,7 @@ def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) {
from('src/main/assets')
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
if (!avatarStartupFix) exclude 'avatar/startup-white-01/**'
if (!emotionManifestSha) exclude 'avatar/a01-expression-action-v1/**'
into(packagedAssets)
}
@@ -88,7 +91,7 @@ android {
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
versionName = avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : 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 }
@@ -103,6 +106,7 @@ android {
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
else if (avatarNatural) versionNameSuffix '-natural-dev'
else if (avatarEngineering) versionNameSuffix '-dev'
buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', avatarStartupFix ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', avatarMouthCandidate ? 'true' : 'false'
@@ -110,6 +114,7 @@ android {
buildConfigField 'String', 'EMOTION_MANIFEST_SHA', '"' + emotionManifestSha + '"'
}
release {
buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', 'false'
buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false'
buildConfigField 'boolean', 'AVATAR_NATURAL', 'false'
buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', 'false'
@@ -9,6 +9,8 @@ import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityNodeInfo
import com.gorios.lanvoice.avatar.ContinuousAvatarView
import com.gorios.lanvoice.avatar.EmotionActionAvatarView
import com.gorios.lanvoice.avatar.StartupAvatarView
/** Optional on-device regression, only launches the explicit sensor-free preview.
* Uses platform instrumentation/accessibility, no external test dependencies.
@@ -25,11 +27,16 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
screen=activity; waitForIdleSync()
fun field(instance: Any,name: String): Any? = instance.javaClass.getDeclaredField(name).apply { isAccessible=true }.get(instance)
check(field(activity,"session")==null && field(activity,"expressions")==null) { "Offline probe created sensors/session" }
var avatar: ContinuousAvatarView?=null
var avatar: View?=null
runOnMainSync { avatar=findAvatar(activity.window.decorView) }
val view=checkNotNull(avatar) { "Continuous avatar missing" }
await { field(view,"renderer")!=null }
val renderer=checkNotNull(field(view,"renderer"))
fun currentRenderer(): Any? = when(view) {
is StartupAvatarView -> (field(view,"full") as? EmotionActionAvatarView)?.let { field(it,"driver") }
is EmotionActionAvatarView -> field(view,"driver")
else -> field(view,"renderer")
}
await { currentRenderer()!=null && (!BuildConfig.AVATAR_STARTUP_FIX || field(activity,"mediaReady")==true) }
val renderer=checkNotNull(currentRenderer())
await { gear()!=null }
assertClean()
val gear=checkNotNull(gear()); val bounds=android.graphics.Rect();gear.getBoundsInScreen(bounds)
@@ -40,17 +47,17 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
await { nodes().any { it.text?.toString()=="关闭" } }
check(nodes().any { it.text?.toString()?.contains("离线 avatar")==true })
val version=targetContext.packageManager.getPackageInfo(targetContext.packageName,0).versionName
val candidate=if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03"
val candidate=if(BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) "整合候选" else if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03"
check(nodes().any { it.text?.toString()?.contains(candidate)==true })
check(nodes().first { it.text?.toString()=="关闭" }.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { nodes().none { it.text?.toString()=="关闭" } && gear()!=null }
assertClean()
runOnMainSync { check(findAvatar(activity.window.decorView)===view) }
check(field(view,"renderer")===renderer) { "Settings restarted body renderer" }
check(currentRenderer()===renderer) { "Settings restarted body renderer" }
check(field(activity,"session")==null && field(activity,"expressions")==null)
}
runOnMainSync { activity.moveTaskToBack(true) }
await { field(view,"renderer")==null }
await { currentRenderer()==null }
result.putString("result","PASS: clean accessibility home / 48dp gear / 3 settings cycles preserve renderer / offline no sensors / background releases renderer")
success=true
} catch(t: Throwable) {
@@ -58,8 +65,8 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
} finally { screen?.let { runOnMainSync { it.finish() } } }
finish(if(success) Activity.RESULT_OK else Activity.RESULT_CANCELED,result)
}
private fun findAvatar(view: View): ContinuousAvatarView? {
if(view is ContinuousAvatarView) return view
private fun findAvatar(view: View): View? {
if(view is StartupAvatarView || view is EmotionActionAvatarView || view is ContinuousAvatarView) return view
if(view is ViewGroup) for(i in 0 until view.childCount) findAvatar(view.getChildAt(i))?.let { return it }
return null
}
@@ -79,7 +86,7 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
check(app.count { it.isClickable }==1 && gear()!=null) { "Home has controls besides gear" }
}
private fun await(condition: ()->Boolean) {
val deadline=SystemClock.uptimeMillis()+8_000
val deadline=SystemClock.uptimeMillis()+90_000
while(!condition()) { check(SystemClock.uptimeMillis()<deadline) { "UI/renderer condition timeout" };SystemClock.sleep(50) }
}
}
@@ -54,7 +54,13 @@ class MainActivity : ComponentActivity() {
private val main = android.os.Handler(android.os.Looper.getMainLooper())
private val pump = Runnable { advanceEntry() }
private val retryTimer = Runnable { advanceEntry() }
private var avatarPack: AvatarPack? = null
private var avatarPack by mutableStateOf<AvatarPack?>(null)
private var startupBase by mutableStateOf<com.gorios.lanvoice.avatar.ContinuousAvatarPack?>(null)
private var startupStage by mutableStateOf(if(BuildConfig.AVATAR_STARTUP_FIX) "preparing" else "ready")
private var loaderCancel: (()->Unit)?=null
private var loaderGeneration=0L
private var firstDrawReady=false
private var mediaReady=false
private val avatarMedia=com.gorios.lanvoice.avatar.AvatarMediaBinding()
private var expressionState by mutableStateOf(ExpressionUiState())
private lateinit var expressions: ExpressionController
@@ -75,8 +81,8 @@ class MainActivity : ComponentActivity() {
entry.permissionResult(permission, granted)
if (permission == EntryPermission.CAMERA && !granted) preferences().edit().putBoolean("cameraWanted", false).apply()
if (!granted && !offlineAvatarPreview) {
if (permission == EntryPermission.MICROPHONE) session.permissionDenied()
else expressions.permissionDenied()
if (permission == EntryPermission.MICROPHONE) { if(::session.isInitialized) session.permissionDenied() }
else if(::expressions.isInitialized) expressions.permissionDenied()
}
scheduleEntry()
}
@@ -86,6 +92,7 @@ class MainActivity : ComponentActivity() {
}
private fun advanceEntry() {
if (!::entry.isInitialized || isDestroyed) return
if(BuildConfig.AVATAR_STARTUP_FIX && (!firstDrawReady || !offlineAvatarPreview && !::session.isInitialized)) return
// First consent is after the foreground Compose host has a stable layout,
// independent of health/WS/HELLO. No request originates from recomposition.
if(inForeground && (!window.decorView.isAttachedToWindow || !window.decorView.isLaidOut)) {
@@ -136,7 +143,7 @@ class MainActivity : ComponentActivity() {
else if(entry.requestPermission(EntryPermission.CAMERA,false)) scheduleEntry()
}
private fun retryConnection() {
if (entry.retry(android.os.SystemClock.elapsedRealtime())) {
if (::session.isInitialized && entry.retry(android.os.SystemClock.elapsedRealtime())) {
session.resetConnection()
scheduleEntry()
}
@@ -144,6 +151,7 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(BuildConfig.AVATAR_STARTUP_FIX) com.gorios.lanvoice.diag.StartupTrace.begin()
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE),
navigationBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE),
@@ -151,22 +159,54 @@ class MainActivity : ComponentActivity() {
appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown"
volumeControlStream = AudioManager.STREAM_MUSIC
offlineAvatarPreview = BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING && intent.getBooleanExtra(OfflineAvatarTrace.EXTRA,false)
if(!BuildConfig.AVATAR_STARTUP_FIX) avatarPack = AvatarPack.load(this)
entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false),
preferences().getBoolean("cameraWanted",true),conversationEnabled=!offlineAvatarPreview,automaticPermissions=!offlineAvatarPreview)
if (offlineAvatarPreview) {
avatarPack = AvatarPack.load(this)
entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false),
conversationEnabled=false,automaticPermissions=false)
setContent { EngineeringPreviewScreen(avatarPack,micGranted,cameraGranted,micSettings,cameraSettings,
permissionPending,::authorizeMicrophone,::authorizeCamera,avatarMedia,::sendDiagnosticReport,reportSending,reportResult) }
permissionPending,::authorizeMicrophone,::authorizeCamera,avatarMedia,::sendDiagnosticReport,reportSending,reportResult,
startupBase,startupStage,::startupVisible,::startAssetLoad,{startupStage="failed"}) }
if(BuildConfig.AVATAR_STARTUP_FIX) startShell()
return // No VoiceSession/audio focus/camera controller; manual permission consent only.
}
if(!BuildConfig.AVATAR_STARTUP_FIX) initializeNormal()
setContent {
CallScreen(
state, entryPhase, permissionMessage, micSettings, cameraSettings, avatarPack, ::retryConnection, ::authorizeMicrophone,
{ val muted = !state.microphoneMuted
preferences().edit().putBoolean("microphoneMuted", muted).apply()
if(::session.isInitialized) session.setMicrophoneMuted(muted) }, ::toggleExpressions,
expressionState, shareFace, { enabled -> shareFace = enabled; if(::session.isInitialized) session.setFaceSharing(enabled) },
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, { if(::session.isInitialized) session.interrupt() },
micGranted,cameraGranted,permissionPending,::authorizeCamera,
onCancelAction = { if(::session.isInitialized) session.cancelAction() },
mediaBinding = avatarMedia,
startupBase = startupBase,startupStage = startupStage,onStartupVisible = ::startupVisible,onRetryAssets = ::startAssetLoad,onStartupFailed = { startupStage="failed" },
onOfflinePreview = {
if(!openingOffline && ::session.isInitialized) {
openingOffline=true;closeCamera()
session.suspendForLocalPreview { safe ->
openingOffline=false
if(safe && inForeground && !isDestroyed) startActivity(android.content.Intent(this,MainActivity::class.java).putExtra(OfflineAvatarTrace.EXTRA,true))
else reportResult="录音停止未确认,暂不进入离线播放检查"
}
}
},
)
}
if(BuildConfig.AVATAR_STARTUP_FIX) startShell()
}
private fun initializeNormal() {
if(::session.isInitialized || offlineAvatarPreview || isDestroyed) return
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
DebugLogUpload.appLaunch(
appVersion,
NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"),
)
// User approved the original crossed-arms reference. Motion approval is separate.
avatarPack = AvatarPack.load(this)
entry = AutoConversation(preferences().getBoolean("micAsked", false), preferences().getBoolean("camAsked", false), preferences().getBoolean("cameraWanted", true))
session = VoiceSession(
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = {
@@ -183,7 +223,8 @@ class MainActivity : ComponentActivity() {
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) },
onPreparePlayback = audioOutput::prepare,
onVoiceStopped = audioOutput::release,
reviewedActionPack = avatarPack?.emotionAction?.actionPack,
reviewedActionPack = avatarPack?.emotionAction?.actionPack?.takeIf { !BuildConfig.AVATAR_STARTUP_FIX || mediaReady },
pendingActionPackSha = { if(BuildConfig.AVATAR_STARTUP_FIX) BuildConfig.EMOTION_MANIFEST_SHA else null },
actionPlayer = avatarMedia,
onPrepareExpression = avatarMedia::prepare,
)
@@ -192,29 +233,40 @@ class MainActivity : ComponentActivity() {
if (expressionState.status != it.status) DebugLogUpload.log("audio", "camera state=${it.status.name.lowercase()}")
expressionState = it
}, onFaceCue = session::observeFace)
setContent {
CallScreen(
state, entryPhase, permissionMessage, micSettings, cameraSettings, avatarPack, ::retryConnection, ::authorizeMicrophone,
{ val muted = !state.microphoneMuted
preferences().edit().putBoolean("microphoneMuted", muted).apply()
session.setMicrophoneMuted(muted) }, ::toggleExpressions,
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
micGranted,cameraGranted,permissionPending,::authorizeCamera,
onCancelAction = session::cancelAction,
mediaBinding = avatarMedia,
onOfflinePreview = {
if(!openingOffline) {
openingOffline=true;closeCamera()
session.suspendForLocalPreview { safe ->
openingOffline=false
if(safe && inForeground && !isDestroyed) startActivity(android.content.Intent(this,MainActivity::class.java).putExtra(OfflineAvatarTrace.EXTRA,true))
else reportResult="录音停止未确认,暂不进入离线播放检查"
}
}
},
)
if(inForeground) session.foreground(connectAutomatically=false)
if(mediaReady) avatarPack?.emotionAction?.actionPack?.let(session::installReviewedActions)
scheduleEntry()
}
private fun startShell() {
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.SHELL_SET_CONTENT)
val view=window.decorView
val listener=object: android.view.ViewTreeObserver.OnDrawListener {
override fun onDraw() {
if(firstDrawReady) return
firstDrawReady=true
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.FIRST_DRAW)
view.post {
if(view.viewTreeObserver.isAlive) view.viewTreeObserver.removeOnDrawListener(this)
if(!isDestroyed && inForeground) { initializeNormal();scheduleEntry() }
}
}
}
view.viewTreeObserver.addOnDrawListener(listener)
startAssetLoad()
}
private fun startAssetLoad() {
if(!BuildConfig.AVATAR_STARTUP_FIX || isDestroyed) return
loaderCancel?.invoke();val token=++loaderGeneration;startupStage="preparing";avatarPack=null
loaderCancel=com.gorios.lanvoice.avatar.StartupAvatarRepository.request(this,
{ base->if(token==loaderGeneration && !isDestroyed) startupBase=base },
{ result->if(token==loaderGeneration && !isDestroyed) {
result.fold({ pack->avatarPack=pack },{ startupStage="failed" })
} })
}
private fun startupVisible() {
mediaReady=true;startupStage="ready"
if(!offlineAvatarPreview && ::session.isInitialized)
avatarPack?.emotionAction?.actionPack?.let(session::installReviewedActions)
}
private fun sendDiagnosticReport() {
@@ -228,15 +280,15 @@ class MainActivity : ComponentActivity() {
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode,
avatarMode = if(offlineAvatarPreview) "offline_preview" else "normal",
avatarPin = BuildConfig.EMOTION_MANIFEST_SHA,
avatarAdmission = avatarPack?.emotionAdmission ?: "static_identity_rejected",
avatarAdmission = avatarPack?.emotionAdmission ?: if(BuildConfig.AVATAR_STARTUP_FIX) "startup_$startupStage" else "static_identity_rejected",
avatarRuntime = avatarMedia.diagnosticState,
actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else session.runtimeProtocolState,
actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else if(::session.isInitialized) session.runtimeProtocolState else "startup_no_session",
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
cameraStatus = expressionState.status,
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
faceSharing = shareFace,
cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else expressions.diagnosticsSnapshot(),
faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else session.faceDiagnosticsSnapshot(),
cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else if(::expressions.isInitialized) expressions.diagnosticsSnapshot() else com.gorios.lanvoice.expression.CameraAnalysisSnapshot(),
faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else if(::session.isInitialized) session.faceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.FaceTransmissionSnapshot(),
rolePlaying = state.phase == VoicePhase.ANSWERING,
role = state.replyEmotion.takeIf { it.turnId != null },
previousRole = state.previousReplyEmotion,
@@ -270,6 +322,7 @@ class MainActivity : ComponentActivity() {
else if (entry.requestPermission(EntryPermission.CAMERA, false)) { preferences().edit().putBoolean("cameraWanted", true).apply(); scheduleEntry() }
}
private fun closeCamera() {
if(!::expressions.isInitialized) return
expressions.stop()
shareFace = false
session.setFaceSharing(false)
@@ -279,7 +332,8 @@ class MainActivity : ComponentActivity() {
inForeground = true
entry.enter()
// The pure coordinator owns bounded connection attempts. No automatic listen here.
if(!offlineAvatarPreview) session.foreground(connectAutomatically = false)
if(!offlineAvatarPreview && ::session.isInitialized) session.foreground(connectAutomatically = false)
if(BuildConfig.AVATAR_STARTUP_FIX && firstDrawReady && !offlineAvatarPreview) initializeNormal()
scheduleEntry()
}
override fun onPause() {
@@ -290,24 +344,25 @@ class MainActivity : ComponentActivity() {
closeCamera()
// Permission windows can pause/stop the Activity. No sensors survive this pause;
// retain only the fenced connection continuation, bounded by VoiceSession's timeout.
session.background(keepConnectionForPermission = true)
if(::session.isInitialized) session.background(keepConnectionForPermission = true)
super.onPause()
}
override fun onStop() {
if (offlineAvatarPreview) { super.onStop(); return }
val pending = entry.permissionPending != null
DebugLogUpload.log("connect", "activity onStop permission=$pending changingConfig=$isChangingConfigurations")
if (!pending) session.background(showDisconnectReason = true)
if (!pending && ::session.isInitialized) session.background(showDisconnectReason = true)
super.onStop()
}
override fun onDestroy() {
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
loaderGeneration++;loaderCancel?.invoke();loaderCancel=null
if (offlineAvatarPreview) { super.onDestroy(); return }
DebugLogUpload.log("audio", "camera stop reason=release")
expressions.release()
if(::expressions.isInitialized) expressions.release()
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
session.release()
if(::session.isInitialized) session.release()
super.onDestroy()
}
}
@@ -51,6 +51,7 @@ class VoiceSession(
private val actionPlayer: ActionPlayer = UnavailableActionPlayer,
private val onPrepareExpression: (ReplyEmotion?) -> Unit = {},
private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {},
private val pendingActionPackSha: ()->String? = { null },
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
@@ -146,6 +147,7 @@ class VoiceSession(
onStatus = {},
onStatusReason = ::onConnection,
actionPackSha = { actions.capability?.manifestSha },
pendingActionPackSha = pendingActionPackSha,
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
@@ -227,6 +229,11 @@ class VoiceSession(
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null, microphoneMuted = microphoneMuted))
startCapture()
}
fun installReviewedActions(pack: ReviewedActionPack) {
checkMainThread()
if(released || !actions.install(pack)) return
dialogue.capabilitiesReady()
}
fun stopVoice(sendControls: Boolean = true,cancelReason: String = "stop_voice") {
checkMainThread()
@@ -22,7 +22,7 @@ interface ActionPlayer {
/** 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 var 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) },
@@ -36,6 +36,12 @@ class ActionController(
private var mediaReleased=false
private var cancellation: Pair<ActionPlan,String>?=null
val active get() = plan != null || stopping
fun install(value: ReviewedActionPack): Boolean {
if(active || pack!=null && pack?.manifestSha!=value.manifestSha) return false
val old=pack;pack=value
if(capability==null) { pack=old;return false }
return true
}
private var deadline = 0L
private var started = 0L
val capability: ReviewedActionPack? get() = pack?.takeIf {
@@ -1,6 +1,8 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.diag.DiagnosticLog
import com.gorios.lanvoice.diag.StartupTrace
import android.os.SystemClock
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
@@ -18,7 +20,7 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
private const val MOTION_ROOT = "avatar/a01-neutral-graph-v1/"
// Add an exact manifest hash only after coordinator preview/edge review. Empty now.
private val APPROVED_MOTION_HASHES = emptySet<String>()
fun load(context: Context): AvatarPack? {
fun load(context: Context,immutableReceipt: Boolean=false): AvatarPack? {
val fallback = STATIC_ROOT + "frames/reference.png"
try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) }
catch (_: Exception) { DiagnosticLog.record("avatar_loader","result=static_identity_rejected");return null }
@@ -27,10 +29,15 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
var stage="index_read_or_hash"
val admitted=try {
val root="avatar/a01-expression-action-v1/"
val parsedAt=SystemClock.elapsedRealtime()
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),
val metadata=jsonMap(JSONObject(String(raw,Charsets.UTF_8)))
StartupTrace.mark(StartupTrace.Phase.INDEX_PARSE,parsedAt)
val verified=mutableMapOf<String,String>()
val runtimesAt=SystemClock.elapsedRealtime()
val index=checkNotNull(EmotionActionManifest.read(metadata,sha(raw),
BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash ->
val runtimeRoot=root+path.substringBeforeLast('/')+"/"
stage="runtime_read_or_hash"
@@ -39,19 +46,29 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
stage="runtime_schema"
val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot))
stage="runtime_body_patch_hash_or_shape"
verifyRuntime(context,runtime);stage="index_schema_or_binding";runtime
if(!immutableReceipt) verifyRuntime(context,runtime,verified)
stage="index_schema_or_binding";runtime
})
StartupTrace.mark(StartupTrace.Phase.RUNTIMES_VERIFY,runtimesAt)
var total=0L
val mediaAt=SystemClock.elapsedRealtime()
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
if(!immutableReceipt && root+clip.path !in verified) {
val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size
verified[root+clip.path]=clip.sha256
} else if(!immutableReceipt) check(verified[root+clip.path]==clip.sha256)
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)
val media=checkNotNull(asset.media)
if(!immutableReceipt) {
val data=read(context,media.root+media.path,128_000_000)
check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000)
}
}
StartupTrace.mark(StartupTrace.Phase.MEDIA_VERIFY,mediaAt)
static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph",emotionAdmission="accepted")
} catch(_: Exception) {
static=static.copy(emotionAdmission=stage)
@@ -125,13 +142,15 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
safeGraph=graph,pathRoot=MOTION_ROOT,motionStatus="approved")
} catch (_: Exception) { static.copy(motionStatus="pack_unavailable") }
}
private fun verifyRuntime(context: Context,runtime: ContinuousAvatarPack) {
private fun verifyRuntime(context: Context,runtime: ContinuousAvatarPack,verified: MutableMap<String,String>) {
check(sha(read(context,runtime.root+runtime.body.path,64_000_000))==runtime.body.sha256)
verified[runtime.root+runtime.body.path]=runtime.body.sha256
runtime.textureImages.forEachIndexed { i,image ->
val bytes=read(context,runtime.root+image.path,256_000);check(sha(bytes)==image.sha256)
val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true }
android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options)
val patch=runtime.patches[i/5];check(options.outWidth==patch.width && options.outHeight==patch.height)
verified[runtime.root+image.path]=image.sha256
}
}
private fun read(context: Context,path: String,maximum: Int): ByteArray = context.assets.open(path).use {
@@ -150,6 +169,13 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
is JSONArray -> (0 until value.length()).map { convert(value.get(it)) }
else -> value
}
private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
private fun sha(bytes: ByteArray): String {
val digest=MessageDigest.getInstance("SHA-256").digest(bytes)
val hex="0123456789abcdef"
return String(CharArray(digest.size*2) { i ->
val value=digest[i/2].toInt() and 255
hex[if(i%2==0) value ushr 4 else value and 15]
})
}
}
}
@@ -40,10 +40,13 @@ private val NoUiAction: ()->Unit = {}
* only changes chrome, never a lifecycle/voice/decoder key or renderer instance. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composable ()->Unit) {
private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composable ()->Unit,
startupStage: String="ready",connecting: Boolean=false) {
var settingsOpen by rememberSaveable { mutableStateOf(false) }
Box(Modifier.fillMaxSize().background(Color.White).testTag("avatar_home")) {
avatar()
StartupStatus(startupStage,connecting,Modifier.align(Alignment.BottomStart)
.windowInsetsPadding(WindowInsets.safeDrawing).padding(start=16.dp,end=88.dp,bottom=16.dp))
IconButton(onClick={settingsOpen=true},modifier=Modifier.align(Alignment.BottomEnd)
.windowInsetsPadding(WindowInsets.safeDrawing).padding(12.dp).size(48.dp)
.background(Color.White.copy(alpha=.72f),CircleShape).testTag("avatar_settings")
@@ -73,6 +76,15 @@ private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composab
}
}
@Composable
private fun StartupStatus(stage: String,connecting: Boolean,modifier: Modifier) {
if(stage!="preparing" && !connecting) return
Column(modifier) {
if(stage=="preparing") Text("准备角色",fontSize=12.sp,color=Color(0xFF59675F))
if(connecting) Text("正在连接",fontSize=12.sp,color=Color(0xFF59675F))
}
}
@Composable
fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,micSettings: Boolean,cameraSettings: Boolean,
pack: AvatarPack?,onRetry: ()->Unit,onAuthorizeMic: ()->Unit,onMute: ()->Unit,onCamera: ()->Unit,
@@ -82,6 +94,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
onCancelAction: ()->Unit,
mediaBinding: AvatarMediaBinding?=null,
onOfflinePreview: ()->Unit=NoUiAction,
startupBase: ContinuousAvatarPack?=null,startupStage: String="ready",
onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar)
@@ -95,7 +109,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
}
}
CleanAvatarScaffold(avatar={
AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding) { video=it }
AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding,
startupBase,onStartupVisible,onStartupFailed,startupStage) { video=it }
},settings={
val status=when(entry) {
EntryPhase.CONNECTING -> "正在连接"
@@ -110,6 +125,10 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
}
}
Text(status,style=MaterialTheme.typography.titleMedium)
if(startupStage=="failed") {
Text("角色准备未完成,基础角色仍可使用",fontSize=12.sp)
TextButton(onClick=onRetryAssets) { Text("重试准备角色") }
}
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("重试连接") }
@@ -147,7 +166,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
TextButton(onClick=onOfflinePreview) { Text("离线播放检查(停止当前会话)") }
reportResult?.let { Text(it,fontSize=12.sp) }
Text(logs.takeLast(10).joinToString("\n"),fontSize=11.sp)
})
},startupStage=startupStage,connecting=BuildConfig.AVATAR_STARTUP_FIX && entry==EntryPhase.CONNECTING)
}
@Composable
@@ -180,7 +199,9 @@ private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
@Composable
fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit,
mediaBinding: AvatarMediaBinding?=null,onReport: ()->Unit=NoUiAction,reportSending: Boolean=false,reportResult: String?=null) {
mediaBinding: AvatarMediaBinding?=null,onReport: ()->Unit=NoUiAction,reportSending: Boolean=false,reportResult: String?=null,
startupBase: ContinuousAvatarPack?=null,startupStage: String="ready",
onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction) {
val activity=LocalContext.current as ComponentActivity
var resumed by remember { mutableStateOf(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }
var trace by remember { mutableStateOf(OfflineAvatarTrace.at(0)) }
@@ -191,10 +212,10 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
var danceActive by remember { mutableStateOf(false) }
var danceStatus by remember { mutableStateOf("idle") }
var nativeState by remember { mutableStateOf("renderer_unavailable") }
val dance=remember(pack,offlineBinding) { OfflineDancePreview(pack?.emotionAction?.actionPack,offlineBinding,
val dance=remember(pack,offlineBinding,startupStage) { OfflineDancePreview(pack?.emotionAction?.actionPack?.takeIf { !BuildConfig.AVATAR_STARTUP_FIX || startupStage=="ready" },offlineBinding,
{ android.os.SystemClock.elapsedRealtime() }) { active,status -> danceActive=active;danceStatus=status } }
var emotionLabel by remember { mutableStateOf("") }
DisposableEffect(activity) {
DisposableEffect(activity,dance) {
val observer=LifecycleEventObserver { _,event ->
if(event==Lifecycle.Event.ON_RESUME) resumed=true
if(event==Lifecycle.Event.ON_PAUSE) { resumed=false;dance.cancel("background") }
@@ -203,7 +224,7 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
onDispose { activity.lifecycle.removeObserver(observer);dance.cancel("disposed") }
}
LaunchedEffect(resumed) { while(resumed) { nativeState=offlineBinding.diagnosticState;delay(500) } }
LaunchedEffect(resumed,restart,override,danceActive) {
LaunchedEffect(resumed,restart,override,danceActive,pack) {
if(resumed && !danceActive) {
val start=android.os.SystemClock.elapsedRealtime()
val emotionSequence=OfflineEmotionSequence(1000+restart)
@@ -223,17 +244,19 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
}
}
CleanAvatarScaffold(avatar={
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize(),if(pack?.emotionAction!=null) offlineBinding else null) { video=it }
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize(),
if(BuildConfig.AVATAR_STARTUP_FIX || pack?.emotionAction!=null) offlineBinding else null,startupBase,onStartupVisible,onStartupFailed,startupStage) { video=it }
},settings={
Text("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp)
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
if(startupStage=="failed") TextButton(onClick=onRetryAssets) { Text("重试准备角色") }
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp)
if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp)
Text("版本 ${BuildConfig.VERSION_NAME} · code ${BuildConfig.VERSION_CODE} · pin ${BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp)
Text("离线媒体:$danceStatus · $nativeState",fontSize=11.sp)
AvatarDiagnostics(pack,video)
if(pack?.emotionAction?.actionPack!=null) {
if(pack?.emotionAction?.actionPack!=null && (!BuildConfig.AVATAR_STARTUP_FIX || startupStage=="ready")) {
Row {
TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_01")},enabled=resumed && !danceActive) { Text("舞蹈 01") }
TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_02")},enabled=resumed && !danceActive) { Text("舞蹈 02") }
@@ -248,16 +271,37 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
TextButton(onClick={dance.cancel();override=AvatarMode.IDLE;restart++}) { Text("Abort") }
TextButton(onClick={override=null;restart++}) { Text("Trace") }
}
})
},startupStage=startupStage)
}
@Composable
private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, turn: Long?, audioEpoch: Long?, modifier: Modifier,
mediaBinding: AvatarMediaBinding?=null,onPresentation: (VideoPresentation) -> Unit) {
mediaBinding: AvatarMediaBinding?=null,startupBase: ContinuousAvatarPack?=null,
onStartupVisible: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,startupStage: String="ready",onPresentation: (VideoPresentation) -> Unit) {
if(BuildConfig.AVATAR_STARTUP_FIX && mediaBinding!=null) {
val activity=LocalContext.current as ComponentActivity
val latest by rememberUpdatedState(onPresentation)
val ready by rememberUpdatedState(onStartupVisible)
val failed by rememberUpdatedState(onStartupFailed)
val stage by rememberUpdatedState(startupStage)
val base by rememberUpdatedState(startupBase)
val admitted by rememberUpdatedState(pack)
val view=remember(mediaBinding) { StartupAvatarView(activity,mediaBinding,{ latest(it) },{ ready() },{failed()}) }
SideEffect { view.update(base,admitted,activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED),stage) }
DisposableEffect(view) {
val observer=LifecycleEventObserver { _,event->
if(event==Lifecycle.Event.ON_PAUSE) view.update(base,admitted,false,stage)
if(event==Lifecycle.Event.ON_RESUME) view.update(base,admitted,true,stage)
}
activity.lifecycle.addObserver(observer)
onDispose { activity.lifecycle.removeObserver(observer);view.dispose() }
}
AndroidView(factory={view},modifier=modifier);return
}
if(pack?.emotionAction!=null && mediaBinding!=null) {
val activity=LocalContext.current as ComponentActivity
val latest by rememberUpdatedState(onPresentation)
val view=remember(pack,mediaBinding) { EmotionActionAvatarView(activity,pack,mediaBinding) { latest(it) } }
val view=remember(pack,mediaBinding) { EmotionActionAvatarView(activity,pack,mediaBinding,{ latest(it) }) }
SideEffect { view.render(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }
DisposableEffect(view) {
val observer=LifecycleEventObserver { _,event->
@@ -27,7 +27,15 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> },
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) }) : ActionPlayer {
private val chooseIdleCycles: ()->Int = { kotlin.random.Random.nextInt(2,4) },
private val holdInitial: Boolean=false) : ActionPlayer {
private var initialHeld=holdInitial
fun releaseInitial() {
if(!active || !initialHeld) return
initialHeld=false
plan()
visible?.takeIf { !holdExit(it) }?.port?.advance()
}
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
private val slots=mutableListOf<Slot>()
@@ -89,7 +97,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
}
fun start() {
if(active || closing!=0) return
active=true;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles()
active=true;initialHeld=holdInitial;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles()
val slot=prepare(index.fallbackId,0);visible=slot
// Ports must deliver callbacks asynchronously, like both Android ports.
}
@@ -141,8 +149,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
}
if(slot===visible) {
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
if(slot===visible && !actionStarted && !holdExit(slot)) slot.port.advance()
if(!inBridge && !initialHeld) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
if(slot===visible && !initialHeld && !actionStarted && !holdExit(slot)) slot.port.advance()
} else if(returning) restoreAction(slot) else plan()
}
},{
@@ -182,7 +190,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
private fun plan() {
val source=visible ?: return
val key=source.key ?: return
if(inBridge || revealing!=null || !active || returning || actionStarted) return
if(initialHeld || inBridge || revealing!=null || !active || returning || actionStarted) return
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else idleTarget ?: selectedId
var reviewedLoop: ConversationEdge?=null
if(source.packageId==wanted) {
@@ -15,7 +15,9 @@ import android.widget.ImageView
/** All views remain in one stable settings-independent composition slot. */
class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
private val binding: AvatarMediaBinding,private val report: (VideoPresentation)->Unit): FrameLayout(context) {
private val binding: AvatarMediaBinding,private val report: (VideoPresentation)->Unit,
private val startupHold: Boolean=false): FrameLayout(context) {
fun releaseStartup() { driver?.releaseInitial() }
private val main=Handler(Looper.getMainLooper())
private val textures=List(4) { TextureView(context).apply { isOpaque=false;alpha=0f } }
private val still=ImageView(context).apply { scaleType=ImageView.ScaleType.FIT_CENTER }
@@ -34,7 +36,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
private val renderers=arrayOfNulls<ContinuousBodyRenderer>(3)
init {
addView(still,LayoutParams(-1,-1))
try { still.setImageBitmap(context.assets.open(pack.fallback).use(BitmapFactory::decodeStream)) } catch(_: Exception) { }
if(!startupHold) try { still.setImageBitmap(context.assets.open(pack.fallback).use(BitmapFactory::decodeStream)) } catch(_: Exception) { }
textures.forEachIndexed { i,view ->
addView(view,LayoutParams(-1,-1))
view.surfaceTextureListener=object: TextureView.SurfaceTextureListener {
@@ -86,19 +88,19 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
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}" } ?: "")) })
clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) },holdInitial=startupHold)
driver=current;main.removeCallbacks(summary);main.postDelayed(summary,10_000);current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie()
}
private fun fitMovie() {
val view=textures[3];if(view.width<=0 || view.height<=0) return
movie?.resize(view.width,view.height)
}
private fun suspend() {
private fun suspend(done: ()->Unit={}) {
main.removeCallbacks(summary)
val old=driver ?: return
old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() }
val old=driver ?: run { done();return }
old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start();done() }
}
fun dispose() { active=false;released=true;suspend() }
fun dispose(done: ()->Unit={}) { active=false;released=true;suspend(done) }
override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() }
}
@@ -0,0 +1,74 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import com.gorios.lanvoice.BuildConfig
import com.gorios.lanvoice.diag.StartupTrace
import org.json.JSONObject
import java.io.File
import java.io.InputStream
import java.security.MessageDigest
import java.util.concurrent.Executors
/** Immutable APK cache; no Activity, Surface, GL texture or camera retained. */
object StartupAvatarRepository {
const val BASIC_SHA="461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2"
private const val ROOT="avatar/startup-white-01/"
private val worker=Executors.newSingleThreadExecutor { Thread(it,"avatar-validation").apply { isDaemon=true } }
private val main=Handler(Looper.getMainLooper())
private val full=StartupLoadCache<AvatarPack>(worker)
private val basic=StartupLoadCache<ContinuousAvatarPack>(worker)
private fun sha(bytes: ByteArray)=MessageDigest.getInstance("SHA-256").digest(bytes)
.joinToString("") { "%02x".format(it) }
private fun readBounded(stream: InputStream,limit: Int): ByteArray = stream.use {
val out=java.io.ByteArrayOutputStream();val buffer=ByteArray(8192)
while(true) { val n=it.read(buffer);if(n<0) break;check(out.size()+n<=limit);out.write(buffer,0,n) };out.toByteArray()
}
fun request(context: Context,onBasic: (ContinuousAvatarPack)->Unit,onFull: (Result<AvatarPack>)->Unit): ()->Unit {
val app=context.applicationContext
val info=app.packageManager.getPackageInfo(app.packageName,0)
val key=StartupAssetKey(info.versionCode.toLong(),info.lastUpdateTime,BuildConfig.EMOTION_MANIFEST_SHA,
"avatar/a01-expression-action-v1/",1)
var cancelled=false
var basicFailed=false
// Both requests use one serial IO worker: the tiny baseline is prioritized.
val cancelBasic=basic.request(key,{
check(Looper.myLooper()!=Looper.getMainLooper())
val start=SystemClock.elapsedRealtime()
val raw=readBounded(app.assets.open(ROOT+"manifest.json"),8192);check(raw.size<=8192 && sha(raw)==BASIC_SHA)
val json=JSONObject(String(raw,Charsets.UTF_8))
check(json.getString("sourceIndexSha256")==BuildConfig.EMOTION_MANIFEST_SHA)
val b=json.getJSONObject("body")
val path=b.getString("path");check(path=="avatar/a01-expression-action-v1/runtime/neutral/body/idle.mp4")
val bytes=readBounded(app.assets.open(path),64_000_000);check(bytes.size<=64_000_000 && sha(bytes)==b.getString("sha256"))
val poster=readBounded(app.assets.open(ROOT+"poster.png"),100_000);check(poster.size<=100_000 && sha(poster)==json.getString("posterSha256"))
val pts=b.getJSONArray("ptsUs");val timeline=List(pts.length()) { pts.getLong(it) }
check(b.getInt("width")==480 && b.getInt("height")==848 &&
BodyTimeline.valid(timeline,b.getInt("frameCount"),b.getLong("durationUs"),b.getInt("fpsNumerator"),b.getInt("fpsDenominator")))
val body=ContinuousBodyAsset(path,b.getString("sha256"),480,848,timeline.size,b.getLong("durationUs"),
timeline,b.getInt("fpsNumerator"),b.getInt("fpsDenominator"))
StartupTrace.mark(StartupTrace.Phase.BASIC_VERIFY,start)
ContinuousAvatarPack(body,emptyList(),emptyMap(),"",BASIC_SHA)
},{ result->main.post { if(!cancelled) result.fold(onBasic,{ basicFailed=true;StartupTrace.mark(StartupTrace.Phase.FULL_FAILED);onFull(Result.failure(it)) }) } })
val cancelFull=full.request(key,{
check(Looper.myLooper()!=Looper.getMainLooper())
StartupTrace.mark(StartupTrace.Phase.CACHE_MISS)
val receipt=BundledValidationReceipt(File(app.filesDir,"bundled-avatar-validation"))
val trusted=receipt.contains(key)
StartupTrace.mark(if(trusted) StartupTrace.Phase.RECEIPT_HIT else StartupTrace.Phase.RECEIPT_MISS)
val pack=checkNotNull(AvatarPack.load(app,trusted))
check(pack.emotionAdmission=="accepted" && pack.emotionAction?.actionPack?.manifestSha==key.pin)
if(!trusted) {
// A failed receipt write cannot invalidate a fully verified current pack.
try { receipt.complete(key);StartupTrace.mark(StartupTrace.Phase.RECEIPT_WRITE) } catch(_: Exception) { }
}
pack
},{ result->main.post { if(!cancelled) {
StartupTrace.mark(if(result.isSuccess) StartupTrace.Phase.FULL_READY else StartupTrace.Phase.FULL_FAILED)
if(!basicFailed) onFull(result)
} } },onHit={ StartupTrace.mark(StartupTrace.Phase.CACHE_HIT) })
return { cancelled=true;cancelBasic();cancelFull() }
}
}
@@ -0,0 +1,115 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import android.graphics.SurfaceTexture
import android.view.Surface
import android.view.TextureView
import android.widget.FrameLayout
import android.widget.ImageView
import com.gorios.lanvoice.R
import com.gorios.lanvoice.diag.StartupTrace
/** One stable host. Only real matching neutral sourceframe0 can hand off the base loop.
* Full renderer is prepared/held hidden; no TextureView output-clock inference. */
class StartupAvatarView(context: Context,private val binding: AvatarMediaBinding,
private val report: (VideoPresentation)->Unit,private val fullVisible: ()->Unit,private val failed: ()->Unit={}): FrameLayout(context) {
private val poster=ImageView(context).apply {
scaleType=ImageView.ScaleType.FIT_CENTER
setImageResource(R.drawable.startup_poster)
}
private val surface=TextureView(context).apply { isOpaque=false;alpha=0f }
private var basic: ContinuousAvatarPack?=null
private var fullPack: AvatarPack?=null
private var renderer: ContinuousBodyRenderer?=null
private var full: EmotionActionAvatarView?=null
private var key: BodyFrameKey?=null
private var fullReady=false
private var switched=false
private var active=false
private var disposed=false
private var epoch=0L
private var basicEpoch=0L
private var baseReleased=false
private var notified=false
private var firstIdle=false
private var startupFailed=false
private var lastStage="preparing"
private var retiring=false
init {
addView(poster,LayoutParams(-1,-1));addView(surface,LayoutParams(-1,-1))
StartupTrace.mark(StartupTrace.Phase.POSTER_READY)
surface.surfaceTextureListener=object: TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(s: SurfaceTexture,w: Int,h: Int) { startBasic() }
override fun onSurfaceTextureSizeChanged(s: SurfaceTexture,w: Int,h: Int) { renderer?.resize(w,h) }
override fun onSurfaceTextureUpdated(s: SurfaceTexture) { }
override fun onSurfaceTextureDestroyed(s: SurfaceTexture): Boolean { closeBasic();return true }
}
}
fun update(base: ContinuousAvatarPack?,pack: AvatarPack?,foreground: Boolean,stage: String="ready") {
active=foreground
if(disposed) return
if(base!=null) basic=base
fullPack=pack
val previousStage=lastStage;lastStage=stage
if(startupFailed && (pack==null || stage=="preparing" && previousStage=="failed")) {
startupFailed=false;val token=++epoch;val old=full;full=null;fullReady=false
retiring=old!=null
old?.dispose {
removeView(old)
if(!disposed && token==epoch) { retiring=false;update(basic,fullPack,active,lastStage) }
}
}
if(!retiring && !startupFailed && pack?.emotionAction!=null && full==null && basic!=null) {
check(pack.emotionAction.packages.getValue(pack.emotionAction.fallbackId).body.sha256==basic!!.body.sha256)
fullPack=pack
val token=epoch
full=EmotionActionAvatarView(context,pack,binding,{ value ->
if(!disposed && token==epoch && active) {
report(value)
if(!switched && !startupFailed && (value.actual=="media_failed" || value.reason !in setOf("reviewed_media_path",""))) {
startupFailed=true;fullReady=false;StartupTrace.mark(StartupTrace.Phase.FULL_FAILED);failed()
}
if(!startupFailed && !fullReady && value.actual=="body_"+pack.emotionAction.fallbackId && value.clipId=="f0_loop0") {
fullReady=true;StartupTrace.mark(StartupTrace.Phase.FULL_FIRST_GL);handoff()
}
if(switched && value.clipId=="f0_loop0") finishHandoff()
}
},startupHold=true).also { it.alpha=0f;addView(it,LayoutParams(-1,-1)) }
}
if(active) { startBasic();full?.render(!startupFailed);if(switched) finishHandoff() }
else { if(!switched) fullReady=false;closeBasic();full?.render(false) }
}
private fun startBasic() {
val pack=basic ?: return
if(!active || disposed || switched || renderer!=null || !surface.isAvailable) return
val token=basicEpoch
renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(surface.surfaceTexture)),surface.width,surface.height,
{ frame,_ -> if(token==basicEpoch && active && !disposed && !switched) {
key=frame.key;surface.alpha=1f;poster.alpha=0f
if(!firstIdle) { firstIdle=true;StartupTrace.mark(StartupTrace.Phase.FIRST_IDLE_FRAME) }
if(frame.key.index==0 && fullReady) handoff() else renderer?.advance()
} },{ _ -> if(token==basicEpoch && !switched) { closeBasic();surface.alpha=0f;poster.alpha=1f } },
automatic=false,mouthEnabled=false)
}
private fun handoff() {
if(startupFailed || !active || disposed || switched || !fullReady || key?.index!=0) return
switched=true
// Both source and target are actual composed frame0 of the exact same body.
full?.alpha=1f;surface.alpha=0f;poster.alpha=0f
StartupTrace.mark(StartupTrace.Phase.HANDOFF)
// The bootstrap decoder must actually release before action capability opens.
val old=renderer;renderer=null
old?.close { if(!disposed) { baseReleased=true;finishHandoff() } }
}
private fun finishHandoff() {
if(!active || disposed || !switched || !baseReleased) return
full?.releaseStartup()
if(!notified) { notified=true;fullVisible() }
}
private fun closeBasic() { basicEpoch++;val old=renderer;renderer=null;key=null;old?.close() }
fun dispose() {
if(disposed) return
disposed=true;active=false;epoch++;closeBasic();full?.dispose();full=null
}
override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() }
}
@@ -0,0 +1,79 @@
package com.gorios.lanvoice.avatar
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.concurrent.Executor
/** Only immutable packaged assets. This receipt NEVER applies to downloaded/runtime files.
* Reconstruct objects through strict parsers on every process; receipt only avoids repeated
* media/PNG byte verification previously completed for this exact installed APK. */
data class StartupAssetKey(val versionCode: Long,val installedAt: Long,val pin: String,
val root: String,val validator: Int) {
init { require(versionCode>0 && installedAt>0 && pin.matches(Regex("[0-9a-f]{64}")) &&
root=="avatar/a01-expression-action-v1/" && 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())
.joinToString("") { "%02x".format(it) }
class BundledValidationReceipt(private val directory: File) {
fun contains(key: StartupAssetKey): Boolean = try {
val file=File(directory,key.fingerprint+".complete")
if(!file.isFile || file.length()>512) false else {
val text="bundled-complete-v1\n"+key.fingerprint+"\n"
file.readText()==text+digest(text)+"\n"
}
} catch(_: Exception) { false }
fun complete(key: StartupAssetKey) {
check(directory.isDirectory || directory.mkdirs())
val text="bundled-complete-v1\n"+key.fingerprint+"\n"
val temp=File.createTempFile("validation-",".tmp",directory)
try {
java.io.FileOutputStream(temp).use { it.write((text+digest(text)+"\n").toByteArray());it.flush();it.fd.sync() }
Files.move(temp.toPath(),File(directory,key.fingerprint+".complete").toPath(),
StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING)
// Keep a bounded history; no old key can satisfy a new install/pin/validator.
directory.listFiles()?.filter { it.name.endsWith(".complete") && it.name!=key.fingerprint+".complete" }
?.forEach { it.delete() }
} finally { temp.delete() }
}
}
/** Shared one-key future. Cancellation removes the Activity listener, not a useful shared
* immutable validation. Failure is not a cached success; retry can start fresh work. */
class StartupLoadCache<T: Any>(private val worker: Executor) {
private class Flight<T>(val key: StartupAssetKey) {
val listeners=linkedMapOf<Long,(Result<T>)->Unit>()
var result: T?=null
}
private val lock=Any()
private var serial=0L
private val flights=linkedMapOf<StartupAssetKey,Flight<T>>()
fun request(key: StartupAssetKey,load: ()->T,callback: (Result<T>)->Unit,onHit: ()->Unit={}): ()->Unit {
val id: Long
val current: Flight<T>
var start=false
var cached: T?=null
synchronized(lock) {
id=++serial
current=flights[key] ?: Flight<T>(key).also { flights[key]=it;start=true }
cached=current.result
if(cached==null) current.listeners[id]=callback
}
if(!start) onHit()
cached?.let { callback(Result.success(it)) }
if(start) worker.execute {
val result=runCatching(load)
val callbacks=synchronized(lock) {
if(result.isSuccess) current.result=result.getOrNull()
else if(flights[key]===current) flights.remove(key)
flights.entries.filter { it.key!=key && it.value.result!=null }.dropLast(1).forEach { flights.remove(it.key) }
current.listeners.values.toList().also { current.listeners.clear() }
}
callbacks.forEach { callback->runCatching { callback(result) } }
}
return { synchronized(lock) { current.listeners.remove(id) };Unit }
}
}
@@ -0,0 +1,26 @@
package com.gorios.lanvoice.diag
import android.os.SystemClock
import android.util.Log
import java.util.concurrent.atomic.AtomicLong
/** Fixed stages and monotonic numbers only. No exceptions, paths, payloads or frames per tick. */
object StartupTrace {
enum class Phase {
ON_CREATE, SHELL_SET_CONTENT, FIRST_DRAW, POSTER_READY, BASIC_VERIFY, FIRST_IDLE_FRAME,
INDEX_PARSE, RUNTIMES_VERIFY, MEDIA_VERIFY, CACHE_MISS, CACHE_HIT, RECEIPT_HIT,
RECEIPT_MISS, RECEIPT_INVALID, RECEIPT_WRITE, FULL_READY, FULL_FAILED, FULL_FIRST_GL,
HANDOFF, HEALTH_START, HEALTH_HTTP, WS_OPEN, AUTH, HELLO, CAP_READY,
CAMERA_MODEL, CAMERA_BIND, CAMERA_READY
}
private val sequence=AtomicLong()
@Volatile private var origin=SystemClock.elapsedRealtime()
fun begin() { sequence.incrementAndGet();origin=SystemClock.elapsedRealtime();mark(Phase.ON_CREATE) }
fun mark(phase: Phase,started: Long?=null) {
val now=SystemClock.elapsedRealtime()
val line="run="+sequence.get()+" phase="+phase.name.lowercase()+" mono_ms="+now+
" elapsed_ms="+(now-origin).coerceAtLeast(0)+" duration_ms="+(started?.let { (now-it).coerceAtLeast(0) } ?: -1)
DiagnosticLog.record("startup",line)
Log.i("LanVoiceStartup",line)
}
}
@@ -41,6 +41,7 @@ class ExpressionController(
var landmarker: FaceLandmarker? = null // Accessed only on this run's executor.
var analysis: ImageAnalysis? = null // Accessed only on main.
var provider: ProcessCameraProvider? = null // Accessed only on main.
var firstReady=false
var lastSampleMs = Long.MIN_VALUE
var lastPublished: List<ExpressionCue>? = null
var lastStableCue = FaceCue.UNKNOWN
@@ -90,7 +91,9 @@ class ExpressionController(
.setOutputFaceBlendshapes(true)
.setOutputFacialTransformationMatrixes(true)
.build()
val modelStart=android.os.SystemClock.elapsedRealtime()
run.landmarker = FaceLandmarker.createFromOptions(appContext, options)
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_MODEL,modelStart)
main.post { if (isCurrent(run)) bind(run) }
} catch (_: Exception) {
fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。", "model_load")
@@ -147,7 +150,9 @@ class ExpressionController(
run.analysis = analysis
analysis.setAnalyzer(run.executor) { image -> analyze(run, image) }
// ImageAnalysis only: no Preview, capture, video recording or image persistence.
val bindStart=android.os.SystemClock.elapsedRealtime()
provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis)
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart)
onState(ExpressionUiState(ExpressionStatus.ACTIVE))
} catch (_: Exception) {
fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind")
@@ -163,6 +168,7 @@ class ExpressionController(
try {
if (!run.active) return
run.diagnostics.received()
if(!run.firstReady) { run.firstReady=true;com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) }
val now = SystemClock.elapsedRealtime()
if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return
run.lastSampleMs = now
@@ -3,6 +3,7 @@ package com.gorios.lanvoice.net
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.gorios.lanvoice.diag.StartupTrace
import okhttp3.Call
import okhttp3.Callback
import okhttp3.EventListener
@@ -43,6 +44,7 @@ class DialogueClient(
private val onProtocolError: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
private val actionPackSha: () -> String? = { null },
private val pendingActionPackSha: () -> String? = { null },
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
) {
private val main = Handler(Looper.getMainLooper())
@@ -79,6 +81,15 @@ class DialogueClient(
private var helloSent = false
private var loggedAudioTurn: Long? = null
private var handshakeTimeout: Runnable? = null
private var pendingOffered: String?=null
private var readyUpdateSent=false
fun capabilitiesReady(): Boolean {
checkMainThread()
val pin=actionPackSha() ?: return false
if(!ready || readyUpdateSent || pendingOffered!=pin || actionNegotiation!="pending_pack") return false
readyUpdateSent=send(DialogueProtocol.capabilitiesReady(pin))
return readyUpdateSent
}
fun connect() {
checkMainThread()
@@ -95,6 +106,7 @@ class DialogueClient(
authReceived = false
helloSent = false
actionNegotiation = "pending"
pendingOffered=null;readyUpdateSent=false
loggedAudioTurn = null
healthCall?.cancel()
healthCall = null
@@ -102,6 +114,7 @@ class DialogueClient(
socket = null
val attempt = generation
updateStatus(ConnectionStatus.CONNECTING, "connect_start")
StartupTrace.mark(StartupTrace.Phase.HEALTH_START)
connectionLog("health checking #$attempt", "connect")
// Arm before submitting the request; synchronous setup failures are terminal too.
handshakeTimeout = Runnable {
@@ -159,6 +172,7 @@ class DialogueClient(
healthCall = null
// Even 404/403/503 establishes HTTPS reachability. /health may be
// absent or protected; only the actual WS handshake decides busy.
StartupTrace.mark(StartupTrace.Phase.HEALTH_HTTP)
connectionLog("health HTTP $code · HTTPS 可达", "connect")
openWebSocket(attempt)
}
@@ -261,6 +275,7 @@ class DialogueClient(
private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
wsOpened = true
StartupTrace.mark(StartupTrace.Phase.WS_OPEN)
connectionLog("ws open")
}
@@ -292,9 +307,11 @@ class DialogueClient(
}
if (authReceived) return@dispatch
authReceived = true
StartupTrace.mark(StartupTrace.Phase.AUTH)
connectionLog("auth ok", "auth")
val offeredPack=actionPackSha()
if (webSocket.send(DialogueProtocol.hello(offeredPack))) {
pendingOffered=if(offeredPack==null) pendingActionPackSha() else null
if (webSocket.send(DialogueProtocol.hello(offeredPack,pendingOffered))) {
helloSent = true
connectionLog("hello sent action_offer=${offeredPack?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }?.take(12) ?: "none"} generation=$attempt", "auth")
} else {
@@ -309,14 +326,25 @@ class DialogueClient(
return@dispatch
}
ready = true
StartupTrace.mark(StartupTrace.Phase.HELLO)
cancelHandshakeTimeout()
actionNegotiation=when {
event.payload.optBoolean("action_pending",false) && pendingOffered!=null -> "pending_pack"
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")
capabilitiesReady()
}
if(event.kind==EventKind.CAPABILITIES && ready && readyUpdateSent) {
val pin=event.payload.optString("action_pack_sha256")
if(pin==pendingOffered && pin==actionPackSha()) {
actionNegotiation=if(event.payload.optBoolean("action_available",false)) "accepted" else "unavailable"
com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAP_READY)
connectionLog("capabilities ready action_pack=$actionNegotiation generation=$attempt","auth")
}
}
if (event.kind == EventKind.ERROR && !ready) {
connectionLog("握手收到 error", "error")
@@ -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, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
AUTH, HELLO, CAPABILITIES, 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,7 +26,7 @@ object DialogueProtocol {
const val UPLINK_PCM_BYTES = 640
const val DOWNLINK_PCM_BYTES = 1_920
fun hello(actionPackSha: String? = null): String = JSONObject()
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null): String = JSONObject()
.put("type", "hello")
.put("codec", "pcm16")
.put("sample_rate", 16_000)
@@ -36,9 +36,18 @@ object DialogueProtocol {
.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"))
} else if(pendingPackSha?.matches(Regex("[0-9a-f]{64}"))==true) {
put("action_protocol",1);put("action_pending_pack_sha256",pendingPackSha)
put("action_kinds",org.json.JSONArray())
} }
.toString()
fun capabilitiesReady(pin: String): String {
require(pin.matches(Regex("[0-9a-f]{64}")))
return JSONObject().put("type","client.capabilities.ready").put("action_protocol",1)
.put("action_pack_sha256",pin).put("action_kinds",org.json.JSONArray().put("dance")).toString()
}
fun listen(start: Boolean): String = JSONObject()
.put("type", "listen")
.put("state", if (start) "start" else "stop")
@@ -90,6 +99,7 @@ object DialogueProtocol {
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
"client.capabilities" -> EventKind.CAPABILITIES
"history" -> EventKind.HISTORY
"listen" -> EventKind.LISTEN
"vad" -> EventKind.VAD