feat: add aperture mouth candidate and early foreground permissions

Route runtime04 curve values to five source-frame lip geometries with level0 body bypass and spatial opacity1 for all other levels. Preserve the continuous decoded body clock and clean home. Request normal permissions after foreground host layout independently of network; support offline manual consent without capture or connection. Add strict 97x5 parsing, renderer and permission regressions, offline EGL shader pixel goldens and exact debug-candidate packaging. Naturalness, visible talk, device colors and perceived response remain pending.
This commit is contained in:
zenord
2026-10-12 22:55:20 +08:00
parent 9ea5eb31c1
commit 7d8ea95f07
22 changed files with 677 additions and 155 deletions
+11 -3
View File
@@ -16,6 +16,10 @@ 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'
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
if (avatarMouthCandidate && (!avatarNatural || avatarUiCandidate)) {
throw new GradleException('Mouth candidate requires natural runtime and a distinct version from UI-only')
}
if (avatarUiCandidate && !avatarNatural) {
throw new GradleException('UI candidate requires the pinned natural debug runtime')
}
@@ -54,6 +58,7 @@ 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/**'
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
into(packagedAssets)
}
@@ -65,8 +70,8 @@ android {
minSdk 26
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)
versionName avatarUiCandidate ? '0.6.2' : '0.6.1'
versionCode avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))
versionName = (avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -74,16 +79,19 @@ android {
buildFeatures { compose true; buildConfig true }
buildTypes {
debug {
if (avatarUiCandidate) versionNameSuffix '-ui-dev'
if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
else 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 'boolean', 'AVATAR_MOUTH_CANDIDATE', avatarMouthCandidate ? 'true' : 'false'
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '"' + (avatarNatural ? naturalManifestSha : '') + '"'
}
release {
buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false'
buildConfigField 'boolean', 'AVATAR_NATURAL', 'false'
buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', 'false'
buildConfigField 'String', 'NATURAL_MANIFEST_SHA', '""'
}
}
@@ -39,7 +39,9 @@ class AvatarCleanUiInstrumentation : Instrumentation() {
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 })
val version=targetContext.packageManager.getPackageInfo(targetContext.packageName,0).versionName
val candidate=if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03"
check(nodes().any { it.text?.toString()?.contains(candidate)==true })
check(nodes().first { it.text?.toString()=="关闭" }.performAction(AccessibilityNodeInfo.ACTION_CLICK))
await { nodes().none { it.text?.toString()=="关闭" } && gear()!=null }
assertClean()
@@ -48,6 +48,9 @@ class MainActivity : ComponentActivity() {
private var permissionMessage by mutableStateOf<String?>(null)
private var micSettings by mutableStateOf(false)
private var cameraSettings by mutableStateOf(false)
private var micGranted by mutableStateOf(false)
private var cameraGranted by mutableStateOf(false)
private var permissionPending by mutableStateOf<EntryPermission?>(null)
private val main = android.os.Handler(android.os.Looper.getMainLooper())
private val pump = Runnable { advanceEntry() }
private val retryTimer = Runnable { advanceEntry() }
@@ -65,11 +68,11 @@ class MainActivity : ComponentActivity() {
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
if (!::entry.isInitialized || isDestroyed || entry.permissionPending!=permission) 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 (!granted && !offlineAvatarPreview) {
if (permission == EntryPermission.MICROPHONE) session.permissionDenied()
else expressions.permissionDenied()
}
@@ -81,12 +84,21 @@ class MainActivity : ComponentActivity() {
}
private fun advanceEntry() {
if (!::entry.isInitialized || isDestroyed) return
// First consent is after the foreground Compose host has a stable layout,
// independent of health/WS/HELLO. No request originates from recomposition.
if(inForeground && (!window.decorView.isAttachedToWindow || !window.decorView.isLaidOut)) {
window.decorView.postOnAnimation { if(inForeground && !isDestroyed) scheduleEntry() }
return
}
val now = android.os.SystemClock.elapsedRealtime()
micGranted=granted(Manifest.permission.RECORD_AUDIO)
cameraGranted=granted(Manifest.permission.CAMERA)
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)
permissionPending=entry.permissionPending
entryPhase = entry.phase
permissionMessage = when {
!granted(Manifest.permission.RECORD_AUDIO) -> "需要麦克风权限才能对话" + if (micSettings) " · 请在应用设置中开启" else ""
@@ -96,9 +108,9 @@ class MainActivity : ComponentActivity() {
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()
EntryEffect.Connect -> if(!offlineAvatarPreview && inForeground) session.dial()
EntryEffect.StartVoice -> if(!offlineAvatarPreview && inForeground && micGranted && state.connection==ConnectionStatus.CONNECTED) session.startVoice(microphoneMuted = preferences().getBoolean("microphoneMuted", false))
EntryEffect.StartCamera -> if (!offlineAvatarPreview && inForeground && cameraGranted) expressions.start()
is EntryEffect.RequestPermission -> {
val mic = action.permission == EntryPermission.MICROPHONE
preferences().edit().putBoolean(if (mic) "micAsked" else "camAsked", true).apply()
@@ -112,10 +124,15 @@ class MainActivity : ComponentActivity() {
android.net.Uri.parse("package:$packageName")))
}
private fun authorizeMicrophone() {
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
if (!inForeground || granted(Manifest.permission.RECORD_AUDIO) || entry.permissionPending != null) return
if (micSettings) openSettings()
else if (entry.requestPermission(EntryPermission.MICROPHONE, false)) scheduleEntry()
}
private fun authorizeCamera() {
if(!inForeground || granted(Manifest.permission.CAMERA) || entry.permissionPending!=null) return
if(cameraSettings) openSettings()
else if(entry.requestPermission(EntryPermission.CAMERA,false)) scheduleEntry()
}
private fun retryConnection() {
if (entry.retry(android.os.SystemClock.elapsedRealtime())) {
session.resetConnection()
@@ -134,8 +151,11 @@ class MainActivity : ComponentActivity() {
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.
entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false),
conversationEnabled=false,automaticPermissions=false)
setContent { EngineeringPreviewScreen(avatarPack,micGranted,cameraGranted,micSettings,cameraSettings,
permissionPending,::authorizeMicrophone,::authorizeCamera) }
return // No VoiceSession/audio focus/camera controller; manual permission consent only.
}
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
DebugLogUpload.appLaunch(
@@ -172,6 +192,7 @@ class MainActivity : ComponentActivity() {
session.setMicrophoneMuted(muted) }, ::toggleExpressions,
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
micGranted,cameraGranted,permissionPending,::authorizeCamera,
)
}
}
@@ -212,7 +233,7 @@ class MainActivity : ComponentActivity() {
}
private fun toggleExpressions() {
if (!inForeground || state.connection != ConnectionStatus.CONNECTED || entry.permissionPending != null) return
if (!inForeground || entry.permissionPending != null) return
val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE)
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() }
@@ -230,18 +251,17 @@ class MainActivity : ComponentActivity() {
}
override fun onResume() {
super.onResume()
if (offlineAvatarPreview) return
inForeground = true
entry.enter()
// The pure coordinator owns bounded connection attempts. No automatic listen here.
session.foreground(connectAutomatically = false)
if(!offlineAvatarPreview) session.foreground(connectAutomatically = false)
scheduleEntry()
}
override fun onPause() {
if (offlineAvatarPreview) { super.onPause(); return }
inForeground = false
entry.leave()
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
if (offlineAvatarPreview) { super.onPause(); return }
closeCamera()
// Permission windows can pause/stop the Activity. No sensors survive this pause;
// retain only the fenced connection continuation, bounded by VoiceSession's timeout.
@@ -257,8 +277,8 @@ class MainActivity : ComponentActivity() {
}
override fun onDestroy() {
if (offlineAvatarPreview) { super.onDestroy(); return }
main.removeCallbacks(pump); main.removeCallbacks(retryTimer)
if (offlineAvatarPreview) { super.onDestroy(); return }
DebugLogUpload.log("audio", "camera stop reason=release")
expressions.release()
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
@@ -11,7 +11,8 @@ sealed interface 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)) {
cameraInitiallyWanted: Boolean = true, private val retryDelaysMs: List<Long> = listOf(1_000, 3_000),
private val conversationEnabled: Boolean = true, automaticPermissions: Boolean = true) {
init { require(retryDelaysMs.size <= 4 && retryDelaysMs.all { it in 500..30_000 }) }
var phase = EntryPhase.CONNECTING; private set
var permissionPending: EntryPermission? = null; private set
@@ -26,8 +27,8 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
private var startIssued = false
private var cameraIssued = false
private var cycleStarted = false
private var autoMicAllowed = !microphoneAsked
private var autoCamAllowed = !cameraAsked
private var autoMicAllowed = automaticPermissions && !microphoneAsked
private var autoCamAllowed = automaticPermissions && !cameraAsked
private var manualPermission: EntryPermission? = null
fun enter() {
@@ -52,13 +53,13 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
if (inProgress) phase = EntryPhase.CONNECTING
}
fun retry(nowMs: Long): Boolean {
if (!foreground || permissionPending != null || connecting || retryAtMs?.let { nowMs < it } == true) return false
if (!conversationEnabled || !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
if (!foreground || permissionPending != null || manualPermission != null || permanentlyDenied) return false
manualPermission = permission
if (permission == EntryPermission.CAMERA) cameraWanted = true
return true
@@ -74,21 +75,8 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
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
}
// Permission consent is foreground/UI driven, independent of network/HELLO.
if (permissionPending == null) {
val ask = manualPermission ?: when {
!microphoneGranted && autoMicAllowed -> EntryPermission.MICROPHONE
@@ -96,13 +84,38 @@ class AutoConversation(microphoneAsked: Boolean = false, cameraAsked: Boolean =
else -> null
}
manualPermission = null
if (ask != null) {
val alreadyGranted=when(ask) {
EntryPermission.MICROPHONE -> microphoneGranted
EntryPermission.CAMERA -> cameraGranted
null -> true
}
if (ask != null && !alreadyGranted) {
permissionPending = ask
if (ask == EntryPermission.MICROPHONE) { micAsked = true; autoMicAllowed = false }
else { camAsked = true; autoCamAllowed = false }
actions += EntryEffect.RequestPermission(ask)
}
}
// Offline preview permits explicit consent only, never transport or sensors.
if (!conversationEnabled) {
phase=if(permissionPending!=null) EntryPhase.AWAITING_PERMISSION else EntryPhase.ACTIVE
return actions
}
if (permissionPending==null && cameraGranted && cameraWanted && !cameraIssued) {
cameraIssued=true;actions+=EntryEffect.StartCamera
}
if (!connected) {
if (connecting) { phase=EntryPhase.CONNECTING;return actions }
val due=attempts==0 || retryAtMs?.let { nowMs>=it }==true
if (!due) { phase=EntryPhase.ERROR;return actions }
attempts++;retryAtMs=null;connecting=true;phase=EntryPhase.CONNECTING
actions+=EntryEffect.Connect
return actions
}
// Consent does not start uplink: MIC, real HELLO and actual foreground are required.
if (permissionPending==null && microphoneGranted && !voiceActive && !startIssued) {
startIssued=true;actions+=EntryEffect.StartVoice
}
phase = when {
!microphoneGranted -> EntryPhase.AWAITING_PERMISSION
voiceActive -> EntryPhase.ACTIVE
@@ -22,15 +22,17 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback
catch (_: Exception) { return null }
val static = AvatarPack(fallback=fallback)
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
val root=MOTION_ROOT+"runtime-03/"
val root=MOTION_ROOT+(if(BuildConfig.AVATAR_MOUTH_CANDIDATE) "runtime-04/" else "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(runtime.apertureMode==BuildConfig.AVATAR_MOUTH_CANDIDATE)
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)
for ((index,image) in runtime.textureImages.withIndex()) {
val patch=runtime.patches[index/(if(runtime.apertureMode) 5 else 1)]
check(sha(read(context,root+image.path,256_000))==image.sha256)
val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true }
val bytes=read(context,root+patch.path,256_000)
val bytes=read(context,root+image.path,256_000)
android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options)
check(options.outWidth==patch.width && options.outHeight==patch.height)
}
@@ -76,6 +76,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
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,
micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit,
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity)
val latestAvatar by rememberUpdatedState(avatar)
@@ -107,13 +108,13 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
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 "允许麦克风") }
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
state.guidance?.let { Text(it,fontSize=13.sp) }
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
Button(onClick=onMute,enabled=state.voiceActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Text(if(state.microphoneMuted) "恢复收音" else "暂停收音")
}
OutlinedButton(onClick=onCamera,enabled=state.connection==com.gorios.lanvoice.net.ConnectionStatus.CONNECTED,
OutlinedButton(onClick=onCamera,
modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Text(if(expression.status in setOf(ExpressionStatus.ACTIVE,ExpressionStatus.STARTING)) "关闭相机" else if(cameraSettings) "相机权限设置" else "开启相机")
}
@@ -135,10 +136,25 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
})
}
@Composable
private fun PermissionSettings(micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
pending: EntryPermission?,onMic: ()->Unit,onCamera: ()->Unit) {
Text("麦克风权限:${if(micGranted) "已授权" else "未授权"} · 摄像头权限:${if(cameraGranted) "已授权" else "未授权"}",fontSize=13.sp)
if(pending!=null) Text("正在申请${if(pending==EntryPermission.MICROPHONE) "麦克风" else "摄像头"}权限",fontSize=12.sp)
if(micSettings || cameraSettings) Text("权限已关闭或不再询问,可打开应用系统权限设置后手动开启",fontSize=12.sp)
TextButton(onClick=onMic,enabled=!micGranted && pending==null) {
Text(if(micGranted) "麦克风已授权" else if(micSettings) "打开麦克风系统权限设置" else "申请麦克风权限")
}
TextButton(onClick=onCamera,enabled=!cameraGranted && pending==null) {
Text(if(cameraGranted) "摄像头已授权" else if(cameraSettings) "打开摄像头系统权限设置" else "申请摄像头权限")
}
}
@Composable
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)
if(BuildConfig.VERSION_NAME=="0.6.2-mouth-dev") Text("嘴部工程候选:源帧自身嘴形五档微动;阶梯感、可见性及变形改善待真机验证",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)
@@ -148,7 +164,8 @@ private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) {
/** Sensor-free synthetic intents, same real renderer and same clean home. */
@Composable
fun EngineeringPreviewScreen(pack: AvatarPack?) {
fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean,
permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit) {
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)) }
@@ -172,7 +189,9 @@ fun EngineeringPreviewScreen(pack: AvatarPack?) {
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("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp)
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
Text("合成意图:${override?.name ?: trace.label}",fontSize=12.sp)
AvatarDiagnostics(pack,video)
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
@@ -1,11 +1,16 @@
package com.gorios.lanvoice.avatar
data class MouthPatchLevel(val levelIndex: Int,val aperture: Float,val path: String,val sha256: String)
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)
val x: Float,val y: Float,val width: Int,val height: Int,val levels: List<MouthPatchLevel> = emptyList())
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)
val curves: Map<String,MouthCurve>,val root: String,val manifestSha: String,val apertureMode: Boolean=false) {
val textureImages: List<MouthPatchLevel> = patches.flatMap { p ->
if(apertureMode) p.levels else listOf(MouthPatchLevel(0,1f,p.path,p.sha256))
}
}
/** This parser admits only coordinator-selected debug runtime data; no production graph. */
object ContinuousAvatarManifest {
@@ -18,7 +23,9 @@ object ContinuousAvatarManifest {
fun smallInt(v: Any?): Int { val n=integer(v);require(n in 0..1_000_000);return n.toInt() }
fun finite(v: Any?): Float { val f=(v as Number).toFloat(); require(f.isFinite()); return f }
fun hash(v: Any?)=(v as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" && root["packId"]=="a01-neutral-graph-v1-runtime-03")
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04"
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" &&
(apertureMode || 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"]),
@@ -29,6 +36,10 @@ object ContinuousAvatarManifest {
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")
if(apertureMode) {
require((patchFormat["apertureLevels"] as List<*>).map(::finite)==listOf(0f,.25f,.5f,.75f,1f))
require(patchFormat["requiresRendererExtension"]==true)
}
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"]),
@@ -37,9 +48,23 @@ object ContinuousAvatarManifest {
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
if(apertureMode) {
val levels=(p["levels"] as List<Map<String,Any?>>).mapIndexed { level,row ->
require(level in 0..4 && smallInt(row["levelIndex"])==level && finite(row["aperture"])==level/4f)
MouthPatchLevel(level,level/4f,row["path"] as String,hash(row["sha256"])).also {
require(it.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png")))
}
}
require(levels.size==5 && patch.path==levels[4].path && patch.sha256==levels[4].sha256)
patch.copy(levels=levels)
} else {
require(p["levels"]==null) // Never silently treat aperture data as opacity.
patch
}
}
require(patches.map { it.path }.distinct().size==97 && patches.sumOf { it.width*it.height*4L }<=8_000_000)
val paths=patches.flatMap { if(apertureMode) it.levels.map { l -> l.path } else listOf(it.path) }
require(paths.distinct().size==if(apertureMode) 485 else 97)
require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=8_000_000)
val states=root["mouthStates"] as List<Map<String,Any?>>
require(states.size==5)
val c=states.associateBy { it["id"] as String }
@@ -69,7 +94,7 @@ object ContinuousAvatarManifest {
required.forEach { (id,targets) ->
val list=routing[id] as List<*>;require(list.size==targets.size && list.toSet()==targets)
}
ContinuousAvatarPack(body,patches,curves,pathRoot,sha)
ContinuousAvatarPack(body,patches,curves,pathRoot,sha,apertureMode)
} catch(_: Exception) { null }
}
}
@@ -57,12 +57,12 @@ class ContinuousAvatarView(context: Context,private val pack: AvatarPack?,privat
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}")
waitMs=frame.mouth.phaseWaitMs,firstFrameMs=firstFrameMs,clipId="body_f${frame.key.index}_loop${frame.key.loopOrdinal}_level${frame.selection.levelIndex ?: "opacity"}")
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")
DiagnosticLog.record("avatar_layer","phase=${frame.mouth.phase} frame=${frame.key.index} loop=${frame.key.loopOrdinal} level=${frame.selection.levelIndex ?: -1} opacity=${frame.selection.opacity} 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)) } })
@@ -47,14 +47,14 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
private var first=true
private var program=0
private var bodyTexture=0
private val patchTextures=IntArray(pack.patches.size)
private val patchTextures=IntArray(pack.textureImages.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 uBody=0; private var uPatch=0; private var uRect=0; private var uOpacity=0
private var startedMs=SystemClock.elapsedRealtime()
private var progressMs=startedMs
private val timeout=Runnable { fail("frame_timeout") }
@@ -77,14 +77,15 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
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 })
uRect=GLES20.glGetUniformLocation(program,"uRect");uOpacity=GLES20.glGetUniformLocation(program,"uOpacity")
check(listOf(aPosition,aUv,uTextureMatrix,uBody,uPatch,uRect,uOpacity).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")
pack.textureImages.forEachIndexed { index,image ->
val p=pack.patches[index/(if(pack.apertureMode) 5 else 1)]
val bitmap=context.assets.open(pack.root+image.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)
@@ -124,31 +125,8 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
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 vertex=shader(GLES20.GL_VERTEX_SHADER,AvatarLayerShader.VERTEX)
val fragment=shader(GLES20.GL_FRAGMENT_SHADER,AvatarLayerShader.FRAGMENT)
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)
@@ -204,8 +182,8 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
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.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,patchTextures[frame.selection.textureSlot]);GLES20.glUniform1i(uPatch,1)
val p=frame.patch;GLES20.glUniform4f(uRect,p.x,p.y,p.width.toFloat(),p.height.toFloat());GLES20.glUniform1f(uOpacity,frame.selection.opacity)
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4)
check(GLES20.glGetError()==GLES20.GL_NO_ERROR && EGL14.eglSwapBuffers(display,window))
}
@@ -238,3 +216,32 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
}
}
}
/** Shared literal shader source is exercised by the offline EGL pixel golden check. */
internal object AvatarLayerShader {
const val VERTEX="""
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; }
"""
const val FRAGMENT="""
#extension GL_OES_EGL_image_external : require
precision highp float;
uniform samplerExternalOES uBody; uniform sampler2D uPatch;
uniform vec4 uRect; uniform float uOpacity;
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(uOpacity<=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=uOpacity*patch.a;
gl_FragColor=vec4(mix(body.rgb,patch.rgb,mask),1.0);
}
}
"""
}
@@ -1,6 +1,15 @@
package com.gorios.lanvoice.avatar
data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPatch,val mouth: MouthLayerSample)
data class MouthPatchSelection(val textureSlot: Int,val levelIndex: Int?,val opacity: Float)
/** In runtime04 aperture chooses geometry, never its opacity. Ties choose the lower level. */
fun selectMouthPatch(pack: ContinuousAvatarPack,frameIndex: Int,aperture: Float): MouthPatchSelection {
require(frameIndex in pack.patches.indices && aperture.isFinite() && aperture in 0f..1f)
if(!pack.apertureMode) return MouthPatchSelection(frameIndex,null,aperture)
val level=(0..4).minBy { kotlin.math.abs(aperture-it/4f) }
return MouthPatchSelection(frameIndex*5+level,level,if(level==0) 0f else 1f)
}
data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPatch,val mouth: MouthLayerSample,
val selection: MouthPatchSelection)
/** 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) }) {
@@ -12,7 +21,8 @@ class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (I
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))
val sample=mouth.sample(nowMs)
val frame=ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha))
drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented.
return frame
}