feat: deliver clean avatar home in 0.6.2 UI debug candidate

Keep the avatar mounted while all connection, permission, privacy and diagnostic controls live in a settings sheet. Save the tested continuous-body renderer, safe transition driver and foreground HELLO/permission workflow from this session. Pin runtime03 for the code14 UI-only candidate; mouth deformation remains unresolved. Add source UI contracts, an optional sensor-free device probe, exact asset import and candidate packaging checks. Portrait binaries and diagnostics remain private and untracked.
This commit is contained in:
zenord
2026-10-12 22:19:56 +08:00
parent fdd91234b5
commit 9ea5eb31c1
57 changed files with 4303 additions and 376 deletions
+42 -4
View File
@@ -13,6 +13,16 @@ if (!expressionVersionFile.isFile()) {
expressionVersionFile.withInputStream { expressionVersions.load(it) }
def cameraVersion = expressionVersions.getProperty('camerax.version')
def mediaPipeVersion = expressionVersions.getProperty('mediapipe.version')
def avatarEngineering = providers.gradleProperty('avatarEngineering').orNull == 'true'
def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
if (avatarUiCandidate && !avatarNatural) {
throw new GradleException('UI candidate requires the pinned natural debug runtime')
}
def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?: ''
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
}
if (!cameraVersion || !mediaPipeVersion) {
throw new GradleException('Incomplete gradle/expression-versions.properties; run scripts/prepare-expression.sh')
}
@@ -38,6 +48,15 @@ def generateNetworkSecurityConfig = tasks.register('generateNetworkSecurityConfi
}
}
// AndroidSourceDirectorySet excludes do not reliably filter mergeAssets. A Sync
// staging directory applies actual file exclusions without touching archived imports.
def packagedAssets = layout.buildDirectory.dir('generated/packagedAssets')
def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) {
from('src/main/assets')
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
into(packagedAssets)
}
android {
namespace 'com.gorios.lanvoice'
compileSdk 34
@@ -45,17 +64,36 @@ android {
applicationId 'com.gorios.lanvoice'
minSdk 26
targetSdk 34
versionCode 11
versionName '0.6.0'
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)
versionName avatarUiCandidate ? '0.6.2' : '0.6.1'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = '17' }
buildFeatures { compose true }
buildFeatures { compose true; buildConfig true }
buildTypes {
debug {
if (avatarUiCandidate) versionNameSuffix '-ui-dev'
else if (avatarNatural) versionNameSuffix '-natural-dev'
else if (avatarEngineering) versionNameSuffix '-dev'
buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false'
buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false'
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '"' + (avatarNatural ? naturalManifestSha : '') + '"'
}
release {
buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false'
buildConfigField 'boolean', 'AVATAR_NATURAL', 'false'
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '""'
}
}
androidResources { noCompress += ['task', 'mp4'] }
sourceSets.main.res.srcDir(networkSecurityResources)
// Retain private archived imports on disk, but never put old seated/arms-down
// animation packs into the new graph APK.
sourceSets.main.assets.setSrcDirs([packagedAssets])
}
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig) }
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig, stagePackagedAssets) }
dependencies {
implementation platform('androidx.compose:compose-bom:2024.09.03')
implementation 'androidx.compose.ui:ui'
@@ -0,0 +1,83 @@
package com.gorios.lanvoice
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityNodeInfo
import com.gorios.lanvoice.avatar.ContinuousAvatarView
/** Optional on-device regression, only launches the explicit sensor-free preview.
* Uses platform instrumentation/accessibility, no external test dependencies.
* No screenshots, face/audio capture, permission grant or backend connection. */
class AvatarCleanUiInstrumentation : Instrumentation() {
private var screen: Activity? = null
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); start() }
override fun onStart() {
val result=Bundle()
var success=false
try {
val activity=startActivitySync(Intent().setClassName(targetContext.packageName,"${targetContext.packageName}.MainActivity")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("avatar_offline_preview",true))
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
runOnMainSync { avatar=findAvatar(activity.window.decorView) }
val view=checkNotNull(avatar) { "Continuous avatar missing" }
await { field(view,"renderer")!=null }
val renderer=checkNotNull(field(view,"renderer"))
await { gear()!=null }
assertClean()
val gear=checkNotNull(gear()); val bounds=android.graphics.Rect();gear.getBoundsInScreen(bounds)
val minimum=(48*targetContext.resources.displayMetrics.density).toInt()-1
check(bounds.width()>=minimum && bounds.height()>=minimum) { "Gear touch target below 48dp" }
repeat(3) {
check(checkNotNull(gear()).performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { nodes().any { it.text?.toString()=="关闭" } }
check(nodes().any { it.text?.toString()?.contains("离线 avatar")==true })
check(nodes().any { it.text?.toString()?.contains("嘴层沿用 runtime03")==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(field(activity,"session")==null && field(activity,"expressions")==null)
}
runOnMainSync { activity.moveTaskToBack(true) }
await { field(view,"renderer")==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) {
result.putString("result","FAIL: ${t.javaClass.simpleName}: ${t.message}")
} 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
if(view is ViewGroup) for(i in 0 until view.childCount) findAvatar(view.getChildAt(i))?.let { return it }
return null
}
private fun nodes(): List<AccessibilityNodeInfo> {
val found=mutableListOf<AccessibilityNodeInfo>()
fun collect(node: AccessibilityNodeInfo?) {
if(node==null) return
if(node.packageName?.toString()==targetContext.packageName) found+=node
for(i in 0 until node.childCount) collect(node.getChild(i))
}
collect(uiAutomation.rootInActiveWindow);return found
}
private fun gear()=nodes().firstOrNull { it.contentDescription?.toString()=="设置" && it.isClickable }
private fun assertClean() {
val app=nodes()
check(app.none { !it.text.isNullOrBlank() }) { "Home contains app text" }
check(app.count { it.isClickable }==1 && gear()!=null) { "Home has controls besides gear" }
}
private fun await(condition: ()->Boolean) {
val deadline=SystemClock.uptimeMillis()+8_000
while(!condition()) { check(SystemClock.uptimeMillis()<deadline) { "UI/renderer condition timeout" };SystemClock.sleep(50) }
}
}
@@ -7,6 +7,8 @@ import android.media.AudioManager
import android.os.Bundle
import android.security.NetworkSecurityPolicy
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.getValue
@@ -20,13 +22,17 @@ import com.gorios.lanvoice.diag.DiagnosticReportInfo
import com.gorios.lanvoice.diag.DiagnosticReportUpload
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.net.DebugLogUpload
import com.gorios.lanvoice.expression.CameraPermissionGate
import com.gorios.lanvoice.expression.ExpressionController
import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.ExpressionUiState
import com.gorios.lanvoice.avatar.AvatarPack
import com.gorios.lanvoice.avatar.CallIntent
import com.gorios.lanvoice.avatar.AutoConversation
import com.gorios.lanvoice.avatar.EntryEffect
import com.gorios.lanvoice.avatar.EntryPermission
import com.gorios.lanvoice.avatar.EntryPhase
import com.gorios.lanvoice.avatar.CallScreen
import com.gorios.lanvoice.avatar.EngineeringPreviewScreen
import com.gorios.lanvoice.avatar.OfflineAvatarTrace
class MainActivity : ComponentActivity() {
private var state by mutableStateOf(VoiceUiState())
@@ -37,50 +43,117 @@ class MainActivity : ComponentActivity() {
private lateinit var session: VoiceSession
private lateinit var audioOutput: AudioOutputGate
private var shareFace by mutableStateOf(false)
private val callIntent = CallIntent()
private var dialing by mutableStateOf(false)
private var callFailure by mutableStateOf(false)
private lateinit var entry: AutoConversation
private var entryPhase by mutableStateOf(EntryPhase.CONNECTING)
private var permissionMessage by mutableStateOf<String?>(null)
private var micSettings by mutableStateOf(false)
private var cameraSettings by mutableStateOf(false)
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 expressionState by mutableStateOf(ExpressionUiState())
private lateinit var expressions: ExpressionController
private val cameraGate = CameraPermissionGate()
private var inForeground = false
private var offlineAvatarPreview = false
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
DebugLogUpload.log("audio", "camera permission_result granted=$granted foreground=$inForeground")
cameraAction(cameraGate.permissionResult(granted))
permissionResult(EntryPermission.CAMERA, granted)
}
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground")
val wanted = callIntent.pending
callIntent.permissionResult(granted)
if (granted && wanted) { session.dial(); startPendingVoice() }
else if (!granted && wanted) {
dialing = false
session.permissionDenied()
permissionResult(EntryPermission.MICROPHONE, granted)
}
private fun granted(permission: String) = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
private fun preferences() = getSharedPreferences("entry-permissions", MODE_PRIVATE)
private fun permissionResult(permission: EntryPermission, granted: Boolean) {
if (!::entry.isInitialized || isDestroyed) return
DebugLogUpload.log("audio", "permission=${permission.name.lowercase()} granted=$granted foreground=$inForeground")
entry.permissionResult(permission, granted)
if (permission == EntryPermission.CAMERA && !granted) preferences().edit().putBoolean("cameraWanted", false).apply()
if (!granted) {
if (permission == EntryPermission.MICROPHONE) session.permissionDenied()
else expressions.permissionDenied()
}
scheduleEntry()
}
private fun scheduleEntry() {
main.removeCallbacks(pump)
if (!isDestroyed) main.post(pump)
}
private fun advanceEntry() {
if (!::entry.isInitialized || isDestroyed) return
val now = android.os.SystemClock.elapsedRealtime()
micSettings = !granted(Manifest.permission.RECORD_AUDIO) && preferences().getBoolean("micAsked", false) &&
!shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)
cameraSettings = !granted(Manifest.permission.CAMERA) && preferences().getBoolean("camAsked", false) &&
!shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)
val actions = entry.drive(granted(Manifest.permission.RECORD_AUDIO), granted(Manifest.permission.CAMERA), state.voiceActive, now)
entryPhase = entry.phase
permissionMessage = when {
!granted(Manifest.permission.RECORD_AUDIO) -> "需要麦克风权限才能对话" + if (micSettings) " · 请在应用设置中开启" else ""
!granted(Manifest.permission.CAMERA) -> "摄像头未授权 · 语音可正常使用"
else -> null
}
main.removeCallbacks(retryTimer)
entry.retryAtMs?.takeIf { inForeground }?.let { main.postDelayed(retryTimer, (it - now).coerceAtLeast(1)) }
for (action in actions) when (action) {
EntryEffect.Connect -> session.dial()
EntryEffect.StartVoice -> session.startVoice(microphoneMuted = preferences().getBoolean("microphoneMuted", false))
EntryEffect.StartCamera -> if (inForeground && granted(Manifest.permission.CAMERA)) expressions.start()
is EntryEffect.RequestPermission -> {
val mic = action.permission == EntryPermission.MICROPHONE
preferences().edit().putBoolean(if (mic) "micAsked" else "camAsked", true).apply()
if (mic) microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
else cameraPermission.launch(Manifest.permission.CAMERA)
}
}
}
private fun openSettings() {
startActivity(android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
android.net.Uri.parse("package:$packageName")))
}
private fun authorizeMicrophone() {
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
if (micSettings) openSettings()
else if (entry.requestPermission(EntryPermission.MICROPHONE, false)) scheduleEntry()
}
private fun retryConnection() {
if (entry.retry(android.os.SystemClock.elapsedRealtime())) {
session.resetConnection()
scheduleEntry()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE),
navigationBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE),
)
appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown"
volumeControlStream = AudioManager.STREAM_MUSIC
offlineAvatarPreview = BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING && intent.getBooleanExtra(OfflineAvatarTrace.EXTRA,false)
if (offlineAvatarPreview) {
avatarPack = AvatarPack.load(this)
setContent { EngineeringPreviewScreen(avatarPack) }
return // No VoiceSession, audio focus, permission launchers or camera controller.
}
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 = {
val ended = state.voiceActive && !it.voiceActive
val lostConnection = state.connection == ConnectionStatus.CONNECTED && it.connection != ConnectionStatus.CONNECTED
state = it
if (ended && inForeground && it.connection != ConnectionStatus.CONNECTED) callFailure = true
if (dialing && !callIntent.permissionPending && it.connection in setOf(ConnectionStatus.DISCONNECTED, ConnectionStatus.BUSY)) {
callIntent.cancel(); dialing = false; callFailure = true
}
if (ended && !cameraGate.permissionPending && ::expressions.isInitialized) closeCamera()
startPendingVoice()
if (lostConnection && ::expressions.isInitialized) closeCamera()
entry.connection(it.connection == ConnectionStatus.CONNECTED, it.connection == ConnectionStatus.CONNECTING,
android.os.SystemClock.elapsedRealtime(), it.connection == ConnectionStatus.BUSY)
scheduleEntry()
},
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) },
onPreparePlayback = audioOutput::prepare,
@@ -93,8 +166,10 @@ class MainActivity : ComponentActivity() {
}, onFaceCue = session::observeFace)
setContent {
CallScreen(
state, dialing, callFailure, avatarPack, ::dialCall, ::hangUp,
{ session.setMicrophoneMuted(!state.microphoneMuted) }, ::toggleExpressions,
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,
)
@@ -112,7 +187,7 @@ class MainActivity : ComponentActivity() {
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode,
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
cameraStatus = expressionState.status,
cameraPermissionPending = cameraGate.permissionPending,
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
faceSharing = shareFace,
cameraAnalysis = expressions.diagnosticsSnapshot(),
faceTransmission = session.faceDiagnosticsSnapshot(),
@@ -137,97 +212,53 @@ class MainActivity : ComponentActivity() {
}
private fun toggleExpressions() {
if (!state.voiceActive) return
val granted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE)
DebugLogUpload.log("audio", "camera click foreground=$inForeground granted=$granted running=$running pending=${cameraGate.permissionPending}")
cameraAction(cameraGate.click(running, granted))
}
private fun cameraAction(action: CameraPermissionGate.Action) {
when (action) {
CameraPermissionGate.Action.REQUEST_PERMISSION -> {
DebugLogUpload.log("audio", "camera permission_request")
cameraPermission.launch(Manifest.permission.CAMERA)
}
CameraPermissionGate.Action.START -> {
if (inForeground && state.voiceActive) {
DebugLogUpload.log("audio", "camera start_attempt")
expressions.start()
}
}
CameraPermissionGate.Action.STOP -> {
DebugLogUpload.log("audio", "camera stop reason=user")
expressions.stop()
}
CameraPermissionGate.Action.DENIED -> expressions.permissionDenied()
CameraPermissionGate.Action.NONE -> Unit
if (running) { preferences().edit().putBoolean("cameraWanted", false).apply(); entry.cameraOff(); closeCamera() }
else if (granted(Manifest.permission.CAMERA)) { preferences().edit().putBoolean("cameraWanted", true).apply(); entry.cameraOn(); scheduleEntry() }
else if (cameraSettings) {
preferences().edit().putBoolean("cameraWanted", true).apply()
entry.cameraOn()
openSettings()
}
else if (entry.requestPermission(EntryPermission.CAMERA, false)) { preferences().edit().putBoolean("cameraWanted", true).apply(); scheduleEntry() }
}
private fun dialCall() {
val granted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
if (!callIntent.dial(state.voiceActive, granted)) return
dialing = true
callFailure = false
if (granted) { session.dial(); startPendingVoice() }
else microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
}
private fun closeCamera() {
cameraGate.cancel()
expressions.stop()
shareFace = false
session.setFaceSharing(false)
}
private fun hangUp() {
callIntent.cancel()
dialing = false
callFailure = false
closeCamera()
session.hangUp()
}
private fun startPendingVoice() {
if (!::session.isInitialized) return
val granted = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
if (callIntent.consumeStart(inForeground, state.connection == ConnectionStatus.CONNECTED, granted)) {
dialing = false
session.startVoice()
}
}
override fun onStart() {
super.onStart()
override fun onResume() {
super.onResume()
if (offlineAvatarPreview) return
inForeground = true
DebugLogUpload.log("connect", "activity onStart")
session.foreground()
cameraAction(cameraGate.onForeground())
startPendingVoice()
entry.enter()
// The pure coordinator owns bounded connection attempts. No automatic listen here.
session.foreground(connectAutomatically = false)
scheduleEntry()
}
override fun onStop() {
override fun onPause() {
if (offlineAvatarPreview) { super.onPause(); return }
inForeground = false
val permissionInFlight = callIntent.permissionPending || cameraGate.permissionPending
if (cameraGate.permissionPending) callIntent.resumeAfterCameraPermission(state.voiceActive)
callIntent.background(preserveForPermission = permissionInFlight)
dialing = callIntent.pending
DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations")
cameraGate.onBackground()
shareFace = false
session.setFaceSharing(false)
DebugLogUpload.log("audio", "camera stop reason=background")
expressions.stop()
session.background(
keepConnectionForPermission = permissionInFlight,
showDisconnectReason = !permissionInFlight,
)
entry.leave()
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
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)
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)
super.onStop()
}
override fun onDestroy() {
cameraGate.release()
if (offlineAvatarPreview) { super.onDestroy(); return }
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
DebugLogUpload.log("audio", "camera stop reason=release")
expressions.release()
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
@@ -116,7 +116,7 @@ class VoiceSession(
onConnectionLog = onConnectionLog,
)
fun foreground() {
fun foreground(connectAutomatically: Boolean = true) {
checkMainThread()
if (released) return
backgroundTimeout?.let { main.removeCallbacks(it) }
@@ -128,15 +128,15 @@ class VoiceSession(
DebugLogUpload.log("connect", "session foreground")
foreground = true
update(state.copy(aec = capture.aecAvailability()))
if (!dialogue.hasActiveConnection()) dialogue.connect()
else DebugLogUpload.log("connect", "foreground reused active connection")
if (connectAutomatically && !dialogue.hasActiveConnection()) dialogue.connect()
else DebugLogUpload.log("connect", if (dialogue.hasActiveConnection()) "foreground reused active connection" else "foreground connection delegated")
}
fun background(keepConnectionForPermission: Boolean = false, showDisconnectReason: Boolean = false) {
checkMainThread()
clearFaceContext()
foreground = false
stopVoice(sendControls = false)
stopVoice(sendControls = keepConnectionForPermission)
backgroundTimeout?.let { main.removeCallbacks(it) }
backgroundTimeout = null
DebugLogUpload.log("connect", "session background permission=$keepConnectionForPermission")
@@ -168,12 +168,12 @@ class VoiceSession(
}
/** Activity verifies runtime permission first; capture still handles permission revocation. */
fun startVoice() {
fun startVoice(microphoneMuted: Boolean = false) {
checkMainThread()
DebugLogUpload.log("audio", "start_voice state=${state.connection.name.lowercase()} foreground=$foreground active=${state.voiceActive}")
if (released || !foreground || state.connection != ConnectionStatus.CONNECTED || state.voiceActive) return
if (!dialogue.listen(true)) return
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null, microphoneMuted = false))
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null, microphoneMuted = microphoneMuted))
startCapture()
}
@@ -199,6 +199,13 @@ class VoiceSession(
if (!released && foreground && !dialogue.hasActiveConnection()) dialogue.connect()
}
/** Explicit reconnect invalidates old audio/socket callbacks; it is not a generation request. */
fun resetConnection() {
checkMainThread()
stopVoice()
dialogue.disconnect("user_retry")
}
fun hangUp() {
checkMainThread()
stopVoice()
@@ -0,0 +1,114 @@
package com.gorios.lanvoice.avatar
/** Pure foreground/HELLO/permission coordinator. Effects execute on the Android main thread.
* Connection retries never generate a reply. Permission dialogs retain intent, not capture. */
enum class EntryPhase { CONNECTING, AWAITING_PERMISSION, ACTIVE, ERROR }
enum class EntryPermission { MICROPHONE, CAMERA }
sealed interface EntryEffect {
data object Connect : EntryEffect
data class RequestPermission(val permission: EntryPermission) : EntryEffect
data object StartVoice : EntryEffect
data object StartCamera : EntryEffect
}
class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean = false,
cameraInitiallyWanted: Boolean = true, private val retryDelaysMs: List<Long> = listOf(1_000, 3_000)) {
init { require(retryDelaysMs.size <= 4 && retryDelaysMs.all { it in 500..30_000 }) }
var phase = EntryPhase.CONNECTING; private set
var permissionPending: EntryPermission? = null; private set
var retryAtMs: Long? = null; private set
var attempts = 0; private set
var cameraWanted = cameraInitiallyWanted; private set
private var foreground = false
private var micAsked = microphoneAsked
private var camAsked = cameraAsked
private var connected = false
private var connecting = false
private var startIssued = false
private var cameraIssued = false
private var cycleStarted = false
private var autoMicAllowed = !microphoneAsked
private var autoCamAllowed = !cameraAsked
private var manualPermission: EntryPermission? = null
fun enter() {
foreground = true
startIssued = false; cameraIssued = false
if (!cycleStarted) { attempts = 0; retryAtMs = null; cycleStarted = true }
}
fun leave() {
foreground = false; startIssued = false; cameraIssued = false
// A permission callback may arrive before onStart. Keep its single continuation.
if (permissionPending == null) { cycleStarted = false; retryAtMs = null }
}
/** CONNECTED must mean server HELLO, not merely an open socket. */
fun connection(helloReady: Boolean, inProgress: Boolean, nowMs: Long, busy: Boolean = false) {
val failedAttempt = (connecting || connected) && !helloReady && !inProgress
connected = helloReady; connecting = inProgress
if (failedAttempt) {
startIssued = false; cameraIssued = false
retryAtMs = if (!busy && attempts in 1..retryDelaysMs.size) nowMs + retryDelaysMs[attempts - 1] else null
phase = EntryPhase.ERROR
}
if (inProgress) phase = EntryPhase.CONNECTING
}
fun retry(nowMs: Long): Boolean {
if (!foreground || permissionPending != null || connecting || retryAtMs?.let { nowMs < it } == true) return false
attempts = 0; retryAtMs = null; connected = false; cycleStarted = true
startIssued = false; cameraIssued = false
return true
}
fun requestPermission(permission: EntryPermission, permanentlyDenied: Boolean): Boolean {
if (!foreground || !connected || permissionPending != null || permanentlyDenied) return false
manualPermission = permission
if (permission == EntryPermission.CAMERA) cameraWanted = true
return true
}
fun permissionResult(permission: EntryPermission, granted: Boolean) {
if (permissionPending != permission) return
permissionPending = null
if (permission == EntryPermission.CAMERA && !granted) cameraWanted = false
}
fun cameraOff() { cameraWanted = false; cameraIssued = false }
fun cameraOn() { cameraWanted = true; cameraIssued = false }
fun drive(microphoneGranted: Boolean, cameraGranted: Boolean, voiceActive: Boolean,
nowMs: Long): List<EntryEffect> {
if (!foreground) return emptyList()
if (!connected) {
if (connecting) { phase = EntryPhase.CONNECTING; return emptyList() }
val due = attempts == 0 || retryAtMs?.let { nowMs >= it } == true
if (!due) { phase = EntryPhase.ERROR; return emptyList() }
attempts++; retryAtMs = null; connecting = true; phase = EntryPhase.CONNECTING
return listOf(EntryEffect.Connect)
}
val actions = mutableListOf<EntryEffect>()
// Voice starts as soon as MIC is granted; video and CAMERA readiness are independent.
if (microphoneGranted && !voiceActive && !startIssued) {
startIssued = true; actions += EntryEffect.StartVoice
}
if (cameraGranted && cameraWanted && !cameraIssued) {
cameraIssued = true; actions += EntryEffect.StartCamera
}
if (permissionPending == null) {
val ask = manualPermission ?: when {
!microphoneGranted && autoMicAllowed -> EntryPermission.MICROPHONE
!cameraGranted && autoCamAllowed -> EntryPermission.CAMERA
else -> null
}
manualPermission = null
if (ask != null) {
permissionPending = ask
if (ask == EntryPermission.MICROPHONE) { micAsked = true; autoMicAllowed = false }
else { camAsked = true; autoCamAllowed = false }
actions += EntryEffect.RequestPermission(ask)
}
}
phase = when {
!microphoneGranted -> EntryPhase.AWAITING_PERMISSION
voiceActive -> EntryPhase.ACTIVE
startIssued && actions.none { it == EntryEffect.StartVoice } -> EntryPhase.ERROR
else -> EntryPhase.AWAITING_PERMISSION
}
return actions
}
}
@@ -6,13 +6,13 @@ import com.gorios.lanvoice.dialogue.RoleEmotion
enum class AvatarMode { WAITING, IDLE, TALK }
data class AssetEmotion(val emotion: RoleEmotion = RoleEmotion.NEUTRAL, val intensity: Int = 0)
data class AvatarSelection(val mode: AvatarMode, val requestedEmotion: ReplyEmotion,
data class AvatarSelection(val desiredMode: AvatarMode, val requestedEmotion: ReplyEmotion,
val resolvedAssetEmotion: AssetEmotion = AssetEmotion()) {
val emotionFallback: Boolean get() = requestedEmotion.turnId != null &&
(requestedEmotion.emotion != resolvedAssetEmotion.emotion || requestedEmotion.intensity != resolvedAssetEmotion.intensity)
}
/** No timers, socket events or camera cues can turn on talking here. */
/** PCM supplies intent only. This value is never a permission to reveal another clip. */
class AvatarController {
fun select(inCall: Boolean, requested: ReplyEmotion, activity: PlaybackActivity?): AvatarSelection =
AvatarSelection(if (!inCall) AvatarMode.WAITING else if (activity?.audible == true &&
@@ -1,46 +1,101 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.security.MessageDigest
import com.gorios.lanvoice.BuildConfig
/** Local APK paths only. Corrupt/missing pack never affects voice. Imported bytes are pinned. */
data class AvatarPack(val idle: String, val talk: String, val fallback: String, val waiting: String) {
/** Static identity approval and motion approval are independent. No metadata self-approval. */
data class AvatarPack(val idle: String = "", val talk: String = "", val fallback: String, val waiting: String = fallback,
val safeGraph: SafeAvatarGraph? = null, val pathRoot: String = "", val motionStatus: String = "anchor_review_pending",
val continuous: ContinuousAvatarPack? = null) {
companion object {
private const val ROOT = "avatar/a01-v1/"
fun load(context: Context): AvatarPack? = try {
val raw = context.assets.open(ROOT + "manifest.json").use { it.readBytes() }
check(sha(raw) == "ca817f1e538a5933beac4f3f4cda6367bf87a2d428b3307622c98842ae8679d1")
val manifest = JSONObject(String(raw, Charsets.UTF_8))
check(manifest.getInt("schemaVersion") == 1 && manifest.getString("identityId") == "a01")
fun checked(row: JSONObject): String {
val path = row.getString("path")
check(path.matches(Regex("(?:videos|frames)/[a-zA-Z0-9_.-]+\\.(?:mp4|png)")))
val bytes = context.assets.open(ROOT + path).use { it.readBytes() }
check(bytes.size <= 8_000_000 && sha(bytes) == row.getString("sha256"))
return ROOT + path
}
val rows = manifest.getJSONArray("assets")
val paths = mutableMapOf<String, String>()
for (i in 0 until rows.length()) {
val row = rows.getJSONObject(i)
check(row.getString("emotion") == "neutral" && row.getInt("intensity") == 0 &&
row.getBoolean("loop") && !row.getBoolean("hasAudio"))
val mode = row.getString("mode")
check(mode in setOf("idle", "talk") && !paths.containsKey(mode))
paths[mode] = checked(row)
}
val fallback = checked(manifest.getJSONObject("staticFallback"))
val waiting = try {
val extra = context.assets.open(ROOT + "call-avatar-manifest.json").use { it.readBytes() }
check(sha(extra) == "3b6918cdc955f6d51e8910cf7a0067f4dedb19d28accbb5525f15876e6ad4d8c")
val supplement = JSONObject(String(extra, Charsets.UTF_8))
check(supplement.getString("identityId") == "a01" && supplement.getString("basePackId") == manifest.getString("packId"))
checked(supplement.getJSONObject("waiting"))
} catch (_: Exception) { fallback }
AvatarPack(checkNotNull(paths["idle"]), checkNotNull(paths["talk"]), fallback, waiting)
} catch (_: Exception) { null }
private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes)
.joinToString("") { "%02x".format(it) }
const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2"
private const val STATIC_ROOT = "avatar/a01-standing-arms-reference/"
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? {
val fallback = STATIC_ROOT + "frames/reference.png"
try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) }
catch (_: Exception) { return null }
val static = AvatarPack(fallback=fallback)
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
val root=MOTION_ROOT+"runtime-03/"
val raw=read(context,root+"manifest.json",512_000)
val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw),
BuildConfig.NATURAL_MANIFEST_SHA,true,root))
check(sha(read(context,root+runtime.body.path,16_000_000))==runtime.body.sha256)
for (patch in runtime.patches) {
check(sha(read(context,root+patch.path,256_000))==patch.sha256)
val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true }
val bytes=read(context,root+patch.path,256_000)
android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options)
check(options.outWidth==patch.width && options.outHeight==patch.height)
}
static.copy(continuous=runtime,motionStatus="natural_engineering_only_quality_pending")
} catch (_: Exception) { static.copy(motionStatus="natural_pack_invalid_or_missing") }
return try {
val raw = read(context,MOTION_ROOT+"manifest.json",256_000)
val hash = sha(raw)
val json = JSONObject(String(raw,Charsets.UTF_8))
if (BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING && hash == EngineeringGraphAdmission.MANIFEST_SHA) {
val graph = checkNotNull(EngineeringGraphAdmission.read(jsonMap(json),hash,true))
val assets = json.getJSONArray("assets")
for (i in 0 until assets.length()) {
val row = assets.getJSONObject(i)
check(sha(read(context,MOTION_ROOT+row.getString("path"),16_000_000)) == row.getString("sha256"))
}
val image = json.getJSONArray("anchorImages").getJSONObject(0)
check(image.getString("id") == "A" && image.getString("path") == "anchors/A.png")
check(sha(read(context,MOTION_ROOT+image.getString("path"),8_000_000)) == image.getString("sha256"))
return static.copy(fallback=MOTION_ROOT+image.getString("path"),waiting=MOTION_ROOT+image.getString("path"),
safeGraph=graph,pathRoot=MOTION_ROOT+"controlled-01/",motionStatus="engineering_only_natural_not_approved")
}
check(json.getString("identityId") == "a01" && json.getString("packId") == "a01-neutral-graph-v1")
val safety = SafeAvatarManifest.read(jsonMap(json),hash,APPROVED_MOTION_HASHES)
if (safety.status != SafetyManifestStatus.APPROVED) return static.copy(motionStatus=safety.status.name.lowercase())
val graph = checkNotNull(safety.graph)
check(NeutralGraphContract.missing(graph).isEmpty())
val assets = json.getJSONArray("assets")
check(assets.length() == 5)
val verifiedPaths = mutableSetOf<String>()
var total = 0L
for (i in 0 until assets.length()) {
val row = assets.getJSONObject(i)
check(row.getString("emotion") == "neutral" && row.getInt("intensity") == 0 && !row.getBoolean("hasAudio"))
val path = row.getString("path")
check(path.matches(Regex("(?:videos|delivery)/[a-zA-Z0-9_.-]+\\.mp4")))
check(verifiedPaths.add(path))
val data = read(context,MOTION_ROOT+path,16_000_000)
check(sha(data) == row.getString("sha256"))
total += data.size; check(total <= 128_000_000)
}
check(graph.clips.values.all { it.path in verifiedPaths })
val stillPath = json.getString("staticFallbackPath")
check(stillPath.matches(Regex("frames/[a-zA-Z0-9_.-]+\\.png")))
check(sha(read(context,MOTION_ROOT+stillPath,8_000_000)) == json.getString("staticFallbackSha256"))
static.copy(fallback=MOTION_ROOT+stillPath,waiting=MOTION_ROOT+stillPath,
safeGraph=graph,pathRoot=MOTION_ROOT,motionStatus="approved")
} catch (_: Exception) { static.copy(motionStatus="pack_unavailable") }
}
private fun read(context: Context,path: String,maximum: Int): ByteArray = context.assets.open(path).use {
val data = it.readBytesBounded(maximum); data
}
private fun java.io.InputStream.readBytesBounded(maximum: Int): ByteArray {
val buffer = java.io.ByteArrayOutputStream()
val chunk = ByteArray(8192)
while (true) { val n = read(chunk); if (n < 0) break; check(buffer.size()+n <= maximum); buffer.write(chunk,0,n) }
return buffer.toByteArray()
}
private fun jsonMap(json: JSONObject): Map<String,Any?> = json.keys().asSequence().associateWith { convert(json.get(it)) }
private fun convert(value: Any?): Any? = when (value) {
JSONObject.NULL -> null
is JSONObject -> jsonMap(value)
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) }
}
}
@@ -4,7 +4,9 @@ import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.SystemClock
import android.view.Surface
import android.view.TextureView
@@ -12,112 +14,105 @@ import android.widget.FrameLayout
import android.widget.ImageView
import com.gorios.lanvoice.diag.DiagnosticLog
/** Two independent muted loops. First-frame callbacks reveal only the current desired mode.
* No seeks or player allocation on syllables; lifecycle release invalidates all callbacks. */
class AvatarVideoView(context: Context, private val pack: AvatarPack?) : FrameLayout(context) {
private data class Clip(val mode: AvatarMode, val path: String, val view: TextureView,
var player: MediaPlayer? = null, var surface: Surface? = null, var ready: Boolean = false)
/** White Fit canvas. Approved static identity works independently of video graph readiness.
* Native codec PTS + latched TextureView timestamp gate all video visibility. */
class AvatarVideoView(context: Context, private val pack: AvatarPack?,
private val onPresentation: (VideoPresentation) -> Unit = {}) : FrameLayout(context) {
private val still = ImageView(context).apply { scaleType = ImageView.ScaleType.FIT_CENTER }
private val clips = mutableListOf<Clip>()
private var desired = AvatarMode.WAITING
private var active = false
private var epoch = 0L
private var failed = false
private val textures = List(2) { TextureView(context).apply { alpha = 0f; isOpaque = false } }
private val ports = arrayOfNulls<CodecAnchorVideoPort>(2)
private val sizes = Array(2) { 941 to 1672 }
private val main = Handler(Looper.getMainLooper())
private var decoderThread: HandlerThread? = null
private var driver: SafeVideoDriver? = null
private var foreground = false
private var failedThisRun = false
private var desired = SafeClipRole.IDLE
private var turn: Long? = null
private var audioEpoch: Long? = null
private var presentation = VideoPresentation()
private var lastLog = -10_000L
private var displayedStill: String? = null
private var idleFirstMs: Long? = null
private var talkFirstMs: Long? = null
private val diagnostics = object : Runnable {
override fun run() {
if (!foreground) return
driver?.sample()?.let(::present)
main.postDelayed(this,1_000)
}
}
init {
addView(still, LayoutParams(-1, -1))
pack?.let {
for ((mode, path) in listOf(AvatarMode.IDLE to it.idle, AvatarMode.TALK to it.talk)) {
val view = TextureView(context).apply { alpha = 0f; isOpaque = false }
val clip = Clip(mode, path, view); clips.add(clip)
addView(view, LayoutParams(-1, -1))
view.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, w: Int, h: Int) { clips.forEach { prepare(it) }; fit(clip) }
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, w: Int, h: Int) { fit(clip) }
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) {}
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean { releasePlayers(); return true }
addView(still,LayoutParams(-1,-1))
try { still.setImageBitmap(pack?.let { context.assets.open(it.fallback).use(BitmapFactory::decodeStream) }) }
catch (_: Exception) { still.setImageDrawable(null) }
textures.forEachIndexed { index, view ->
addView(view,LayoutParams(-1,-1))
view.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture,w: Int,h: Int) { fit(index); startIfReady() }
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture,w: Int,h: Int) { fit(index) }
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) { ports[index]?.textureLatched(texture.timestamp) }
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {
// No stale visible layer/old output is retained after a destroyed surface.
stopDriver(); present(VideoPresentation(reason="surface_lost")); return true
}
}
}
reveal()
}
fun render(mode: AvatarMode, foreground: Boolean) {
desired = mode
val run = foreground && mode != AvatarMode.WAITING
if (active && !run) { active = false; releasePlayers() }
if (!active && run) {
active = true; failed = false
clips.forEach { prepare(it) }
fun render(mode: AvatarMode, foreground: Boolean, turnId: Long? = null, playbackGeneration: Long? = null) {
desired = if (mode == AvatarMode.TALK) SafeClipRole.TALK else SafeClipRole.IDLE
turn = turnId
val newEpoch = audioEpoch != playbackGeneration
audioEpoch = playbackGeneration
if (this.foreground != foreground) {
this.foreground = foreground
main.removeCallbacks(diagnostics)
if (!foreground) { stopDriver(); present(VideoPresentation(reason="background")) }
else { failedThisRun = false; main.post(diagnostics) }
}
reveal()
startIfReady()
driver?.desire(desired,turn,newEpoch)
}
private fun prepare(clip: Clip) {
if (!active || failed || clip.player != null || !clip.view.isAvailable) return
val fence = epoch
val started = SystemClock.elapsedRealtime()
try {
val player = MediaPlayer(); clip.player = player
val surface = Surface(checkNotNull(clip.view.surfaceTexture)); clip.surface = surface
player.setSurface(surface); player.setVolume(0f, 0f); player.isLooping = true
context.assets.openFd(clip.path).use { player.setDataSource(it.fileDescriptor, it.startOffset, it.length) }
player.setOnPreparedListener {
if (valid(clip, player, fence)) { fit(clip); player.start() }
}
player.setOnInfoListener { _, what, _ ->
if (valid(clip, player, fence) && what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
clip.ready = true
val elapsed = (SystemClock.elapsedRealtime()-started).coerceIn(0,60000)
if (clip.mode == AvatarMode.IDLE) idleFirstMs = elapsed else talkFirstMs = elapsed
if (clips.all { it.ready }) diagnostic("decoder=ready idle_first_ms=$idleFirstMs talk_first_ms=$talkFirstMs")
reveal()
}
true
}
player.setOnErrorListener { _, _, _ -> if (valid(clip, player, fence)) decoderFailed(); true }
player.prepareAsync()
} catch (_: Exception) { decoderFailed() }
}
private fun valid(clip: Clip, player: MediaPlayer, fence: Long) = active && !failed && epoch == fence && clip.player === player
private fun fit(clip: Clip) {
val w = clip.view.width.toFloat(); val h = clip.view.height.toFloat()
if (w <= 0 || h <= 0) return
val vw = clip.player?.videoWidth?.takeIf { it > 0 }?.toFloat() ?: 480f
val vh = clip.player?.videoHeight?.takeIf { it > 0 }?.toFloat() ?: 848f
val scale = minOf(w / vw, h / vh)
clip.view.setTransform(Matrix().apply { setScale(vw * scale / w, vh * scale / h, w / 2, h / 2) })
}
private fun reveal() {
val ready = active && !failed && clips.size == 2 && clips.all { it.ready }
clips.forEach { it.view.alpha = if (ready && it.mode == desired) 1f else 0f }
still.alpha = if (ready) 0f else 1f
val path = if (desired == AvatarMode.WAITING) pack?.waiting else pack?.fallback
if (path != displayedStill) {
displayedStill = path
try { still.setImageBitmap(path?.let { context.assets.open(it).use(BitmapFactory::decodeStream) }) }
catch (_: Exception) { still.setImageDrawable(null) }
private fun startIfReady() {
if (!foreground || failedThisRun || driver != null || textures.any { !it.isAvailable }) return
val graph = pack?.safeGraph ?: run {
present(VideoPresentation(reason=pack?.motionStatus ?: "pack_missing")); return
}
val thread = HandlerThread("avatar-decode").apply { start() }; decoderThread = thread
val current = SafeVideoDriver(graph,createPort = { index ->
CodecAnchorVideoPort(context,Surface(checkNotNull(textures[index].surfaceTexture)),pack.pathRoot,thread.looper) { w,h ->
sizes[index] = w to h; fit(index)
}.also { ports[index] = it }
}, reveal = { index ->
textures.forEachIndexed { i,v -> v.alpha = if (i == index) 1f else 0f }
still.alpha = 0f
}, showStatic = { textures.forEach { it.alpha = 0f }; still.alpha = 1f },
now = SystemClock::elapsedRealtime, report = { value ->
if (value.reason.startsWith("video_") || value.reason in setOf("entry_missed","startup_unreviewed","startup_rejected")) failedThisRun = true
present(value)
})
driver = current
current.desire(desired,turn)
current.start()
}
private fun decoderFailed() { failed = true; releasePlayers(); diagnostic("decoder=failed fallback=static"); reveal() }
private fun diagnostic(message: String) {
private fun present(value: VideoPresentation) {
if (presentation != value) { presentation = value; onPresentation(value) }
val now = SystemClock.elapsedRealtime()
if (now - lastLog < 1_000) return
lastLog = now; DiagnosticLog.record("avatar", message)
}
private fun releasePlayers() {
epoch++
clips.forEach {
it.ready = false
try { it.player?.release() } catch (_: Exception) { }
it.player = null; it.surface?.release(); it.surface = null; it.view.alpha = 0f
if (now-lastLog >= 1_000) {
lastLog = now
DiagnosticLog.record("avatar_video", "actual=${value.actual} clip=${value.clipId} reason=${value.reason} wait_ms=${value.waitMs.coerceIn(0,60000)} mouth_active_lag_ms=${value.mouthActiveLagMs?.coerceIn(0,60000)} closed_lag_ms=${value.closingLagMs?.coerceIn(0,60000)} first_ms=${value.firstFrameMs?.coerceIn(0,60000)}")
}
}
fun dispose() { active = false; releasePlayers() }
private fun fit(index: Int) {
val view = textures[index]
if (view.width <= 0 || view.height <= 0) return
val (w,h) = sizes[index]
val fit = fitVideo(view.width,view.height,w,h)
view.setTransform(Matrix().apply { setScale(fit.scaleX,fit.scaleY,view.width/2f,view.height/2f) })
}
private fun stopDriver() {
driver?.stop(); driver = null
ports.indices.forEach { ports[it]?.close(); ports[it] = null }
decoderThread?.quitSafely(); decoderThread = null
textures.forEach { it.alpha = 0f }; still.alpha = 1f
}
fun dispose() { foreground = false; main.removeCallbacks(diagnostics); stopDriver() }
override fun onDetachedFromWindow() { dispose(); super.onDetachedFromWindow() }
}
@@ -1,8 +1,7 @@
package com.gorios.lanvoice.avatar
import android.graphics.BitmapFactory
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
@@ -10,13 +9,17 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
@@ -29,106 +32,198 @@ import com.gorios.lanvoice.audio.VoiceUiState
import com.gorios.lanvoice.expression.ExpressionControls
import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.ExpressionUiState
import com.gorios.lanvoice.BuildConfig
/** The avatar always occupies the same composition slot. Opening/closing the sheet
* 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) {
var settingsOpen by rememberSaveable { mutableStateOf(false) }
Box(Modifier.fillMaxSize().background(Color.White).testTag("avatar_home")) {
avatar()
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")
.semantics { contentDescription="设置" }) {
Canvas(Modifier.size(22.dp)) {
val ink=Color(0xFF59675F)
repeat(8) { i -> rotate(i*45f) {
drawRect(ink,Offset(center.x-size.width*.09f,size.height*.02f),Size(size.width*.18f,size.height*.23f))
} }
drawCircle(ink,radius=size.width*.34f)
drawCircle(Color.White,radius=size.width*.14f)
}
}
}
if(settingsOpen) {
ModalBottomSheet(onDismissRequest={settingsOpen=false},sheetState=rememberModalBottomSheetState(skipPartiallyExpanded=true),
containerColor=Color.White,modifier=Modifier.testTag("avatar_settings_sheet")) {
Column(Modifier.fillMaxWidth().heightIn(max=640.dp).verticalScroll(rememberScrollState()).padding(horizontal=24.dp)) {
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.SpaceBetween) {
Text("设置",style=MaterialTheme.typography.titleLarge)
TextButton(onClick={settingsOpen=false},modifier=Modifier.testTag("avatar_settings_close")) { Text("关闭") }
}
settings()
Spacer(Modifier.height(24.dp))
}
}
}
}
@Composable
fun CallScreen(state: VoiceUiState, dialing: Boolean, failure: Boolean, pack: AvatarPack?,
onDial: () -> Unit, onHangUp: () -> Unit, onMute: () -> Unit, onCamera: () -> Unit,
expression: ExpressionUiState, shareFace: Boolean, onShare: (Boolean) -> Unit,
logs: List<String>, onReport: () -> Unit, reportSending: Boolean, reportResult: String?, onInterrupt: () -> Unit,
fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,micSettings: Boolean,cameraSettings: Boolean,
pack: AvatarPack?,onRetry: ()->Unit,onAuthorizeMic: ()->Unit,onMute: ()->Unit,onCamera: ()->Unit,
expression: ExpressionUiState,shareFace: Boolean,onShare: (Boolean)->Unit,
logs: List<String>,onReport: ()->Unit,reportSending: Boolean,reportResult: String?,onInterrupt: ()->Unit,
) {
val muted = Color(0xFFB5B7C6)
val gold = Color(0xFFE8C884)
val context = LocalContext.current
val avatar = remember { AvatarController() }.select(state.voiceActive, state.replyEmotion, state.playbackActivity)
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity)
val latestAvatar by rememberUpdatedState(avatar)
LaunchedEffect(state.voiceActive) {
if (state.voiceActive) while (true) {
val selected = latestAvatar
DiagnosticLog.record("avatar", "mode=${selected.mode.name.lowercase()} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} selected=${selected.resolvedAssetEmotion.emotion.wire}/${selected.resolvedAssetEmotion.intensity} fallback=${selected.emotionFallback}")
var video by remember(pack) { mutableStateOf(VideoPresentation()) }
val latestVideo by rememberUpdatedState(video)
LaunchedEffect(state.voiceActive,pack) {
if(state.voiceActive) while(true) {
val selected=latestAvatar
DiagnosticLog.record("avatar","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} selected=${selected.resolvedAssetEmotion.emotion.wire}/${selected.resolvedAssetEmotion.intensity} fallback=${selected.emotionFallback}")
delay(1_000)
}
}
var details by remember { mutableStateOf(false) }
val waiting = remember(pack) { try {
pack?.let { context.assets.open(it.waiting).use { stream -> BitmapFactory.decodeStream(stream)?.asImageBitmap() } }
} catch (_: Exception) { null } }
Column(Modifier.fillMaxSize().background(Color(0xFF121220)).windowInsetsPadding(WindowInsets.safeDrawing)
.padding(horizontal = 20.dp, vertical = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Text(if (state.voiceActive) "通话中 · " + when (state.phase) {
VoicePhase.LISTENING -> if (state.microphoneMuted) "麦克风已静音" else "听取中"
VoicePhase.RECOGNIZING -> "识别中"
VoicePhase.THINKING -> "思考中"
VoicePhase.ANSWERING -> "回答中"
else -> "已连接"
} else if (dialing) "正在连接…" else if (failure) "连接失败" else "声伴", color = gold, fontSize = 15.sp)
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
if (state.voiceActive) {
val width = minOf(maxWidth, maxHeight * (480f / 848f))
AvatarPortrait(pack, avatar.mode, Modifier.width(width).aspectRatio(480f / 848f))
} else {
val size = minOf(maxWidth, maxHeight * .65f, 320.dp)
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.verticalScroll(rememberScrollState())) {
if (waiting != null) Image(waiting, "待接听角色头像", Modifier.size(size).clip(CircleShape))
else Box(Modifier.size(size).clip(CircleShape).background(Color(0xFF292A3C)), contentAlignment = Alignment.Center) {
Text("声伴", color = gold, fontSize = 30.sp)
}
Spacer(Modifier.height(20.dp))
Text("声伴", color = Color.White, fontSize = 28.sp)
Text("视频角色 · 候选素材", color = muted, fontSize = 12.sp)
}
CleanAvatarScaffold(avatar={
AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize()) { video=it }
},settings={
val status=when(entry) {
EntryPhase.CONNECTING -> "正在连接"
EntryPhase.AWAITING_PERMISSION -> "等待麦克风授权"
EntryPhase.ERROR -> "连接或语音启动失败"
EntryPhase.ACTIVE -> when(state.phase) {
VoicePhase.LISTENING -> if(state.microphoneMuted) "麦克风已暂停" else "正在听你说"
VoicePhase.RECOGNIZING -> "正在识别"
VoicePhase.THINKING -> "正在思考"
VoicePhase.ANSWERING -> "正在回答"
else -> "已连接"
}
}
state.guidance?.let { Text(it, color = gold, fontSize = 12.sp, textAlign = TextAlign.Center) }
if (state.voiceActive) {
Row(Modifier.widthIn(max = 520.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CallButton(if (state.microphoneMuted) "取消静音" else "麦克风静音", onMute, Modifier.weight(1f), Color(0xFF343648))
CallButton(if (expression.status in setOf(ExpressionStatus.ACTIVE, ExpressionStatus.STARTING)) "关闭相机" else "开启相机", onCamera, Modifier.weight(1f), Color(0xFF343648))
CallButton("挂断", onHangUp, Modifier.weight(1f), Color(0xFFB83B50))
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)
TextButton(onClick=onRetry) { Text("重试连接") }
permissionMessage?.let { Text(it,fontSize=13.sp) }
if(entry==EntryPhase.AWAITING_PERMISSION) TextButton(onClick=onAuthorizeMic) { Text(if(micSettings) "打开麦克风权限设置" else "允许麦克风") }
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)) {
Text(if(state.microphoneMuted) "恢复收音" else "暂停收音")
}
} else {
CallButton(if (dialing) "取消连接" else "拨通", if (dialing) onHangUp else onDial,
Modifier.widthIn(max = 360.dp).fillMaxWidth(), if (dialing) Color(0xFF343648) else Color(0xFF267E63))
}
TextButton(onClick = { details = !details }) { Text(if (details) "收起详情" else "通话详情", color = muted, fontSize = 12.sp) }
if (details) Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally) {
Text("角色:${state.roleLabel}", color = gold, fontSize = 12.sp)
Text("请求表达:" + if (state.replyEmotion.turnId == null) "尚未收到" else
"${state.replyEmotion.label} (${state.replyEmotion.emotion.wire}/${state.replyEmotion.intensity})", color = muted, fontSize = 12.sp)
state.previousReplyEmotion?.let { Text("上一轮:${it.label}", color = muted, fontSize = 12.sp) }
Text("素材:中立 · ${avatar.mode.name.lowercase()}" + if (avatar.emotionFallback) "(当前表达缺素材,降级中立)" else "", color = muted, fontSize = 12.sp)
Text(if (pack == null) "素材包缺失或校验失败 · 语音仍可用" else "素材审核 / 设备验收待完成", color = muted, fontSize = 11.sp)
ExpressionControls(expression, onCamera, shareFace, onShare, controlsEnabled = state.voiceActive)
Text("AEC:${state.aec.name} · 效果待真机验证", color = muted, fontSize = 11.sp)
Row {
TextButton(onClick = onInterrupt, enabled = state.voiceActive) { Text("打断") }
TextButton(onClick = onReport, enabled = !reportSending) { Text(if (reportSending) "发送中…" else "发送诊断报告") }
OutlinedButton(onClick=onCamera,enabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED,
modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Text(if(expression.status in setOf(ExpressionStatus.ACTIVE,ExpressionStatus.STARTING)) "关闭相机" else if(cameraSettings) "相机权限设置" else "开启相机")
}
reportResult?.let { Text(it, color = muted, fontSize = 11.sp) }
Text(logs.takeLast(10).joinToString("\n"), color = muted, fontSize = 10.sp)
}
}
ExpressionControls(expression,onCamera,shareFace,onShare,controlsEnabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED)
HorizontalDivider(Modifier.padding(vertical=12.dp))
Text("角色:${state.roleLabel}",fontSize=13.sp)
Text("请求表达:"+if(state.replyEmotion.turnId==null) "尚未收到" else "${state.replyEmotion.label} (${state.replyEmotion.emotion.wire}/${state.replyEmotion.intensity})",fontSize=12.sp)
state.previousReplyEmotion?.let { Text("上一轮:${it.label}",fontSize=12.sp) }
Text("解析素材:中立0 · ${video.actual};意图 ${avatar.desiredMode.name.lowercase()}"+if(avatar.emotionFallback) "(素材缺失,回退中立)" else "",fontSize=12.sp)
AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
Row {
TextButton(onClick=onInterrupt,enabled=state.voiceActive) { Text("打断回答") }
TextButton(onClick=onReport,enabled=!reportSending) { Text(if(reportSending) "发送中…" else "发送诊断报告") }
}
reportResult?.let { Text(it,fontSize=12.sp) }
Text(logs.takeLast(10).joinToString("\n"),fontSize=11.sp)
})
}
@Composable
private fun CallButton(label: String, onClick: () -> Unit, modifier: Modifier, color: Color) {
Button(onClick, modifier.heightIn(min = 52.dp), colors = ButtonDefaults.buttonColors(containerColor = color), contentPadding = PaddingValues(8.dp)) {
Text(label, fontSize = 13.sp, textAlign = TextAlign.Center)
private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
if(BuildConfig.AVATAR_ENGINEERING) Text("工程候选:自然度待验",color=Color(0xFF94652D),fontSize=13.sp)
if(BuildConfig.VERSION_NAME=="0.6.2-ui-dev") Text("本版仅修复界面;嘴层沿用 runtime03,变形问题尚未修复",fontSize=13.sp)
Text("画面:${video.clipId} / ${video.reason}",fontSize=12.sp)
Text("相位等待 ${video.waitMs}ms · 首帧 ${video.firstFrameMs ?: "未知"}ms",fontSize=12.sp)
Text("口部活动延后 ${video.mouthActiveLagMs ?: "未知"}ms · 稳定闭嘴延后 ${video.closingLagMs ?: "未知"}ms",fontSize=12.sp)
Text(if(pack?.continuous!=null) "连续身体+局部嘴层 · 感知响应与自然度待验" else "画面资源:${pack?.motionStatus ?: "缺失"}",fontSize=12.sp)
Text("≤1s感知响应尚未认证;相机表情验收独立进行",fontSize=12.sp)
}
/** Sensor-free synthetic intents, same real renderer and same clean home. */
@Composable
fun EngineeringPreviewScreen(pack: AvatarPack?) {
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)) }
var override by remember { mutableStateOf<AvatarMode?>(null) }
var restart by remember { mutableStateOf(0L) }
var video by remember { mutableStateOf(VideoPresentation()) }
DisposableEffect(activity) {
val observer=LifecycleEventObserver { _,event ->
if(event==Lifecycle.Event.ON_RESUME) resumed=true
if(event==Lifecycle.Event.ON_PAUSE) resumed=false
}
activity.lifecycle.addObserver(observer)
onDispose { activity.lifecycle.removeObserver(observer) }
}
LaunchedEffect(resumed,restart) {
if(resumed) {
val start=android.os.SystemClock.elapsedRealtime()
while(true) { trace=OfflineAvatarTrace.at(android.os.SystemClock.elapsedRealtime()-start);delay(20) }
}
}
CleanAvatarScaffold(avatar={
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize()) { video=it }
},settings={
Text("离线 avatar · 无连接 / 无麦克风 / 无相机",fontSize=13.sp)
Text("合成意图:${override?.name ?: trace.label}",fontSize=12.sp)
AvatarDiagnostics(pack,video)
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") }
TextButton(onClick={override=AvatarMode.TALK}) { Text("Talk") }
TextButton(onClick={override=AvatarMode.IDLE;restart++}) { Text("Abort") }
TextButton(onClick={override=null;restart++}) { Text("Trace") }
}
})
}
@Composable
private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, modifier: Modifier) {
private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, turn: Long?, audioEpoch: Long?, modifier: Modifier, onPresentation: (VideoPresentation) -> Unit) {
if (BuildConfig.AVATAR_NATURAL) {
ContinuousPortrait(pack,mode,turn,audioEpoch,modifier,onPresentation)
return
}
val activity = LocalContext.current as ComponentActivity
val view = remember(pack) { AvatarVideoView(activity, pack) }
val latestPresentation by rememberUpdatedState(onPresentation)
val view = remember(pack) { AvatarVideoView(activity, pack) { latestPresentation(it) } }
val currentMode by rememberUpdatedState(mode)
SideEffect { view.render(mode, activity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
val currentTurn by rememberUpdatedState(turn)
val currentEpoch by rememberUpdatedState(audioEpoch)
SideEffect { view.render(mode, activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED), turn, audioEpoch) }
DisposableEffect(view) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_STOP) view.render(AvatarMode.WAITING, false)
if (event == Lifecycle.Event.ON_START) view.render(currentMode, true)
if (event == Lifecycle.Event.ON_PAUSE) view.render(AvatarMode.WAITING, false)
if (event == Lifecycle.Event.ON_RESUME) view.render(currentMode, true, currentTurn, currentEpoch)
}
activity.lifecycle.addObserver(observer)
onDispose { activity.lifecycle.removeObserver(observer); view.dispose() }
}
AndroidView(factory = { view }, modifier = modifier)
}
@Composable
private fun ContinuousPortrait(pack: AvatarPack?,mode: AvatarMode,turn: Long?,audioEpoch: Long?,modifier: Modifier,onPresentation: (VideoPresentation)->Unit) {
val activity=LocalContext.current as ComponentActivity
val latest by rememberUpdatedState(onPresentation)
val view=remember(pack) { ContinuousAvatarView(activity,pack) { latest(it) } }
val currentMode by rememberUpdatedState(mode)
val currentTurn by rememberUpdatedState(turn)
val currentEpoch by rememberUpdatedState(audioEpoch)
SideEffect { view.render(mode,activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED),turn,audioEpoch) }
DisposableEffect(view) {
val observer=LifecycleEventObserver { _,event ->
if(event==Lifecycle.Event.ON_PAUSE) view.render(AvatarMode.IDLE,false,null,null)
if(event==Lifecycle.Event.ON_RESUME) view.render(currentMode,true,currentTurn,currentEpoch)
}
activity.lifecycle.addObserver(observer)
onDispose { activity.lifecycle.removeObserver(observer);view.dispose() }
}
AndroidView(factory={view},modifier=modifier)
}
@@ -0,0 +1,179 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import android.media.MediaCodec
import android.media.MediaExtractor
import android.media.MediaFormat
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.Surface
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.abs
/** Native silent video-only decoder. Each released output must be latched by TextureView
* with its codec PTS before another output is submitted. No decoder callback is a safe cut.
* CFR and zero-origin timestamps are checked; unsupported surfaces fail to the standing still. */
class CodecAnchorVideoPort(private val context: Context, private val surface: Surface,
private val pathRoot: String, decoderLooper: Looper, private val onSize: (Int,Int) -> Unit) : AnchorVideoPort {
private val main = Handler(Looper.getMainLooper())
private val worker = Handler(decoderLooper)
private val closed = AtomicBoolean(false)
private var listener: AnchorVideoPort.Listener? = null
private lateinit var clip: SafeAvatarClip
private lateinit var entry: AnchorInterval
private var extractor: MediaExtractor? = null
private var codec: MediaCodec? = null
private var inputEnded = false
private var loop = 0L
private var first = true
private var lastFrame = -1
private var held = false
private var heldAt = 0L
private var advanceRequestedAt = 0L
@Volatile private var advancing = false
private var lastPtsUs = 0L
private var decodeStartedAt = 0L
private var serial = 0L
private var latched: DisplayedVideoFrame? = null
@Volatile private var submitted: DisplayedVideoFrame? = null
@Volatile private var expectedTimestampNs = -1L
private val watchdog = Runnable { fail(VideoFailure.PREPARE_TIMEOUT) }
private val frameTimeout = Runnable { fail(VideoFailure.FRAME_TIMEOUT) }
private var releasedSurface = false
override fun prepare(clip: SafeAvatarClip, entry: AnchorInterval, listener: AnchorVideoPort.Listener) {
this.clip = clip; this.entry = entry; this.listener = listener
main.postDelayed(watchdog,5_000)
worker.post {
guard {
val ex = MediaExtractor(); extractor = ex
context.assets.openFd(pathRoot + clip.path).use { ex.setDataSource(it.fileDescriptor,it.startOffset,it.length) }
val tracks = (0 until ex.trackCount).filter { ex.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("video/") == true }
check(tracks.size == 1)
val format = ex.getTrackFormat(tracks.single()); ex.selectTrack(tracks.single())
check(ex.sampleTime == 0L)
val width = format.getInteger(MediaFormat.KEY_WIDTH); val height = format.getInteger(MediaFormat.KEY_HEIGHT)
check(width in 1..4096 && height in 1..4096)
main.post { if (!closed.get()) onSize(width,height) }
val decoder = MediaCodec.createDecoderByType(checkNotNull(format.getString(MediaFormat.KEY_MIME)))
codec = decoder; decoder.configure(format,surface,null,0); decoder.start()
ex.seekTo(entry.startMs*1000,MediaExtractor.SEEK_TO_PREVIOUS_SYNC)
decodeStartedAt = SystemClock.elapsedRealtime()
pump()
}
}
}
/** Called on main from onSurfaceTextureUpdated. Exact PTS association is required.
* The output remains paused until the driver explicitly advances the held frame. */
fun textureLatched(timestampNs: Long) {
if (closed.get()) return
val frame = submitted ?: return
if (abs(timestampNs - expectedTimestampNs) > 1_000L) {
fail(VideoFailure.TIMESTAMP); return
}
submitted = null; latched = frame; advancing = false
main.removeCallbacks(watchdog); main.removeCallbacks(frameTimeout)
worker.post { heldAt = SystemClock.elapsedRealtime() }
listener?.frame(frame)
}
// An old texture cannot be resampled as fresh while a newer output is in flight.
override fun displayed(): DisplayedVideoFrame? = if (closed.get() || advancing) null else latched
override fun advance() {
if (closed.get() || advancing) return
advancing = true
val requestedAt = SystemClock.elapsedRealtime()
worker.post {
guard {
if (!held || submitted != null) { advancing = false; return@guard }
held = false
advanceRequestedAt = requestedAt
decodeStartedAt = SystemClock.elapsedRealtime()
if (lastFrame == clip.frameCount - 1) {
if (!clip.mayLoop) { main.post { if (!closed.get()) { advancing = false; listener?.ended() } }; return@guard }
// An explicit codec/extractor wrap, gated by approved seam. Never infer
// it from a wall timer or silently loop an unreviewed speaking crop.
checkNotNull(codec).flush()
checkNotNull(extractor).seekTo(0,MediaExtractor.SEEK_TO_PREVIOUS_SYNC)
loop++; inputEnded = false; lastFrame = -1
}
pump()
}
}
}
private fun pump() {
if (closed.get() || held || submitted != null) return
if (SystemClock.elapsedRealtime() - decodeStartedAt > 3_000) { fail(VideoFailure.FRAME_TIMEOUT); return }
val decoder = checkNotNull(codec); val ex = checkNotNull(extractor)
// Nonblocking dequeue; one bounded input/output iteration before yielding the worker.
if (!inputEnded) {
val input = decoder.dequeueInputBuffer(0)
if (input >= 0) {
val buffer = checkNotNull(decoder.getInputBuffer(input)); buffer.clear()
val size = ex.readSampleData(buffer,0)
if (size < 0) {
inputEnded = true; decoder.queueInputBuffer(input,0,0,0,MediaCodec.BUFFER_FLAG_END_OF_STREAM)
} else {
decoder.queueInputBuffer(input,0,size,ex.sampleTime,0); ex.advance()
}
}
}
val info = MediaCodec.BufferInfo()
val output = decoder.dequeueOutputBuffer(info,0)
if (output >= 0) {
if (info.size == 0 && info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
decoder.releaseOutputBuffer(output,false)
fail(VideoFailure.FORMAT) // early EOS: the manifest's final frame never appeared
return
}
val ptsUs = info.presentationTimeUs
val frame = ((ptsUs * clip.fpsNumerator + 500_000L * clip.fpsDenominator) / (1_000_000L * clip.fpsDenominator)).toInt()
val framePtsUs = frame.toLong() * 1_000_000L * clip.fpsDenominator / clip.fpsNumerator
if (frame !in 0 until clip.frameCount || abs(framePtsUs-ptsUs) > 2_000) {
decoder.releaseOutputBuffer(output,false); fail(VideoFailure.FORMAT); return
}
val position = ptsUs / 1000
if (first && (position < entry.startMs || frame < entry.startFrame)) {
decoder.releaseOutputBuffer(output,false)
} else {
if (first && !entry.contains(position,frame)) {
decoder.releaseOutputBuffer(output,false); fail(VideoFailure.ENTRY_MISSED); return
}
if (!first && frame != lastFrame+1) {
decoder.releaseOutputBuffer(output,false); fail(VideoFailure.FORMAT); return
}
val delay = if (first) 0L else if (frame == 0) 1000L*clip.fpsDenominator/clip.fpsNumerator
else ((ptsUs-lastPtsUs)/1000).coerceAtLeast(0)
val renderAfter = if (first) 0 else (maxOf(heldAt,advanceRequestedAt)+delay-SystemClock.elapsedRealtime()).coerceAtLeast(0)
held = true; first = false; lastFrame = frame; lastPtsUs = ptsUs
worker.postDelayed({ guard {
expectedTimestampNs = ptsUs*1000
submitted = DisplayedVideoFrame(position,frame,loop,++serial)
main.post { if (!closed.get()) main.postDelayed(frameTimeout,2_000) }
decoder.releaseOutputBuffer(output,true)
} },renderAfter)
return
}
}
worker.postDelayed({ guard { pump() } },2)
}
private inline fun guard(action: () -> Unit) {
if (closed.get()) return
try { action() } catch (_: Exception) { fail(VideoFailure.DECODE) }
}
private fun fail(reason: VideoFailure) {
main.post { if (!closed.get()) { listener?.failed(reason); close() } }
}
override fun close() {
if (!closed.compareAndSet(false,true)) return
main.removeCallbacks(watchdog); main.removeCallbacks(frameTimeout)
latched = null; submitted = null
worker.removeCallbacksAndMessages(null)
worker.post {
try { codec?.stop() } catch (_: Exception) { }
try { codec?.release() } catch (_: Exception) { }
try { extractor?.release() } catch (_: Exception) { }
if (!releasedSurface) { releasedSurface = true; surface.release() }
}
}
}
@@ -0,0 +1,75 @@
package com.gorios.lanvoice.avatar
data class RegisteredMouthPatch(val frameIndex: Int,val ptsUs: Long,val path: String,val sha256: String,
val x: Float,val y: Float,val width: Int,val height: Int)
data class ContinuousBodyAsset(val path: String,val sha256: String,val width: Int,val height: Int,
val frameCount: Int,val durationUs: Long)
data class ContinuousAvatarPack(val body: ContinuousBodyAsset,val patches: List<RegisteredMouthPatch>,
val curves: Map<String,MouthCurve>,val root: String,val manifestSha: String)
/** This parser admits only coordinator-selected debug runtime data; no production graph. */
object ContinuousAvatarManifest {
@Suppress("UNCHECKED_CAST")
fun read(root: Map<String,Any?>,sha: String,expectedSha: String,debug: Boolean,pathRoot: String): ContinuousAvatarPack? {
if(!debug || !expectedSha.matches(Regex("[0-9a-f]{64}")) || sha!=expectedSha) return null
return try {
fun obj(v: Any?)=v as Map<String,Any?>
fun integer(v: Any?): Long { val n=v as Number; val l=n.toLong(); require(n.toDouble()==l.toDouble()); return l }
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}"))) }
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" && root["packId"]=="a01-neutral-graph-v1-runtime-03")
require(root["publishApproval"]==false && root["runtimeReady"]==true)
val b=obj(root["body"])
val body=ContinuousBodyAsset(b["path"] as String,hash(b["sha256"]),smallInt(b["width"]),smallInt(b["height"]),
smallInt(b["frameCount"]),integer(b["durationUs"]))
require(body.path.matches(Regex("body/[a-zA-Z0-9_.-]+\\.mp4")))
require(body.width==480 && body.height==848 && body.frameCount==97 && kotlin.math.abs(body.durationUs-4_041_667)<=2)
require(integer(b["fpsNumerator"])==24L && integer(b["fpsDenominator"])==1L && b["hasAudio"]==false)
require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L)
val patchFormat=obj(root["patchFormat"])
require(patchFormat["alphaEncoding"]=="straight_unassociated" && patchFormat["format"]=="PNG RGBA 8bit")
val rows=root["patches"] as List<Map<String,Any?>>; require(rows.size==97)
val patches=rows.mapIndexed { index,p ->
val patch=RegisteredMouthPatch(smallInt(p["frameIndex"]),integer(p["ptsUs"]),p["path"] as String,hash(p["sha256"]),
finite(p["x"]),finite(p["y"]),smallInt(p["width"]),smallInt(p["height"]))
require(patch.frameIndex==index && kotlin.math.abs(patch.ptsUs-index*1_000_000L/24)<=2)
require(patch.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png")))
require(patch.width in 1..128 && patch.height in 1..128 && patch.x>=0 && patch.y>=0 &&
patch.x+patch.width<=480 && patch.y+patch.height<=848)
patch
}
require(patches.map { it.path }.distinct().size==97 && patches.sumOf { it.width*it.height*4L }<=8_000_000)
val states=root["mouthStates"] as List<Map<String,Any?>>
require(states.size==5)
val c=states.associateBy { it["id"] as String }
require(c.keys==setOf("idle","opening","talk1","talk2","end-talk"))
val curves=c.mapValues { (id,v) ->
val row=obj(v); val duration=integer(row["durationMs"])
val alpha=(row["globalAlphaByFrame"] as List<*>).map(::finite)
val bridge=id in setOf("opening","end-talk")
require(duration==if(bridge) 250L else 500L)
require(alpha.size==if(bridge) 6 else 12)
require(integer(row["frameCount"])==alpha.size.toLong() && integer(row["fpsNumerator"])==24L && integer(row["fpsDenominator"])==1L)
require(alpha.all { it in 0f..1f })
require(row["entryMouthAnchor"]==if(id in setOf("idle","opening")) "A" else "B")
require(row["exitMouthAnchor"]==if(id in setOf("idle","end-talk")) "A" else "B")
when(id) {
"idle" -> require(alpha.all { it==0f })
"opening" -> require(alpha.first()==0f && alpha.last()==1f)
"end-talk" -> require(alpha.first()==1f && alpha.last()==0f)
else -> require(alpha.first()==1f && alpha.last()==1f && alpha.min()<.5f)
}
MouthCurve(id,duration,alpha)
}
val routing=obj(root["stateRouting"])
val required=mapOf("idle" to setOf("idle","opening"),"opening" to setOf("talk1","talk2","end-talk"),
"talk1" to setOf("talk1","talk2","end-talk"),"talk2" to setOf("talk1","talk2","end-talk"),"end-talk" to setOf("idle"))
require(routing.keys==required.keys)
required.forEach { (id,targets) ->
val list=routing[id] as List<*>;require(list.size==targets.size && list.toSet()==targets)
}
ContinuousAvatarPack(body,patches,curves,pathRoot,sha)
} catch(_: Exception) { null }
}
}
@@ -0,0 +1,77 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.SurfaceTexture
import android.view.Surface
import android.view.TextureView
import android.widget.FrameLayout
import android.widget.ImageView
import com.gorios.lanvoice.diag.DiagnosticLog
/** A single composited TextureView. The image remains visible until first successful
* EGL swap, and immediately returns on background/error; no decoder touches audio. */
class ContinuousAvatarView(context: Context,private val pack: AvatarPack?,private val report: (VideoPresentation)->Unit): FrameLayout(context) {
private val texture=TextureView(context).apply { isOpaque=false;alpha=0f }
private val still=ImageView(context).apply { scaleType=ImageView.ScaleType.FIT_CENTER }
private var renderer: ContinuousBodyRenderer?=null
private var foreground=false
private var failed=false
private var epoch=0L
private var generation=0L
private var revision=0L
private var turn: Long?=null
private var audioEpoch: Long?=null
private var desired=false
private var lastLog=-10_000L
private var firstFrameMs: Long?=null
init {
addView(still,LayoutParams(-1,-1));addView(texture,LayoutParams(-1,-1))
try { still.setImageBitmap(pack?.let { context.assets.open(it.fallback).use(BitmapFactory::decodeStream) }) } catch(_: Exception) { }
texture.surfaceTextureListener=object: TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(s: SurfaceTexture,w: Int,h: Int) { start() }
override fun onSurfaceTextureSizeChanged(s: SurfaceTexture,w: Int,h: Int) { renderer?.resize(w,h) }
override fun onSurfaceTextureUpdated(s: SurfaceTexture) { }
override fun onSurfaceTextureDestroyed(s: SurfaceTexture): Boolean { stop();return true }
}
}
fun render(mode: AvatarMode,active: Boolean,turnId: Long?,playbackGeneration: Long?) {
val next=mode==AvatarMode.TALK
val changed=next!=desired || turnId!=turn || playbackGeneration!=audioEpoch
if(turnId!=turn || playbackGeneration!=audioEpoch) { generation++;revision=0 }
desired=next;turn=turnId;audioEpoch=playbackGeneration
if(foreground!=active) {
foreground=active
if(!active) stop() else { failed=false;generation++;revision=0 }
}
start()
if(changed) renderer?.intent(desired,generation,++revision)
}
private fun start() {
if(!foreground || failed || renderer!=null || !texture.isAvailable) return
val runtime=pack?.continuous ?: run { report(VideoPresentation(reason=pack?.motionStatus ?: "pack_missing"));return }
val fence=++epoch;firstFrameMs=null
renderer=ContinuousBodyRenderer(context,runtime,Surface(checkNotNull(texture.surfaceTexture)),texture.width,texture.height,
presented={frame,elapsed ->
if(foreground && fence==epoch) {
texture.alpha=1f;still.alpha=0f
if(firstFrameMs==null) firstFrameMs=elapsed
val p=VideoPresentation(actual=frame.mouth.phase,reason="natural_candidate_atomic_layer",
waitMs=frame.mouth.phaseWaitMs,firstFrameMs=firstFrameMs,clipId="body_f${frame.key.index}_loop${frame.key.loopOrdinal}")
report(p)
val now=android.os.SystemClock.elapsedRealtime()
if(now-lastLog>=1_000) {
lastLog=now
DiagnosticLog.record("avatar_layer","phase=${frame.mouth.phase} frame=${frame.key.index} loop=${frame.key.loopOrdinal} pts_us=${frame.key.ptsUs} generation=${frame.mouth.generation} phase_wait_ms=${frame.mouth.phaseWaitMs.coerceAtMost(60000)} first_ms=$firstFrameMs perceived_lag=unknown")
}
}
},failure={reason -> if(fence==epoch) { failed=true;stop();report(VideoPresentation(reason=reason)) } })
renderer?.intent(desired,generation,++revision)
}
private fun stop() {
epoch++;renderer?.close();renderer=null
texture.alpha=0f;still.alpha=1f;report(VideoPresentation(reason="background_or_surface_release"))
}
fun dispose() { foreground=false;stop() }
override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() }
}
@@ -0,0 +1,240 @@
package com.gorios.lanvoice.avatar
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.SurfaceTexture
import android.media.MediaCodec
import android.media.MediaExtractor
import android.media.MediaFormat
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.opengl.EGLSurface
import android.opengl.GLES11Ext
import android.opengl.GLES20
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.SystemClock
import android.view.Surface
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicBoolean
/** One decoder, one EGL window/pass. Continuous body and the selected registered
* patch are drawn together; no TextureView/Compose overlay races, no runtime SSD.
* Only small patch bitmaps are cached at startup. Audio never waits on this worker. */
class ContinuousBodyRenderer(private val context: Context,private val pack: ContinuousAvatarPack,
private val output: Surface,private var width: Int,private var height: Int,
private val presented: (ComposedBodyFrame,Long)->Unit,private val failure: (String)->Unit) {
private val alive=AtomicBoolean(true)
private val thread=HandlerThread("avatar-body-gl").apply { start() }
private val worker=Handler(thread.looper)
private val main=Handler(Looper.getMainLooper())
private val gate=ContinuousFramePresenter(pack)
private var display: EGLDisplay=EGL14.EGL_NO_DISPLAY
private var eglContext: EGLContext=EGL14.EGL_NO_CONTEXT
private var window: EGLSurface=EGL14.EGL_NO_SURFACE
private var inputTexture: SurfaceTexture?=null
private var inputSurface: Surface?=null
private var extractor: MediaExtractor?=null
private var codec: MediaCodec?=null
private var inputEnded=false
private var waiting=false
private var lastIndex=-1
private var lastPresentedMs=0L
private var first=true
private var program=0
private var bodyTexture=0
private val patchTextures=IntArray(pack.patches.size)
private val textureMatrix=FloatArray(16)
private val positions=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer()
private val uv=ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
put(floatArrayOf(0f,0f,1f,0f,0f,1f,1f,1f));position(0)
}
private var aPosition=0; private var aUv=0; private var uTextureMatrix=0
private var uBody=0; private var uPatch=0; private var uRect=0; private var uAlpha=0
private var startedMs=SystemClock.elapsedRealtime()
private var progressMs=startedMs
private val timeout=Runnable { fail("frame_timeout") }
init { worker.post { guarded { initialize(); pump() } } }
fun intent(talk: Boolean,generation: Long,revision: Long) { worker.post { if(alive.get()) gate.intent(talk,generation,revision,SystemClock.elapsedRealtime()) } }
fun resize(w: Int,h: Int) { worker.post { if(alive.get()) { width=w; height=h } } }
private fun initialize() {
display=EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);check(display!=EGL14.EGL_NO_DISPLAY)
val version=IntArray(2);check(EGL14.eglInitialize(display,version,0,version,1))
val configs=arrayOfNulls<EGLConfig>(1);val count=IntArray(1)
check(EGL14.eglChooseConfig(display,intArrayOf(EGL14.EGL_RENDERABLE_TYPE,EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_SURFACE_TYPE,EGL14.EGL_WINDOW_BIT,EGL14.EGL_RED_SIZE,8,EGL14.EGL_GREEN_SIZE,8,
EGL14.EGL_BLUE_SIZE,8,EGL14.EGL_ALPHA_SIZE,8,EGL14.EGL_NONE),0,configs,0,1,count,0) && count[0]>0)
eglContext=EGL14.eglCreateContext(display,configs[0],EGL14.EGL_NO_CONTEXT,intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION,2,EGL14.EGL_NONE),0)
check(eglContext!=EGL14.EGL_NO_CONTEXT)
window=EGL14.eglCreateWindowSurface(display,configs[0],output,intArrayOf(EGL14.EGL_NONE),0)
check(window!=EGL14.EGL_NO_SURFACE && EGL14.eglMakeCurrent(display,window,window,eglContext))
program=createProgram()
aPosition=GLES20.glGetAttribLocation(program,"aPosition");aUv=GLES20.glGetAttribLocation(program,"aUv")
uTextureMatrix=GLES20.glGetUniformLocation(program,"uTextureMatrix")
uBody=GLES20.glGetUniformLocation(program,"uBody");uPatch=GLES20.glGetUniformLocation(program,"uPatch")
uRect=GLES20.glGetUniformLocation(program,"uRect");uAlpha=GLES20.glGetUniformLocation(program,"uAlpha")
check(listOf(aPosition,aUv,uTextureMatrix,uBody,uPatch,uRect,uAlpha).all { it>=0 })
val texture=IntArray(1);GLES20.glGenTextures(1,texture,0);bodyTexture=texture[0]
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture)
configureTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES)
GLES20.glGenTextures(patchTextures.size,patchTextures,0)
pack.patches.forEachIndexed { index,p ->
val bitmap=context.assets.open(pack.root+p.path).use { BitmapFactory.decodeStream(it) } ?: error("patch_decode")
try {
check(bitmap.width==p.width && bitmap.height==p.height)
val pixels=IntArray(p.width*p.height);bitmap.getPixels(pixels,0,p.width,0,0,p.width,p.height)
// getPixels returns straight ARGB even when Bitmap stores premultiplied
// pixels. Explicit byte upload prevents multiplying mask twice.
val rgba=ByteBuffer.allocateDirect(pixels.size*4)
pixels.forEach { c -> rgba.put((c ushr 16).toByte());rgba.put((c ushr 8).toByte());rgba.put(c.toByte());rgba.put((c ushr 24).toByte()) }
rgba.position(0);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[index]);configureTexture(GLES20.GL_TEXTURE_2D)
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D,0,GLES20.GL_RGBA,p.width,p.height,0,GLES20.GL_RGBA,GLES20.GL_UNSIGNED_BYTE,rgba)
} finally { bitmap.recycle() }
}
check(GLES20.glGetError()==GLES20.GL_NO_ERROR)
inputTexture=SurfaceTexture(bodyTexture).also {
it.setDefaultBufferSize(pack.body.width,pack.body.height)
it.setOnFrameAvailableListener({ consumeFrame() },worker)
}
inputSurface=Surface(checkNotNull(inputTexture))
val ex=MediaExtractor();extractor=ex
context.assets.openFd(pack.root+pack.body.path).use { ex.setDataSource(it.fileDescriptor,it.startOffset,it.length) }
check(ex.trackCount==1)
val format=ex.getTrackFormat(0);check(format.getString(MediaFormat.KEY_MIME)=="video/avc")
check(format.getInteger(MediaFormat.KEY_WIDTH)==480 && format.getInteger(MediaFormat.KEY_HEIGHT)==848)
ex.selectTrack(0);check(ex.sampleTime==0L)
codec=MediaCodec.createDecoderByType("video/avc").also { it.configure(format,checkNotNull(inputSurface),null,0);it.start() }
progressMs=SystemClock.elapsedRealtime()
}
private fun configureTexture(target: Int) {
GLES20.glTexParameteri(target,GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_LINEAR)
GLES20.glTexParameteri(target,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR)
GLES20.glTexParameteri(target,GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexParameteri(target,GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE)
}
private fun createProgram(): Int {
fun shader(type: Int,source: String): Int {
val id=GLES20.glCreateShader(type);GLES20.glShaderSource(id,source);GLES20.glCompileShader(id)
val status=IntArray(1);GLES20.glGetShaderiv(id,GLES20.GL_COMPILE_STATUS,status,0)
if(status[0]!=GLES20.GL_TRUE) { GLES20.glDeleteShader(id);error("shader_compile") }
return id
}
val vertex=shader(GLES20.GL_VERTEX_SHADER,"""
attribute vec2 aPosition; attribute vec2 aUv;
uniform mat4 uTextureMatrix; varying vec2 vBody; varying vec2 vLogical;
void main() { gl_Position=vec4(aPosition,0.0,1.0); vLogical=aUv;
vBody=(uTextureMatrix*vec4(aUv,0.0,1.0)).xy; }
""")
val fragment=shader(GLES20.GL_FRAGMENT_SHADER,"""
#extension GL_OES_EGL_image_external : require
precision highp float;
uniform samplerExternalOES uBody; uniform sampler2D uPatch;
uniform vec4 uRect; uniform float uAlpha;
varying vec2 vBody; varying vec2 vLogical;
void main() {
vec4 body=texture2D(uBody,vBody);
vec2 pixel=vec2(vLogical.x*480.0,(1.0-vLogical.y)*848.0);
vec2 local=(pixel-uRect.xy)/uRect.zw;
if(uAlpha<=0.0 || local.x<0.0 || local.y<0.0 || local.x>=1.0 || local.y>=1.0) {
gl_FragColor=vec4(body.rgb,1.0);
} else {
vec4 patch=texture2D(uPatch,local);
float mask=uAlpha*patch.a;
gl_FragColor=vec4(mix(body.rgb,patch.rgb,mask),1.0);
}
}
""")
val result=GLES20.glCreateProgram();GLES20.glAttachShader(result,vertex);GLES20.glAttachShader(result,fragment)
GLES20.glLinkProgram(result);GLES20.glDeleteShader(vertex);GLES20.glDeleteShader(fragment)
val status=IntArray(1);GLES20.glGetProgramiv(result,GLES20.GL_LINK_STATUS,status,0)
check(status[0]==GLES20.GL_TRUE);return result
}
private fun pump(): Unit = guarded {
if(waiting) return@guarded
check(SystemClock.elapsedRealtime()-progressMs<=3_000)
val decoder=checkNotNull(codec);val ex=checkNotNull(extractor)
if(!inputEnded) {
val input=decoder.dequeueInputBuffer(0)
if(input>=0) {
val buffer=checkNotNull(decoder.getInputBuffer(input));buffer.clear();val size=ex.readSampleData(buffer,0)
if(size<0) { inputEnded=true;decoder.queueInputBuffer(input,0,0,0,MediaCodec.BUFFER_FLAG_END_OF_STREAM) }
else { decoder.queueInputBuffer(input,0,size,ex.sampleTime,0);ex.advance() }
}
}
val info=MediaCodec.BufferInfo();val outputIndex=decoder.dequeueOutputBuffer(info,0)
if(outputIndex>=0) {
check(!(info.size==0 && info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM!=0)) { "early_eos" }
val key=gate.decoded(info.presentationTimeUs)
waiting=true;lastIndex=key.index
val step=if(key.index==0) 41L else key.index*1000L/24-(key.index-1)*1000L/24
val delay=if(first) 0L else (lastPresentedMs+step-SystemClock.elapsedRealtime()).coerceAtLeast(0)
worker.postDelayed({ guarded {
worker.postDelayed(timeout,2_000)
decoder.releaseOutputBuffer(outputIndex,true)
} },delay)
} else worker.postDelayed({ pump() },2)
}
private fun consumeFrame(): Unit = guarded {
check(waiting)
val texture=checkNotNull(inputTexture);texture.updateTexImage();texture.getTransformMatrix(textureMatrix)
val now=SystemClock.elapsedRealtime()
val result=checkNotNull(gate.present(texture.timestamp,now) { draw(it) })
worker.removeCallbacks(timeout);waiting=false;first=false;lastPresentedMs=SystemClock.elapsedRealtime();progressMs=lastPresentedMs
main.post { if(alive.get()) presented(result,(lastPresentedMs-startedMs).coerceAtLeast(0)) }
if(lastIndex==pack.body.frameCount-1) {
gate.wrap();checkNotNull(codec).flush();checkNotNull(extractor).seekTo(0,MediaExtractor.SEEK_TO_PREVIOUS_SYNC)
inputEnded=false
}
worker.post { pump() }
}
private fun draw(frame: ComposedBodyFrame) {
check(width>0 && height>0)
GLES20.glViewport(0,0,width,height);GLES20.glClearColor(1f,1f,1f,1f);GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
val rect=bodyFit(width,height)
val left=rect.left/width*2-1;val right=(rect.left+rect.width)/width*2-1
val top=1-rect.top/height*2;val bottom=1-(rect.top+rect.height)/height*2
positions.clear();positions.put(floatArrayOf(left,bottom,right,bottom,left,top,right,top));positions.position(0);uv.position(0)
GLES20.glUseProgram(program)
GLES20.glVertexAttribPointer(aPosition,2,GLES20.GL_FLOAT,false,0,positions);GLES20.glEnableVertexAttribArray(aPosition)
GLES20.glVertexAttribPointer(aUv,2,GLES20.GL_FLOAT,false,0,uv);GLES20.glEnableVertexAttribArray(aUv)
GLES20.glUniformMatrix4fv(uTextureMatrix,1,false,textureMatrix,0)
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture);GLES20.glUniform1i(uBody,0)
GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[frame.key.index]);GLES20.glUniform1i(uPatch,1)
val p=frame.patch;GLES20.glUniform4f(uRect,p.x,p.y,p.width.toFloat(),p.height.toFloat());GLES20.glUniform1f(uAlpha,frame.mouth.alpha)
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4)
check(GLES20.glGetError()==GLES20.GL_NO_ERROR && EGL14.eglSwapBuffers(display,window))
}
private inline fun guarded(action: ()->Unit) {
if(!alive.get()) return
try { action() } catch(_: Exception) { fail("decoder_or_gl") }
}
private fun fail(reason: String) {
if(!alive.get()) return
main.post { failure("natural_$reason") }
close()
}
fun close() {
if(!alive.compareAndSet(true,false)) return
worker.removeCallbacksAndMessages(null)
worker.post {
gate.close()
try { codec?.stop() } catch(_: Exception) { }
try { codec?.release() } catch(_: Exception) { }
try { extractor?.release() } catch(_: Exception) { }
try { inputSurface?.release();inputTexture?.release() } catch(_: Exception) { }
if(display!=EGL14.EGL_NO_DISPLAY) {
try { GLES20.glDeleteTextures(patchTextures.size,patchTextures,0);GLES20.glDeleteTextures(1,intArrayOf(bodyTexture),0);GLES20.glDeleteProgram(program) } catch(_: Exception) { }
EGL14.eglMakeCurrent(display,EGL14.EGL_NO_SURFACE,EGL14.EGL_NO_SURFACE,EGL14.EGL_NO_CONTEXT)
if(window!=EGL14.EGL_NO_SURFACE) EGL14.eglDestroySurface(display,window)
if(eglContext!=EGL14.EGL_NO_CONTEXT) EGL14.eglDestroyContext(display,eglContext)
EGL14.eglTerminate(display);EGL14.eglReleaseThread()
}
output.release();thread.quitSafely()
}
}
}
@@ -0,0 +1,21 @@
package com.gorios.lanvoice.avatar
data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPatch,val mouth: MouthLayerSample)
/** The real EGL renderer uses this gate immediately around updateTexImage + draw/swap.
* No other thread can choose a patch or change body phase. close() fences stale output. */
class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
private val clock=ContinuousFrameClock(pack.body.frameCount)
private val mouth=ContinuousMouth(pack.curves,choose)
private var active=true
fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && mouth.request(talk,generation,revision,nowMs)
fun decoded(ptsUs: Long): BodyFrameKey { check(active); return clock.decoded(ptsUs) }
fun present(timestampNs: Long,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? {
if(!active) return null
val key=clock.latched(timestampNs)
val frame=ComposedBodyFrame(key,pack.patches[key.index],mouth.sample(nowMs))
drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented.
return frame
}
fun wrap() { check(active); clock.wrap() }
fun close() { active=false }
}
@@ -0,0 +1,98 @@
package com.gorios.lanvoice.avatar
data class MouthCurve(val id: String, val durationMs: Long, val alpha: List<Float>)
data class MouthLayerSample(val phase: String, val alpha: Float, val generation: Long, val revision: Long,
val phaseWaitMs: Long=0)
/** Body-independent authored phase controller. No perceived-mouth SLA is inferred. */
class ContinuousMouth(private val curves: Map<String,MouthCurve>, private val choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
private var desired = false
private var generation = -1L
private var revision = -1L
private var phase = "idle"
private var startedAt = 0L
private var lastTime = 0L
private var initialized = false
private var previousTalk: String? = null
private var requestedAt: Long? = null
fun request(talk: Boolean, generation: Long, revision: Long,nowMs: Long?=null): Boolean {
if (generation < this.generation || generation == this.generation && revision <= this.revision) return false
this.generation=generation; this.revision=revision; desired=talk
requestedAt=nowMs ?: if(initialized) lastTime else null
return true
}
fun sample(nowMs: Long): MouthLayerSample {
require(nowMs >= lastTime)
lastTime=nowMs
if (!initialized) { startedAt=nowMs; initialized=true }
if(requestedAt==null) requestedAt=nowMs
if (phase=="idle" && desired) { phase="opening"; startedAt=nowMs }
var count=0
while (phase!="idle" && nowMs-startedAt >= curves.getValue(phase).durationMs) {
check(++count<=64) { "Mouth clock gap" }
startedAt+=curves.getValue(phase).durationMs
phase=when (phase) {
"opening" -> if (desired) nextTalk() else "end-talk"
"talk1","talk2" -> if (desired) nextTalk() else "end-talk"
"end-talk" -> "idle"
else -> error("Invalid phase")
}
}
if (phase=="idle" && desired) { phase="opening";startedAt=nowMs }
val satisfied=if(desired) phase in setOf("talk1","talk2") else phase=="idle"
val wait=if(satisfied) 0 else (nowMs-checkNotNull(requestedAt)).coerceAtLeast(0)
if (phase=="idle") return MouthLayerSample(phase,0f,generation,revision,wait)
val c=curves.getValue(phase)
// Authored endpoints are at (n-1)/24. Hold their value only for the last
// natural display interval; do not manufacture a body freeze or reverse.
val index=((nowMs-startedAt)*24.0/1000).coerceIn(0.0,(c.alpha.size-1).toDouble())
val lower=index.toInt(); val upper=minOf(lower+1,c.alpha.lastIndex)
val alpha=c.alpha[lower]+(c.alpha[upper]-c.alpha[lower])*(index-lower).toFloat()
return MouthLayerSample(phase,alpha,generation,revision,wait)
}
private fun nextTalk(): String {
val options=listOf("talk1","talk2").filter { it!=previousTalk }
val id=options[choose(options.size).coerceIn(0,options.lastIndex)]
previousTalk=id; return id
}
}
data class BodyFrameKey(val index: Int, val loopOrdinal: Long, val ptsUs: Long)
/** Decoder order and SurfaceTexture consumption are separately checked. */
class ContinuousFrameClock(private val frames: Int=97) {
private var expected=0
private var loop=0L
private var pending: BodyFrameKey?=null
fun decoded(ptsUs: Long): BodyFrameKey {
check(pending==null)
val index=((ptsUs*24+500_000)/1_000_000).toInt()
check(index==expected && kotlin.math.abs(ptsUs-index*1_000_000L/24)<=2_000)
return BodyFrameKey(index,loop,ptsUs).also { pending=it }
}
fun latched(timestampNs: Long): BodyFrameKey {
val key=checkNotNull(pending)
check(kotlin.math.abs(timestampNs-key.ptsUs*1000)<=1_000)
pending=null; expected++
return key
}
fun wrap() {
check(pending==null && expected==frames)
expected=0; loop++
}
}
data class BodyFitRect(val left: Float,val top: Float,val width: Float,val height: Float)
fun bodyFit(viewW: Int,viewH: Int,mediaW: Int=480,mediaH: Int=848): BodyFitRect {
require(viewW>0 && viewH>0 && mediaW>0 && mediaH>0)
val scale=minOf(viewW.toFloat()/mediaW,viewH.toFloat()/mediaH)
val w=mediaW*scale; val h=mediaH*scale
return BodyFitRect((viewW-w)/2,(viewH-h)/2,w,h)
}
fun patchUv(x: Float,y: Float,patch: RegisteredMouthPatch): Pair<Float,Float>? {
if(x<patch.x || y<patch.y || x>=patch.x+patch.width || y>=patch.y+patch.height) return null
return (x-patch.x)/patch.width to (y-patch.y)/patch.height
}
fun composeMouthChannel(body: Float,patch: Float,mask: Float,global: Float): Float {
val a=mask*global
return body*(1-a)+patch*a
}
@@ -0,0 +1,74 @@
package com.gorios.lanvoice.avatar
/** Coordinator-authorized decoder experiment, NOT production/perceptual approval.
* The unchanged pinned manifest supplies frame endpoints/edges. No interior windows
* or perceived mouth events are synthesized. Asset bytes are verified by AvatarPack.
*/
object EngineeringGraphAdmission {
const val MANIFEST_SHA = "e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09"
@Suppress("UNCHECKED_CAST")
fun read(root: Map<String, Any?>, hash: String, debugAuthorized: Boolean): SafeAvatarGraph? {
if (!debugAuthorized || hash != MANIFEST_SHA) return null
return try {
fun map(value: Any?) = value as Map<String, Any?>
fun number(value: Any?): Long {
val n = value as Number
val v = n.toLong()
require(n.toDouble() == v.toDouble())
return v
}
require(root["packId"] == "a01-neutral-graph-v1-controlled-01" && root["identityId"] == "a01")
require(root["publishApproval"] == false && root["naturalQualityStatus"] == "not_approved")
val safety = map(root["safeTransitions"])
require(safety["reviewStatus"] == "pending" && (safety["transitions"] as List<*>).isEmpty())
val candidate = map(root["candidateGraph"])
require(candidate["exitPolicy"] == "complete_candidate_node_at_shared_rendered_anchor")
val exits = map(candidate["earliestExitFrames"])
val review = AnchorReview.TECHNICAL_DEBUG
val anchors = mapOf("A" to VisualAnchor("A",true,review), "B" to VisualAnchor("B",false,review))
val rows = root["assets"] as List<Map<String,Any?>>
require(rows.size == 5 && rows.map { it["id"] }.toSet() == setOf("idle","opening","talk1","talk2","end-talk"))
val clips = rows.associate { row ->
val id = row["id"] as String
require(row["hasAudio"] == false && row["width"] == 480 && row["height"] == 848)
require(row["path"] == "controlled-01/delivery/$id.mp4")
val frames = number(row["frameCount"]).toInt()
val duration = number(row["durationMs"])
require(number(row["fpsNumerator"]) == 24L && number(row["fpsDenominator"]) == 1L)
val bridge = id in setOf("opening","end-talk")
require(frames == if (bridge) 6 else 12)
require(duration == if (bridge) 250L else 500L)
require(number(exits[id]) == (frames-1).toLong())
val entryAnchor = if (id in setOf("idle","opening")) "A" else "B"
val exitAnchor = if (id in setOf("idle","end-talk")) "A" else "B"
require(row["entryAnchor"] == entryAnchor && row["exitAnchor"] == exitAnchor)
val role = when (id) { "idle" -> SafeClipRole.IDLE; "opening" -> SafeClipRole.OPENING;
"end-talk" -> SafeClipRole.CLOSING; else -> SafeClipRole.TALK }
// Integer intervals contain the actual CFR timestamp, only frame 0 /
// the declared final frame. Never extend an expired/EOS exit window.
id to SafeAvatarClip(id,"delivery/$id.mp4",role,duration,frames,24,1,
listOf(AnchorInterval("in",entryAnchor,0,42,0,1,review)),
listOf(AnchorInterval("out",exitAnchor,(frames-1)*1000L/24,duration,frames-1,frames,review)),
review,loop=!bridge,loopSeamReview=if (!bridge) review else AnchorReview.UNKNOWN,
seekReview=review, mouthStateWindows=emptyList())
}
val pairs = (candidate["edges"] as List<Map<String,Any?>>).map {
val source = it["source"] as String; val target = it["target"] as String
require(source in clips && target in clips)
require(it["anchor"] == clips.getValue(source).safeExitWindows.single().anchorId &&
it["anchor"] == clips.getValue(target).entryAnchors.single().anchorId)
source to target
}
require(pairs.size == 12 && pairs.distinct().size == 12)
require(setOf("idle","talk1","talk2").all { (it to it) in pairs })
val edges = pairs.filter { it.first != it.second }.map { (source,target) ->
SafeAvatarEdge("${source}_$target",source,"out",target,"in",review,
if (clips.getValue(source).mayLoop) MissedWindowPolicy.NEXT_REVIEWED_LOOP else MissedWindowPolicy.HOLD,
latestWaitMs=1_000)
}
SafeAvatarGraph(clips,anchors,edges,"idle","in",review).also {
require(NeutralGraphContract.missing(it).isEmpty())
}
} catch (_: Exception) { null }
}
}
@@ -0,0 +1,51 @@
package com.gorios.lanvoice.avatar
/** Product graph completeness is distinct from syntactic validity and individual edge approval. */
object NeutralGraphContract {
fun missing(graph: SafeAvatarGraph): List<String> {
val clips = graph.clips.values
val idle = clips.singleOrNull { it.role == SafeClipRole.IDLE }
val opening = clips.singleOrNull { it.role == SafeClipRole.OPENING }
val closing = clips.singleOrNull { it.role == SafeClipRole.CLOSING }
val talks = clips.filter { it.role == SafeClipRole.TALK }
if (clips.size != 5 || idle == null || opening == null || closing == null || talks.size != 2)
return listOf("five_neutral_nodes_required")
val missing = mutableListOf<String>()
if (graph.initialClip != idle.id) missing += "initial_idle"
if (opening.loop || closing.loop) missing += "bridges_must_not_loop"
for (clip in listOf(idle) + talks) if (!clip.mayLoop) missing += "loop_${clip.id}"
for (clip in clips) {
if (!graph.accepts(clip.review) || !graph.accepts(clip.seekReview)) missing += "review_${clip.id}"
}
val requiredPairs = mutableSetOf<Pair<String,String>>()
fun edge(from: SafeAvatarClip, to: SafeAvatarClip) {
requiredPairs += from.id to to.id
if (graph.edges.none { it.source == from.id && it.target == to.id && graph.approved(it) })
missing += "edge_${from.id}_${to.id}"
}
edge(idle,opening); edge(closing,idle)
talks.forEach { edge(opening,it); edge(it,closing) }
edge(talks[0],talks[1]); edge(talks[1],talks[0])
val optionalReversal = opening.id to closing.id
if (graph.edges.any { graph.approved(it) && (it.source to it.target) !in requiredPairs &&
(it.source to it.target) != optionalReversal })
missing += "unsupported_graph_shortcut"
val a = idle.entryAnchors.single { it.id == graph.initialEntry }.anchorId
val b = talks.flatMap { it.entryAnchors }.filter { graph.accepts(it.review) }.map { it.anchorId }.distinct().singleOrNull()
if (!graph.anchors.getValue(a).closedMouth || b == null || graph.anchors.getValue(b).closedMouth || a == b)
missing += "closed_A_small_open_B_required"
if (b != null) for (clip in clips) {
val expectedEntry = if (clip.role in setOf(SafeClipRole.IDLE,SafeClipRole.OPENING)) a else b
val expectedExit = if (clip.role in setOf(SafeClipRole.IDLE,SafeClipRole.CLOSING)) a else b
if (clip.entryAnchors.any { graph.accepts(it.review) && it.anchorId != expectedEntry } ||
clip.safeExitWindows.any { graph.accepts(it.review) && it.anchorId != expectedExit })
missing += "node_anchor_${clip.id}"
}
if (!graph.accepts(graph.review)) missing += "graph_review"
for (talk in talks) if (graph.review != AnchorReview.TECHNICAL_DEBUG && talk.mouthStateWindows.none { graph.accepts(it.review) && it.state == ReviewedMouthState.ACTIVE })
missing += "mouth_activity_evidence_${talk.id}"
if (graph.review != AnchorReview.TECHNICAL_DEBUG && idle.mouthStateWindows.none { graph.accepts(it.review) && it.state == ReviewedMouthState.CLOSED_STABLE })
missing += "closed_stable_evidence"
return missing
}
}
@@ -0,0 +1,25 @@
package com.gorios.lanvoice.avatar
/** Synthetic mouth intents only; never opens a socket, AudioRecord or camera. */
object OfflineAvatarTrace {
const val EXTRA = "avatar_offline_preview"
data class Intent(val mode: AvatarMode, val turn: Long, val generation: Long, val label: String)
fun at(elapsedMs: Long): Intent {
val time = elapsedMs.coerceAtLeast(0) % 20_000
val cycle = elapsedMs.coerceAtLeast(0) / 20_000
val epoch = cycle * 2 + if (time >= 12_500) 2 else 1
val mode = if (time in 1_200..4_999 || time in 7_000..7_099 || time in 9_000..12_499 || time in 15_000..17_999)
AvatarMode.TALK else AvatarMode.IDLE
val label = when {
time < 1_200 -> "idle"
time < 5_000 -> "talk / legal variants"
time < 7_000 -> "stop → idle"
time < 9_000 -> "100ms intent reversal"
time < 12_500 -> "resume talk"
time < 15_000 -> "abort / new generation closing"
time < 18_000 -> "new turn talk"
else -> "drained → idle"
}
return Intent(mode,cycle*2+if(time>=15_000) 2 else 1,epoch,label)
}
}
@@ -0,0 +1,109 @@
package com.gorios.lanvoice.avatar
enum class AnchorReview { UNKNOWN, PENDING, APPROVED, REJECTED, TECHNICAL_DEBUG }
enum class SafeClipRole { IDLE, OPENING, TALK, CLOSING, WAITING }
enum class MissedWindowPolicy { NEXT_REVIEWED_LOOP, HOLD }
enum class ReviewedMouthState { ACTIVE, CLOSED_STABLE }
/** Reviewed observations, independent of the clip's name/role or playback visibility. */
data class MouthStateWindow(val state: ReviewedMouthState, val startMs: Long, val endMs: Long,
val startFrame: Int, val endFrame: Int, val review: AnchorReview) {
fun contains(positionMs: Long, frame: Int) = review == AnchorReview.APPROVED &&
positionMs >= startMs && positionMs < endMs && frame >= startFrame && frame < endFrame
}
/** IDs describe pre-authored material, never pose estimated from a user's camera. */
data class VisualAnchor(val id: String, val closedMouth: Boolean, val review: AnchorReview)
data class AnchorInterval(val id: String, val anchorId: String,
val startMs: Long, val endMs: Long, val startFrame: Int, val endFrame: Int,
val review: AnchorReview) {
fun contains(positionMs: Long, frame: Int) = positionMs >= startMs && positionMs < endMs &&
frame >= startFrame && frame < endFrame
}
data class SafeAvatarClip(val id: String, val path: String, val role: SafeClipRole,
val durationMs: Long, val frameCount: Int, val fpsNumerator: Int, val fpsDenominator: Int,
val entryAnchors: List<AnchorInterval>, val safeExitWindows: List<AnchorInterval>,
val review: AnchorReview, val loop: Boolean = false,
val loopSeamReview: AnchorReview = AnchorReview.UNKNOWN,
val seekReview: AnchorReview = AnchorReview.UNKNOWN,
val mouthStateWindows: List<MouthStateWindow> = emptyList()) {
fun frameAt(positionMs: Long): Int = (positionMs * fpsNumerator / (1000L * fpsDenominator)).toInt()
val mayLoop: Boolean get() = loop && review in setOf(AnchorReview.APPROVED, AnchorReview.TECHNICAL_DEBUG) && loopSeamReview == review
}
data class SafeAvatarEdge(val id: String, val source: String, val sourceWindow: String,
val target: String, val targetEntry: String, val review: AnchorReview,
val missedWindowPolicy: MissedWindowPolicy = MissedWindowPolicy.NEXT_REVIEWED_LOOP,
val earliestWaitMs: Long = 0, val latestWaitMs: Long? = null)
/** latestWaitMs is a diagnostic budget; exceeding it NEVER grants a cut. */
data class SafeAvatarGraph(val clips: Map<String, SafeAvatarClip>, val anchors: Map<String, VisualAnchor>,
val edges: List<SafeAvatarEdge>, val initialClip: String, val initialEntry: String,
val review: AnchorReview) {
init {
require(clips.size in 1..32 && anchors.size in 1..64 && edges.size <= 128)
require(clips.values.all { it.id in clips && clips[it.id] === it })
require(initialClip in clips && clips.getValue(initialClip).entryAnchors.any { it.id == initialEntry })
require(edges.map { it.id }.distinct().size == edges.size)
fun validId(id: String) = id.matches(Regex("[a-zA-Z0-9_-]{1,64}"))
require(anchors.values.all { validId(it.id) && anchors[it.id] === it })
for (clip in clips.values) {
require(validId(clip.id) && clip.path.matches(Regex("(?:videos|frames|delivery)/[a-zA-Z0-9_.-]+\\.(?:mp4|png)")))
require(clip.durationMs in 1..60_000 && clip.frameCount in 1..3600 &&
clip.fpsNumerator in 1..120_000 && clip.fpsDenominator in 1..10_000)
require(clip.frameAt(clip.durationMs - 1) < clip.frameCount)
val timebase = 1000L * clip.fpsDenominator
val expectedFrames = (clip.durationMs * clip.fpsNumerator + timebase - 1) / timebase
require(kotlin.math.abs(expectedFrames - clip.frameCount) <= 1)
require(clip.entryAnchors.isNotEmpty() && clip.entryAnchors.size <= 32 && clip.safeExitWindows.size <= 32)
require(clip.mouthStateWindows.size <= 64)
for (window in clip.mouthStateWindows) {
require(window.startMs >= 0 && window.startMs < window.endMs && window.endMs <= clip.durationMs)
require(window.startFrame >= 0 && window.startFrame < window.endFrame && window.endFrame <= clip.frameCount)
require(kotlin.math.abs(clip.frameAt(window.startMs) - window.startFrame) <= 1)
require(kotlin.math.abs(clip.frameAt(window.endMs-1) - (window.endFrame-1)) <= 1)
}
require((clip.entryAnchors + clip.safeExitWindows).map { it.id }.distinct().size == clip.entryAnchors.size + clip.safeExitWindows.size)
for (interval in clip.entryAnchors + clip.safeExitWindows) {
require(validId(interval.id) && interval.anchorId in anchors)
require(interval.startMs >= 0 && interval.startMs < interval.endMs && interval.endMs <= clip.durationMs)
require(interval.startFrame >= 0 && interval.startFrame < interval.endFrame && interval.endFrame <= clip.frameCount)
// Reject inconsistent time/index annotation. Tolerance is only frame rounding.
require(kotlin.math.abs(clip.frameAt(interval.startMs) - interval.startFrame) <= 1)
require(kotlin.math.abs(clip.frameAt(interval.endMs - 1) - (interval.endFrame - 1)) <= 1)
}
}
for (edge in edges) {
require(validId(edge.id) && edge.source != edge.target && edge.source in clips && edge.target in clips)
require(edge.earliestWaitMs in 0..60_000 && (edge.latestWaitMs == null || edge.latestWaitMs in edge.earliestWaitMs..60_000))
val exit = clips.getValue(edge.source).safeExitWindows.single { it.id == edge.sourceWindow }
val entry = clips.getValue(edge.target).entryAnchors.single { it.id == edge.targetEntry }
require(exit.anchorId == entry.anchorId) { "Unmatched entry/exit anchor" }
}
}
fun exit(edge: SafeAvatarEdge) = clips.getValue(edge.source).safeExitWindows.single { it.id == edge.sourceWindow }
fun entry(edge: SafeAvatarEdge) = clips.getValue(edge.target).entryAnchors.single { it.id == edge.targetEntry }
// Technical authorization is a separate, exact-hash debug scope. Pending reviews
// are never playable and technical evidence cannot satisfy a production graph.
fun accepts(value: AnchorReview) = review in setOf(AnchorReview.APPROVED, AnchorReview.TECHNICAL_DEBUG) && value == review
fun approved(edge: SafeAvatarEdge): Boolean {
val from = clips.getValue(edge.source); val to = clips.getValue(edge.target)
val exit = exit(edge); val entry = entry(edge)
return listOf(edge.review, from.review, to.review, exit.review, entry.review,
anchors.getValue(exit.anchorId).review, to.seekReview).all(::accepts)
}
/** Small bounded BFS: closing/opening are actual bridge nodes, not invented crossfades. */
fun nextEdge(source: String, desired: SafeClipRole): SafeAvatarEdge? {
val todo = java.util.ArrayDeque<Pair<String, SafeAvatarEdge?>>()
val visited = mutableSetOf(source)
todo.add(source to null)
while (todo.isNotEmpty()) {
val (id, first) = todo.removeFirst()
if (clips.getValue(id).role == desired) return first
for (edge in edges.filter { it.source == id && approved(it) }) {
if (visited.add(edge.target)) todo.add(edge.target to (first ?: edge))
}
}
return null
}
}
@@ -0,0 +1,89 @@
package com.gorios.lanvoice.avatar
enum class SafetyManifestStatus { LEGACY_UNANNOTATED, INVALID, REVIEW_PENDING, HASH_NOT_APPROVED, APPROVED }
data class SafetyManifestResult(val status: SafetyManifestStatus, val graph: SafeAvatarGraph? = null)
/** Optional schemaVersion1 extension. Metadata alone cannot self-approve a real pack:
* activation additionally requires the coordinator-approved manifest SHA in an explicit allowlist. */
object SafeAvatarManifest {
fun read(root: Map<String, Any?>, manifestSha256: String,
approvedManifestHashes: Set<String> = emptySet()): SafetyManifestResult {
if (!root.containsKey("safeTransitions")) return SafetyManifestResult(SafetyManifestStatus.LEGACY_UNANNOTATED)
return try {
require(integer(root["schemaVersion"]) == 1L)
val assets = objects(root["assets"],32).associate { row ->
text(row,"id") to text(row,"path")
}
require(assets.size == objects(root["assets"],32).size)
val extension = obj(root["safeTransitions"])
require(integer(extension["version"]) == 1L)
// Pending authors may intentionally leave all anchor times unknown. Do not
// demand fabricated intervals, and never expose a runnable partial graph.
if (review(extension,"reviewStatus") != AnchorReview.APPROVED)
return SafetyManifestResult(SafetyManifestStatus.REVIEW_PENDING)
val anchors = objects(extension["anchors"],64).map { row ->
VisualAnchor(text(row,"id"), boolean(row,"closedMouth"), review(row,"reviewStatus"))
}
require(anchors.map { it.id }.distinct().size == anchors.size)
val clips = objects(extension["clips"],32).map { row ->
val id = text(row,"assetId")
val role = when (val name = text(row,"role")) {
"end-talk", "idle-start" -> SafeClipRole.CLOSING
else -> SafeClipRole.valueOf(name.uppercase())
}
SafeAvatarClip(id,checkNotNull(assets[id]),role,
number(row,"durationMs"),int(row,"frameCount"),int(row,"fpsNumerator"),int(row,"fpsDenominator"),
intervals(row["entryAnchors"]),intervals(row["safeExitWindows"]),review(row,"reviewStatus"),
boolean(row,"loop"),review(row,"loopSeamReviewStatus"),review(row,"seekReviewStatus"),
row["mouthStateWindows"]?.let { value -> objects(value,64).map { window ->
MouthStateWindow(ReviewedMouthState.valueOf(text(window,"state").uppercase()),
number(window,"startMs"),number(window,"endMs"),int(window,"startFrame"),
int(window,"endFrame"),review(window,"reviewStatus"))
} } ?: emptyList())
}
require(clips.map { it.id }.distinct().size == clips.size)
val edges = objects(extension["transitions"],128).map { row ->
// Opening/closing bridge assets are explicit clip nodes with their own reviewed edges.
// Refuse an opaque bridge shortcut; every junction needs a source window/entry pair.
require(row["bridgeAssetId"] == null)
require(text(row,"earliestPolicy") == "next_safe_window")
val missed = when (text(row,"latestPolicy")) {
"next_reviewed_loop" -> MissedWindowPolicy.NEXT_REVIEWED_LOOP
"hold" -> MissedWindowPolicy.HOLD
else -> error("Invalid late policy")
}
SafeAvatarEdge(text(row,"id"),text(row,"sourceAssetId"),text(row,"sourceWindowId"),
text(row,"targetAssetId"),text(row,"targetEntryId"),review(row,"reviewStatus"),missed,
number(row,"earliestWaitMs"),row["latestWaitMs"]?.let(::integer))
}
val graph = SafeAvatarGraph(clips.associateBy { it.id },anchors.associateBy { it.id },edges,
text(extension,"initialAssetId"),text(extension,"initialEntryId"),review(extension,"reviewStatus"))
when {
graph.review != AnchorReview.APPROVED -> SafetyManifestResult(SafetyManifestStatus.REVIEW_PENDING)
!manifestSha256.matches(Regex("[a-f0-9]{64}")) || manifestSha256 !in approvedManifestHashes -> SafetyManifestResult(SafetyManifestStatus.HASH_NOT_APPROVED)
else -> SafetyManifestResult(SafetyManifestStatus.APPROVED,graph)
}
} catch (_: Exception) { SafetyManifestResult(SafetyManifestStatus.INVALID) }
}
private fun intervals(value: Any?) = objects(value,32).map { row ->
AnchorInterval(text(row,"id"),text(row,"anchorId"),number(row,"startMs"),number(row,"endMs"),
int(row,"startFrame"),int(row,"endFrame"),review(row,"reviewStatus"))
}
private fun review(row: Map<String,Any?>, name: String): AnchorReview =
when (row[name]) { null,"unknown" -> AnchorReview.UNKNOWN; "pending" -> AnchorReview.PENDING
"approved" -> AnchorReview.APPROVED; "rejected" -> AnchorReview.REJECTED; else -> error("Invalid review") }
private fun text(row: Map<String,Any?>, name: String): String = (row[name] as? String)?.also { require(it.length in 1..128) } ?: error("Missing text")
private fun boolean(row: Map<String,Any?>, name: String): Boolean = row[name] as? Boolean ?: error("Missing bool")
private fun integer(value: Any?): Long = when (value) { is Int -> value.toLong(); is Long -> value; else -> error("Not an integer") }
private fun number(row: Map<String,Any?>, name: String) = integer(row[name])
private fun int(row: Map<String,Any?>, name: String): Int = number(row,name).also { require(it in Int.MIN_VALUE..Int.MAX_VALUE) }.toInt()
private fun obj(value: Any?): Map<String,Any?> {
require(value is Map<*,*> && value.keys.all { it is String })
@Suppress("UNCHECKED_CAST") return value as Map<String,Any?>
}
private fun objects(value: Any?, maximum: Int): List<Map<String,Any?>> {
require(value is List<*> && value.size <= maximum)
return value.map(::obj)
}
}
@@ -0,0 +1,278 @@
package com.gorios.lanvoice.avatar
enum class VisualIntentReason { PCM, ABORT, DRAINED, DISCONNECT, HANGUP, FOREGROUND }
data class MouthIntent(val generation: Long, val revision: Long, val turnId: Long?,
val desired: SafeClipRole, val reason: VisualIntentReason = VisualIntentReason.PCM)
/** Both PTS and texture frame must come from the renderer, not a predicted wall-clock timer. */
data class ClipObservation(val clipId: String, val positionMs: Long, val frame: Int,
val loop: Long, val serial: Long, val sampledAtMs: Long, val ended: Boolean = false,
val continuous: Boolean = true)
data class StageTicket(val id: Long, val rendererEpoch: Long, val generation: Long,
val revision: Long, val edgeId: String, val target: String, val entryId: String)
data class StagedFrame(val ticket: StageTicket, val positionMs: Long, val frame: Int,
val paused: Boolean, val seekComplete: Boolean, val textureReady: Boolean)
data class CutTicket(val stage: StageTicket, val sourceSerial: Long, val sourceLoop: Long,
val expiresAtMs: Long)
enum class TransitionReason { STEADY, STAGING, TARGET_NOT_READY, ANCHOR_WAIT, WINDOW_MISSED,
NO_REVIEWED_EDGE, CANCELED, OLD_INTENT, OLD_CALLBACK, STALE_POSITION, LATE_CUT,
WAIT_BUDGET_EXCEEDED, SWITCHED, LOOP_UNREVIEWED, BACKGROUND, RESUME_REQUIRED }
sealed interface TransitionAction {
data class Stage(val ticket: StageTicket, val entry: AnchorInterval) : TransitionAction
data class Cancel(val ticket: StageTicket) : TransitionAction
data class OfferCut(val ticket: CutTicket) : TransitionAction
data class Reveal(val target: String, val ticket: StageTicket) : TransitionAction
data class Hold(val reason: TransitionReason) : TransitionAction
data object Release : TransitionAction
}
data class TransitionSnapshot(val desired: SafeClipRole, val actualClip: String,
val actualRole: SafeClipRole, val generation: Long, val revision: Long,
val reason: TransitionReason, val visualWaitMs: Long, val closedMouthLagMs: Long?,
val exitPending: Boolean, val switches: Int, val cancellations: Int,
val mouthActiveLagMs: Long? = null)
/** No audio dependency. A fresh second source sample is required to commit every cut.
* Safety has no timeout bypass: missed windows wait or hold, never perform a late hard cut. */
class SafeTransitionPlanner(private val graph: SafeAvatarGraph, initialClip: String,
private val positionFreshMs: Long = 40,
private val chooseVariant: (Int) -> Int = { kotlin.random.Random.nextInt(it) }) {
init { require(initialClip in graph.clips && positionFreshMs in 1..100) }
private var actual = initialClip
private var intent = MouthIntent(0, 0, null, graph.clips.getValue(initialClip).role, VisualIntentReason.FOREGROUND)
private var enabled = true
private var rendererEpoch = 0L
private var nextTicket = 0L
private var staged: StageTicket? = null
private var ready: StagedFrame? = null
private var offered: CutTicket? = null
private var edgeLoop: Long? = null
private var lastSerial = -1L
private var lastLoop = -1L
private var lastPosition = -1L
private var requestedAt = 0L
private var closingSince: Long? = null
private var lastClosingLag: Long? = null
private var lastActiveLag: Long? = null
private var intentSatisfied = true
private var reason = TransitionReason.STEADY
private var switches = 0
private var cancellations = 0
private var resumeStage: StageTicket? = null
fun request(next: MouthIntent, nowMs: Long): List<TransitionAction> {
require(next.generation >= 0 && next.revision >= 0 && nowMs >= 0)
require(next.desired in setOf(SafeClipRole.IDLE, SafeClipRole.TALK, SafeClipRole.WAITING))
require(next.reason !in setOf(VisualIntentReason.ABORT, VisualIntentReason.DRAINED, VisualIntentReason.DISCONNECT) || next.desired == SafeClipRole.IDLE)
require(next.reason != VisualIntentReason.HANGUP || next.desired == SafeClipRole.WAITING)
if (next.generation < intent.generation || next.generation == intent.generation &&
(next.revision <= intent.revision || next.turnId != intent.turnId &&
(next.reason == VisualIntentReason.PCM || next.turnId != null))) {
return hold(TransitionReason.OLD_INTENT)
}
val cancel = staged?.let { TransitionAction.Cancel(it) }
if (cancel != null) cancellations = (cancellations + 1).coerceAtMost(1_000_000)
staged = null; ready = null; offered = null; edgeLoop = null
intent = next; requestedAt = nowMs
intentSatisfied = false
if (next.desired == SafeClipRole.TALK) lastActiveLag = null else lastClosingLag = null
closingSince = if (next.desired != SafeClipRole.TALK) nowMs else null
reason = if (cancel != null) TransitionReason.CANCELED else TransitionReason.ANCHOR_WAIT
return listOfNotNull(cancel) // Changing an intent never changes a visible clip.
}
/** Prepare/seek must hold the target PAUSED at an approved entry and await a latched texture.
* MEDIA_INFO_VIDEO_RENDERING_START alone is insufficient. */
fun targetReady(frame: StagedFrame): Boolean {
val ticket = staged
if (!enabled || ticket == null || frame.ticket != ticket || ticket.rendererEpoch != rendererEpoch) {
reason = TransitionReason.OLD_CALLBACK; return false
}
val edge = graph.edges.single { it.id == ticket.edgeId }
val entry = graph.entry(edge)
if (!frame.paused || !frame.seekComplete || !frame.textureReady || !entry.contains(frame.positionMs, frame.frame)) {
ready = null; reason = TransitionReason.TARGET_NOT_READY; return false
}
ready = frame; return true
}
private fun fresh(observation: ClipObservation, nowMs: Long): Boolean {
if (!observation.continuous || observation.clipId != actual || observation.serial <= lastSerial ||
observation.positionMs < 0 || observation.positionMs >= graph.clips.getValue(actual).durationMs ||
observation.frame !in 0 until graph.clips.getValue(actual).frameCount ||
kotlin.math.abs(graph.clips.getValue(actual).frameAt(observation.positionMs) - observation.frame) > 1 ||
observation.sampledAtMs > nowMs || nowMs - observation.sampledAtMs > positionFreshMs ||
observation.loop < lastLoop || (observation.loop == lastLoop && observation.positionMs < lastPosition)) return false
lastSerial = observation.serial; lastLoop = observation.loop; lastPosition = observation.positionMs
return true
}
/** Staging needs no fresh source position: it changes only the hidden decoder.
* In particular an abort can prepare closing while the next source frame is in flight. */
fun prepareNext(): List<TransitionAction> {
if (!enabled) return hold(TransitionReason.BACKGROUND)
if (staged != null) return emptyList()
val edge = nextEdge() ?: return emptyList()
return stageEdge(edge,lastLoop.takeIf { it >= 0 })
}
private fun stageEdge(edge: SafeAvatarEdge, loop: Long?): List<TransitionAction> {
val ticket = StageTicket(++nextTicket, rendererEpoch, intent.generation, intent.revision, edge.id, edge.target, edge.targetEntry)
staged = ticket; ready = null; offered = null; edgeLoop = loop
reason = TransitionReason.STAGING
return listOf(TransitionAction.Stage(ticket,graph.entry(edge)))
}
fun tick(observation: ClipObservation, nowMs: Long): List<TransitionAction> {
if (!enabled) return hold(TransitionReason.BACKGROUND)
if (!fresh(observation, nowMs)) return hold(TransitionReason.STALE_POSITION)
val current = graph.clips.getValue(actual)
observeMouth(observation.positionMs,observation.frame,nowMs)
if (observation.loop > 0 && !current.mayLoop) {
return hold(TransitionReason.LOOP_UNREVIEWED)
}
// EOS means the final frame's playback interval has elapsed. Keeping that
// image visible is an exceptional hold, never a way to extend an exit window.
if (observation.ended) return hold(TransitionReason.WINDOW_MISSED)
// Select once when a segment starts, then preroll exactly that target. A stop
// cancels it and stages closing; random selection never changes an offered edge.
val edge = staged?.let { ticket -> graph.edges.single { it.id == ticket.edgeId } } ?: nextEdge()
if (edge == null) return hold(if (observation.ended && !current.mayLoop) TransitionReason.LOOP_UNREVIEWED
else if (current.role == intent.desired && current.mayLoop) TransitionReason.STEADY else TransitionReason.NO_REVIEWED_EDGE)
if (staged?.edgeId != edge.id) {
return stageEdge(edge,observation.loop)
}
if (edgeLoop == null) edgeLoop = observation.loop
if (edge.missedWindowPolicy == MissedWindowPolicy.HOLD && observation.loop != edgeLoop) {
return hold(TransitionReason.WINDOW_MISSED)
}
if (nowMs - requestedAt < edge.earliestWaitMs) return hold(TransitionReason.ANCHOR_WAIT)
if (ready == null) return hold(TransitionReason.TARGET_NOT_READY)
val exit = graph.exit(edge)
if (!exit.contains(observation.positionMs, observation.frame)) {
return hold(if (edge.latestWaitMs?.let { nowMs - requestedAt > it } == true) TransitionReason.WAIT_BUDGET_EXCEEDED
else if (observation.positionMs >= exit.endMs) TransitionReason.WINDOW_MISSED else TransitionReason.ANCHOR_WAIT)
}
val deadline = observation.sampledAtMs + minOf(positionFreshMs, exit.endMs - observation.positionMs)
val ticket = CutTicket(checkNotNull(staged), observation.serial, observation.loop, deadline)
offered = ticket; reason = TransitionReason.ANCHOR_WAIT
return listOf(TransitionAction.OfferCut(ticket))
}
/** Called immediately before revealing; the adapter must not reveal after a rejected commit. */
fun commit(ticket: CutTicket, sourceNow: ClipObservation, targetNow: StagedFrame, nowMs: Long): List<TransitionAction> {
if (!enabled || offered != ticket || staged != ticket.stage ||
ticket.stage.generation != intent.generation || ticket.stage.revision != intent.revision ||
ticket.stage.rendererEpoch != rendererEpoch) return hold(TransitionReason.OLD_CALLBACK)
if (nowMs >= ticket.expiresAtMs || sourceNow.ended || sourceNow.loop != ticket.sourceLoop ||
sourceNow.serial <= ticket.sourceSerial || !fresh(sourceNow, nowMs)) {
offered = null; return hold(TransitionReason.LATE_CUT)
}
val edge = graph.edges.single { it.id == ticket.stage.edgeId }
if (!graph.approved(edge) || !graph.exit(edge).contains(sourceNow.positionMs, sourceNow.frame) || !targetReady(targetNow)) {
offered = null; return hold(TransitionReason.LATE_CUT)
}
actual = edge.target; switches = (switches + 1).coerceAtMost(1_000_000)
observeMouth(targetNow.positionMs,targetNow.frame,nowMs)
staged = null; ready = null; offered = null; edgeLoop = null
lastSerial = -1; lastLoop = -1; lastPosition = -1
reason = TransitionReason.SWITCHED
return listOf(TransitionAction.Reveal(actual, ticket.stage))
}
private fun nextEdge(): SafeAvatarEdge? {
val current = graph.clips.getValue(actual)
if (intent.desired == SafeClipRole.TALK && current.role in setOf(SafeClipRole.TALK,SafeClipRole.OPENING)) {
val variants = graph.edges.filter { it.source == actual && graph.approved(it) &&
graph.clips.getValue(it.target).role == SafeClipRole.TALK }
// Self loops use the codec's separately reviewed seam. If another legal
// talk exists prefer it, so two variants don't immediately repeat.
if (variants.isNotEmpty()) return variants[chooseVariant(variants.size).also { require(it in variants.indices) }]
}
return graph.nextEdge(actual,intent.desired)
}
private fun observeMouth(positionMs: Long, frame: Int, nowMs: Long) {
if (intentSatisfied) return
val state = if (intent.desired == SafeClipRole.TALK) ReviewedMouthState.ACTIVE else ReviewedMouthState.CLOSED_STABLE
if (graph.clips.getValue(actual).mouthStateWindows.any { it.state == state && it.contains(positionMs,frame) }) {
intentSatisfied = true
if (state == ReviewedMouthState.ACTIVE) lastActiveLag = (nowMs-requestedAt).coerceAtLeast(0)
else { lastClosingLag = (nowMs-requestedAt).coerceAtLeast(0); closingSince = null }
}
}
fun background(): List<TransitionAction> {
enabled = false; rendererEpoch++
val cancel = staged?.let { TransitionAction.Cancel(it) }
staged = null; ready = null; offered = null
resumeStage = null
reason = TransitionReason.BACKGROUND
return listOfNotNull(cancel, TransitionAction.Release)
}
fun stageForeground(generation: Long): TransitionAction.Stage? {
if (enabled || generation <= intent.generation || !graph.accepts(graph.review)) return null
val clip = graph.clips.getValue(graph.initialClip)
val entry = clip.entryAnchors.single { it.id == graph.initialEntry }
if (clip.role != SafeClipRole.IDLE || !graph.accepts(clip.review) || !graph.accepts(clip.seekReview) ||
!graph.accepts(entry.review) || !graph.accepts(graph.anchors.getValue(entry.anchorId).review)) return null
val ticket = StageTicket(++nextTicket,rendererEpoch,generation,0,"startup",clip.id,entry.id)
resumeStage = ticket
return TransitionAction.Stage(ticket,entry)
}
/** New foreground is a new renderer epoch; initial entry must be verified before this call.
* The caller cannot resume an old talk or old stage, and must assign a new visual generation. */
fun foreground(generation: Long, preparedInitialClip: String, preparedEntry: AnchorInterval,
frame: StagedFrame, nowMs: Long): Boolean {
if (enabled || generation <= intent.generation || preparedInitialClip != graph.initialClip ||
frame.ticket != resumeStage || frame.ticket.rendererEpoch != rendererEpoch || frame.ticket.generation != generation ||
preparedEntry != graph.clips.getValue(graph.initialClip).entryAnchors.single { it.id == graph.initialEntry } ||
!graph.accepts(graph.review) ||
graph.clips.getValue(preparedInitialClip).role != SafeClipRole.IDLE ||
!graph.accepts(preparedEntry.review) ||
!graph.accepts(graph.anchors.getValue(preparedEntry.anchorId).review) ||
!frame.paused || !frame.seekComplete || !frame.textureReady ||
!preparedEntry.contains(frame.positionMs, frame.frame)) {
reason = TransitionReason.RESUME_REQUIRED; return false
}
rendererEpoch++; actual = preparedInitialClip; enabled = true
resumeStage = null
intent = MouthIntent(generation,0,null,SafeClipRole.IDLE,VisualIntentReason.FOREGROUND)
requestedAt = nowMs; lastSerial = -1; lastLoop = -1; lastPosition = -1
closingSince = null; intentSatisfied = true; reason = TransitionReason.STEADY
return true
}
fun snapshot(nowMs: Long) = TransitionSnapshot(intent.desired, actual, graph.clips.getValue(actual).role,
intent.generation, intent.revision, reason,
if (intentSatisfied) 0 else (nowMs - requestedAt).coerceAtLeast(0),
lastClosingLag,
intent.desired == SafeClipRole.WAITING && graph.clips.getValue(actual).role != SafeClipRole.WAITING, switches, cancellations,lastActiveLag)
private fun hold(value: TransitionReason): List<TransitionAction> { reason = value; return listOf(TransitionAction.Hold(value)) }
}
/** Wraps are inferred from successive actual MediaPlayer positions, never a duration timer.
* A caller must treat discontinuities/seeks as a new cursor epoch; missed whole loops stay unknown. */
class ActualClipCursor {
private var previous: Long? = null
private var loop = 0L
private var serial = 0L
private var previousTime: Long? = null
private var continuous = true
fun observe(clip: SafeAvatarClip, positionMs: Long, displayedFrame: Int, nowMs: Long, ended: Boolean = false): ClipObservation {
require(positionMs in 0 until clip.durationMs)
require(displayedFrame in 0 until clip.frameCount)
previousTime?.let { if (nowMs <= it || nowMs - it >= clip.durationMs) continuous = false }
previous?.let {
if (positionMs < it) {
val seamBand = (2000L * clip.fpsDenominator / clip.fpsNumerator).coerceAtLeast(1)
if (it >= clip.durationMs - seamBand && positionMs <= seamBand) loop++ else continuous = false
}
}
previous = positionMs
previousTime = nowMs
return ClipObservation(clip.id,positionMs,displayedFrame,loop,++serial,nowMs,ended,continuous)
}
fun reset() { previous = null; previousTime = null; continuous = true; loop = 0; serial = 0 }
}
@@ -0,0 +1,182 @@
package com.gorios.lanvoice.avatar
/** One decoder output at a time. A port is held after each displayed frame until advance().
* Hidden targets decode/preroll to an entry and remain held; they never free-run. */
interface AnchorVideoPort {
fun prepare(clip: SafeAvatarClip, entry: AnchorInterval, listener: Listener)
fun advance()
fun displayed(): DisplayedVideoFrame?
fun close()
interface Listener {
fun frame(frame: DisplayedVideoFrame)
fun ended()
fun failed(reason: VideoFailure)
}
}
enum class VideoFailure { DECODE, SURFACE, TIMESTAMP, ENTRY_MISSED, PREPARE_TIMEOUT, FRAME_TIMEOUT, FORMAT }
data class DisplayedVideoFrame(val positionMs: Long, val frame: Int, val loop: Long, val textureSerial: Long)
data class VideoPresentation(val actual: String = "static", val reason: String = "review_pending",
val waitMs: Long = 0, val closingLagMs: Long? = null, val firstFrameMs: Long? = null,
val mouthActiveLagMs: Long? = null, val clipId: String = "static")
/** Main-thread real renderer coordinator, independently testable with frame/decoder doubles.
* No audio dependency and no timer that grants a cut. Two ports max, one held output each. */
class SafeVideoDriver(private val graph: SafeAvatarGraph, private val createPort: (Int) -> AnchorVideoPort,
private val reveal: (Int) -> Unit, private val showStatic: () -> Unit,
private val now: () -> Long, private val report: (VideoPresentation) -> Unit,
chooseVariant: (Int) -> Int = { kotlin.random.Random.nextInt(it) }) {
private val planner = SafeTransitionPlanner(graph, graph.initialClip,chooseVariant=chooseVariant)
private var epoch = 0L
private var generation = 0L
private var revision = 0L
private var intentTurn: Long? = null
private var desired = SafeClipRole.IDLE
private var running = false
private var activeSlot: Int? = null
private val ports = arrayOfNulls<AnchorVideoPort>(2)
private var pending: TransitionAction.Stage? = null
private var pendingSlot: Int? = null
private var pendingReady: StagedFrame? = null
private var sourceEnded = false
private var serial = 0L
private var firstFrameMs: Long? = null
private var startedAt = 0L
private var failureReason: String? = null
init { planner.background() }
fun start() {
if (running) return
running = true; epoch++; generation++; revision = 0
failureReason = null
startedAt = now(); firstFrameMs = null; sourceEnded = false
val stage = planner.stageForeground(generation) ?: run { fail("startup_unreviewed"); return }
stage(stage, 0)
}
/** Caller supplies the latest already-fenced VoiceSession state, never raw network events. */
fun desire(mode: SafeClipRole, turn: Long?, newAudioEpoch: Boolean = false) {
require(mode == SafeClipRole.IDLE || mode == SafeClipRole.TALK)
if (mode == desired && turn == intentTurn && !newAudioEpoch) return
val oldTurn = intentTurn
desired = mode; intentTurn = turn
if (!running || activeSlot == null) return // startup will apply the latest intent
if (oldTurn != turn || newAudioEpoch) { generation++; revision = 0 }
apply(planner.request(MouthIntent(generation, ++revision, turn, mode,
if (turn == null && mode == SafeClipRole.IDLE) VisualIntentReason.ABORT else VisualIntentReason.PCM), now()))
apply(planner.prepareNext())
// No cut on request: wait for a latched source frame at a legal window.
inspectHeldSource()
publish()
}
fun stop() {
failureReason = null
epoch++; running = false; activeSlot = null
pending = null; pendingSlot = null; pendingReady = null; sourceEnded = false
planner.background()
ports.indices.forEach { i -> ports[i]?.close(); ports[i] = null }
showStatic(); report(VideoPresentation(reason = "background"))
}
fun sample(): VideoPresentation {
val s = planner.snapshot(now())
return VideoPresentation(if (activeSlot == null) "static" else s.actualRole.name.lowercase(),
failureReason ?: s.reason.name.lowercase(), s.visualWaitMs, s.closedMouthLagMs, firstFrameMs,s.mouthActiveLagMs,s.actualClip)
}
private fun publish() { report(sample()) }
private fun fail(reason: String) {
stop(); failureReason = reason; report(VideoPresentation(reason = reason))
}
private fun stage(action: TransitionAction.Stage, slot: Int = 1 - checkNotNull(activeSlot)) {
ports[slot]?.close()
val port = createPort(slot); ports[slot] = port
pending = action; pendingSlot = slot; pendingReady = null
val fence = epoch
port.prepare(graph.clips.getValue(action.ticket.target), action.entry, object : AnchorVideoPort.Listener {
private fun valid() = running && epoch == fence && ports[slot] === port
override fun frame(frame: DisplayedVideoFrame) {
if (!valid()) return
if (activeSlot == slot) {
inspectHeldSource()
if (valid() && activeSlot == slot && !sourceEnded) port.advance()
return
}
if (pending != action || pendingSlot != slot) return
val staged = StagedFrame(action.ticket,frame.positionMs,frame.frame,true,true,true)
if (!action.entry.contains(frame.positionMs,frame.frame)) { fail("entry_missed"); return }
if (action.ticket.edgeId == "startup") {
if (!planner.foreground(action.ticket.generation, action.ticket.target, action.entry, staged, now())) {
fail("startup_rejected"); return
}
firstFrameMs = (now() - startedAt).coerceAtLeast(0)
activeSlot = slot; pending = null; pendingSlot = null; pendingReady = null
reveal(slot)
// Startup neutral is explicit; latest PCM intention may have changed while decoding.
generation++; revision = 0
apply(planner.request(MouthIntent(generation, ++revision, intentTurn, desired),now()))
apply(planner.prepareNext())
inspectHeldSource(); if (valid() && activeSlot == slot) port.advance()
} else {
pendingReady = staged
planner.targetReady(staged)
if (sourceEnded) inspectHeldSource()
}
publish()
}
override fun ended() {
if (!valid()) return
if (activeSlot == slot) { sourceEnded = true; inspectHeldSource(); publish() }
else fail("entry_missed")
}
override fun failed(reason: VideoFailure) { if (valid()) fail("video_${reason.name.lowercase()}") }
})
}
private fun observation(slot: Int): ClipObservation? {
val f = ports[slot]?.displayed() ?: return null
return ClipObservation(planner.snapshot(now()).actualClip,f.positionMs,f.frame,f.loop,++serial,now(),sourceEnded)
}
private fun inspectHeldSource() {
val slot = activeSlot ?: return
val sample = observation(slot) ?: return
apply(planner.tick(sample,now()))
publish()
}
private fun apply(actions: List<TransitionAction>) {
for (action in actions) when (action) {
is TransitionAction.Stage -> stage(action)
is TransitionAction.Cancel -> {
if (pending?.ticket == action.ticket) {
pendingSlot?.let { ports[it]?.close(); ports[it] = null }
pending = null; pendingSlot = null; pendingReady = null
}
}
is TransitionAction.OfferCut -> {
val slot = activeSlot ?: continue
val targetSlot = pendingSlot ?: continue
val target = pendingReady ?: continue
// Both ports are held: sample the actual latched texture again, then commit.
val f = ports[targetSlot]?.displayed() ?: continue
val current = observation(slot) ?: continue
apply(planner.commit(action.ticket,current,target.copy(positionMs=f.positionMs,frame=f.frame),now()))
}
is TransitionAction.Reveal -> {
val next = pendingSlot ?: continue
val old = activeSlot
// Target has a latched paused frame. Visibility changes before any advancement.
reveal(next); activeSlot = next; sourceEnded = false
pending = null; pendingSlot = null; pendingReady = null
if (old != null) { ports[old]?.close(); ports[old] = null }
// Begin preparing the next legal variant/bridge at segment entry.
inspectHeldSource()
ports[next]?.advance()
}
is TransitionAction.Hold -> Unit
TransitionAction.Release -> stop()
}
}
}
/** Texture fit transform; the full body stays inside the white viewport at any aspect. */
data class VideoFit(val scaleX: Float, val scaleY: Float)
fun fitVideo(viewWidth: Int, viewHeight: Int, mediaWidth: Int, mediaHeight: Int): VideoFit {
require(viewWidth > 0 && viewHeight > 0 && mediaWidth > 0 && mediaHeight > 0)
val scale = minOf(viewWidth.toFloat()/mediaWidth,viewHeight.toFloat()/mediaHeight)
return VideoFit(mediaWidth*scale/viewWidth,mediaHeight*scale/viewHeight)
}
@@ -0,0 +1,16 @@
package com.gorios.lanvoice.avatar
/** Finite local summary, <=1Hz. No PCM, images, exception text or chat. */
class TransitionDiagnostics {
private var lastMs: Long? = null
fun summary(snapshot: TransitionSnapshot, requestedEmotion: AssetEmotion, nowMs: Long): String? {
if (lastMs?.let { nowMs - it < 1000 } == true) return null
lastMs = nowMs
return "desired=${snapshot.desired.name.lowercase()} actual=${snapshot.actualRole.name.lowercase()} " +
"requested=${requestedEmotion.emotion.wire}/${requestedEmotion.intensity} " +
"reason=${snapshot.reason.name.lowercase()} wait_ms=${snapshot.visualWaitMs.coerceIn(0,60000)} " +
"closed_lag_ms=${snapshot.closedMouthLagMs?.coerceIn(0,60000)} exit_pending=${snapshot.exitPending} " +
"mouth_active_lag_ms=${snapshot.mouthActiveLagMs?.coerceIn(0,60000)} " +
"switches=${snapshot.switches} cancellations=${snapshot.cancellations}"
}
}
@@ -35,37 +35,37 @@ fun ExpressionControls(
state.facePresence == FacePresence.PRESENT -> "有人脸"
state.facePresence == FacePresence.ABSENT -> "尚无结果"
else -> "尚无结果"
}, fontSize = 12.sp, color = Color(0xFFE8C884),
}, fontSize = 12.sp, color = Color(0xFF385B46),
)
TextButton(onClick = onToggle, enabled = controlsEnabled) {
Text(when {
state.status == ExpressionStatus.STARTING -> "取消开启"
enabled -> "关闭摄像头"
else -> "开启表情线索"
}, fontSize = 12.sp, color = Color(0xFFE8C884))
}, fontSize = 12.sp, color = Color(0xFF385B46))
}
}
Text("表情线索:" + when (state.stableCue) {
FaceCue.SMILING -> "明显微笑"
FaceCue.BROW_FURROWED -> "明显皱眉"
else -> "未见明显线索"
}, fontSize = 12.sp, color = Color(0xFF9CA3AF))
}, fontSize = 12.sp, color = Color(0xFF59675F))
if (state.status == ExpressionStatus.STARTING) {
Text("正在开启摄像头…", color = Color(0xFF9CA3AF), fontSize = 12.sp)
Text("正在开启摄像头…", color = Color(0xFF59675F), fontSize = 12.sp)
}
state.guidance?.let {
Text(it, fontSize = 12.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center)
Text(it, fontSize = 12.sp, color = Color(0xFF59675F), textAlign = TextAlign.Center)
}
Text(
"表情不等于情绪;线索仅供参考,不代表真实情绪",
fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center,
fontSize = 11.sp, color = Color(0xFF59675F), textAlign = TextAlign.Center,
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text("将表情线索用于对话", color = Color(0xFF9CA3AF), fontSize = 12.sp)
Text("将表情线索用于对话", color = Color(0xFF59675F), fontSize = 12.sp)
Switch(checked = shareFace, onCheckedChange = onShareFace, enabled = controlsEnabled)
}
if (shareFace && state.status != ExpressionStatus.ACTIVE) {
Text("摄像头关闭时不发送线索", color = Color(0xFF9CA3AF), fontSize = 11.sp)
Text("摄像头关闭时不发送线索", color = Color(0xFF59675F), fontSize = 11.sp)
}
}
}