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:
+42
-4
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 0.6.1-dev / code12 内部工程候选
|
||||
|
||||
本包仅验证真实 MediaCodec 短片解码、五节点调度、TextureView PTS、前台生命周期和自动连接权限 UX。界面显著标注“工程候选:自然度待验”。不是最终自然度产品,也不认证 ≤1s 感知响应;肖像商用权利仍未核实。
|
||||
|
||||
## 素材与技术准入
|
||||
|
||||
只使用 a01-neutral-graph-v1 controlled-01 原始 manifest,SHA256:
|
||||
`e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09`。
|
||||
原 manifest `safeTransitions.reviewStatus=pending`、`approvedEdges=[]`、`safeExits=[]`、`publishApproval=false` 保持不变。生产 allowlist 仍为空。只有显式 `-PavatarEngineering=true` 的 debug 构建可走 `TECHNICAL_DEBUG` 范围;release 永远关闭此入口。技术字段不能满足生产图的审核范围。
|
||||
|
||||
五段实际离线视频:idle/talk1/talk2 各 12 帧、500ms;opening/end-talk 各 6 帧、250ms,24fps、480×848、H264 Main3.1、yuv420p、无音轨。入口只 frame0;出口只 manifest 指定的 frame11/frame5,CFR PTS 对应 458.333/208.333ms。独立编码边不 pixel identical;端点授权是工程实验准入,不是安全视觉验收。
|
||||
|
||||
图为 idle A→A、opening A→B、talk1/talk2 B→B、end-talk B→A(closing 别名)。保留三 self-loop、八必需转换和 opening→end-talk 反转边;缺边拒绝。窗口错过、目标未 ready、解码异常都不能强行切换。音频不等待视频;实际 PCM 播放头只提交 mouth 意图。口部感知证据不从 authored alpha 伪造,因此 mouth activity / closed-stable 延后诊断保持未知。
|
||||
|
||||
controlled-01 是 A/B 局部嘴层加最多约 0.6px/0.15px 合成身体形变,无眨眼;可能机械、照片感、肤色唇影接缝或 ghost。900ms 只是素材参数预算,不含设备解码、实际显示或用户感知。natural-02 不在本包。
|
||||
|
||||
## 复现
|
||||
|
||||
私密二进制只放 ignored `.runtime`、`app/src/main/assets/avatar`、`artifacts`,不提交 Git。
|
||||
|
||||
```sh
|
||||
python3 scripts/package-avatar-engineering.py --import-only
|
||||
./scripts/check-avatar-regressions.sh
|
||||
/home/ubuntu/miniconda3/envs/gori-speech/bin/python gateway/scripts/check-archive.py --vad-model /home/ubuntu/miniconda3/envs/gori-speech/lib/python3.12/site-packages/silero_vad/data/silero_vad.onnx > logs/avatar-safe-061/gateway-tests.txt 2>&1
|
||||
python3 scripts/package-avatar-engineering.py
|
||||
```
|
||||
|
||||
导入逐项核原 manifest/静态 A/五 MP4 哈希,检查 CFR PTS、帧数及完整解码。打包入口拒绝覆盖已有工程 APK,验证 min26/target34/arm64、同 051/052/060 debug 证书、APK 内素材字节与未压缩 MP4、HTTP APK/sidecar 字节。最终 v061 文件不使用,旧 060/052/051 保留;无提交推送、无后端变更或重启。
|
||||
|
||||
## 协调 Windows ADB 离线验收
|
||||
|
||||
安装保留数据,不加 `-g`,不清数据。先停止旧 Activity,再带 extra 启动新 Activity:
|
||||
|
||||
```sh
|
||||
adb -s 0123456789ABCDEF install -r lan-voice-v061-engineering-arm64-debug.apk
|
||||
adb -s 0123456789ABCDEF shell am force-stop com.gorios.lanvoice
|
||||
adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity --ez avatar_offline_preview true
|
||||
```
|
||||
|
||||
离线入口在创建 VoiceSession/音频焦点/相机控制器之前返回;不连接后端,不申请权限,不录音、不分析相机。使用真实播放器,每20s循环合成 idle/talk/stop/100ms反转/resume/abort-new-generation/drained 意图;也可手动 Idle/Talk/Abort/Trace。合成意图不是 PCM 测量。后台释放、前台重新预备 neutral 入口;横屏/平板白底 Fit 不拉伸裁头脚。应检查首帧、末帧转换、loop、黑帧、decoder fallback、后台恢复及设备资源限制;不采集用户视频/脸/音频。
|
||||
|
||||
**正常桌面启动有不同效果:** 自动连接,真实 HELLO 后申请 MIC/CAMERA;如果已授权且实际前台,会直接开启语音和相机分析。face-cue 分享仍独立默认关闭。首次设备验收请使用上面的离线命令;本 agent 不安装、不启动设备传感器。
|
||||
|
||||
JVM 使用真实 driver/codec 控制代码加确定性 Android doubles,不证明硬件解码能力或系统权限弹窗行为。硬件 PTS/双 decoder、首帧及长期资源、感知自然度、嘴活动/闭嘴 ≤1s、摄像头算法均待设备独立验收。
|
||||
@@ -1,5 +1,7 @@
|
||||
# Android 0.6.0 / code11 — neutral avatar candidate MVP
|
||||
|
||||
This describes the retained released APK only. The later user requirement replaces dial/hangup with automatic foreground connection and sequential MIC/CAMERA requests, and replaces seated media with a standing full-body identity under review. That uncommitted development is documented in [AVATAR_UX_NEXT.md](AVATAR_UX_NEXT.md) and [AVATAR_SAFE_TRANSITIONS.md](AVATAR_SAFE_TRANSITIONS.md). It has not changed or replaced this0.6.0 artifact; the default-off camera-request policy below is historical release behavior.
|
||||
|
||||
This release replaces the debug home with a video-call style single page. Before dialing it displays the a01 waiting portrait, title “声伴” and Dial; no listen/start or microphone capture occurs until the user explicitly dials and grants microphone permission. WS/health preparation alone is not a call. Connecting has a cancel action, duplicate dialing is fenced, denial shows guidance. These labels describe an app conversation, not a real person's ringing/answering. The existing hello has no character display field consumed by this client, so no private persona name is embedded.
|
||||
|
||||
During a call the 480×848 portrait fits the available width/height without stretching. Bottom controls hang up, mute the microphone, or explicitly enable the camera. Status is short; actual requested role expression, previous reply, selected neutral asset/fallback, camera presence/cue, interruption and diagnostic upload live in the expandable details. Insets are respected; details have bounded scrolling and portrait shrinks for small/landscape screens. Physical small-screen/tablet rendering remains pending.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# 0.6.1-natural-dev / code13 自然工程候选
|
||||
|
||||
本阶段授权 continuous body + registered local mouth layer Android 集成。与 code12 controlled01 五 wholeframe clip 的方法不同,仍是工程候选,不认证最终自然度或 ≤1s 感知响应。后端、模型/TTS 参数、相机算法不变;没有新 AI 付费、安装或传感器采集。
|
||||
|
||||
## 精确素材与范围
|
||||
|
||||
runtime-03 manifest SHA256:`87ad2b2ad0e96fe64943692da363c856939ad4aad57073c589d53130c2f2073c`。
|
||||
来源 `.runtime/avatar-imports/a01-neutral-graph-v1/runtime-03/`,导出自 natural03。body SHA `177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762`,97帧、480×848、24fps、4041667us、静音 H264。97张局部嘴 PNG 为 straight RGBA8,注册/tone/空间羽化已离线烘焙,无实时 SSD。
|
||||
|
||||
保留 manifest publishApproval=false、safeTransitions pending、approvedEdges=[]、naturalQuality/deviceTest pending。仅 `-PavatarNatural=true -PnaturalManifestSha=<exact SHA>` debug 构建准入;release 关闭 runtime override,生产图 allowlist 仍为空。旧 controlled01 manifest/素材/code12 APK 保留原哈希,natural02/03 失败或审查视频不作为 runtime 片段打包。
|
||||
|
||||
## 实装路径
|
||||
|
||||
ContinuousBodyRenderer 使用一个 MediaCodec → OES SurfaceTexture → GLES2/EGL window。每次仅释放一个解码输出;updateTexImage 后核 SurfaceTexture timestamp 与 decoder PTS,ContinuousFrameClock 校验0..96连续索引及 wrap。按已消费 index 选 patch,body 和局部嘴层同一 draw/swap 完成,不独立 Compose overlay,不取 MediaPlayer position 猜相位。swap 成功仅表示合成 buffer 提交,不证明物理屏幕/用户感知时刻。
|
||||
|
||||
body 持续前进,嘴相位独立 IDLE→OPENING→TALKING→STOPPING→IDLE;250ms opening/end、500ms talk 单元。持续 talk 在合法曲线端点选择 talk1/2,有另一合法变体时不连续重复;latest generation/revision 覆盖旧请求,abort 立即由既有音频实现停止声音,嘴完成当前短单元和 closing;opening 反转可完成后 closing,stop 中恢复先完成 closing→idle,再 opening。mouth 变化不 flush/seek body。只有完整97帧 wrap 才 flush/seek0、ordinal+1。
|
||||
|
||||
PNG 启动时97张小图解码并缓存 GL texture,总 RGBA 上限8MB(本包约341KB),不每帧解码/分配全身 bitmap。Bitmap getPixels 取得 straight ARGB 后显式 RGBA byte 上传,shader `out=body*(1-g*a)+patchRGB*(g*a)`,g=0 原 body;不二次乘空间 alpha。body 和 patch 使用同一 top-left480×848坐标与白底 Fit,不裁头脚或拉伸。GLES highp 失败、PTS错配、早EOS、超时或 surface问题均回原静态兜底并记录限频 enum,无超时猜 patch、无音频等待。后台释放 decoder/EGL/GL资源并 fence旧callback;前台重新初始 body/neutral mouth。
|
||||
|
||||
## 复现与工程证据
|
||||
|
||||
```sh
|
||||
python3 scripts/package-avatar-natural.py --import-only
|
||||
python3 scripts/check-reply-regressions.py --suite avatar --runtime-manifest .runtime/avatar-imports/a01-neutral-graph-v1/runtime-03/manifest.json > logs/avatar-natural-061/actual-manifest-tests.txt 2>&1
|
||||
./scripts/check-avatar-regressions.sh
|
||||
/home/ubuntu/miniconda3/envs/gori-speech/bin/python gateway/scripts/check-archive.py --vad-model /home/ubuntu/miniconda3/envs/gori-speech/lib/python3.12/site-packages/silero_vad/data/silero_vad.onnx > logs/avatar-safe-061/gateway-tests.txt 2>&1
|
||||
python3 scripts/package-avatar-natural.py
|
||||
```
|
||||
|
||||
导入逐项核97 PNG/body SHA、尺寸/alpha/bounds、所有 body PTS/CFR和完整解码;实际 manifest 另外编译给 production Kotlin parser 验证。独立 CPU 验证97帧 alpha0 恒等及 alpha.5/1 straight/premul source-over代数;不是 GPU 像素认证。保持已有9 JVM entry points+74 gateway,全编译/验签/badging/精确APK素材清单/未压缩 MP4/HTTP SHA。真实 ContinuousBodyRenderer 也在确定性 Android MediaCodec/EGL doubles 下测帧索引、同次draw/swap、loop、停止时body连续、timestamp/swap/size/timeout失败和释放;doubles不证明硬件decoder/GLES兼容。
|
||||
|
||||
源码/素材/交付 checkpoint 与报告见 ignored `logs/avatar-natural-061/`;APK `artifacts/lan-voice-v061-natural-engineering-arm64-debug.apk`,不覆盖 code12/V060/052/051、不提交肖像 Git、不 commit/push final。
|
||||
|
||||
## 设备离线验证
|
||||
|
||||
```sh
|
||||
adb -s 0123456789ABCDEF install -r lan-voice-v061-natural-engineering-arm64-debug.apk
|
||||
adb -s 0123456789ABCDEF shell am force-stop com.gorios.lanvoice
|
||||
adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity --ez avatar_offline_preview true
|
||||
```
|
||||
|
||||
extra 保留相同精确名;此入口在 VoiceSession/AudioOutputGate/ExpressionController 构建前返回,完全不连WS、不请求权限、不录音不开相机。20s synthetic intent trace+Idle/Talk/Abort/Trace按钮走真实连续body renderer。观察嘴切换时 body/眼睛是否连续,97frame wrap、贴层上下方向/位置、错帧、首帧/黑帧、后台恢复/旋转/Fit、decoder/GLES错误fallback。
|
||||
|
||||
正常桌面启动仍为 foreground自动连接→真实HELLO→MIC/CAMERA权限;已有权限会直接对话和相机分析,请协调首次使用离线命令。拒相机不阻断音频;face-cue分享独立默认off,无背景服务。
|
||||
|
||||
## 未测边界
|
||||
|
||||
body loop seam 自身、头部旋转/缩放使 translation-only嘴层失配、tone/唇影/纹理接缝、Bitmap premul量化、GPU颜色转换/采样、设备短时/长期资源/温度、权限系统弹窗及硬件物理显示时间均待真机。原素材 registration0撞界不代表贴合全通过。authored alpha125–500ms不是 perceived/device latency;250/500ms曲线参数不构成 ≤1s SLA。用户相机人脸仍独立验收,肖像商业权利unverified。
|
||||
@@ -0,0 +1,41 @@
|
||||
# Fixed neutral graph — asset handoff for 0.6.1
|
||||
|
||||
This replaces the failed raw-talk slicing route. The arms reference is the accepted original SHA256 `36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2`. Cleanup and all rejected wide-mouth/sigh-like takes are excluded. The material owner owns `.runtime/avatar-imports/a01-neutral-graph-v1/`; Android work must not write there. Generation is bounded to at most five video calls, estimated total ≤$1.70, with opening/talk1 quality gates first. First/last image constraints are production inputs, not junction approval.
|
||||
|
||||
## Five real nodes and required junctions
|
||||
|
||||
| Node role | Anchors | Runtime operation |
|
||||
|---|---|---|
|
||||
| idle | A→A, closed mouth | independently reviewed loop |
|
||||
| opening | A→B | real opening bridge |
|
||||
| talk1 | B→B | independently reviewed small-articulation loop |
|
||||
| talk2 | B→B | independently reviewed small-articulation loop |
|
||||
| closing | B→A | `end-talk` / `idle-start` are names of this same node/file |
|
||||
|
||||
Required explicit approved transitions: idle→opening; opening→talk1 and →talk2; talk1→talk2 and talk2→talk1; talk1→closing and talk2→closing; closing→idle. In addition, idle, talk1 and talk2 each require their own reviewed self-loop seam. Absence of any junction rejects the complete product graph. Clip IDs can differ from these display names. The role accepts `closing`, `end-talk`, or `idle-start` as aliases; they must not create three different nodes.
|
||||
|
||||
The owner changed the production method after the initial two1s calls (total$0.20) gave opening but insufficient talking articulation. A controlled local mouth layer over common A/B body data is an admissible candidate, not automatic approval. Preserve original AI masters, edited B and B-compositing metadata; disclose the ellipse/feathered mouth mask, mouth/lower-jaw parameters and procedural body-deformation curves per frame. No further paid call or model installation is implied. Zero endpoint velocity is a construction constraint; final pixels and neighboring full-speed motion still need review. Local mouth blending must not conceal whole-face/body cuts or make a static portrait pass as animated idle. Keep semantic small-talk quality and all graph edge/loop gates independent.
|
||||
|
||||
The runtime preselects one legal upcoming talk variant at segment entry and prepares it on the second decoder. Another legal variant is preferred over immediate repetition; only two decoders exist. Stop cancels that hidden continuation and prepares closing. A visible opening may complete through a legal talk entry before closing. Reversal always uses the latest intent and reviewed paths.
|
||||
|
||||
An additional independently reviewed opening→closing B junction is allowed for reversal. It avoids an unnecessary talk node when the latest intention is idle, but does not replace any required junction or loop. Unknown/pending reversal metadata never becomes a shortcut.
|
||||
|
||||
## Delivery fields
|
||||
|
||||
Use `docs/AVATAR_SAFE_TRANSITIONS.md` for the exact safeTransitions v1 schema. Final pack top level: schemaVersion=1, packId=`a01-neutral-graph-v1`, identityId=`a01`, five assets, staticFallbackPath under `frames/`, staticFallbackSha256, source/provenance/rights status. Each asset has id/path/sha256/emotion=`neutral`/intensity=0/hasAudio=false. Runtime paths are `videos/<name>.mp4` or `delivery/<name>.mp4`, never audit-run paths. Keep original source spans and source PTS in separate provenance/review evidence; normalized clips have zero-origin PTS. Never round a candidate into approved metadata.
|
||||
|
||||
Each clip provides durationMs/frameCount/fpsNumerator/fpsDenominator, role, entryAnchors, safeExitWindows, loop/loopSeamReviewStatus/seekReviewStatus/reviewStatus. Intervals use startMs/endMs and startFrame/endFrame, end exclusive. For 24fps preserve exact PTS in evidence and choose integer-ms bounds that actually contain the annotated frame PTS after runtime floor-to-ms conversion. Source and target intervals share a reviewed anchor. This asserts inspected complete-state AND velocity compatibility for all permitted frame pairs, not just matching mouths.
|
||||
|
||||
Also supply `mouthStateWindows` on clips when verified: objects with state=`active` or `closed_stable`, startMs/endMs/startFrame/endFrame/reviewStatus. They record actual small conversational mouth activity and stable mouth closure seen in reviewed frames. They are independent of role/filename/anchor IDs. Missing evidence stays empty and latency stays unknown; transition or loop approval alone cannot manufacture a mouth-completion time. Fields are optional for legacy parsing but required evidence for final graph activation. Do not mark a prolonged open mouth `active` merely to satisfy this field.
|
||||
|
||||
Each junction needs dense face/fullbody/arms/feet-shadow context and full-speed repeats, including self-loops and both talk directions. Check head/eyes/blinks/lips/jaw/body/hands/feet/background/shadow plus motion speed/direction. At least 10s original-speed talk continuation and synthetic cue scenarios must be visually reviewed; no reverse/freeze/retiming/double-face crossfade. Quality and junction approval are separate gates. Until review: safeTransitions pending, approvedEdges=[], safeExits=[]; no invented windows or approved hash.
|
||||
|
||||
## Response budget and acceptance
|
||||
|
||||
Goal ≤1s means intention→observed small mouth activity, and silence/abort→observed stable closed mouth, NOT transition-start time. For natural silence count the actual-playhead detector's 120ms release; abort stops audio immediately and adds no audio wait. Worst-case source-window wait + target preparation (where not already overlapped) + bridge-to-mouth-event + presentation must fit the remaining budget.
|
||||
|
||||
Requested talk 0.4–0.7s and bridges 0.15–0.3s are search preferences, not guarantees. 0.7s wait + 0.3s closing + 0.12s detector =1.12s before decoder/presentation, hence fails. A 0.4–0.55s maximum exit gap plus 0.15–0.2s closing may leave a workable margin; still measure, do not approve from arithmetic alone. Idle exit density is equally necessary. A unique 4s exit fails.
|
||||
|
||||
Trace latest intent time/revision/generation, active source real PTS/frame, approved exit interval, target prepared time, actual reveal, actual mouth event/closed-stable frame, superseded requests and gate-wait reasons. Exercise cue offsets throughout each loop, opening reversal, ongoing talk variant changes, stop/resume, abort, late target, missed windows and background. Unknown/failed endpoints remain null. No PCM, chat, user face images or camera head pose needed.
|
||||
|
||||
Only a coordinator-reviewed exact manifest hash may enter the runtime allowlist. `scripts/import-avatar-graph.py SOURCE --approved-manifest-sha SHA --verify-only` checks bytes without importing; omit verify-only only after the handoff is reviewed. No candidate is currently allowlisted. Original 0.6.0 remains the rollback APK.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Continuous body / registered mouth runtime engineering interface
|
||||
|
||||
仅 debug 自然工程候选,不是五 wholeframe clip graph,不改 pending/final 审核状态。素材 owner 独立导出,Android 不实时 SSD。导出 partial 不算完成;须最后写 manifest,核所有文件 SHA。
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"identityId": "a01",
|
||||
"publishApproval": false,
|
||||
"packId": "a01-neutral-graph-v1-runtime-03",
|
||||
"runtimeReady": true,
|
||||
"patchFormat": {"format": "PNG RGBA 8bit", "alphaEncoding": "straight_unassociated"},
|
||||
"body": {
|
||||
"path": "body/body.mp4", "sha256": "<actual SHA256>",
|
||||
"width": 480, "height": 848, "frameCount": 97,
|
||||
"fpsNumerator": 24, "fpsDenominator": 1,
|
||||
"frameDurationUsNumerator": 1000000, "frameDurationUsDenominator": 24,
|
||||
"durationUs": 4041667, "hasAudio": false
|
||||
},
|
||||
"patches": [
|
||||
{"frameIndex": 0, "ptsUs": 0, "path": "patches/f000.png",
|
||||
"sha256": "<actual SHA256>", "x": 210, "y": 111, "width": 42, "height": 24}
|
||||
],
|
||||
"mouthStates": [
|
||||
{"id": "opening", "durationMs": 250, "frameCount": 6,
|
||||
"fpsNumerator": 24, "fpsDenominator": 1,
|
||||
"entryMouthAnchor": "A", "exitMouthAnchor": "B",
|
||||
"globalAlphaByFrame": [0, 0.0954915, 0.3454915, 0.6545085, 0.9045085, 1]}
|
||||
],
|
||||
"stateRouting": {
|
||||
"idle": ["idle", "opening"],
|
||||
"opening": ["talk1", "talk2", "end-talk"],
|
||||
"talk1": ["talk1", "talk2", "end-talk"],
|
||||
"talk2": ["talk1", "talk2", "end-talk"],
|
||||
"end-talk": ["idle"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上面是字段示例,不是可直接导入的真实数据/批准 hash。mouthStates 必须完整五种:idle12个alpha0;opening6个0→1;talk1/talk2各12个1→1且中间min<.5;end-talk6个1→0。对应500/250ms,不伪增安全审核。patches 需要按真实 frameIndex0..96 完整有序列出;ptsUs=floor(index*1000000/24),容差2us。每帧 RGBA patch 可已烘焙亚像素平移、tone 和空间 mask;x/y 是在480×848 top-left 像素空间的摆放位置,不是 UV,允许有限小数。width/height 1..128,总 decoded RGBA <=8MB,每路径必须唯一。颜色按 sRGB encoded 值混合以复现当前离线 NumPy 算法;不是 linear-light 质量认证。
|
||||
|
||||
runtime 没有静态 loopOrdinal 表:ContinuousFrameClock 检查每个实际 decoded PTS/frame 连续顺序;SurfaceTexture updateTexImage 后核 timestamp,合法完成97帧后 flush/seek0 时 ordinal+1。patch 按 latched index 选,不取 MediaPlayer position。共用一个 EGL window、GLES pass 和 Fit,body OES texture 与 patch 2D texture 原子绘制后 swap;最新 mouth 曲线独立于 body loop,不因 intent seek/restart body。
|
||||
|
||||
Android Bitmap PNG 可能内部 premultiply,因此用 getPixels 提取 straight ARGB,再明确写 RGBA ByteBuffer 上传;shader global alpha g 只乘一次空间 alpha a:out=body*(1-g*a)+patchRGB*(g*a),g=0 完全原 body。所有97个小 patch 仅启动时解码/cache/upload,不每帧 allocate 全身图。音频线程不等待 GL;后台关闭 decoder/EGL/texture,旧 generation callbacks 丢弃。
|
||||
|
||||
必须提供真实 body loop 审核范围、preview/source SHA、方法与风险,仍为工程 candidate;稀疏 safe graph 不伪补 approved。runtime03 可以记录 pending,因为 debug 精确 manifest hash 准入代表本次实验授权,不代表 final quality/1sSLA。实际输出字段若不同,先发送真实 manifest 供适配,不需要覆盖既有包。
|
||||
@@ -0,0 +1,66 @@
|
||||
# Android 0.6.1/code12 — safe neutral graph integration
|
||||
|
||||
Development stage, not a released APK. The user resumed complete Android implementation, self-validation and final packaging. Final activation needs the coordinator's actual material/edge review and exact manifest SHA; no additional per-step user approval is required. The owner is producing `a01-neutral-graph-v1` independently, bounded to five video calls (estimated ≤$1.70). Failed old raw/large-mouth/sigh-like clips must never be substituted. At this stage the allowlist is empty and no graph APK has been packaged, committed, pushed or installed.
|
||||
|
||||
Retain `fdd91234b5910ee18e4a75c24c0a49de596cc4fa` and the existing 0.6.0/code11 artifact unchanged: `artifacts/lan-voice-v060-arm64-debug.apk`, SHA256 `37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e`. 0.5.1/0.5.2 artifacts are retained too. Android may reject a lower version code over a newer installation; no downgrade/data-preservation promise or device data clearing is implied.
|
||||
|
||||
## Implemented behavior
|
||||
|
||||
Foreground entry automatically attempts health→authenticated WS→real server HELLO. Then MIC/CAMERA permission requests are sequential and remembered. No recording before MIC grant and actual foreground. Granted MIC starts voice independently of camera or video readiness; denied camera permits audio. Denied MIC has an explicit authorization/settings action, no automatic prompt loop. Three transport attempts per foreground cycle use 1s/3s backoff, stop on busy and expose manual retry. Transport retry does not generate another LLM reply. Failed voice start is visibly bounded too.
|
||||
|
||||
No dial/hangup or simulated incoming-call UX remains in the screen. Close/background the app to stop. PAUSE stops mic/camera/audio/video and clears face/sharing. A pending system permission may also STOP the Activity: retain only its continuation and fenced socket for at most 30s, never sensors. A genuine STOP disconnects WS; DESTROY releases all resources. Initially muted start is applied before capture; camera-off/denial persists. Explicit camera settings enable intent survives return from settings. Face sharing remains independently default off and clears on camera-off/disconnect/background; camera permission alone never enables sharing or image transmission.
|
||||
|
||||
The single white full-canvas screen uses Fit, preserving complete head/feet and aspect ratio on portrait/landscape/tablets. White system bars and safe insets, a status pill, visible mic/camera status, bounded scrollable controls and expandable details support small screens. Details preserve the real current/previous seven-state reply tags, neutral asset resolution/fallback, face presence/cue, AEC and explicit diagnostics. No happy/sad/etc video is claimed. Existing face model/thresholds/10Hz/TTL/diagnostics are unchanged; face acceptance is separate. Physical layout/font-scale/ROM permission acceptance remains device work.
|
||||
|
||||
## Actual renderer, not just a pure planner
|
||||
|
||||
`SafeTransitionPlanner` consumes only latest generation/revision/turn-scoped desired mouth state. That desired state comes from actual AudioTrack playback-head consumption of 20ms RMS/peak metadata, with the existing bounded 120ms silence/underrun release. Arrival, writes, tts-start and ANSWERING phase never authorize a reveal. Partial writes/cross-block windows/u32 wrap/reset/bounded metadata and drained/abort fences remain. No fixed startup buffer was added; audio never waits for video.
|
||||
|
||||
The fixed five-node contract is idle A→A / opening A→B / talk1 B→B / talk2 B→B / closing B→A. `end-talk` and `idle-start` alias that same closing node/file. The two talk self-loops, both mutual directions, both opening→talk and talk→closing edges, idle→opening and closing→idle must all be reviewed. Missing any required junction rejects complete activation. The planner chooses a legal upcoming variant at segment entry with injectable randomness, preferring the other legal talk over an immediate repeat. Stop cancels its hidden continuation and prepares closing. Opening reversal follows legal short completion/junctions toward the latest idle intent; an old callback cannot restore an old turn's talk. Native audio abort remains immediate.
|
||||
|
||||
`SafeVideoDriver` operates at most two `AnchorVideoPort`s: current clip and one paused upcoming entry. `CodecAnchorVideoPort` uses native MediaExtractor/MediaCodec on a worker looper. It seeks to a preceding sync frame, discards preroll, validates normalized CFR/PTS and renders one output at a time. TextureView's actual latched timestamp must match the submitted codec PTS. The target remains held at its reviewed entry, never an unrelated running phase. A source with another output in flight cannot supply its old texture as a fresh observation.
|
||||
|
||||
A reveal requires the target's verified entry plus a real source displayed frame inside an approved exit, followed by a fresh second source observation and successful planner commit. No timer or expired budget grants a hard cut. Late windows wait for a separately approved loop; ended nonloop clips cannot extend their last-frame window to authorize a late cut. A final-frame hold after a missed nonloop window is an exceptional failed route, not continuous animation or a freeze-based material fix. A loop may wrap only with approved seam metadata. Releasing/restarting epochs fences old source/target/error callbacks. Decode/resource/format/timestamp/timeout failures show a static exception with a retained failure enum and never delay audio. No double-face crossfade, reverse, acceleration or mouth-coordinate camera input is used.
|
||||
|
||||
The controlled local-layer candidate also offers opening→closing for reversal. This optional direct B junction is accepted only if individually reviewed and does not remove any required talk edge. Its shared authored mouth alpha/body deformation and exact raw endpoint pixels are provenance/production constraints, not encoded-edge approval. Authored alpha thresholds alone cannot mark perceived mouthStateWindows approved.
|
||||
|
||||
Prepared targets may require decoder creation repeatedly at short segment boundaries. Two-decoder capacity, TextureView timestamps at PTS0, scheduling/pacing/seek cost, frame drops/black flashes and thermal behavior need actual API31 device validation. Tests with deterministic Android API doubles verify control flow; they cannot certify hardware decoding or seamless motion.
|
||||
|
||||
## Honest response measurements
|
||||
|
||||
Each approved clip may contain reviewed `mouthStateWindows` (`active` / `closed_stable`) with exact frame intervals. Only a displayed frame in those windows completes a measured mouth response. Entering TALK or revealing a clip does not. Missing evidence leaves `mouthActiveLagMs`/`closingLagMs` null and visual wait pending. Logs expose desired/actual clip, requested/selected emotion, finite reason, full pending wait and completed response durations at ≤1Hz, clamped for diagnostic upload. No raw PCM/chat/images/coefficients/error text is added.
|
||||
|
||||
Target ≤1s remains an acceptance goal, not an achieved claim. Natural silence includes 120ms detector release, source-window wait, nonoverlapped preparation, bridge-to-mouth-event and presentation. A 0.7s talk wait +0.3s closing +0.12s release already totals1.12s, so preferred clip ranges alone cannot pass. Opening/closing activity timing, idle exit spacing and full-route latency need actual material traces and device measurement. No exact phoneme/real-person lip sync or 200ms guarantee is claimed.
|
||||
|
||||
## Private asset import and release gate
|
||||
|
||||
Accepted original crossed-arms test reference SHA256: `36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2`. Rights remain unverified; test identity approval is not commercial authorization. It is imported separately as static fallback; no failed video was imported. The complete graph source is `.runtime/avatar-imports/a01-neutral-graph-v1/`, manifest SHA **pending coordinator review**. Reference/source lineage, motion quality, edges, loops, preparation and device acceptance are distinct gates.
|
||||
|
||||
`docs/AVATAR_NEUTRAL_GRAPH_INTERFACE.md` defines the exact handoff/evidence/budget. `SafeAvatarManifest` rejects malformed metadata, returns no runnable graph for pending/unannotated/rejected material, and requires an exact approved SHA allowlist. The runtime additionally verifies five neutral/silent file hashes, all graph paths, full contract completeness and static fallback hash. Unknown pack/decoder failure visibly falls back; it cannot activate archived clips. Original imports remain intact; Gradle excludes old seated/arms-down packs from the new APK.
|
||||
|
||||
Reproduce after obtaining authorized private material out of band:
|
||||
|
||||
```bash
|
||||
python3 scripts/import-standing-avatar.py /path/to/original-arms-reference.png --arms-reference
|
||||
# Only after the coordinator approves actual evidence and supplies the exact final hash:
|
||||
python3 scripts/import-avatar-graph.py /path/to/a01-neutral-graph-v1 --approved-manifest-sha SHA --verify-only
|
||||
python3 scripts/import-avatar-graph.py /path/to/a01-neutral-graph-v1 --approved-manifest-sha SHA
|
||||
./scripts/check-avatar-regressions.sh
|
||||
./scripts/build.sh :app:compileDebugKotlin
|
||||
# Requires matching docs/avatar manifest/review text and runtime SHA allowlist:
|
||||
./scripts/package-avatar-safe-release.sh
|
||||
```
|
||||
|
||||
The importer confines paths/size/hashes, preflights existing bytes and refuses unknown overwrites. Private directories/files use0700/0600. Runtime imports, portraits/videos/logs/APKs remain ignored. Git will contain code, tests, docs and exact text manifest/hash/review only. No portrait binary is committed. A source checkout alone cannot reproduce the private visuals.
|
||||
|
||||
`scripts/package-avatar-safe-release.sh` checks tested-source hashes, all nine JVM entry points, full74 gateway regression, exact reviewed/allowlisted manifest and imported bytes; then builds through the isolated toolchain. It validates0.6.1/code12, arm64/min26/target34, apksigner and identical certificate to0.5.1/0.5.2/0.6.0, exact APK asset bytes and uncompressedMP4, and HTTP APK/checksum bytes. It refuses replacing retained APKs or an existing0.6.1. HTTP revalidation can use `--verify-existing` without rebuilding. Final path will be `artifacts/lan-voice-v061-arm64-debug.apk` plus `.apk.sha256`; no such final artifact exists at this stage.
|
||||
|
||||
## Validation and remaining work
|
||||
|
||||
Use `logs/avatar-safe-061/` for current client/expression/gateway/compile evidence and source hashes. Synthetic planner/driver fixtures use20fps made-up intervals; `synthetic-player-trace.json` is a finite control trace, not footage annotations, real PCM or material approval. Tests cover full graph/missing junctions, seeded continuation, entry/texture gating, missed windows/EOS/wrap, cancel/reversal/abort/old-turn/background, decoder errors/watchdogs, two-port bounds, mouth-event evidence/nulls, Fit aspect, sequential permissions/denials/settings and finite reconnect, plus retained native audio/capture/protocol/face regressions. The74 gateway suite runs temporary source copies with a checksum-verified existing Silero artifact, no service calls or live dialogue inference.
|
||||
|
||||
Before final package: receive reviewed new graph, read real quality/edge/loop/PTS evidence and previews, align normalized paths/windows, record exact manifest/review text, enable its hash, rerun affected checks and compile, then package/commit/push. If opening/talk quality or any junction fails, report the specific missing node/bridge instead of shipping a fake full graph. No extra generation beyond the bounded owner batch is initiated here.
|
||||
|
||||
On the coordinator's existing Windows USB ADB (`-s 0123456789ABCDEF`), install the verified final APK with `install -r` and check package version/signature. This agent does not configure USB/wireless/USBIP/SSH, clear data, launch recording or grant permissions. Device acceptance: first entry/granted/denied/permanently denied/revoked permissions and dialog STOP orders; mic mute; independent camera/share; busy/network failure/retry; voice/PCM silence/underrun/drain/abort; all graph junctions, stop/resume/reversal at varied offsets; actual mouth-response times; background/resume; portrait/landscape/small screen/tablet/large fonts; unsupported decoder/static failure. No new device report or face-recovery claim exists.
|
||||
|
||||
Backend/provider/model/TTS voice parameters, ASR/VAD services and container configuration were not changed or restarted.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Safe avatar transition interface — implementation and synthetic tests, not material approval
|
||||
|
||||
PCM native playback activity provides the latest desired mouth mode. It does not change video visibility. `SafeTransitionPlanner` is a pure state machine with no audio/network dependency. Audio abort and capture stop remain immediate; visual closing uses reviewed edges and may lag. No waiting policy delays audio or adds an audio startup buffer. Neither 200ms nor a 4s visual wait is accepted or claimed.
|
||||
|
||||
## Optional manifest extension
|
||||
|
||||
`SafeAvatarManifest.read(Map, actualManifestSha256, approvedManifestHashes)` supports an optional `schemaVersion:1` extension, `safeTransitions.version:1`. No extension gives LEGACY_UNANNOTATED and no runnable graph. Pending/unknown review gives REVIEW_PENDING and no graph even when times are omitted; inventing intervals to make a candidate parse is forbidden. Malformed approved metadata gives INVALID. Approved metadata needs the coordinator-approved **exact SHA256** allowlist too; by default that list is empty. The current AvatarPack loader performs JSON-to-Map conversion, bounded byte/hash validation and fixed neutral graph completeness checks. The target is a01-neutral-graph-v1; its exact manifest hash allowlist is currently empty. See AVATAR_SAFE_061.md and AVATAR_NEUTRAL_GRAPH_INTERFACE.md for the current integration boundary.
|
||||
|
||||
A minimal honest candidate extension, with no synthetic timestamps:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"reviewStatus": "pending",
|
||||
"anchors": [],
|
||||
"clips": [],
|
||||
"transitions": []
|
||||
}
|
||||
```
|
||||
|
||||
For a reviewed extension the following fields are required:
|
||||
|
||||
| Object | Fields and meaning |
|
||||
|---|---|
|
||||
| Graph | reviewStatus, initialAssetId, initialEntryId, anchors, clips, transitions |
|
||||
| Anchor | id, closedMouth (reviewed entry observation), reviewStatus |
|
||||
| Clip | assetId referencing a declared id/path; role idle/opening/talk/closing/waiting; durationMs, frameCount, fpsNumerator/fpsDenominator; entryAnchors, safeExitWindows; reviewStatus, loop, loopSeamReviewStatus, seekReviewStatus |
|
||||
| Entry/exit interval | id, anchorId, startMs/endMs, startFrame/endFrame, reviewStatus; both ends are **exclusive at end**, frame indices start at0 |
|
||||
| Transition | id, sourceAssetId, sourceWindowId, targetAssetId, targetEntryId, reviewStatus, earliestPolicy=`next_safe_window`, latestPolicy=`next_reviewed_loop` or `hold`, earliestWaitMs, optional latestWaitMs |
|
||||
|
||||
Limits:32 clips,64 anchors,128 edges,32 entries/exits per clip, ≤60s duration and wait budget, ≤3600 frames, bounded safe identifiers and relative paths under videos/frames/delivery. Time/index annotations must agree within frame rounding. Source window and target entry refer to the **same reviewed anchor ID**. A shared ID asserts that **every allowed source/entry frame combination and motion junction** was inspected, not that a single still looked similar. Shorter windows or explicit distinct anchors/edges are necessary if only specific frame pairs match. Frame0 or final frame is not automatically safe. Displayed head/eyes/mouth/body/hands/feet/background/shadow and motion speed/direction all matter.
|
||||
|
||||
Opening and closing are explicit actual clip nodes: idle→opening→talk→closing→idle, only if each junction is approved. No opaque bridgeAssetId shortcut is accepted. An already visible bridge follows a reviewed route for the newest intention; a reversal may require finishing its short path before closing. More poses/idle variations use pre-authored anchor IDs and assets, never the user's camera head pose. No complete emotion/pose cross-product is required. Review state is unknown/pending/approved/rejected; unknowns and rejected edges stay unusable.
|
||||
|
||||
`latestWaitMs` is a **diagnostic budget only**; exceeding it cannot authorize a cut. Clip lengths and budgets are metadata/configuration, never hardcoded4s. `next_reviewed_loop` can retry a missed window only when the source clip and its seam are approved. `hold` refuses to carry the offered edge into another loop. A talk segment cut out of an otherwise continuous source still needs its own approved tail→head loop. Matching first/last stills is insufficient to certify the seam or arbitrary-time transitions.
|
||||
|
||||
## Driver contract
|
||||
|
||||
1. Set a monotonic generation/revision/turn-scoped MouthIntent. Latest valid intent cancels staged old targets/offers. Wrong-turn PCM, old generations/revisions and old callbacks are fenced. Callbacks never write mouth intent. Abort/disconnect/drained desire idle; the legacy hangup planner case desires waiting but the latest UX has no hangup control.
|
||||
2. `tick` consumes fresh actual video positions and actual displayed-frame indices, loop ordinal, serial and continuity status. `ActualClipCursor` only tracks successive actual samples; it requires a separately observed displayedFrame, not a predicted frame. Wrap is recognized only near last/first two frames. Backward jitter, a seek or a gap long enough to miss a loop makes continuity unknown until reset. Position-derived frame estimates alone cannot prove that the target texture is showing that frame.
|
||||
3. On Stage, pause and seek/preload the hidden target at its approved entry. Await **seek completion and a latched displayed texture frame** in the interval. Do not advance an unrelated hidden clip phase. MEDIA_INFO_VIDEO_RENDERING_START alone is inadequate. Actual MediaPlayer/SurfaceTexture seek and texture timestamp behavior, decoder/GOP support, seek cost and target drift must be verified before connecting this contract to production UI.
|
||||
4. An OfferCut is only a proposal. Immediately before revealing, obtain a **second fresh source observation** still inside the same source window/loop and revalidate the paused target. `commit` returning Reveal is the only switch permission. A missed/stale/expired offer yields Hold; do not apply a delayed alpha change or crossfade. Default sample freshness40ms is configurable1–100ms; it is sample validity, not a synchronization SLA.
|
||||
5. A bridge may continue through approved junctions to the latest desired state. No reviewed path means keep the current mode and report NO_REVIEWED_EDGE; no invented closed pose, timeout cut, double-face crossfade or fake loop. An unreviewed loop cannot run forever; the future driver must stop advancing across its seam and report unavailable/hold according to explicit failure UX. Holding a final frame or emergency static fallback is an exception, not a reviewed continuous animation. Background releases immediately and invalidates renderer epochs. Foreground requires a new generation and an explicitly staged, verified neutral startup entry.
|
||||
|
||||
Optional reviewed mouthStateWindows (active/closed_stable with frame/time intervals) measure actual displayed mouth events, independently of role/reveal. Missing events leave completed response latency null; an ongoing wait is never reported as completed closure. Snapshot diagnostics include desired/actual role, generation/revision, finite reason, full pending visual wait, closing-entry lag, pending exit, switch/cancel counts. `TransitionDiagnostics` emits≤1Hz and clamps reported times to60s; snapshots retain full wait for local evaluation. Closing lag measures arrival at a reviewed closed-mouth entry, not a phoneme or every intervening frame. No chat, PCM, images, coefficients or raw error text. Requested reply expression remains separately real; neutral resolved fallback never rewrites it.
|
||||
|
||||
## Current integration boundary and materials
|
||||
|
||||
The planner, strict optional manifest reader, cursor and diagnostics are implemented and tested against **synthetic1s/20fps graph fixtures**, which are not annotations for a01 material. They are now wired to SafeVideoDriver and the native CodecAnchorVideoPort with actual codec PTS/TextureView timestamp gates; deterministic API-double tests cover the adapter, while hardware/device rendering remains pending. The old arbitrary phase-switch renderer has been removed from current code. The latest UI supplies no seated motion pack. No approved safe graph is packaged. Audio/permission UX can therefore be tested independently; visual production completion still requires real reviewed assets and driver/device acceptance.
|
||||
|
||||
a01-v1 original materials and the published0.6.0 APK remain intact. Seated a01-v2, arms-down standing-v3, crossed-arms v2/v3-motion and the single3s raw experiment are archives with no usable approved graph. The latest accepted original crossed-arms reference SHA is36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2. The owner is producing a01-neutral-graph-v1 under the bounded five-call budget; quality gates and actual windows are pending. Do not promote first/last constraints, similarity rankings or static identity approval into safe motion approval.
|
||||
|
||||
Necessary material evidence before integration: accepted reference identity; actual decoded frame/time intervals for each entry/exit; approved edges including real opening/closing bridges if needed; approved idle/talk loop seams and ability to stage entry on target device; short dense ±0.5s junction sequences plus full-speed repeated loops and transitions; explicit latency tradeoff approval if safe exits are sparse. The number/cost of candidates is finite and separately agreed; no additional video generation is initiated here.
|
||||
|
||||
Available archived seated candidate previews (not standing materials):
|
||||
|
||||
- `.runtime/avatar-imports/a01-v2/review/switch-boundary-only-candidate.mp4` — complete-cycle candidate,20s.
|
||||
- `.runtime/avatar-imports/a01-v2/review/switch-boundary-only.gif` — convenience240px/12fps reduction, not acceptance at delivery spec.
|
||||
- `.runtime/avatar-imports/a01-v2/review/boundary-idle-to-talk-dense-24.png`
|
||||
- `.runtime/avatar-imports/a01-v2/review/boundary-talk-to-idle-dense-24.png`
|
||||
- `.runtime/avatar-imports/a01-v2/review/idle-loop-5x.mp4`
|
||||
- `.runtime/avatar-imports/a01-v2/review/talk-loop-3x.mp4`
|
||||
|
||||
Coordinator has local copies under `/mnt/d/baji-vc-install/avatar-review/a01-v2/`. Existing NumPy/Pillow interpreter is `/home/ubuntu/miniconda3/bin/python3`; ffmpeg `/home/ubuntu/gori-bin/ffmpeg`. No installation required. Viewing sampled PNGs or decoding frames does not establish full-speed visual or device approval.
|
||||
@@ -0,0 +1,60 @@
|
||||
# 0.6.2-ui-dev / code14 — clean home UI candidate
|
||||
|
||||
This authorized internal debug APK fixes the app UI over code13. Mouth rendering and all portrait asset bytes remain identical to runtime03; the reported mouth deformation is **not fixed** in this version. It is not a final natural-quality release or a certified ≤1s perceived-mouth response. No backend, provider, TTS, voice, camera model/threshold, system toolchain or service change is included.
|
||||
|
||||
## Home and settings
|
||||
|
||||
Normal and offline entry show a white full-screen Fit avatar and one bottom-right settings gear. The touch target is 48dp plus safe drawing insets. No app title, connection/error strip, candidate banner, emotion/face labels, diagnostic text or mic/camera bar covers the home. System permission dialogs and OS privacy indicators remain visible.
|
||||
|
||||
The scrollable settings bottom sheet holds connection/retry/error and permission information, mic pause/resume, camera control, independent face-cue sharing (default off), current/previous requested emotion and selected neutral fallback, diagnostic report action/results, player diagnostics and candidate limitations. Offline Idle/Talk/Abort/Trace controls also live here. The sheet explicitly states that runtime03 mouth deformation remains unresolved.
|
||||
|
||||
The avatar stays in the same composition slot outside the conditional sheet. Opening or closing the sheet neither keys nor recreates the AndroidView/renderer, changes Activity lifecycle, nor calls the connection/session coordinator. Avatar time and conversation continue while settings are open. On short/landscape/tablet screens the sheet scrolls; the body uses one shared Fit transform without stretching or cropping head/feet.
|
||||
|
||||
Foreground still automatically connects, waits for real server HELLO, then sequentially requests MIC/CAMERA as required. Already granted permissions can immediately start recording/camera analysis. Denied camera permits voice, denied mic starts no recording, asked/denied/off choices prevent prompt loops. Permission pauses stop sensors while retaining bounded connection continuation. Genuine background releases capture/audio/camera/video, clears face/share and disconnects. No background service. Settings permissions/control actions retain these guards.
|
||||
|
||||
## Exact assets and mouth investigation boundary
|
||||
|
||||
Runtime manifest SHA256: `87ad2b2ad0e96fe64943692da363c856939ad4aad57073c589d53130c2f2073c`.
|
||||
Body SHA256: `177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762`.
|
||||
Source: `.runtime/avatar-imports/a01-neutral-graph-v1/runtime-03/`.
|
||||
Accepted test static reference SHA256: `36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2`.
|
||||
All pending natural/device/rights/publish flags are retained. Debug exact-hash admission grants this experiment only. Production motion hash allowlist remains empty. Portrait images/videos, logs and APKs stay ignored in Git.
|
||||
|
||||
The read-only code audit found no proven double-premultiplication, UV inversion or frame-index bug. Bitmap defaults to premultiplied decode, then getPixels yields straight ARGB for explicit RGBA upload. Fragment output is `body*(1-g*a)+patchRGB*(g*a)`, opaque alpha1; fresh EGL context has fixed-function blending disabled. Patch uses GL_LINEAR. Body transform comes from SurfaceTexture; top-left patch coordinates use the logical480×848 quad. One pending decoded output is latched/timestamp-checked and its corresponding patch is composed in the same GLES draw/swap. Both share Fit. No explicit linear-light or sRGB conversion is applied.
|
||||
|
||||
This source audit and CPU export equality do not validate actual Android GPU color/UV/Bitmap output or rule out asset defects. Intermediate opacity mixes two lip anatomies and can ghost; feather sampling/quantization, color mismatch and translation-only registration under rotation/scale remain possible contributors. Runtime04's proposed per-body-frame aperture-level patches are a different parser/shader contract and are not admitted here. No asset directory is overwritten and no mouth alpha is suppressed to hide the issue.
|
||||
|
||||
## Reproduce without committing portrait binaries
|
||||
|
||||
Use the existing private source packs. Import the accepted original arms PNG with `scripts/import-standing-avatar.py --arms-reference <exact-original-PNG>`. Restore controlled01 using `scripts/package-avatar-engineering.py --import-only`; it preserves pending flags and pins manifest `e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09`. Import runtime03 using the command below. Missing, drifted or invalid data stops packaging; on-device invalid/missing runtime falls back to the verified still image, and a missing still produces the clean white canvas with gear. No unsafe pack substitution is allowed.
|
||||
|
||||
```sh
|
||||
/home/ubuntu/miniconda3/bin/python3 scripts/package-avatar-ui.py --import-only
|
||||
python3 scripts/check-reply-regressions.py --suite avatar --runtime-manifest .runtime/avatar-imports/a01-neutral-graph-v1/runtime-03/manifest.json > logs/avatar-062/actual-manifest-tests.txt 2>&1
|
||||
./scripts/check-avatar-regressions.sh
|
||||
/home/ubuntu/miniconda3/envs/gori-speech/bin/python gateway/scripts/check-archive.py --vad-model /home/ubuntu/miniconda3/envs/gori-speech/lib/python3.12/site-packages/silero_vad/data/silero_vad.onnx > logs/avatar-safe-061/gateway-tests.txt 2>&1
|
||||
./scripts/build.sh compileDebugKotlin assembleDebugAndroidTest -PavatarNatural=true -PavatarUiCandidate=true -PnaturalManifestSha=87ad2b2ad0e96fe64943692da363c856939ad4aad57073c589d53130c2f2073c > logs/avatar-062/android-test-compile.txt 2>&1
|
||||
/home/ubuntu/miniconda3/bin/python3 scripts/package-avatar-ui.py
|
||||
```
|
||||
|
||||
The packager requires current source regression hashes, actual production Kotlin manifest parsing, unchanged mouth renderer fingerprints, exact body/97patch hashes/full decode, all74 gateway tests, compiled optional UI instrumentation, package/signature/SDK/ABI and ZIP byte checks. It compares all avatar bytes with retained code13, verifies HTTP APK/checksum bytes and refuses to overwrite an existing artifact. Version0.6.2-ui-dev/code14, min26/target34/arm64-v8a, same existing debug certificate. Baseline051/052/060/code12/code13 remain byte-identical. No store/release signing is used.
|
||||
|
||||
## Validation and physical-device boundary
|
||||
|
||||
Executed checks: nine existing JVM entrypoints including production MediaCodec/EGL renderer under deterministic doubles, current permission/background/auto-entry/mute tests and repeated ACTIVE coordinator drives representing settings recomposition; clean-home source contracts; actual runtime03 production parser; complete Kotlin/Android test APK compile; all74 isolated gateway tests. Clean-home source contracts verify only avatar+gear outside the sheet and that sheet state never keys the renderer/session. These are not an executed Compose UI/instrumentation test or a physical screen assertion.
|
||||
|
||||
An optional platform-only instrumentation probe is compiled in `app/src/androidTest/java/com/gorios/lanvoice/AvatarCleanUiInstrumentation.kt`. It explicitly uses offline mode, checks the accessibility home has no app text and only one48dp gear, opens/closes settings three times while verifying the identical avatar View and renderer instance, checks no VoiceSession/ExpressionController is constructed, and backgrounds the Activity to check renderer release. It captures no screenshots/audio/camera data. It has not run here; coordinator must first confirm the device is online. OEM accessibility, keyboard/navigation insets, real permission dialogs, actual decoder/GLES appearance, performance and user-perceived latency remain untested in this build.
|
||||
|
||||
```sh
|
||||
adb -s 0123456789ABCDEF install -r lan-voice-v062-ui-candidate-arm64-debug.apk
|
||||
adb -s 0123456789ABCDEF shell am force-stop com.gorios.lanvoice
|
||||
adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity --ez avatar_offline_preview true
|
||||
```
|
||||
|
||||
This exact extra returns before constructing session/audio/camera. Open the gear to find synthetic intent controls. For the optional UI probe, after installing `app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk` built by the commands above:
|
||||
|
||||
```sh
|
||||
adb -s 0123456789ABCDEF shell am instrument -w com.gorios.lanvoice.test/com.gorios.lanvoice.AvatarCleanUiInstrumentation
|
||||
```
|
||||
|
||||
Normal launcher entry can activate already-granted MIC/CAMERA after HELLO; use the offline command for sensor-free verification. No automatic installation, permission granting, recording or device-network configuration is performed by this task. User camera/face algorithm acceptance remains separate.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Current avatar UX — clean home in 0.6.2 UI candidate
|
||||
|
||||
The user has resumed complete implementation, self-validation and final APK production. This supersedes both the released0.6.0 dial/hangup design and the intervening development pause. Final motion activation still requires coordinator review of actual material/edges and an exact manifest hash; no repeated per-step user permission is required. Current implementation, limitations and release gate: [AVATAR_SAFE_061.md](AVATAR_SAFE_061.md). Material owner interface: [AVATAR_NEUTRAL_GRAPH_INTERFACE.md](AVATAR_NEUTRAL_GRAPH_INTERFACE.md).
|
||||
|
||||
## Foreground conversation
|
||||
|
||||
RESUMED automatically attempts health→authenticated WS→real HELLO. Only after HELLO request microphone and camera sequentially, once unless explicitly retried. Already granted MIC can start voice immediately, independently of camera/video preparation. Denied camera permits audio; denied MIC starts no capture and exposes authorization/settings. Persist asked/denied/mute/camera-off preferences; no repeated automatic permission prompts.
|
||||
|
||||
CONNECTING / AWAITING_PERMISSION / ACTIVE / ERROR are the page states. Transport retry is finite (three attempts,1s/3s backoff), stops on busy and leaves visible manual Retry. It never requests duplicate LLM generation. No dial/hangup, fake ringing, real-person acceptance claim, account or router UI. Users close/background the app to exit.
|
||||
|
||||
PAUSE stops sensors/audio/video and clears face/sharing. Pending system permission can also cause STOP: retain only continuation and a bounded30s fenced socket, never sensors. Genuine STOP disconnects WS; DESTROY releases. Callbacks arriving while paused cannot start capture. A remembered microphone mute applies before starting capture. Explicit camera settings action retains enable intent on return; denied/user-off camera stays off without such an action. Face-cue sharing is separate, default off and cleared on camera-off/disconnect/background. No images transmitted.
|
||||
|
||||
## Screen
|
||||
|
||||
White full canvas with Fit media and white system bars; preserve complete body/head/feet, no stretching or centerCrop. Home contains only the avatar and one bottom-right48dp settings gear with safe insets. All connection/error states, recording/camera controls, permissions, emotions, diagnostics, candidate warnings and offline controls are inside a scrollable settings sheet. Closing it restores the clean home without restarting player/session. System privacy indicators/dialogs remain visible. Requested current/previous seven-state reply tags stay real; selected neutral asset/fallback stays separate. Details include face presence/cue, AEC and explicit diagnostic report action. No camera model/threshold/TTL or10Hz processing change; face acceptance remains separate.
|
||||
|
||||
Title falls back to 声伴; no private persona data is embedded. No server display-name field is currently consumed. Layout, fonts and OEM/system permission behavior still require physical screen acceptance.
|
||||
|
||||
## Materials and continuity
|
||||
|
||||
Current accepted pose is natural crossed arms, original reference SHA25636a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2. Standing-v2 face revision is lineage, not the latest arms-down animation pose. Cleanup remains unconfirmed and is not the new graph baseline. Static reference approval/test use is separate from rights/commercial use and every animation edge/loop review.
|
||||
|
||||
The only target motion pack is a01-neutral-graph-v1: idle A-A, opening A-B, talk1 B-B, talk2 B-B, end-talk B-A. All required junctions and three self-loops must be reviewed. Failed prior seated/arms-down/arms wide-mouth/raw loops remain archived; never substitute them to ship a video version. Motion graph allowlist is currently empty.
|
||||
|
||||
PCM actual playback-head activity supplies latest mouth intent only. Reviewed source windows and a paused prepared/latching target gate actual reveals. The real codec/driver implementation is tested with Android API doubles; hardware/device acceptance remains pending. Audio never waits for picture. ≤1s mouth activity/closed-stable response needs actual reviewed frame events and full-route measurement, not merely a switch-start timer.
|
||||
|
||||
## Release boundary
|
||||
|
||||
Current UI-only candidate targets0.6.2-ui-dev/code14, retaining runtime03 mouth rendering unchanged; mouth deformation is unresolved. See [AVATAR_UI_062.md](AVATAR_UI_062.md) for exact reproduction and test boundaries. Code12/code13 and retained0.6.0/code11 APK stay byte-identical. Current checks and staged material blockers are recorded in AVATAR_SAFE_061.md and ignored logs/avatar-safe-061/. Final material hash, signature/badging/HTTP checks, commit/push and coordinator Windows USB installation follow actual graph review. No device sensors/install or backend/provider/model/TTS change is performed by this agent.
|
||||
@@ -2,17 +2,18 @@
|
||||
# Production Kotlin with local deterministic media/transport doubles, no real capture.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p logs/avatar-060
|
||||
python3 scripts/check-reply-regressions.py > logs/avatar-060/client-tests.txt 2>&1
|
||||
./scripts/check-expression-rules.sh > logs/avatar-060/expression-tests.txt 2>&1
|
||||
mkdir -p logs/avatar-safe-061
|
||||
python3 scripts/check-reply-regressions.py > logs/avatar-safe-061/client-tests.txt 2>&1
|
||||
./scripts/check-expression-rules.sh > logs/avatar-safe-061/expression-tests.txt 2>&1
|
||||
python3 scripts/check-avatar-ui.py > logs/avatar-safe-061/ui-contract-tests.txt 2>&1
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import hashlib,json
|
||||
root=Path.cwd()
|
||||
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
|
||||
paths += [root/'scripts/check-reply-regressions.py',root/'scripts/check-expression-rules.sh',root/'scripts/check-avatar-regressions.sh']
|
||||
result={'status':'passed','jvm_entry_points':9,'real_device':'pending',
|
||||
paths=list((root/'app/src/main/java').rglob('*.kt'))+list((root/'app/src/androidTest').rglob('*.kt'))+list((root/'tests').rglob('*.kt'))
|
||||
paths += [root/p for p in ('app/build.gradle','scripts/check-reply-regressions.py','scripts/check-expression-rules.sh','scripts/check-avatar-regressions.sh','scripts/check-avatar-ui.py','scripts/import-avatar-graph.py','scripts/package-avatar-safe-release.sh','scripts/package-avatar-safe-release.py','scripts/package-avatar-engineering.py','scripts/package-avatar-natural.py','scripts/package-avatar-ui.py')]
|
||||
result={'status':'passed','jvm_entry_points':9,'uiSourceContracts':'passed','uiDeviceInstrumentation':'not_run','real_device':'pending',
|
||||
'hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(paths)}}
|
||||
(root/'logs/avatar-060/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
(root/'logs/avatar-safe-061/client-tests.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('PASS: nine JVM entry points, including avatar/native-head activity and call lifecycle; no real phone capture')
|
||||
PY
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Clean-home source contracts. Complements compiled UI and optional real-device probe;
|
||||
this does not claim to run Compose or prove device appearance/lifecycle."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt').read_text()
|
||||
# Blank comments/strings without changing offsets, so nested lambdas can be inspected.
|
||||
pattern=r'"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|//[^\n]*|/\*[\s\S]*?\*/'
|
||||
clean=re.sub(pattern,lambda m:' '*len(m[0]),source)
|
||||
|
||||
def block(marker,within=None):
|
||||
start,end=within or (0,len(source))
|
||||
at=clean.index(marker,start,end)
|
||||
left=clean.index('{',at+len(marker),end)
|
||||
depth=1;right=left+1
|
||||
while depth:
|
||||
assert right<end,'Unclosed Kotlin block'
|
||||
depth+=(clean[right]=='{')-(clean[right]=='}');right+=1
|
||||
return left+1,right-1
|
||||
|
||||
def text(span): return source[slice(*span)]
|
||||
def no_calls(span,names):
|
||||
for name in names:
|
||||
assert not re.search(r'\b'+name+r'\s*\(',clean[slice(*span)]),f'Forbidden {name} outside settings'
|
||||
|
||||
scaffold=block('fun CleanAvatarScaffold')
|
||||
home=block('Box(',scaffold)
|
||||
sheet=block('if(settingsOpen)',scaffold)
|
||||
assert text(home).count('avatar()')==1
|
||||
assert text(home).count('IconButton(')==1
|
||||
assert 'Alignment.BottomEnd' in text(home) and 'size(48.dp)' in text(home)
|
||||
assert 'WindowInsets.safeDrawing' in text(home)
|
||||
assert 'settingsOpen=true' in text(home)
|
||||
no_calls(home,['Text','TextButton','Button','OutlinedButton','AvatarDiagnostics','ExpressionControls','settings'])
|
||||
assert 'rememberSaveable { mutableStateOf(false) }' in text(scaffold)
|
||||
assert text(sheet).count('settings()')==1 and text(sheet).count('settingsOpen=false')==2
|
||||
no_calls(sheet,['avatar','AvatarPortrait','ContinuousPortrait','dial','render','startVoice','setContent'])
|
||||
assert 'LaunchedEffect' not in text(scaffold) and 'DisposableEffect' not in text(scaffold)
|
||||
for name in ('CallScreen','EngineeringPreviewScreen'):
|
||||
fn=block('fun '+name)
|
||||
avatar=block('CleanAvatarScaffold(avatar=',fn);settings=block('},settings=',fn)
|
||||
assert text(avatar).count('AvatarPortrait(')==1
|
||||
no_calls(avatar,['Text','AvatarDiagnostics','ExpressionControls','Button','TextButton'])
|
||||
assert 'AvatarDiagnostics(pack,video)' in text(settings)
|
||||
assert 'settingsOpen' not in text(fn)
|
||||
if name=='CallScreen':
|
||||
for expected in ('正在连接','重试连接','permissionMessage','onAuthorizeMic','onMute','onCamera','ExpressionControls','请求表达','onReport'):
|
||||
assert expected in text(settings)
|
||||
else:
|
||||
for expected in ('离线 avatar','Idle','Talk','Abort','Trace'):
|
||||
assert expected in text(settings)
|
||||
for name in ('AvatarPortrait','ContinuousPortrait'):
|
||||
fn=text(block('fun '+name))
|
||||
assert 'remember(pack)' in fn and 'DisposableEffect(view)' in fn
|
||||
assert 'settingsOpen' not in fn
|
||||
activity=(ROOT/'app/src/main/java/com/gorios/lanvoice/MainActivity.kt').read_text()
|
||||
offline=activity[activity.index('if (offlineAvatarPreview) {'):activity.index('audioOutput = AudioOutputGate')]
|
||||
assert 'EngineeringPreviewScreen' in offline and 'return' in offline
|
||||
for forbidden in ('VoiceSession(', 'ExpressionController(', 'permission.launch(', '.dial('): assert forbidden not in offline
|
||||
assert '本版仅修复界面;嘴层沿用 runtime03,变形问题尚未修复' in source
|
||||
print('PASS: clean home has persistent avatar + one 48dp safe-inset gear; normal/offline text and controls are sheet-only; sheet state never keys renderer/session; offline construction bypasses sensors/network. Source contracts only; real-device probe pending.')
|
||||
@@ -3,6 +3,8 @@
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import argparse
|
||||
import json
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CACHE = Path('/home/ubuntu/android-build/gradle-home/caches/modules-2/files-2.1')
|
||||
@@ -25,13 +27,38 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice'
|
||||
suites = [
|
||||
('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
|
||||
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']),
|
||||
('avatar','AvatarCheckKt', [source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
|
||||
('avatar','AvatarCheckKt', [source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
|
||||
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
|
||||
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||
]
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--suite', choices=[name for name, _, _ in suites])
|
||||
parser.add_argument('--runtime-manifest',type=Path,help='Additionally exercise real continuous parser with actual offline manifest metadata')
|
||||
args = parser.parse_args()
|
||||
for name, main, real in suites:
|
||||
if args.suite and name != args.suite: continue
|
||||
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
|
||||
files = list((ROOT/'tests'/name).glob('*.kt')) + real
|
||||
if name == 'avatar' and args.runtime_manifest:
|
||||
def kotlin(value):
|
||||
if value is None: return 'null'
|
||||
if isinstance(value,bool): return str(value).lower()
|
||||
if isinstance(value,str): return json.dumps(value,ensure_ascii=False).replace('$','\\$')
|
||||
if isinstance(value,int): return str(value)+'L'
|
||||
if isinstance(value,float): return repr(value)
|
||||
if isinstance(value,list): return 'listOf<Any?>('+','.join(map(kotlin,value))+')'
|
||||
if isinstance(value,dict): return 'mapOf<String,Any?>('+','.join(kotlin(k)+' to '+kotlin(v) for k,v in value.items())+')'
|
||||
raise TypeError(type(value))
|
||||
import hashlib
|
||||
raw=args.runtime_manifest.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
||||
extra=Path(out)/'ActualRuntimeCheck.kt'
|
||||
extra.write_text('import com.gorios.lanvoice.avatar.*\nfun main() {\nval root='+kotlin(json.loads(raw))+'\n'+
|
||||
'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+
|
||||
'check(pack.patches.size==97 && pack.body.frameCount==97 && pack.curves.size==5)\n'+
|
||||
'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; 97 body/patch frames and five authored curves/routing")\n}\n')
|
||||
files.append(extra)
|
||||
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib',
|
||||
'-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT)
|
||||
subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30)
|
||||
if name == 'avatar' and args.runtime_manifest:
|
||||
subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Import an exact coordinator-reviewed neutral graph; runtime SHA allowlist is independent."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PACK = 'a01-neutral-graph-v1'
|
||||
|
||||
def sha(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('source', type=Path)
|
||||
parser.add_argument('--approved-manifest-sha', required=True)
|
||||
parser.add_argument('--verify-only', action='store_true')
|
||||
args = parser.parse_args()
|
||||
source = args.source.resolve(strict=True)
|
||||
raw = (source/'manifest.json').read_bytes()
|
||||
assert len(raw) <= 256_000
|
||||
assert re.fullmatch('[0-9a-f]{64}', args.approved_manifest_sha)
|
||||
assert sha(raw) == args.approved_manifest_sha, 'Manifest bytes differ from reviewed hash'
|
||||
manifest = json.loads(raw)
|
||||
assert manifest['schemaVersion'] == 1 and manifest['packId'] == PACK and manifest['identityId'] == 'a01'
|
||||
graph = manifest['safeTransitions']
|
||||
assert graph['version'] == 1 and graph['reviewStatus'] == 'approved'
|
||||
assert len(graph['clips']) == 5
|
||||
assert len(manifest['assets']) == 5
|
||||
files = {'manifest.json': raw}
|
||||
|
||||
def read(name, expected, maximum, pattern):
|
||||
assert re.fullmatch(pattern, name), f'Invalid delivery path: {name}'
|
||||
path = (source/name).resolve(strict=True)
|
||||
assert path.is_relative_to(source), 'Path escaped source pack'
|
||||
assert path.stat().st_size <= maximum
|
||||
data = path.read_bytes()
|
||||
assert sha(data) == expected, f'Asset hash mismatch: {name}'
|
||||
assert name not in files
|
||||
files[name] = data
|
||||
|
||||
ids = set()
|
||||
for row in manifest['assets']:
|
||||
assert row['id'] not in ids
|
||||
ids.add(row['id'])
|
||||
assert row['emotion'] == 'neutral' and row['intensity'] == 0 and row['hasAudio'] is False
|
||||
read(row['path'], row['sha256'], 16_000_000, r'(videos|delivery)/[A-Za-z0-9_.-]+\.mp4')
|
||||
assert {row['assetId'] for row in graph['clips']} == ids
|
||||
assert sum(map(len, files.values())) <= 128_000_000
|
||||
read(manifest['staticFallbackPath'], manifest['staticFallbackSha256'], 8_000_000, r'frames/[A-Za-z0-9_.-]+\.png')
|
||||
target = ROOT/'app/src/main/assets/avatar'/PACK
|
||||
# Preflight every existing byte before writing anything. Never erase another pack.
|
||||
for name, data in files.items():
|
||||
dest = target/name
|
||||
assert not dest.exists() or sha(dest.read_bytes()) == sha(data), f'Unknown existing file: {dest}'
|
||||
if not args.verify_only:
|
||||
for name, data in files.items():
|
||||
dest = target/name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.import-', dir=dest.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(data)
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, dest)
|
||||
finally:
|
||||
if os.path.exists(temporary): os.unlink(temporary)
|
||||
print(json.dumps({'pack': PACK, 'manifestSha256': sha(raw), 'imported': not args.verify_only,
|
||||
'runtimeActivation': 'requires exact SHA allowlist plus complete approved graph validation',
|
||||
'rightsStatus': manifest.get('rightsStatus', 'unverified')}, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Import a pinned accepted reference, or review motion bytes without activating them."""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, json, re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STILL_SHA = '5dd89c63879f250d05745b506bb79329aa69171b2f6d1660879af85cea926329'
|
||||
|
||||
def sha(data): return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def review_motion(source):
|
||||
raw=(source/'manifest.json').read_bytes()
|
||||
assert len(raw)<=256000
|
||||
manifest=json.loads(raw)
|
||||
assert manifest['schemaVersion']==1 and manifest['identityId']=='a01'
|
||||
rows=manifest['assets']; assert isinstance(rows,list) and len(rows)<=32
|
||||
total=0
|
||||
for row in rows:
|
||||
name=row['path']; assert re.fullmatch(r'(videos|delivery)/[A-Za-z0-9_.-]+\.mp4',name)
|
||||
path=(source/name).resolve(strict=True); assert path.is_relative_to(source)
|
||||
data=path.read_bytes(); assert len(data)<=16000000 and sha(data)==row['sha256']
|
||||
assert row['emotion']=='neutral' and row['intensity']==0 and row['hasAudio'] is False
|
||||
total+=len(data); assert total<=128000000
|
||||
ext=manifest.get('safeTransitions',{})
|
||||
print(json.dumps({'manifestSha256':sha(raw),'reviewStatus':ext.get('reviewStatus','unknown'),
|
||||
'edgesDeclared':len(ext.get('transitions',[])),'activated':False,
|
||||
'note':'Read-only byte/hash review. No import/approval; runtime allowlist remains explicit and empty until coordinator approval.'},indent=2))
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('source',type=Path)
|
||||
parser.add_argument('--review-motion-only',action='store_true')
|
||||
parser.add_argument('--arms-reference',action='store_true',help='SOURCE is the exact accepted original crossed-arms PNG')
|
||||
args=parser.parse_args(); source=args.source.resolve(strict=True)
|
||||
if args.arms_reference:
|
||||
assert not args.review_motion_only
|
||||
expected='36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2'
|
||||
assert source.is_file() and source.stat().st_size<=8_000_000
|
||||
data=source.read_bytes(); assert sha(data)==expected
|
||||
dest=ROOT/'app/src/main/assets/avatar/a01-standing-arms-reference/frames/reference.png'
|
||||
assert not dest.exists() or sha(dest.read_bytes())==expected, 'Unknown existing static asset'
|
||||
dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
dest.write_bytes(data); dest.chmod(0o600)
|
||||
print(json.dumps({'staticReferenceSha256':expected,'motionActivated':False,'rightsStatus':'unverified'}))
|
||||
return
|
||||
if args.review_motion_only: review_motion(source); return
|
||||
raw=(source/'reference-manifest.json').read_bytes(); manifest=json.loads(raw)
|
||||
assert manifest['schemaVersion']==1 and manifest['packId']=='a01-standing-v2' and manifest['identityId']=='a01'
|
||||
assert manifest['referencePath']=='frames/standing-reference.png' and manifest['sha256']==STILL_SHA
|
||||
image=(source/manifest['referencePath']).resolve(strict=True); assert image.is_relative_to(source)
|
||||
data=image.read_bytes(); assert len(data)<=8000000 and sha(data)==STILL_SHA
|
||||
target=ROOT/'app/src/main/assets/avatar/a01-standing-v2'
|
||||
files={'frames/standing-reference.png':data,'reference-manifest.json':raw}
|
||||
for name,contents in files.items():
|
||||
dest=target/name
|
||||
assert not dest.exists() or sha(dest.read_bytes())==sha(contents),f'Unknown existing asset: {dest}'
|
||||
for name,contents in files.items():
|
||||
dest=target/name; dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
dest.write_bytes(contents); dest.chmod(0o600)
|
||||
print(json.dumps({'pack':'a01-standing-v2','staticIdentityApproval':'user confirmed this exact image for testing',
|
||||
'sha256':STILL_SHA,'motionActivated':False,'rightsStatus':'unverified'},indent=2))
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned controlled01 internal debug experiment. Never grants production approval."""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, json, os, re, subprocess, tempfile, urllib.request, zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT/'.runtime/avatar-imports/a01-neutral-graph-v1'
|
||||
PACK = ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1'
|
||||
LOG = ROOT/'logs/avatar-engineering-061'
|
||||
ARTIFACT = ROOT/'artifacts/lan-voice-v061-engineering-arm64-debug.apk'
|
||||
TOOLS = Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
||||
PIN = 'e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09'
|
||||
OLD = '37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e'
|
||||
sha = lambda data: hashlib.sha256(data).hexdigest()
|
||||
|
||||
def run(args, name):
|
||||
result = subprocess.run(list(map(str,args)),cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||
(LOG/name).write_text(result.stdout)
|
||||
assert result.returncode == 0, f'{args[0]} failed: {LOG/name}'
|
||||
return result.stdout
|
||||
|
||||
def import_pack():
|
||||
raw = (SOURCE/'manifest.json').read_bytes()
|
||||
assert sha(raw) == PIN, 'Authorized manifest drift: stop, do not admit another hash'
|
||||
m = json.loads(raw)
|
||||
assert m['publishApproval'] is False and m['safeTransitions']['reviewStatus'] == 'pending'
|
||||
assert m['naturalQualityStatus'] == 'not_approved' and not m['approvedEdges'] and not m['safeExits']
|
||||
files={'manifest.json':raw}
|
||||
rows=m['assets']; assert len(rows)==5
|
||||
assert {r['id'] for r in rows}=={'idle','opening','talk1','talk2','end-talk'}
|
||||
for row in rows + [m['anchorImages'][0]]:
|
||||
name=row['path']
|
||||
assert name==('controlled-01/delivery/'+row['id']+'.mp4' if row['id']!='A' else 'anchors/A.png')
|
||||
source=(SOURCE/name).resolve(strict=True)
|
||||
assert source.is_relative_to(SOURCE.resolve()) and source.stat().st_size <= 16_000_000
|
||||
data=source.read_bytes(); assert sha(data)==row['sha256']
|
||||
files[name]=data
|
||||
# Preflight every destination; preserve unknown files rather than overwrite them.
|
||||
for name,data in files.items():
|
||||
dest=PACK/name
|
||||
assert not dest.exists() or dest.read_bytes()==data, f'Unknown import at {dest}'
|
||||
for name,data in files.items():
|
||||
dest=PACK/name; dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
if not dest.exists():
|
||||
fd,tmp=tempfile.mkstemp(prefix='.engineering-',dir=dest.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'wb') as stream: stream.write(data)
|
||||
os.chmod(tmp,0o600); os.replace(tmp,dest)
|
||||
finally:
|
||||
if os.path.exists(tmp): os.unlink(tmp)
|
||||
assert (SOURCE/'manifest.json').read_bytes()==raw
|
||||
return m,files
|
||||
|
||||
def decode(m):
|
||||
evidence={}
|
||||
for row in m['assets']:
|
||||
path=PACK/row['path']
|
||||
output=run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',path],f"probe-{row['id']}.json")
|
||||
probe=json.loads(output); assert len(probe['streams'])==1
|
||||
stream=probe['streams'][0]; frames=probe['frames']
|
||||
assert stream['codec_type']=='video' and stream['codec_name']=='h264' and stream['pix_fmt']=='yuv420p'
|
||||
assert stream['width']==480 and stream['height']==848 and stream['r_frame_rate']=='24/1'
|
||||
assert len(frames)==row['frameCount']
|
||||
pts=[float(f['best_effort_timestamp_time']) for f in frames]
|
||||
assert all(abs(t-i/24)<0.00001 for i,t in enumerate(pts))
|
||||
assert frames[0]['key_frame']==1
|
||||
run(['/home/ubuntu/gori-bin/ffmpeg','-hide_banner','-v','error','-xerror','-i',path,'-map','0:v:0','-f','null','-'],f"decode-{row['id']}.txt")
|
||||
evidence[row['id']]={'frames':len(frames),'ptsUs':[round(t*1e6) for t in pts],'sha256':row['sha256'],'entryFrame':0,'exitFrame':m['candidateGraph']['earliestExitFrames'][row['id']]}
|
||||
(LOG/'decode-evidence.json').write_text(json.dumps(evidence,indent=2)+'\n')
|
||||
|
||||
def tested():
|
||||
tests=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||
assert tests['status']=='passed' and tests['jvm_entry_points']==9
|
||||
for name,digest in tests['hashes'].items(): assert sha((ROOT/name).read_bytes())==digest, f'Untested source: {name}'
|
||||
assert re.search(r'Ran 74 tests .*\n\nOK\s*$',(ROOT/'logs/avatar-safe-061/gateway-tests.txt').read_text())
|
||||
assert sha((ROOT/'artifacts/lan-voice-v060-arm64-debug.apk').read_bytes())==OLD
|
||||
loader=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
|
||||
assert 'APPROVED_MOTION_HASHES = emptySet<String>()' in loader
|
||||
assert 'BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING' in loader
|
||||
|
||||
def verify(apk,files):
|
||||
badge=run([TOOLS/'aapt','dump','badging',apk],'badging.txt')
|
||||
for s in ("name='com.gorios.lanvoice'","versionCode='12'","versionName='0.6.1-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
assert s in badge,s
|
||||
assert re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'"
|
||||
signature=run([TOOLS/'apksigner','verify','--verbose','--print-certs',apk],'signature.txt')
|
||||
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
|
||||
cert=re.search(pattern,signature)[1]
|
||||
for version in ('051','052','060'):
|
||||
other=run([TOOLS/'apksigner','verify','--print-certs',ROOT/f'artifacts/lan-voice-v{version}-arm64-debug.apk'],f'signature-{version}.txt')
|
||||
assert re.search(pattern,other)[1]==cert
|
||||
expected={'assets/avatar/a01-neutral-graph-v1/'+n:d for n,d in files.items()}
|
||||
still='assets/avatar/a01-standing-arms-reference/frames/reference.png'
|
||||
data=(ROOT/'app/src/main'/still).read_bytes()
|
||||
assert sha(data)=='36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2'
|
||||
expected[still]=data
|
||||
with zipfile.ZipFile(apk) as z:
|
||||
actual={n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
assert actual==set(expected),f'Unexpected APK avatar assets: {actual-set(expected)}'
|
||||
for name,data in expected.items():
|
||||
assert z.read(name)==data,name
|
||||
if name.endswith('.mp4'): assert z.getinfo(name).compress_type==zipfile.ZIP_STORED
|
||||
return cert
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--import-only',action='store_true')
|
||||
parser.add_argument('--verify-existing',action='store_true')
|
||||
args=parser.parse_args(); LOG.mkdir(parents=True,exist_ok=True)
|
||||
m,files=import_pack()
|
||||
if args.import_only:
|
||||
decode(m); print('PASS: exact pending manifest imported unchanged, five CFR clips fully decoded, final-frame technical gates only'); return
|
||||
tested()
|
||||
if args.verify_existing: assert ARTIFACT.is_file(); cert=verify(ARTIFACT,files)
|
||||
else:
|
||||
assert not ARTIFACT.exists(),'Engineering artifact already exists; do not overwrite'
|
||||
run([ROOT/'scripts/build.sh','assembleDebug','-PavatarEngineering=true'],'assemble.txt')
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk'; cert=verify(built,files)
|
||||
with ARTIFACT.open('xb') as stream: stream.write(built.read_bytes())
|
||||
digest=sha(ARTIFACT.read_bytes()); checksum=f'{digest} {ARTIFACT.name}\n'.encode()
|
||||
sidecar=ARTIFACT.with_suffix('.apk.sha256')
|
||||
assert not sidecar.exists() or sidecar.read_bytes()==checksum
|
||||
sidecar.write_bytes(checksum)
|
||||
url='http://192.168.31.124:8080/'+ARTIFACT.name
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url,timeout=15) as response:
|
||||
data=response.read(); assert response.status==200 and len(data)==ARTIFACT.stat().st_size and sha(data)==digest
|
||||
with opener.open(url+'.sha256',timeout=15) as response: assert response.status==200 and response.read()==checksum
|
||||
assert sha((ROOT/'artifacts/lan-voice-v060-arm64-debug.apk').read_bytes())==OLD
|
||||
result={'scope':'engineering_debug_only','version':'0.6.1-dev','versionCode':12,'apk':str(ARTIFACT),'bytes':ARTIFACT.stat().st_size,'sha256':digest,
|
||||
'url':url,'sameCertificateSha256':cert,'manifestSha256':PIN,'productionApproval':False,'naturalQuality':'not_approved','deviceTests':'pending',
|
||||
'perceivedMouthLatencyMs':None,'compliance1s':'not_measured','httpBytesVerified':True,'gitCommitPush':False}
|
||||
(LOG/'delivery.json').write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned runtime03 natural engineering candidate; no final approval, overwrite or device action."""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, importlib.util, json, os, re, subprocess, tempfile, urllib.request, zipfile
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SOURCE=ROOT/'.runtime/avatar-imports/a01-neutral-graph-v1/runtime-03'
|
||||
PACK=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1/runtime-03'
|
||||
LOG=ROOT/'logs/avatar-natural-061'
|
||||
ARTIFACT=ROOT/'artifacts/lan-voice-v061-natural-engineering-arm64-debug.apk'
|
||||
PIN='87ad2b2ad0e96fe64943692da363c856939ad4aad57073c589d53130c2f2073c'
|
||||
BASELINE='9fcfd258a214be0fbe4a3ebd8141221f078ba0e6af0aaf6955437d725eecf814'
|
||||
TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
||||
sha=lambda data:hashlib.sha256(data).hexdigest()
|
||||
|
||||
def run(args,name):
|
||||
result=subprocess.run(list(map(str,args)),cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||
(LOG/name).write_text(result.stdout)
|
||||
assert result.returncode==0,f'{args[0]} failed: {LOG/name}'
|
||||
return result.stdout
|
||||
|
||||
def import_runtime():
|
||||
raw=(SOURCE/'manifest.json').read_bytes();assert sha(raw)==PIN,'Runtime manifest drift; stop admission'
|
||||
m=json.loads(raw)
|
||||
assert m['runtimeReady'] is True and m['publishApproval'] is False
|
||||
assert m['safeTransitions']['reviewStatus']=='pending' and not m['approvedEdges']
|
||||
assert m['naturalQualityStatus']=='pending' and m['deviceTestStatus']=='pending'
|
||||
body=m['body'];assert body['frameCount']==97 and body['durationUs']==4041667 and body['hasAudio'] is False
|
||||
assert body['width']==480 and body['height']==848 and body['fpsNumerator']==24 and body['fpsDenominator']==1
|
||||
assert m['patchFormat']['alphaEncoding']=='straight_unassociated'
|
||||
files={'manifest.json':raw};patches=m['patches'];assert len(patches)==97
|
||||
size=0
|
||||
for index,row in enumerate([body]+patches):
|
||||
name=row['path']
|
||||
assert re.fullmatch(r'body/[A-Za-z0-9_.-]+\.mp4' if index==0 else r'patches/[A-Za-z0-9_.-]+\.png',name)
|
||||
path=(SOURCE/name).resolve(strict=True);assert path.is_relative_to(SOURCE.resolve())
|
||||
assert path.stat().st_size<16_000_000 if index==0 else path.stat().st_size<256_000
|
||||
data=path.read_bytes();assert sha(data)==row['sha256']
|
||||
assert name not in files;files[name]=data
|
||||
if index:
|
||||
assert row['frameIndex']==index-1 and abs(row['ptsUs']-(index-1)*1000000//24)<=2
|
||||
assert 0<=row['x'] and 0<=row['y'] and row['x']+row['width']<=480 and row['y']+row['height']<=848
|
||||
with Image.open(path) as im:
|
||||
assert im.mode=='RGBA' and im.size==(row['width'],row['height'])
|
||||
size+=row['width']*row['height']*4
|
||||
assert size<=8_000_000
|
||||
for name,data in files.items():
|
||||
dest=PACK/name;assert not dest.exists() or dest.read_bytes()==data,f'Unknown destination: {dest}'
|
||||
for name,data in files.items():
|
||||
dest=PACK/name;dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
if not dest.exists():
|
||||
fd,tmp=tempfile.mkstemp(prefix='.runtime03-',dir=dest.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'wb') as stream:stream.write(data)
|
||||
os.chmod(tmp,0o600);os.replace(tmp,dest)
|
||||
finally:
|
||||
if os.path.exists(tmp):os.unlink(tmp)
|
||||
assert sha((SOURCE/'manifest.json').read_bytes())==PIN
|
||||
return m,files
|
||||
|
||||
def verify_decode(m):
|
||||
body=m['body'];path=PACK/body['path']
|
||||
probe=json.loads(run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',path],'body-probe.json'))
|
||||
assert len(probe['streams'])==1 and len(probe['frames'])==97
|
||||
stream=probe['streams'][0];assert stream['codec_type']=='video' and stream['codec_name']=='h264' and stream['pix_fmt']=='yuv420p'
|
||||
assert stream['width']==480 and stream['height']==848 and stream['r_frame_rate']=='24/1'
|
||||
assert all(abs(float(f['best_effort_timestamp_time'])-i/24)<1e-5 for i,f in enumerate(probe['frames']))
|
||||
run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',path,'-map','0:v:0','-f','null','-'],'body-full-decode.txt')
|
||||
# Stream frames without keeping wholebody frame stacks in memory. Independently
|
||||
# validate exact alpha-zero identity and straight vs premul source-over algebra.
|
||||
process=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(path),'-map','0:v:0','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
checks=[]
|
||||
try:
|
||||
for index,p in enumerate(m['patches']):
|
||||
data=process.stdout.read(480*848*3);assert len(data)==480*848*3
|
||||
bodypixels=np.frombuffer(data,np.uint8).reshape(848,480,3)
|
||||
patch=np.asarray(Image.open(PACK/p['path']).convert('RGBA'),np.float32)/255
|
||||
x,y=p['x'],p['y'];assert isinstance(x,int) and isinstance(y,int)
|
||||
base=bodypixels[y:y+p['height'],x:x+p['width']].astype(np.float32)/255
|
||||
a=patch[:,:,3:4];rgb=patch[:,:,:3]
|
||||
for g in (0,.5,1):
|
||||
straight=base*(1-g*a)+rgb*(g*a)
|
||||
premul=base*(1-g*a)+(rgb*a)*g
|
||||
assert np.max(np.abs(straight-premul))<1e-6
|
||||
if g==0:assert np.array_equal(straight,base)
|
||||
if index in (0,17,34,43,52,78,96):
|
||||
checks.append({'frame':index,'globalAlpha':g,'alphaZeroExactBody':True if g==0 else None,
|
||||
'straightVsPremulMaxDiff':float(np.max(np.abs(straight-premul))),
|
||||
'scope':'CPU algebra only; Android GPU/Bitmap colors and perceived naturalness pending'})
|
||||
assert process.stdout.read(1)==b'';assert process.wait(timeout=20)==0
|
||||
finally:
|
||||
if process.poll() is None:process.kill();process.wait()
|
||||
(LOG/'independent-alpha-checks.json').write_text(json.dumps(checks,indent=2)+'\n')
|
||||
|
||||
def tests_current():
|
||||
tests=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||
assert tests['status']=='passed' and tests['jvm_entry_points']==9
|
||||
for name,h in tests['hashes'].items():assert sha((ROOT/name).read_bytes())==h,f'Untested source: {name}'
|
||||
assert re.search(r'Ran 74 tests .*\n\nOK\s*$',(ROOT/'logs/avatar-safe-061/gateway-tests.txt').read_text())
|
||||
assert PIN in (LOG/'actual-manifest-tests.txt').read_text() and 'PASS: actual exported runtime manifest parsed' in (LOG/'actual-manifest-tests.txt').read_text()
|
||||
assert sha((ROOT/'artifacts/lan-voice-v061-engineering-arm64-debug.apk').read_bytes())==BASELINE
|
||||
assert sha((ROOT/'artifacts/lan-voice-v060-arm64-debug.apk').read_bytes())=='37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e'
|
||||
assert 'APPROVED_MOTION_HASHES = emptySet<String>()' in (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
|
||||
|
||||
def verify(apk,files,version_code=13,version_name='0.6.1-natural-dev'):
|
||||
badge=run([TOOLS/'aapt','dump','badging',apk],'badging.txt')
|
||||
for value in ("name='com.gorios.lanvoice'",f"versionCode='{version_code}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
assert value in badge,value
|
||||
assert re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'"
|
||||
signature=run([TOOLS/'apksigner','verify','--verbose','--print-certs',apk],'signature.txt')
|
||||
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)';cert=re.search(pattern,signature)[1]
|
||||
for suffix in ('051','052','060','061-engineering'):
|
||||
other=run([TOOLS/'apksigner','verify','--print-certs',ROOT/f'artifacts/lan-voice-v{suffix}-arm64-debug.apk'],f'signature-{suffix}.txt')
|
||||
assert re.search(pattern,other)[1]==cert
|
||||
# Keep controlled01 code/data as the existing engineering baseline; verify every
|
||||
# byte without admitting any natural02/03 review demo as a runtime substitute.
|
||||
base=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1'
|
||||
oldraw=(base/'manifest.json').read_bytes();assert sha(oldraw)=='e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09'
|
||||
old=json.loads(oldraw)
|
||||
expected={'assets/avatar/a01-neutral-graph-v1/runtime-03/'+n:d for n,d in files.items()}
|
||||
expected['assets/avatar/a01-neutral-graph-v1/manifest.json']=oldraw
|
||||
for row in old['assets']+[old['anchorImages'][0]]:
|
||||
data=(base/row['path']).read_bytes();assert sha(data)==row['sha256']
|
||||
expected['assets/avatar/a01-neutral-graph-v1/'+row['path']]=data
|
||||
still='assets/avatar/a01-standing-arms-reference/frames/reference.png';data=(ROOT/'app/src/main'/still).read_bytes()
|
||||
assert sha(data)=='36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2';expected[still]=data
|
||||
with zipfile.ZipFile(apk) as z:
|
||||
actual={n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
assert actual==set(expected),f'Unexpected/missing avatar files: {actual^set(expected)}'
|
||||
for name,data in expected.items():
|
||||
assert z.read(name)==data,name
|
||||
if name.endswith('.mp4'):assert z.getinfo(name).compress_type==zipfile.ZIP_STORED
|
||||
return cert
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--import-only',action='store_true');parser.add_argument('--verify-existing',action='store_true')
|
||||
args=parser.parse_args();LOG.mkdir(parents=True,exist_ok=True)
|
||||
m,files=import_runtime()
|
||||
if args.import_only:
|
||||
verify_decode(m);print('PASS: runtime03 exact candidate manifest, body/97 RGBA patch bytes, complete CFR decode, independent alpha-zero/straight-premul algebra');return
|
||||
tests_current()
|
||||
if args.verify_existing:assert ARTIFACT.is_file();cert=verify(ARTIFACT,files)
|
||||
else:
|
||||
assert not ARTIFACT.exists(),'Preserve existing natural engineering artifact; no overwrite'
|
||||
run([ROOT/'scripts/build.sh','assembleDebug','-PavatarNatural=true','-PnaturalManifestSha='+PIN],'assemble.txt')
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';cert=verify(built,files)
|
||||
with ARTIFACT.open('xb') as stream:stream.write(built.read_bytes())
|
||||
digest=sha(ARTIFACT.read_bytes());checksum=f'{digest} {ARTIFACT.name}\n'.encode();side=ARTIFACT.with_suffix('.apk.sha256')
|
||||
assert not side.exists() or side.read_bytes()==checksum;side.write_bytes(checksum)
|
||||
url='http://192.168.31.124:8080/'+ARTIFACT.name;opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url,timeout=15) as response:
|
||||
data=response.read();assert response.status==200 and len(data)==ARTIFACT.stat().st_size and sha(data)==digest
|
||||
with opener.open(url+'.sha256',timeout=15) as response:assert response.status==200 and response.read()==checksum
|
||||
result={'scope':'natural_engineering_candidate_only','version':'0.6.1-natural-dev','versionCode':13,'apk':str(ARTIFACT),'url':url,
|
||||
'bytes':ARTIFACT.stat().st_size,'sha256':digest,'sameCertificateSha256':cert,'manifestSha256':PIN,'httpBytesVerified':True,
|
||||
'productionApproval':False,'naturalQuality':'pending_device_visual_review','bodyLoopSeam':'pending_device_visual_review','actualPerceivedMouthLatencyMs':None,
|
||||
'devicePerf':'not_tested','compliance1s':'not_certified','gitCommitPush':False,'offlineExtra':'avatar_offline_preview'}
|
||||
(LOG/'delivery.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build/verify 0.6.1 only after exact graph review, tests, private import and signature checks."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOGS = ROOT/'logs/avatar-safe-061'
|
||||
TOOLS = Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
||||
ARTIFACT = ROOT/'artifacts/lan-voice-v061-arm64-debug.apk'
|
||||
PACK = ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1'
|
||||
RETAINED_060_SHA = '37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e'
|
||||
|
||||
def sha(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def command(args, log):
|
||||
result = subprocess.run(list(map(str,args)), cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
(LOGS/log).write_text(result.stdout)
|
||||
assert result.returncode == 0, f'{args[0]} failed; see {LOGS/log}'
|
||||
return result.stdout
|
||||
|
||||
def preflight():
|
||||
tests = json.loads((LOGS/'client-tests.json').read_text())
|
||||
assert tests['status'] == 'passed' and tests['jvm_entry_points'] == 9
|
||||
for name, expected in tests['hashes'].items():
|
||||
assert sha((ROOT/name).read_bytes()) == expected, f'Tested source changed: {name}'
|
||||
gateway = (LOGS/'gateway-tests.txt').read_text()
|
||||
assert re.search(r'Ran 74 tests .*\n\nOK\s*$', gateway), 'Full isolated gateway regression required'
|
||||
raw = (ROOT/'docs/avatar/a01-neutral-graph-v1.manifest.json').read_bytes()
|
||||
assert raw == (PACK/'manifest.json').read_bytes(), 'Reviewed text manifest differs from imported bytes'
|
||||
digest = sha(raw)
|
||||
loader = (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
|
||||
allowlist = re.search(r'APPROVED_MOTION_HASHES\s*=\s*setOf\((.*?)\)', loader, re.S)
|
||||
assert allowlist and digest in re.findall(r'"([0-9a-f]{64})"', allowlist[1]), 'Exact reviewed SHA is not allowlisted'
|
||||
manifest = json.loads(raw)
|
||||
assert manifest['packId'] == 'a01-neutral-graph-v1' and manifest['safeTransitions']['reviewStatus'] == 'approved'
|
||||
assert len(manifest['assets']) == 5
|
||||
# The production Kotlin loader also validates completeness; preserve the review
|
||||
# record identifying the exact hash and every actual junction, never self-approve here.
|
||||
review = json.loads((ROOT/'docs/avatar/a01-neutral-graph-v1.review.json').read_text())
|
||||
assert review['manifestSha256'] == digest and review['graphReviewStatus'] == 'approved'
|
||||
assert review['requiredJunctionsReviewed'] is True and review['talkQualityReviewed'] is True
|
||||
subprocess.run(['python3', str(ROOT/'scripts/import-avatar-graph.py'),str(PACK),
|
||||
'--approved-manifest-sha', digest, '--verify-only'],check=True,cwd=ROOT)
|
||||
old = ROOT/'artifacts/lan-voice-v060-arm64-debug.apk'
|
||||
assert sha(old.read_bytes()) == RETAINED_060_SHA, 'Retained 0.6.0 differs'
|
||||
return manifest, digest
|
||||
|
||||
def verify(apk, manifest):
|
||||
badge = command([TOOLS/'aapt','dump','badging',apk],'badging.txt')
|
||||
for value in ("name='com.gorios.lanvoice'","versionCode='12'","versionName='0.6.1'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
assert value in badge, value
|
||||
assert re.search(r'^native-code: (.+)$',badge,re.M)[1].strip() == "'arm64-v8a'"
|
||||
sig = command([TOOLS/'apksigner','verify','--verbose','--print-certs',apk],'signature.txt')
|
||||
pattern = r'Signer #1 certificate SHA-256 digest: (\w+)'
|
||||
for version in ('051','052','060'):
|
||||
retained = ROOT/f'artifacts/lan-voice-v{version}-arm64-debug.apk'
|
||||
output = command([TOOLS/'apksigner','verify','--print-certs',retained],f'signature-{version}.txt')
|
||||
assert re.search(pattern,output)[1] == re.search(pattern,sig)[1], 'Signing certificate mismatch'
|
||||
expected = {'assets/avatar/a01-neutral-graph-v1/manifest.json': (PACK/'manifest.json').read_bytes()}
|
||||
for row in manifest['assets']:
|
||||
data = (PACK/row['path']).read_bytes()
|
||||
assert sha(data) == row['sha256']
|
||||
expected['assets/avatar/a01-neutral-graph-v1/'+row['path']] = data
|
||||
still = manifest['staticFallbackPath']
|
||||
data = (PACK/still).read_bytes()
|
||||
assert sha(data) == manifest['staticFallbackSha256']
|
||||
expected['assets/avatar/a01-neutral-graph-v1/'+still] = data
|
||||
fallback = 'assets/avatar/a01-standing-arms-reference/frames/reference.png'
|
||||
data = (ROOT/'app/src/main'/fallback).read_bytes()
|
||||
assert sha(data) == '36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2'
|
||||
expected[fallback] = data
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
actual = {name for name in archive.namelist() if name.startswith('assets/avatar/') and not name.endswith('/')}
|
||||
assert actual == set(expected), 'Unexpected or missing private avatar assets in APK'
|
||||
for name,data in expected.items():
|
||||
assert archive.read(name) == data, name
|
||||
if name.endswith('.mp4'): assert archive.getinfo(name).compress_type == zipfile.ZIP_STORED
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--preflight-only',action='store_true')
|
||||
parser.add_argument('--verify-existing',action='store_true',help='Verify preserved APK/HTTP again without rebuilding')
|
||||
args = parser.parse_args()
|
||||
LOGS.mkdir(parents=True,exist_ok=True)
|
||||
manifest, manifest_sha = preflight()
|
||||
if args.preflight_only:
|
||||
print('PASS: tested source, exact reviewed graph and private import preflight')
|
||||
return
|
||||
if args.verify_existing:
|
||||
assert ARTIFACT.is_file()
|
||||
verify(ARTIFACT,manifest)
|
||||
else:
|
||||
assert not ARTIFACT.exists(), 'Refuse overwriting 0.6.1 artifact'
|
||||
command([ROOT/'scripts/build.sh'],'assemble.txt')
|
||||
built = ROOT/'app/build/outputs/apk/debug/app-debug.apk'
|
||||
verify(built,manifest)
|
||||
ARTIFACT.parent.mkdir(parents=True,exist_ok=True)
|
||||
with ARTIFACT.open('xb') as stream: stream.write(built.read_bytes())
|
||||
digest = sha(ARTIFACT.read_bytes())
|
||||
sidecar = ARTIFACT.with_suffix('.apk.sha256')
|
||||
checksum = f'{digest} {ARTIFACT.name}\n'.encode()
|
||||
assert not sidecar.exists() or sidecar.read_bytes() == checksum
|
||||
sidecar.write_bytes(checksum)
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
url = None
|
||||
for prefix in ('','artifacts/'):
|
||||
candidate = 'http://192.168.31.124:8080/'+prefix+ARTIFACT.name
|
||||
try:
|
||||
with opener.open(candidate,timeout=15) as response:
|
||||
data = response.read()
|
||||
assert response.status == 200 and len(data) == ARTIFACT.stat().st_size and sha(data) == digest
|
||||
with opener.open(candidate+'.sha256',timeout=15) as response:
|
||||
assert response.status == 200 and response.read() == checksum
|
||||
url = candidate
|
||||
break
|
||||
except Exception: pass
|
||||
assert url, 'APK preserved; matching HTTP unavailable. Use --verify-existing after delivery repair; never rebuild/overwrite.'
|
||||
result = {'version':'0.6.1','versionCode':12,'apk':str(ARTIFACT.relative_to(ROOT)),'sha256':digest,
|
||||
'bytes':ARTIFACT.stat().st_size,'url':url,'httpBytesVerified':True,'manifestSha256':manifest_sha,
|
||||
'sameCertificateAs':['0.5.1','0.5.2','0.6.0'],'deviceTestStatus':'pending',
|
||||
'actualVisualResponse1s':'requires material trace and device measurement'}
|
||||
(LOGS/'release.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Complete reviewed graph only. Never overwrite retained APKs or configure a device.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
source /home/ubuntu/android-build/env.sh
|
||||
python3 scripts/package-avatar-safe-release.py "$@"
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the authorized UI-only internal debug candidate; runtime03 remains unchanged."""
|
||||
from pathlib import Path
|
||||
import argparse, hashlib, importlib.util, json, re, urllib.request, zipfile
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('natural_packaging',ROOT/'scripts/package-avatar-natural.py')
|
||||
natural=importlib.util.module_from_spec(spec);spec.loader.exec_module(natural)
|
||||
LOG=ROOT/'logs/avatar-062';natural.LOG=LOG
|
||||
ARTIFACT=ROOT/'artifacts/lan-voice-v062-ui-candidate-arm64-debug.apk'
|
||||
BASELINE=ROOT/'artifacts/lan-voice-v061-natural-engineering-arm64-debug.apk'
|
||||
BASELINE_SHA='8809ff5c2bec26f229b3c4dd505c54f7a3e02756f33bee4db904f1253b49e0fc'
|
||||
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
|
||||
# Saved code13 source fingerprints: this delivery changes chrome, not mouth rendering.
|
||||
UNCHANGED={
|
||||
'ContinuousBodyRenderer.kt':'4144db91db07585bf066080a251dc40b664775baab33b6267ef1c895d323f0f7',
|
||||
'ContinuousAvatarView.kt':'ff1952f2975902834010c68bc7307e61eb80d2edfe5b4449e99d26577cafb4c4',
|
||||
'ContinuousFramePresenter.kt':'78a2a33ef672d1245bfc5d65d6fd700f22ec190dc0d00b1035140b51514ecc0b',
|
||||
'ContinuousMouth.kt':'19a599297219a312a6600cc46d86b4190ad5a6066754954fcf51d4601bcef3e2',
|
||||
}
|
||||
sha=lambda data:hashlib.sha256(data).hexdigest()
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--import-only',action='store_true')
|
||||
parser.add_argument('--verify-existing',action='store_true')
|
||||
args=parser.parse_args();LOG.mkdir(parents=True,exist_ok=True)
|
||||
assert sha(BASELINE.read_bytes())==BASELINE_SHA,'Code13 baseline drift'
|
||||
for name,digest in UNCHANGED.items():
|
||||
assert sha((ROOT/'app/src/main/java/com/gorios/lanvoice/avatar'/name).read_bytes())==digest,'Unexpected mouth renderer change: '+name
|
||||
m,files=natural.import_runtime()
|
||||
if args.import_only:
|
||||
natural.verify_decode(m)
|
||||
print('PASS: unchanged runtime03 exact manifest/body/97patch hashes, CFR/full decode and independent alpha algebra; no renderer or mouth repair claimed')
|
||||
return
|
||||
natural.tests_current()
|
||||
assert 'PASS: clean home' in (ROOT/'logs/avatar-safe-061/ui-contract-tests.txt').read_text()
|
||||
assert 'BUILD SUCCESSFUL' in (LOG/'android-test-compile.txt').read_text(),'Compile optional device UI probe first'
|
||||
if args.verify_existing:
|
||||
assert ARTIFACT.is_file();built=ARTIFACT
|
||||
else:
|
||||
assert not ARTIFACT.exists(),'Never overwrite an existing delivered candidate'
|
||||
natural.run([ROOT/'scripts/build.sh','assembleDebug','-PavatarNatural=true','-PavatarUiCandidate=true','-PnaturalManifestSha='+natural.PIN],'assemble.txt')
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk'
|
||||
cert=natural.verify(built,files,14,'0.6.2-ui-dev');assert cert==CERT
|
||||
signature=natural.run([natural.TOOLS/'apksigner','verify','--print-certs',BASELINE],'signature-code13.txt')
|
||||
assert CERT in signature
|
||||
with zipfile.ZipFile(built) as new,zipfile.ZipFile(BASELINE) as old:
|
||||
names={n for n in old.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
assert names=={n for n in new.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
assert all(new.read(n)==old.read(n) for n in names),'UI-only APK changed portrait asset bytes'
|
||||
if not args.verify_existing:
|
||||
with ARTIFACT.open('xb') as stream:stream.write(built.read_bytes())
|
||||
digest=sha(ARTIFACT.read_bytes());checksum=f'{digest} {ARTIFACT.name}\n'.encode()
|
||||
side=ARTIFACT.with_suffix('.apk.sha256');assert not side.exists() or side.read_bytes()==checksum
|
||||
side.write_bytes(checksum)
|
||||
url='http://192.168.31.124:8080/'+ARTIFACT.name
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url,timeout=15) as response:
|
||||
data=response.read();assert response.status==200 and len(data)==ARTIFACT.stat().st_size and sha(data)==digest
|
||||
with opener.open(url+'.sha256',timeout=15) as response:assert response.status==200 and response.read()==checksum
|
||||
result={'scope':'ui_only_internal_debug_candidate','version':'0.6.2-ui-dev','versionCode':14,
|
||||
'apk':str(ARTIFACT),'url':url,'bytes':ARTIFACT.stat().st_size,'sha256':digest,
|
||||
'sameCertificateSha256':cert,'manifestSha256':natural.PIN,'httpBytesVerified':True,
|
||||
'mouthChanged':False,'mouthDeformationResolved':False,'naturalQuality':'not_certified',
|
||||
'uiDeviceInstrumentation':'compiled_not_run','devicePerf':'not_tested',
|
||||
'actualGpuUvColor':'not_measured','compliance1s':'not_certified','productionApproval':False,
|
||||
'offlineExtra':'avatar_offline_preview'}
|
||||
(LOG/'delivery.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,68 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
fun checkAutoConversation() {
|
||||
val flow=AutoConversation()
|
||||
check(flow.drive(false,false,false,0).isEmpty()) // not in actual foreground
|
||||
flow.enter()
|
||||
check(flow.drive(false,false,false,0) == listOf(EntryEffect.Connect))
|
||||
check(flow.drive(false,false,false,1).isEmpty()) // duplicate entry/pump never reconnects
|
||||
flow.connection(false,true,2)
|
||||
check(flow.drive(false,false,false,2).isEmpty()) // health/open socket isn't HELLO
|
||||
flow.connection(true,false,10)
|
||||
check(flow.drive(false,false,false,10) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
check(flow.drive(false,false,false,11).isEmpty()) // one dialog at a time
|
||||
flow.leave(); check(flow.permissionPending == EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.CAMERA,true) // wrong callback cannot clear MIC
|
||||
check(flow.permissionPending == EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(flow.drive(true,false,false,12).isEmpty()) // permission result in background starts no sensor
|
||||
flow.enter()
|
||||
check(flow.drive(true,false,false,13) == listOf(EntryEffect.StartVoice,EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
flow.leave(); flow.permissionResult(EntryPermission.CAMERA,true)
|
||||
check(flow.drive(true,true,false,14).isEmpty())
|
||||
flow.enter()
|
||||
check(flow.drive(true,true,false,15) == listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
check(flow.drive(true,true,true,16).isEmpty() && flow.phase == EntryPhase.ACTIVE)
|
||||
flow.cameraOff(); flow.leave(); flow.enter()
|
||||
check(flow.drive(true,true,false,20) == listOf(EntryEffect.StartVoice))
|
||||
// Denial survives reentry and never loops a system permission request.
|
||||
val denied=AutoConversation(); denied.enter(); denied.drive(false,false,false,0); denied.connection(true,false,1)
|
||||
denied.drive(false,false,false,1); denied.permissionResult(EntryPermission.MICROPHONE,false)
|
||||
check(denied.drive(false,false,false,2) == listOf(EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
denied.permissionResult(EntryPermission.CAMERA,false)
|
||||
denied.leave(); denied.enter(); denied.connection(true,false,3)
|
||||
check(denied.drive(false,false,false,3).isEmpty() && denied.phase == EntryPhase.AWAITING_PERMISSION)
|
||||
check(!denied.requestPermission(EntryPermission.MICROPHONE,true)) // UI must open settings
|
||||
check(denied.requestPermission(EntryPermission.MICROPHONE,false))
|
||||
check(denied.drive(false,false,false,4) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
denied.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(denied.drive(true,false,false,5) == listOf(EntryEffect.StartVoice)) // camera refusal does not block audio
|
||||
check(denied.drive(true,false,true,6).isEmpty() && denied.phase == EntryPhase.ACTIVE)
|
||||
// Three finite transport attempts: 1s and 3s backoff; no inference effects.
|
||||
val retry=AutoConversation(); retry.enter(); check(retry.drive(false,false,false,0).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,100); check(retry.phase == EntryPhase.ERROR && retry.retryAtMs == 1100L)
|
||||
check(!retry.retry(101))
|
||||
check(retry.drive(false,false,false,1099).isEmpty())
|
||||
check(retry.drive(false,false,false,1100).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,1200); check(retry.retryAtMs == 4200L)
|
||||
check(retry.drive(false,false,false,4200).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,4300); check(retry.retryAtMs == null && retry.attempts == 3)
|
||||
check(retry.drive(false,false,false,900000).isEmpty())
|
||||
check(retry.retry(900001)); check(retry.drive(false,false,false,900001).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,900002,busy=true)
|
||||
check(retry.retryAtMs == null && retry.drive(false,false,false,910000).isEmpty())
|
||||
retry.leave(); check(retry.drive(true,true,false,1000000).isEmpty())
|
||||
val persisted=AutoConversation(true,true,cameraInitiallyWanted=false); persisted.enter()
|
||||
persisted.drive(true,true,false,0); persisted.connection(true,false,1)
|
||||
check(persisted.drive(true,true,false,1) == listOf(EntryEffect.StartVoice))
|
||||
check(persisted.drive(true,true,false,2).isEmpty() && persisted.phase == EntryPhase.ERROR) // failed audio start isn't retried forever
|
||||
// Opening/closing in-Activity settings has no enter/leave transition or effects.
|
||||
// Recomposition while ACTIVE must never reconnect, restart capture or request permission.
|
||||
val settings=AutoConversation(true,true);settings.enter()
|
||||
settings.drive(true,true,false,0);settings.connection(true,false,1)
|
||||
check(settings.drive(true,true,false,1)==listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
repeat(20) { check(settings.drive(true,true,true,2L+it).isEmpty() && settings.phase==EntryPhase.ACTIVE) }
|
||||
settings.cameraOff();check(settings.drive(true,true,true,30).isEmpty())
|
||||
settings.leave();check(settings.drive(true,true,true,31).isEmpty())
|
||||
println("PASS: automatic foreground connection/real HELLO/sequential permission continuations, denial/settings/camera-off, audio independent of camera/video, finite retry and busy stop, failed audio-start bound; no device permission granted by tests")
|
||||
}
|
||||
+20
-32
@@ -6,16 +6,27 @@ import android.media.MediaPlayer
|
||||
import android.view.TextureView
|
||||
|
||||
fun main() {
|
||||
checkContinuous()
|
||||
checkEngineering()
|
||||
checkSafeDriver()
|
||||
checkCodecPort()
|
||||
checkAutoConversation()
|
||||
checkSafePlanner()
|
||||
checkSafetyManifest()
|
||||
val unannotated = AvatarVideoView(Context(),AvatarPack("idle.mp4","talk.mp4","static.png","waiting.png"))
|
||||
unannotated.render(AvatarMode.IDLE,true); unannotated.render(AvatarMode.TALK,true)
|
||||
check(MediaPlayer.created.isEmpty()) // no implicit hard-cut path for unreviewed metadata
|
||||
unannotated.dispose()
|
||||
val controller = AvatarController()
|
||||
for (emotion in RoleEmotion.entries) for (intensity in if (emotion == RoleEmotion.NEUTRAL) listOf(0) else listOf(1,2)) {
|
||||
val request = ReplyEmotion(emotion, intensity, EmotionSource.MODEL,7L,2)
|
||||
val selected = controller.select(true,request,PlaybackActivity(7,3,true,960,1920))
|
||||
check(selected.mode == AvatarMode.TALK && selected.requestedEmotion == request)
|
||||
check(selected.desiredMode == AvatarMode.TALK && selected.requestedEmotion == request)
|
||||
check(selected.resolvedAssetEmotion == AssetEmotion())
|
||||
check(selected.emotionFallback == (emotion != RoleEmotion.NEUTRAL))
|
||||
check(controller.select(false,request,PlaybackActivity(7,3,true,960,1920)).mode == AvatarMode.WAITING)
|
||||
check(controller.select(true,request,PlaybackActivity(6,2,true,960,1920)).mode == AvatarMode.IDLE)
|
||||
check(controller.select(true,request,null).mode == AvatarMode.IDLE)
|
||||
check(controller.select(false,request,PlaybackActivity(7,3,true,960,1920)).desiredMode == AvatarMode.WAITING)
|
||||
check(controller.select(true,request,PlaybackActivity(6,2,true,960,1920)).desiredMode == AvatarMode.IDLE)
|
||||
check(controller.select(true,request,null).desiredMode == AvatarMode.IDLE)
|
||||
}
|
||||
val call = CallIntent()
|
||||
check(!call.consumeStart(true,true,true))
|
||||
@@ -32,33 +43,10 @@ fun main() {
|
||||
check(call.consumeStart(true,true,true))
|
||||
check(call.dial(false,true)); call.background(); check(!call.pending)
|
||||
|
||||
val view = AvatarVideoView(Context(),AvatarPack("idle.mp4","talk.mp4","static.png","waiting.png"))
|
||||
view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 2)
|
||||
val players = MediaPlayer.created.toList()
|
||||
check(players.all { it.looping && it.volume == 0f })
|
||||
val textures = view.children.filterIsInstance<TextureView>()
|
||||
players.forEach { it.prepared?.invoke(it) }
|
||||
players[0].info?.invoke(players[0],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
view.render(AvatarMode.TALK,true)
|
||||
check(textures.all { it.alpha == 0f }) // first-frame gate, static stays visible
|
||||
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
check(textures[1].alpha == 1f && textures[0].alpha == 0f)
|
||||
repeat(10) { view.render(if (it%2==0) AvatarMode.IDLE else AvatarMode.TALK,true) }
|
||||
check(MediaPlayer.created.size == 2) // switches don't recreate or seek players
|
||||
view.render(AvatarMode.WAITING,true)
|
||||
check(players.all { it.released } && textures.all { it.alpha == 0f })
|
||||
view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 4)
|
||||
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
check(textures.all { it.alpha == 0f }) // stale callbacks can't show old talk
|
||||
val latest = MediaPlayer.created.takeLast(2)
|
||||
latest[0].error?.invoke(latest[0],1,0)
|
||||
check(latest.all { it.released } && textures.all { it.alpha == 0f })
|
||||
view.render(AvatarMode.TALK,true); check(MediaPlayer.created.size == 4) // fail to static for the current run
|
||||
view.render(AvatarMode.IDLE,false); view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 6)
|
||||
view.dispose(); check(MediaPlayer.created.all { it.released })
|
||||
val still = AvatarVideoView(Context(),AvatarPack(fallback="standing.png"))
|
||||
still.render(AvatarMode.TALK,true,5,1)
|
||||
check(MediaPlayer.created.isEmpty()) // metadata absence cannot activate arbitrary switching
|
||||
still.render(AvatarMode.IDLE,false); still.dispose()
|
||||
AvatarVideoView(Context(),null).render(AvatarMode.TALK,true)
|
||||
println("PASS: seven requested labels preserved/neutral resolved fallback, old-turn fence; explicit dial/permission/cancel/background; actual video view two muted loops/first-frame gate/switch reuse/stale callback/failure/static/missing pack/lifecycle")
|
||||
println("PASS: seven requested labels preserved/neutral resolved fallback, old-turn fence; explicit dial/permission/cancel/background; static standing view/missing graph never allocates legacy players")
|
||||
}
|
||||
|
||||
+35
-1
@@ -1,2 +1,36 @@
|
||||
package android.os
|
||||
object SystemClock { fun elapsedRealtime() = System.nanoTime()/1000000 }
|
||||
|
||||
object SystemClock { fun elapsedRealtime() = TestScheduler.now }
|
||||
class Looper { companion object { private val main = Looper(); fun getMainLooper() = main } }
|
||||
class HandlerThread(name: String) { val looper = Looper(); fun start() {} ; fun quitSafely() {} }
|
||||
class Handler(val looper: Looper = Looper.getMainLooper()) {
|
||||
fun post(action: Runnable): Boolean = postDelayed(action,0)
|
||||
fun postDelayed(action: Runnable, delay: Long): Boolean { TestScheduler.add(this,action,delay); return true }
|
||||
fun removeCallbacks(action: Runnable) { TestScheduler.remove(this,action) }
|
||||
fun removeCallbacksAndMessages(token: Any?) { TestScheduler.remove(this,null) }
|
||||
}
|
||||
object TestScheduler {
|
||||
var now = 0L; private set
|
||||
private var serial = 0L
|
||||
private data class Task(val handler: Handler,val action: Runnable,val due: Long,val serial: Long)
|
||||
private val tasks = java.util.PriorityQueue<Task>(compareBy<Task> { it.due }.thenBy { it.serial })
|
||||
fun add(handler: Handler,action: Runnable,delay: Long) { tasks.add(Task(handler,action,now+delay,++serial)) }
|
||||
fun remove(handler: Handler,action: Runnable?) { tasks.removeIf { it.handler === handler && (action == null || it.action === action) } }
|
||||
fun reset() { tasks.clear(); now=0; serial=0 }
|
||||
fun until(limitMs: Long = 10_000,condition: () -> Boolean) {
|
||||
val end=now+limitMs
|
||||
var count=0
|
||||
while (!condition()) {
|
||||
val task=tasks.poll() ?: error("No scheduled task before condition")
|
||||
check(task.due <= end && ++count <= 100_000) { "Scheduler bound exceeded" }
|
||||
now=task.due; task.action.run()
|
||||
}
|
||||
}
|
||||
fun advanceBy(ms: Long) {
|
||||
val end=now+ms; var count=0
|
||||
while (tasks.peek()?.due?.let { it <= end } == true) {
|
||||
val task=tasks.poll(); now=task.due; task.action.run(); check(++count < 100_000)
|
||||
}
|
||||
now=end
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package android.media
|
||||
|
||||
import android.view.Surface
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/** Deterministic API doubles exercise production codec control; no Android decoder claim. */
|
||||
object CodecFixture {
|
||||
var frames=20; var fps=20; var gop=4; var firstPtsUs=0L
|
||||
var timestampOffsetUs=0L; var outputEnabled=true; var configureFails=false
|
||||
var seeks=mutableListOf<Long>(); var releases=0; var flushes=0
|
||||
var rendered=mutableListOf<Long>(); var onRender: ((Long) -> Unit)? = null
|
||||
fun reset() {
|
||||
frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false
|
||||
seeks.clear(); releases=0; flushes=0; rendered.clear(); onRender=null
|
||||
}
|
||||
}
|
||||
class MediaFormat {
|
||||
companion object { const val KEY_MIME="mime"; const val KEY_WIDTH="width"; const val KEY_HEIGHT="height" }
|
||||
fun getString(key: String): String? = "video/avc"
|
||||
fun getInteger(key: String): Int = if (key == KEY_WIDTH) 480 else 848
|
||||
}
|
||||
class MediaExtractor {
|
||||
val trackCount=1; private var frame=0
|
||||
val sampleTime: Long get() = if (frame >= CodecFixture.frames) -1L else CodecFixture.firstPtsUs+frame*1_000_000L/CodecFixture.fps
|
||||
fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) {}
|
||||
fun getTrackFormat(index: Int) = MediaFormat()
|
||||
fun selectTrack(index: Int) {}
|
||||
fun seekTo(time: Long,mode: Int) { CodecFixture.seeks += time; frame=(time*CodecFixture.fps/1_000_000).toInt()/CodecFixture.gop*CodecFixture.gop }
|
||||
fun readSampleData(buffer: ByteBuffer,offset: Int): Int = if (frame >= CodecFixture.frames) -1 else 1
|
||||
fun advance() { frame++ }
|
||||
fun release() {}
|
||||
companion object { const val SEEK_TO_PREVIOUS_SYNC=0 }
|
||||
}
|
||||
class MediaCodec {
|
||||
class BufferInfo { var presentationTimeUs=0L; var flags=0; var size=0 }
|
||||
private data class Output(val pts: Long,val flags: Int,val size: Int)
|
||||
private val queue=java.util.ArrayDeque<Output>(); private var current: Output? = null
|
||||
companion object {
|
||||
const val BUFFER_FLAG_END_OF_STREAM=4
|
||||
fun createDecoderByType(mime: String) = MediaCodec()
|
||||
}
|
||||
fun configure(format: MediaFormat,surface: Surface,crypto: Any?,flags: Int) { check(!CodecFixture.configureFails) }
|
||||
fun start() {}
|
||||
fun dequeueInputBuffer(timeout: Long) = 0
|
||||
fun getInputBuffer(index: Int): ByteBuffer = ByteBuffer.allocate(32)
|
||||
fun queueInputBuffer(index: Int,offset: Int,size: Int,pts: Long,flags: Int) { queue.add(Output(pts+CodecFixture.timestampOffsetUs,flags,size)) }
|
||||
fun dequeueOutputBuffer(info: BufferInfo,timeout: Long): Int {
|
||||
if (!CodecFixture.outputEnabled || queue.isEmpty()) return -1
|
||||
val out=queue.removeFirst(); current=out
|
||||
info.presentationTimeUs=out.pts; info.flags=out.flags; info.size=out.size
|
||||
return 0
|
||||
}
|
||||
fun releaseOutputBuffer(index: Int,render: Boolean) {
|
||||
if (render) { val pts=checkNotNull(current).pts; CodecFixture.rendered += pts; CodecFixture.onRender?.invoke(pts) }
|
||||
}
|
||||
fun flush() { queue.clear(); CodecFixture.flushes++ }
|
||||
fun stop() {}
|
||||
fun release() { CodecFixture.releases++ }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.content.Context
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.CodecFixture
|
||||
import android.os.*
|
||||
import android.view.Surface
|
||||
|
||||
private class CodecRig(val clip: SafeAvatarClip = syntheticGraph().clips.getValue("idle"),
|
||||
val entry: AnchorInterval = clip.entryAnchors.single(), latch: Boolean = true, wrongTimestamp: Boolean = false) {
|
||||
val port = CodecAnchorVideoPort(Context(),Surface(SurfaceTexture()),"fixture/",Looper()) { w,h -> check(w==480 && h==848) }
|
||||
val frames=mutableListOf<DisplayedVideoFrame>(); val failures=mutableListOf<VideoFailure>()
|
||||
var ended=0; var autoAdvance=false
|
||||
init {
|
||||
if (latch) CodecFixture.onRender = { pts -> Handler().post {
|
||||
port.textureLatched(pts*1000 + if (wrongTimestamp) 10_000 else 0)
|
||||
} }
|
||||
port.prepare(clip,entry,object : AnchorVideoPort.Listener {
|
||||
override fun frame(frame: DisplayedVideoFrame) { frames += frame; if (autoAdvance) port.advance() }
|
||||
override fun ended() { ended++ }
|
||||
override fun failed(reason: VideoFailure) { failures += reason }
|
||||
})
|
||||
}
|
||||
fun first() { TestScheduler.until { frames.isNotEmpty() || failures.isNotEmpty() } }
|
||||
fun close() { port.close(); TestScheduler.advanceBy(10) }
|
||||
}
|
||||
fun checkCodecPort() {
|
||||
fun reset() { TestScheduler.reset(); CodecFixture.reset() }
|
||||
reset()
|
||||
val idle=syntheticGraph().clips.getValue("idle")
|
||||
val entry=AnchorInterval("mid","closed",450,500,9,10,AnchorReview.APPROVED)
|
||||
val staged=CodecRig(idle,entry); staged.first()
|
||||
check(staged.frames.single().frame==9 && CodecFixture.seeks.single()==450_000L)
|
||||
check(CodecFixture.rendered==listOf(450_000L)) // preroll outputs discarded until entry
|
||||
TestScheduler.advanceBy(1_000); check(staged.frames.size==1) // hidden phase never advances
|
||||
val before=SystemClock.elapsedRealtime(); staged.port.advance()
|
||||
check(staged.port.displayed()==null) // old texture is not a fresh sample during flight
|
||||
TestScheduler.until { staged.frames.size==2 }
|
||||
check(SystemClock.elapsedRealtime()-before >= 50 && staged.frames.last().frame==10)
|
||||
staged.autoAdvance=true; staged.port.advance()
|
||||
TestScheduler.until { staged.frames.any { it.loop==1L } }
|
||||
check(staged.frames.last().frame==0 && CodecFixture.flushes==1 && staged.failures.isEmpty())
|
||||
staged.close(); val n=staged.frames.size; staged.port.textureLatched(0); TestScheduler.advanceBy(100)
|
||||
check(staged.frames.size==n && CodecFixture.releases==1)
|
||||
|
||||
reset(); CodecFixture.fps=24; CodecFixture.frames=12
|
||||
val c24=idle.copy(durationMs=500,frameCount=12,fpsNumerator=24,
|
||||
entryAnchors=listOf(AnchorInterval("entry","closed",0,42,0,1,AnchorReview.APPROVED)),
|
||||
safeExitWindows=listOf(AnchorInterval("exit","closed",458,500,11,12,AnchorReview.APPROVED)),mouthStateWindows=emptyList())
|
||||
val fps24=CodecRig(c24); fps24.autoAdvance=true; fps24.first()
|
||||
TestScheduler.until { fps24.frames.any { it.loop==1L } }
|
||||
check(fps24.frames.take(12).map { it.frame }==(0..11).toList() && fps24.failures.isEmpty())
|
||||
check(fps24.frames[11].positionMs==458L)
|
||||
fps24.close()
|
||||
|
||||
reset(); val bridge=CodecRig(syntheticGraph().clips.getValue("opening")); bridge.autoAdvance=true; bridge.first()
|
||||
TestScheduler.until { bridge.ended==1 }
|
||||
check(bridge.frames.size==20 && bridge.frames.last().frame==19 && CodecFixture.flushes==0)
|
||||
check(bridge.port.displayed()?.frame==19); bridge.close()
|
||||
|
||||
reset(); val timestamp=CodecRig(wrongTimestamp=true); timestamp.first()
|
||||
check(timestamp.failures==listOf(VideoFailure.TIMESTAMP)); timestamp.close()
|
||||
reset(); val noLatch=CodecRig(latch=false)
|
||||
TestScheduler.until { noLatch.failures.isNotEmpty() }
|
||||
check(noLatch.failures==listOf(VideoFailure.FRAME_TIMEOUT)); noLatch.close()
|
||||
reset(); CodecFixture.outputEnabled=false; val stuck=CodecRig()
|
||||
TestScheduler.until { stuck.failures.isNotEmpty() }
|
||||
check(stuck.failures==listOf(VideoFailure.FRAME_TIMEOUT)); stuck.close()
|
||||
reset(); CodecFixture.configureFails=true; val resource=CodecRig(); resource.first()
|
||||
check(resource.failures==listOf(VideoFailure.DECODE)); resource.close()
|
||||
reset(); CodecFixture.firstPtsUs=50_000; val origin=CodecRig(); origin.first()
|
||||
check(origin.failures==listOf(VideoFailure.DECODE)); origin.close()
|
||||
reset(); CodecFixture.timestampOffsetUs=10_000; val cfr=CodecRig(); cfr.first()
|
||||
check(cfr.failures==listOf(VideoFailure.FORMAT)); cfr.close()
|
||||
reset(); CodecFixture.frames=10; val truncated=CodecRig(); truncated.autoAdvance=true; truncated.first()
|
||||
TestScheduler.until { truncated.failures.isNotEmpty() }
|
||||
check(truncated.failures==listOf(VideoFailure.FORMAT)); truncated.close()
|
||||
reset(); val canceled=CodecRig(); canceled.close(); TestScheduler.advanceBy(10_000)
|
||||
check(canceled.frames.isEmpty() && canceled.failures.isEmpty())
|
||||
println("PASS: production codec control with deterministic Android API doubles: seek/preroll, latched entry/held phase, in-flight sample fence, frame pacing, approved wrap, nonloop tail, timestamp/decode/resource/early-EOS errors, watchdogs and canceled callbacks; hardware decoder/device pending")
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.content.Context
|
||||
import android.graphics.*
|
||||
import android.media.CodecFixture
|
||||
import android.opengl.GLFixture
|
||||
import android.os.TestScheduler
|
||||
import android.view.Surface
|
||||
|
||||
private val runtimeSha="b".repeat(64)
|
||||
fun continuousFixture(): Map<String,Any?> {
|
||||
val ids=listOf("idle","opening","talk1","talk2","end-talk")
|
||||
return mapOf("schemaVersion" to 1,"packId" to "a01-neutral-graph-v1-runtime-03","identityId" to "a01","publishApproval" to false,"runtimeReady" to true,
|
||||
"body" to mapOf("path" to "body/idle.mp4","sha256" to runtimeSha,"width" to 480,"height" to 848,"frameCount" to 97,
|
||||
"durationUs" to 4041667,"fpsNumerator" to 24,"fpsDenominator" to 1,"hasAudio" to false,
|
||||
"frameDurationUsNumerator" to 1000000,"frameDurationUsDenominator" to 24),
|
||||
"patchFormat" to mapOf("format" to "PNG RGBA 8bit","alphaEncoding" to "straight_unassociated"),
|
||||
"patches" to (0..96).map { mapOf("frameIndex" to it,"ptsUs" to it*1000000L/24,"path" to "patches/$it.png","sha256" to runtimeSha,
|
||||
"x" to 211,"y" to 112,"width" to 40,"height" to 22) },
|
||||
"mouthStates" to ids.map { id ->
|
||||
val bridge=id in setOf("opening","end-talk")
|
||||
val alpha=when(id) {
|
||||
"idle" -> List(12) { 0f }
|
||||
"opening" -> listOf(0f,.1f,.35f,.65f,.9f,1f)
|
||||
"end-talk" -> listOf(1f,.9f,.65f,.35f,.1f,0f)
|
||||
else -> listOf(1f,.8f,.4f,.1f,.4f,.8f,.8f,.4f,.1f,.4f,.8f,1f)
|
||||
}
|
||||
mapOf("id" to id,"durationMs" to if(bridge) 250 else 500,"frameCount" to alpha.size,"fpsNumerator" to 24,"fpsDenominator" to 1,
|
||||
"entryMouthAnchor" to if(id in setOf("idle","opening")) "A" else "B",
|
||||
"exitMouthAnchor" to if(id in setOf("idle","end-talk")) "A" else "B","globalAlphaByFrame" to alpha)
|
||||
},"stateRouting" to mapOf("idle" to listOf("idle","opening"),"opening" to listOf("talk1","talk2","end-talk"),
|
||||
"talk1" to listOf("talk1","talk2","end-talk"),"talk2" to listOf("talk1","talk2","end-talk"),"end-talk" to listOf("idle")))
|
||||
}
|
||||
fun continuousPack(): ContinuousAvatarPack = checkNotNull(ContinuousAvatarManifest.read(continuousFixture(),runtimeSha,runtimeSha,true,"runtime/"))
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkContinuous() {
|
||||
val root=continuousFixture();val pack=continuousPack()
|
||||
check(ContinuousAvatarManifest.read(root,runtimeSha,runtimeSha,false,"runtime/")==null)
|
||||
check(ContinuousAvatarManifest.read(root,"c".repeat(64),runtimeSha,true,"runtime/")==null)
|
||||
fun invalid(r: Map<String,Any?>) { check(ContinuousAvatarManifest.read(r,runtimeSha,runtimeSha,true,"runtime/")==null) }
|
||||
val patches=root["patches"] as List<Map<String,Any?>>
|
||||
for(c in listOf(mapOf("x" to -1),mapOf("x" to 479),mapOf("width" to 129),mapOf("path" to "../secret.png"),mapOf("ptsUs" to 90000),mapOf("frameIndex" to 2),mapOf("y" to Double.NaN)))
|
||||
invalid(root+("patches" to listOf(patches.first()+c)+patches.drop(1)))
|
||||
invalid(root+("patches" to patches.drop(1)))
|
||||
invalid(root+("publishApproval" to true))
|
||||
invalid(root+("patchFormat" to mapOf("format" to "PNG RGBA 8bit","alphaEncoding" to "premultiplied")))
|
||||
val routing=root["stateRouting"] as Map<String,Any?>
|
||||
invalid(root+("stateRouting" to routing+("end-talk" to listOf("talk1"))))
|
||||
val states=root["mouthStates"] as List<Map<String,Any?>>
|
||||
invalid(root+("mouthStates" to listOf(states.first()+("globalAlphaByFrame" to List(12){1f}))+states.drop(1)))
|
||||
|
||||
val mouth=ContinuousMouth(pack.curves) {0}
|
||||
check(mouth.sample(0).alpha==0f)
|
||||
check(mouth.request(true,1,1));check(mouth.sample(100).phase=="opening")
|
||||
check(!mouth.request(false,0,99));check(!mouth.request(false,1,1))
|
||||
check(mouth.sample(350).phase=="talk1")
|
||||
check(mouth.sample(850).phase=="talk2")
|
||||
check(mouth.request(false,2,1));check(!mouth.request(true,1,999))
|
||||
check(mouth.sample(1000).phase=="talk2") // stop finishes current small unit
|
||||
check(mouth.sample(1350).phase=="end-talk")
|
||||
check(mouth.request(true,2,2))
|
||||
check(mouth.sample(1500).phase=="end-talk")
|
||||
check(mouth.sample(1600).phase=="opening" && mouth.sample(1600).alpha==0f)
|
||||
val reversal=ContinuousMouth(pack.curves){0}
|
||||
reversal.request(true,1,1);reversal.sample(0);reversal.request(false,1,2)
|
||||
check(reversal.sample(250).phase=="end-talk");check(reversal.sample(500).phase=="idle")
|
||||
val seed=kotlin.random.Random(7);val random=ContinuousMouth(pack.curves,seed::nextInt)
|
||||
random.request(true,1,1);random.sample(0);var last=""
|
||||
repeat(20) { val p=random.sample(250+it*500L).phase;check(p in setOf("talk1","talk2") && p!=last);last=p }
|
||||
|
||||
val gate=ContinuousFramePresenter(pack){0};gate.intent(true,1,1)
|
||||
val observed=mutableListOf<ComposedBodyFrame>()
|
||||
repeat(2) { loop ->
|
||||
repeat(97) { index ->
|
||||
val pts=index*1_000_000L/24;gate.decoded(pts)
|
||||
gate.present(pts*1000,(loop*97L+index)*42) { observed+=it }
|
||||
check(observed.last().key==BodyFrameKey(index,loop.toLong(),pts))
|
||||
check(observed.last().patch.frameIndex==index)
|
||||
if(index==20) gate.intent(false,2,1)
|
||||
}
|
||||
gate.wrap()
|
||||
}
|
||||
gate.close();check(gate.present(0,9000){ error("stale callback drawn") }==null)
|
||||
check(runCatching { ContinuousFrameClock().decoded(41666) }.isFailure)
|
||||
val clock=ContinuousFrameClock();clock.decoded(0)
|
||||
check(runCatching { clock.latched(9999999) }.isFailure)
|
||||
check(runCatching { ContinuousFrameClock().wrap() }.isFailure)
|
||||
for((w,h) in listOf(480 to 848,1080 to 1920,1920 to 1080,800 to 1280,1200 to 800)) {
|
||||
val rect=bodyFit(w,h);check(rect.left>=0 && rect.top>=0 && rect.width<=w+.01f && rect.height<=h+.01f)
|
||||
check(kotlin.math.abs(rect.width/rect.height-480f/848)<.0001f)
|
||||
}
|
||||
val p=pack.patches.first();check(patchUv(p.x+20,p.y+11,p)==(.5f to .5f));check(patchUv(p.x-1,p.y,p)==null)
|
||||
for(b in listOf(0f,.123f,1f)) for(a in listOf(0f,.5f,1f)) check(composeMouthChannel(b,.8f,a,0f)==b)
|
||||
check(kotlin.math.abs(composeMouthChannel(.2f,.8f,.5f,.5f)-.35f)<.00001)
|
||||
checkContinuousRenderer(pack)
|
||||
println("PASS: continuous runtime strict hash/bounds/97frame/routing/alpha parser; independent mouth state/latest generation/abort/reversal/random continuation; actual decoded-latched frame+loop indexing; Fit/patch mapping/alpha-zero; atomic presenter lifecycle and failure fences")
|
||||
}
|
||||
private fun checkContinuousRenderer(pack: ContinuousAvatarPack) {
|
||||
fun reset() { TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false;CodecFixture.frames=97;CodecFixture.fps=24 }
|
||||
fun rig(): Triple<ContinuousBodyRenderer,MutableList<ComposedBodyFrame>,MutableList<String>> {
|
||||
val frames=mutableListOf<ComposedBodyFrame>();val errors=mutableListOf<String>()
|
||||
CodecFixture.onRender={ pts -> SurfaceTexture.lastCreated?.emit(pts*1000) }
|
||||
val renderer=ContinuousBodyRenderer(Context(),pack,Surface(SurfaceTexture()),1080,1920,{f,_->frames+=f},{errors+=it})
|
||||
return Triple(renderer,frames,errors)
|
||||
}
|
||||
reset();val (renderer,frames,errors)=rig()
|
||||
renderer.intent(true,1,1);TestScheduler.advanceBy(2000);renderer.intent(false,2,1)
|
||||
TestScheduler.advanceBy(2500)
|
||||
check(errors.isEmpty() && frames.size>97 && frames[97].key.index==0 && frames[97].key.loopOrdinal==1L)
|
||||
check(GLFixture.swaps==frames.size && GLFixture.draws==frames.size)
|
||||
check(frames.map { it.key.index+1 }==GLFixture.rendered.map { it.first })
|
||||
check(frames.last().mouth.phase=="idle")
|
||||
val before=frames.size;renderer.close();TestScheduler.advanceBy(1000)
|
||||
check(frames.size==before && CodecFixture.releases==1 && GLFixture.deleted==98 && GLFixture.terminated==1)
|
||||
reset();val (timestamp,_,timestampErrors)=rig();CodecFixture.onRender={pts->SurfaceTexture.lastCreated?.emit(pts*1000+100000)}
|
||||
TestScheduler.advanceBy(100);check(timestampErrors.size==1);timestamp.close()
|
||||
reset();GLFixture.swapFails=true;val (swap,swapFrames,swapErrors)=rig();TestScheduler.advanceBy(100)
|
||||
check(swapFrames.isEmpty() && swapErrors.size==1 && CodecFixture.releases==1);swap.close()
|
||||
reset();BitmapFactory.wrongSize=true;val (size,sizeFrames,sizeErrors)=rig();TestScheduler.advanceBy(100)
|
||||
check(sizeFrames.isEmpty() && sizeErrors.size==1);size.close();BitmapFactory.wrongSize=false
|
||||
reset();CodecFixture.onRender=null;val (timeout,_,timeoutErrors)=rig();CodecFixture.onRender=null
|
||||
TestScheduler.advanceBy(2100);check(timeoutErrors.size==1);timeout.close()
|
||||
reset();val (cancel,cancelFrames,_)=rig();cancel.close();TestScheduler.advanceBy(100)
|
||||
check(cancelFrames.isEmpty())
|
||||
println("PASS: real ContinuousBodyRenderer with deterministic Android MediaCodec/EGL doubles: one atomic draw/swap per decoded+latched body frame, 97frame wrap, patch selection, stop body continuity, timestamp/swap/size/timeout failures and resource teardown; actual GPU/device pending")
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private class TestPort : AnchorVideoPort {
|
||||
private lateinit var listener: AnchorVideoPort.Listener
|
||||
private var held: DisplayedVideoFrame? = null
|
||||
private var serial=0L
|
||||
override fun prepare(clip: SafeAvatarClip, entry: AnchorInterval, listener: AnchorVideoPort.Listener) { this.listener=listener }
|
||||
fun frame(ms: Long, index: Int) { held=DisplayedVideoFrame(ms,index,0,++serial); listener.frame(checkNotNull(held)) }
|
||||
override fun displayed()=held
|
||||
override fun advance() { held=null }
|
||||
override fun close() { held=null }
|
||||
}
|
||||
|
||||
fun engineeringFixture(): Map<String,Any?> {
|
||||
val ids=listOf("idle","opening","talk1","talk2","end-talk")
|
||||
val rows=ids.map { id ->
|
||||
val bridge=id in setOf("opening","end-talk")
|
||||
mapOf("id" to id,"path" to "controlled-01/delivery/$id.mp4","frameCount" to if(bridge) 6 else 12,
|
||||
"durationMs" to if(bridge) 250.0 else 500.0,"fpsNumerator" to 24,"fpsDenominator" to 1,
|
||||
"width" to 480,"height" to 848,"hasAudio" to false,
|
||||
"entryAnchor" to if(id in setOf("idle","opening")) "A" else "B",
|
||||
"exitAnchor" to if(id in setOf("idle","end-talk")) "A" else "B")
|
||||
}
|
||||
val pairs=listOf("idle" to "idle","idle" to "opening","opening" to "talk1","opening" to "talk2",
|
||||
"opening" to "end-talk","talk1" to "talk1","talk1" to "talk2","talk2" to "talk1",
|
||||
"talk2" to "talk2","talk1" to "end-talk","talk2" to "end-talk","end-talk" to "idle")
|
||||
return mapOf("schemaVersion" to 1,"packId" to "a01-neutral-graph-v1-controlled-01","identityId" to "a01",
|
||||
"publishApproval" to false,"naturalQualityStatus" to "not_approved",
|
||||
"safeTransitions" to mapOf("version" to 1,"reviewStatus" to "pending","transitions" to emptyList<Any>()),"assets" to rows,
|
||||
"candidateGraph" to mapOf("exitPolicy" to "complete_candidate_node_at_shared_rendered_anchor",
|
||||
"earliestExitFrames" to ids.associateWith { if(it in setOf("opening","end-talk")) 5 else 11 },
|
||||
"edges" to pairs.map { (s,t) -> mapOf("source" to s,"target" to t,"anchor" to if(s in setOf("idle","end-talk")) "A" else "B") }))
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkEngineering() {
|
||||
val root=engineeringFixture(); val hash=EngineeringGraphAdmission.MANIFEST_SHA
|
||||
check(EngineeringGraphAdmission.read(root,hash,false)==null)
|
||||
check(EngineeringGraphAdmission.read(root,"0".repeat(64),true)==null)
|
||||
val graph=checkNotNull(EngineeringGraphAdmission.read(root,hash,true))
|
||||
check(graph.review==AnchorReview.TECHNICAL_DEBUG && NeutralGraphContract.missing(graph).isEmpty())
|
||||
check(graph.clips.values.all { it.mouthStateWindows.isEmpty() })
|
||||
check(NeutralGraphContract.missing(graph.copy(review=AnchorReview.APPROVED)).isNotEmpty())
|
||||
check(!graph.copy(review=AnchorReview.APPROVED).approved(graph.edges.first()))
|
||||
check(SafeAvatarManifest.read(root,hash,setOf(hash)).status==SafetyManifestStatus.REVIEW_PENDING)
|
||||
for(edge in graph.edges) check(NeutralGraphContract.missing(graph.copy(edges=graph.edges-edge)).isNotEmpty() || edge.source=="opening" && edge.target=="end-talk")
|
||||
val candidate=root["candidateGraph"] as Map<String,Any?>
|
||||
fun changed(c: Map<String,Any?>) = EngineeringGraphAdmission.read(root+("candidateGraph" to (candidate+c)),hash,true)
|
||||
check(changed(mapOf("earliestExitFrames" to mapOf("idle" to 10)))==null)
|
||||
check(changed(mapOf("edges" to (candidate["edges"] as List<*>).drop(1)))==null)
|
||||
check(changed(mapOf("exitPolicy" to "force_cut"))==null)
|
||||
val assets=root["assets"] as List<Map<String,Any?>>
|
||||
for(change in listOf(mapOf("path" to "../other.mp4"),mapOf("hasAudio" to true),mapOf("durationMs" to 500.5),mapOf("entryAnchor" to "B")))
|
||||
check(EngineeringGraphAdmission.read(root+("assets" to listOf(assets.first()+change)+assets.drop(1)),hash,true)==null)
|
||||
// Real driver with held-frame ports uses the exact technical graph, not a mock planner.
|
||||
var now=0L; val created=mutableListOf<TestPort>(); val shown=mutableListOf<Int>()
|
||||
val driver=SafeVideoDriver(graph,{ TestPort().also { created+=it } },{shown+=it},{},{now},{},chooseVariant={0})
|
||||
driver.start(); created.first().frame(0,0)
|
||||
driver.desire(SafeClipRole.TALK,1)
|
||||
created.last().frame(0,0)
|
||||
created.first().frame(417,10); check(shown.size==1)
|
||||
now=458; created.first().frame(458,11); check(shown.size==2 && driver.sample().clipId=="opening")
|
||||
driver.stop(); check(driver.sample().mouthActiveLagMs==null)
|
||||
check(OfflineAvatarTrace.at(0).mode==AvatarMode.IDLE)
|
||||
check(OfflineAvatarTrace.at(1200).mode==AvatarMode.TALK)
|
||||
check(OfflineAvatarTrace.at(7100).mode==AvatarMode.IDLE)
|
||||
check(OfflineAvatarTrace.at(12500).generation>OfflineAvatarTrace.at(12499).generation)
|
||||
check(OfflineAvatarTrace.at(20000).generation>OfflineAvatarTrace.at(19999).generation)
|
||||
println("PASS: pinned debug-only admission, production pending preserved, last-frame gates, all edges, no forged perceived mouth evidence, offline synthetic reversal/abort generations")
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package android.opengl
|
||||
|
||||
import java.nio.Buffer
|
||||
object GLFixture {
|
||||
var swaps=0;var draws=0;var deleted=0;var terminated=0;var swapFails=false;var shaderFails=false
|
||||
var alpha=0f;var patchTexture=0;var activeUnit=0
|
||||
val rendered=mutableListOf<Pair<Int,Float>>()
|
||||
fun reset() { swaps=0;draws=0;deleted=0;terminated=0;swapFails=false;shaderFails=false;alpha=0f;patchTexture=0;activeUnit=0;rendered.clear() }
|
||||
}
|
||||
class EGLDisplay
|
||||
class EGLContext
|
||||
class EGLSurface
|
||||
class EGLConfig
|
||||
object EGL14 {
|
||||
val EGL_NO_DISPLAY=EGLDisplay();val EGL_NO_CONTEXT=EGLContext();val EGL_NO_SURFACE=EGLSurface()
|
||||
const val EGL_DEFAULT_DISPLAY=0;const val EGL_RENDERABLE_TYPE=1;const val EGL_OPENGL_ES2_BIT=2
|
||||
const val EGL_SURFACE_TYPE=3;const val EGL_WINDOW_BIT=4;const val EGL_RED_SIZE=5;const val EGL_GREEN_SIZE=6
|
||||
const val EGL_BLUE_SIZE=7;const val EGL_ALPHA_SIZE=8;const val EGL_NONE=9;const val EGL_CONTEXT_CLIENT_VERSION=10
|
||||
fun eglGetDisplay(id: Int)=EGLDisplay()
|
||||
fun eglInitialize(d: EGLDisplay,v: IntArray,o: Int,v2: IntArray,o2: Int)=true
|
||||
fun eglChooseConfig(d: EGLDisplay,attrs: IntArray,o: Int,configs: Array<EGLConfig?>,co: Int,size: Int,count: IntArray,no: Int): Boolean { configs[0]=EGLConfig();count[0]=1;return true }
|
||||
fun eglCreateContext(d: EGLDisplay,c: EGLConfig?,share: EGLContext,attrs: IntArray,o: Int)=EGLContext()
|
||||
fun eglCreateWindowSurface(d: EGLDisplay,c: EGLConfig?,native: Any,attrs: IntArray,o: Int)=EGLSurface()
|
||||
fun eglMakeCurrent(d: EGLDisplay,draw: EGLSurface,read: EGLSurface,c: EGLContext)=true
|
||||
fun eglSwapBuffers(d: EGLDisplay,s: EGLSurface): Boolean { GLFixture.swaps++;return !GLFixture.swapFails }
|
||||
fun eglDestroySurface(d: EGLDisplay,s: EGLSurface)=true
|
||||
fun eglDestroyContext(d: EGLDisplay,c: EGLContext)=true
|
||||
fun eglTerminate(d: EGLDisplay): Boolean { GLFixture.terminated++;return true }
|
||||
fun eglReleaseThread()=true
|
||||
}
|
||||
object GLES11Ext { const val GL_TEXTURE_EXTERNAL_OES=100 }
|
||||
object GLES20 {
|
||||
const val GL_TEXTURE_2D=101;const val GL_TEXTURE_MIN_FILTER=102;const val GL_TEXTURE_MAG_FILTER=103
|
||||
const val GL_LINEAR=104;const val GL_TEXTURE_WRAP_S=105;const val GL_TEXTURE_WRAP_T=106;const val GL_CLAMP_TO_EDGE=107
|
||||
const val GL_RGBA=108;const val GL_UNSIGNED_BYTE=109;const val GL_NO_ERROR=0;const val GL_VERTEX_SHADER=110
|
||||
const val GL_FRAGMENT_SHADER=111;const val GL_COMPILE_STATUS=112;const val GL_TRUE=1;const val GL_LINK_STATUS=113
|
||||
const val GL_COLOR_BUFFER_BIT=114;const val GL_FLOAT=115;const val GL_TEXTURE0=116;const val GL_TEXTURE1=117;const val GL_TRIANGLE_STRIP=118
|
||||
fun glGetAttribLocation(p: Int,name: String)=if(name=="aPosition") 1 else 2
|
||||
fun glGetUniformLocation(p: Int,name: String)=when(name) { "uAlpha"->3;"uRect"->4;else->5 }
|
||||
fun glGenTextures(n: Int,ids: IntArray,o: Int) { repeat(n) { ids[o+it]=it+1 } }
|
||||
fun glBindTexture(target: Int,id: Int) { if(target==GL_TEXTURE_2D && GLFixture.activeUnit==GL_TEXTURE1) GLFixture.patchTexture=id }
|
||||
fun glTexParameteri(target: Int,name: Int,value: Int) {}
|
||||
fun glTexImage2D(target: Int,level: Int,format: Int,w: Int,h: Int,border: Int,format2: Int,type: Int,data: Buffer) {}
|
||||
fun glGetError()=GL_NO_ERROR
|
||||
fun glCreateShader(type: Int)=1
|
||||
fun glShaderSource(id: Int,source: String) {}
|
||||
fun glCompileShader(id: Int) {}
|
||||
fun glGetShaderiv(id: Int,p: Int,status: IntArray,o: Int) { status[o]=if(GLFixture.shaderFails) 0 else GL_TRUE }
|
||||
fun glDeleteShader(id: Int) {}
|
||||
fun glCreateProgram()=1
|
||||
fun glAttachShader(program: Int,shader: Int) {}
|
||||
fun glLinkProgram(program: Int) {}
|
||||
fun glGetProgramiv(id: Int,p: Int,status: IntArray,o: Int) { status[o]=GL_TRUE }
|
||||
fun glViewport(x: Int,y: Int,w: Int,h: Int) {}
|
||||
fun glClearColor(r: Float,g: Float,b: Float,a: Float) {}
|
||||
fun glClear(mask: Int) {}
|
||||
fun glUseProgram(p: Int) {}
|
||||
fun glVertexAttribPointer(location: Int,size: Int,type: Int,normalized: Boolean,stride: Int,data: Buffer) {}
|
||||
fun glEnableVertexAttribArray(location: Int) {}
|
||||
fun glUniformMatrix4fv(location: Int,count: Int,transpose: Boolean,value: FloatArray,o: Int) {}
|
||||
fun glActiveTexture(id: Int) { GLFixture.activeUnit=id }
|
||||
fun glUniform1i(location: Int,value: Int) {}
|
||||
fun glUniform4f(location: Int,a: Float,b: Float,c: Float,d: Float) {}
|
||||
fun glUniform1f(location: Int,value: Float) { if(location==3) GLFixture.alpha=value }
|
||||
fun glDrawArrays(mode: Int,first: Int,count: Int) { GLFixture.draws++;GLFixture.rendered+=GLFixture.patchTexture to GLFixture.alpha }
|
||||
fun glDeleteTextures(n: Int,textures: IntArray,o: Int) { GLFixture.deleted+=n }
|
||||
fun glDeleteProgram(p: Int) {}
|
||||
}
|
||||
@@ -1,4 +1,23 @@
|
||||
package android.graphics
|
||||
class Matrix { fun setScale(x: Float,y: Float,px: Float,py: Float) {} }
|
||||
class SurfaceTexture
|
||||
object BitmapFactory { fun decodeStream(input: java.io.InputStream): Any? = Any() }
|
||||
class SurfaceTexture(textureName: Int=0) {
|
||||
var timestamp = 0L
|
||||
private var listener: ((SurfaceTexture)->Unit)?=null
|
||||
private var handler: android.os.Handler?=null
|
||||
init { lastCreated=this }
|
||||
fun setDefaultBufferSize(w: Int,h: Int) {}
|
||||
fun setOnFrameAvailableListener(listener: (SurfaceTexture)->Unit,handler: android.os.Handler) { this.listener=listener;this.handler=handler }
|
||||
fun emit(ptsNs: Long) { timestamp=ptsNs;handler?.post { listener?.invoke(this) } }
|
||||
fun updateTexImage() {}
|
||||
fun getTransformMatrix(matrix: FloatArray) { matrix.fill(0f);listOf(0,5,10,15).forEach { matrix[it]=1f } }
|
||||
fun release() { released++ }
|
||||
companion object { var lastCreated: SurfaceTexture?=null;var released=0 }
|
||||
}
|
||||
class Bitmap(val width: Int=40,val height: Int=22) {
|
||||
fun getPixels(pixels: IntArray,offset: Int,stride: Int,x: Int,y: Int,w: Int,h: Int) { pixels.fill(0x80aa6644.toInt()) }
|
||||
fun recycle() { BitmapFactory.recycled++ }
|
||||
}
|
||||
object BitmapFactory {
|
||||
var recycled=0;var wrongSize=false
|
||||
fun decodeStream(input: java.io.InputStream): Bitmap = Bitmap(if(wrongSize) 41 else 40,22)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
// File loading is separately verified against imported APK bytes; no Android assets here.
|
||||
data class AvatarPack(val idle: String,val talk: String,val fallback: String,val waiting: String)
|
||||
// Loader has independent byte/hash verification; no real portrait bytes in JVM fixtures.
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.os.*
|
||||
|
||||
/** Synthetic small graph, never a timestamp annotation for generated portraits. */
|
||||
fun neutralGraphFixture(): SafeAvatarGraph {
|
||||
val ok=AnchorReview.APPROVED
|
||||
val anchors=listOf(VisualAnchor("A",true,ok),VisualAnchor("B",false,ok)).associateBy { it.id }
|
||||
fun clip(id: String,role: SafeClipRole,a: String,b: String,frames: Int): SafeAvatarClip {
|
||||
val duration=frames*50L
|
||||
val mouth=when (role) {
|
||||
SafeClipRole.IDLE -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,0,duration,0,frames,ok))
|
||||
SafeClipRole.TALK -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,0,duration,0,frames,ok))
|
||||
SafeClipRole.OPENING -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,100,duration,2,frames,ok))
|
||||
else -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,100,duration,2,frames,ok))
|
||||
}
|
||||
return SafeAvatarClip(id,"videos/$id.mp4",role,duration,frames,20,1,
|
||||
listOf(AnchorInterval("in",a,0,50,0,1,ok)),
|
||||
listOf(AnchorInterval("out",b,duration-50,duration,frames-1,frames,ok)),ok,
|
||||
role in setOf(SafeClipRole.IDLE,SafeClipRole.TALK),ok,ok,mouth)
|
||||
}
|
||||
val clips=listOf(clip("idle",SafeClipRole.IDLE,"A","A",10),clip("opening",SafeClipRole.OPENING,"A","B",3),
|
||||
clip("talk1",SafeClipRole.TALK,"B","B",10),clip("talk2",SafeClipRole.TALK,"B","B",10),
|
||||
clip("end-talk",SafeClipRole.CLOSING,"B","A",3)).associateBy { it.id }
|
||||
fun edge(a: String,b: String) = SafeAvatarEdge("${a}_$b",a,"out",b,"in",ok,latestWaitMs=1000)
|
||||
val edges=listOf(edge("idle","opening"),edge("opening","talk1"),edge("opening","talk2"),
|
||||
edge("talk1","talk2"),edge("talk2","talk1"),edge("talk1","end-talk"),edge("talk2","end-talk"),edge("end-talk","idle"))
|
||||
return SafeAvatarGraph(clips,anchors,edges,"idle","in",ok)
|
||||
}
|
||||
private class FramePort(private val readyDelay: Long = 0) : AnchorVideoPort {
|
||||
private val handler=Handler()
|
||||
lateinit var clip: SafeAvatarClip; lateinit var listener: AnchorVideoPort.Listener
|
||||
var last: DisplayedVideoFrame?=null; var held=false; var closed=false
|
||||
private var serial=0L
|
||||
override fun prepare(clip: SafeAvatarClip,entry: AnchorInterval,listener: AnchorVideoPort.Listener) {
|
||||
this.clip=clip; this.listener=listener
|
||||
handler.postDelayed({ emit(entry.startFrame,0) },readyDelay)
|
||||
}
|
||||
fun emit(frame: Int,loop: Long) {
|
||||
if (closed) return
|
||||
last=DisplayedVideoFrame(frame*50L,frame,loop,++serial); held=true; listener.frame(checkNotNull(last))
|
||||
}
|
||||
override fun displayed() = if (held && !closed) last else null
|
||||
override fun advance() {
|
||||
val f=displayed() ?: return
|
||||
held=false
|
||||
handler.postDelayed({
|
||||
if (!closed) {
|
||||
if (f.frame+1 < clip.frameCount) emit(f.frame+1,f.loop)
|
||||
else if (clip.mayLoop) emit(0,f.loop+1)
|
||||
else { held=true; listener.ended() }
|
||||
}
|
||||
},50)
|
||||
}
|
||||
override fun close() { closed=true; handler.removeCallbacksAndMessages(null) }
|
||||
}
|
||||
private class VideoRig(graph: SafeAvatarGraph = neutralGraphFixture(), delay: (Int) -> Long = { 0 }) {
|
||||
val ports=mutableListOf<FramePort>(); val reports=mutableListOf<VideoPresentation>(); val visible=mutableListOf<Int>()
|
||||
val trace=mutableListOf<Pair<Long,VideoPresentation>>()
|
||||
var still=0; var maxPorts=0
|
||||
private val random=kotlin.random.Random(7)
|
||||
val driver=SafeVideoDriver(graph,{ slot -> FramePort(delay(slot)).also { port ->
|
||||
ports += port; maxPorts=maxOf(maxPorts,ports.count { !it.closed })
|
||||
} },{ visible += it },{ still++ },SystemClock::elapsedRealtime,{ reports += it; trace += SystemClock.elapsedRealtime() to it },random::nextInt)
|
||||
fun run(ms: Long) { TestScheduler.advanceBy(ms) }
|
||||
fun clip() = driver.sample().clipId
|
||||
}
|
||||
fun checkSafeDriver() {
|
||||
TestScheduler.reset()
|
||||
val graph=neutralGraphFixture()
|
||||
check(NeutralGraphContract.missing(graph).isEmpty())
|
||||
val choices=mutableSetOf<String>()
|
||||
for (seed in 0..15) {
|
||||
val random=kotlin.random.Random(seed)
|
||||
val p=SafeTransitionPlanner(graph,"opening",chooseVariant=random::nextInt)
|
||||
p.request(MouthIntent(1,1,1,SafeClipRole.TALK),0)
|
||||
val action=p.tick(ClipObservation("opening",0,0,0,1,0),0).single() as TransitionAction.Stage
|
||||
choices += action.ticket.target
|
||||
}
|
||||
check(choices==setOf("talk1","talk2"))
|
||||
for (edge in graph.edges) check(NeutralGraphContract.missing(graph.copy(edges=graph.edges-edge)).isNotEmpty())
|
||||
val reversalEdge=SafeAvatarEdge("opening_end-talk","opening","out","end-talk","in",AnchorReview.APPROVED)
|
||||
val withReversal=graph.copy(edges=graph.edges+reversalEdge)
|
||||
check(NeutralGraphContract.missing(withReversal).isEmpty())
|
||||
val reversing=SafeTransitionPlanner(withReversal,"opening")
|
||||
reversing.request(MouthIntent(1,1,null,SafeClipRole.IDLE,VisualIntentReason.ABORT),0)
|
||||
check((reversing.prepareNext().single() as TransitionAction.Stage).ticket.target=="end-talk")
|
||||
val shortcut=SafeAvatarEdge("idle_talk1","idle","out","talk1","in",AnchorReview.PENDING)
|
||||
// An unapproved shortcut never becomes runnable (anchor mismatch is rejected at construction).
|
||||
check(runCatching { graph.copy(edges=graph.edges+shortcut) }.isFailure)
|
||||
val open=graph.clips.getValue("opening")
|
||||
check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(open.id to open.copy(loop=true)))).isNotEmpty())
|
||||
for (id in listOf("idle","talk1","talk2")) {
|
||||
val c=graph.clips.getValue(id)
|
||||
check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(id to c.copy(loopSeamReview=AnchorReview.PENDING)))).isNotEmpty())
|
||||
}
|
||||
val rig=VideoRig(); rig.driver.desire(SafeClipRole.TALK,7) // newest startup intent must survive preroll
|
||||
rig.driver.start(); rig.run(2000)
|
||||
val talkSequence=rig.reports.map { it.clipId }.filter { it.startsWith("talk") }.fold(mutableListOf<String>()) { acc,id ->
|
||||
if (acc.lastOrNull()!=id) acc+=id; acc
|
||||
}
|
||||
check(talkSequence.size >= 3 && talkSequence.zipWithNext().all { it.first != it.second })
|
||||
check(rig.maxPorts==2 && rig.driver.sample().mouthActiveLagMs != null)
|
||||
rig.driver.desire(SafeClipRole.IDLE,null,true); rig.run(800)
|
||||
check(rig.clip()=="idle" && rig.driver.sample().closingLagMs in 0L..1000L)
|
||||
val traceFile=java.io.File("logs/avatar-safe-061/synthetic-player-trace.json")
|
||||
traceFile.parentFile.mkdirs()
|
||||
traceFile.writeText("{\"kind\":\"synthetic_control_trace_not_material_review\",\"fps\":20,\"seed\":7,\"events\":[" +
|
||||
rig.trace.joinToString(",") { (time,v) -> "{\"atMs\":$time,\"clip\":\"${v.clipId}\",\"reason\":\"${v.reason}\",\"waitMs\":${v.waitMs},\"mouthActiveLagMs\":${v.mouthActiveLagMs},\"closedStableLagMs\":${v.closingLagMs}}" } + "]}\n")
|
||||
// Old active/staged callbacks after stop cannot resurrect talk or reveal.
|
||||
val old=rig.ports.last(); rig.driver.stop(); val reveals=rig.visible.size
|
||||
old.listener.frame(DisplayedVideoFrame(0,0,0,999)); old.listener.ended(); old.listener.failed(VideoFailure.DECODE)
|
||||
check(rig.visible.size==reveals && rig.ports.all { it.closed })
|
||||
rig.driver.desire(SafeClipRole.IDLE,null); rig.driver.start(); rig.run(100)
|
||||
check(rig.clip()=="idle")
|
||||
rig.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val reversal=VideoRig(); reversal.driver.start(); reversal.run(50)
|
||||
reversal.driver.desire(SafeClipRole.TALK,10); reversal.run(450)
|
||||
check(reversal.clip()=="opening")
|
||||
reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(800)
|
||||
check(reversal.clip()=="idle") // short opening completes, legal talk junction then closing
|
||||
reversal.driver.desire(SafeClipRole.TALK,11,true); reversal.run(10)
|
||||
val retiredTarget=reversal.ports.last()
|
||||
reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(500)
|
||||
check(reversal.clip()=="idle") // idle reversal cancels an obsolete hidden opening
|
||||
val count=reversal.visible.size
|
||||
retiredTarget.listener.frame(DisplayedVideoFrame(0,0,0,99))
|
||||
retiredTarget.listener.failed(VideoFailure.DECODE)
|
||||
check(reversal.visible.size==count && reversal.clip()=="idle")
|
||||
reversal.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val delayed=VideoRig(delay={ 1100 }); delayed.driver.start(); delayed.run(1100)
|
||||
delayed.driver.desire(SafeClipRole.TALK,1); delayed.run(1100)
|
||||
check(delayed.clip()=="idle") // target arriving after a window cannot cause a late cut
|
||||
delayed.run(400); check(delayed.clip()=="opening")
|
||||
delayed.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val fail=VideoRig(); fail.driver.start(); fail.run(0)
|
||||
fail.ports.single().listener.failed(VideoFailure.DECODE)
|
||||
check(fail.ports.all { it.closed } && fail.reports.last().reason=="video_decode")
|
||||
// Presentation fitting preserves complete body on portrait/landscape/tablet canvases.
|
||||
for ((w,h) in listOf(320 to 640,1080 to 2400,2400 to 1080,1600 to 2560)) {
|
||||
val fit=fitVideo(w,h,480,848)
|
||||
check(fit.scaleX in 0f..1f && fit.scaleY in 0f..1f)
|
||||
check(kotlin.math.abs(w*fit.scaleX/(h*fit.scaleY)-480f/848)<0.0001)
|
||||
}
|
||||
// Unknown mouth evidence is never substituted with a role-name latency measurement.
|
||||
val noMouth=graph.copy(clips=graph.clips.mapValues { (_,c) -> c.copy(mouthStateWindows=emptyList()) })
|
||||
TestScheduler.reset(); val unknown=VideoRig(noMouth); unknown.driver.start(); unknown.run(0)
|
||||
unknown.driver.desire(SafeClipRole.TALK,1); unknown.run(1500)
|
||||
check(unknown.driver.sample().mouthActiveLagMs==null && unknown.driver.sample().waitMs==1500L)
|
||||
unknown.driver.stop()
|
||||
println("PASS: production video driver with held-frame ports: complete fixed graph/all required edges, alternating legal variants, startup intent, stop/abort/reversal, target-not-ready/late-window wait, renderer epochs/background/failure, two-port bound, mouth evidence latency and fullbody Fit; synthetic materials/device pending")
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private val approved = AnchorReview.APPROVED
|
||||
// Entirely synthetic, 20fps/1s fixture. No real avatar annotations or approval claims.
|
||||
fun syntheticGraph(): SafeAvatarGraph {
|
||||
val anchors = listOf(VisualAnchor("closed",true,approved),VisualAnchor("open",false,approved)).associateBy { it.id }
|
||||
fun interval(id: String,anchor: String,start: Long,end: Long) = AnchorInterval(id,anchor,start,end,(start/50).toInt(),(end/50).toInt(),approved)
|
||||
fun clip(id: String,role: SafeClipRole,entry: String,exit: String) = SafeAvatarClip(id,"videos/$id.mp4",role,1000,20,20,1,
|
||||
listOf(interval("entry",entry,0,100)),listOf(interval("exit",exit,800,900)),approved,
|
||||
loop=role in setOf(SafeClipRole.IDLE,SafeClipRole.TALK),loopSeamReview=approved,seekReview=approved,
|
||||
mouthStateWindows=listOf(MouthStateWindow(if (entry == "closed") ReviewedMouthState.CLOSED_STABLE else ReviewedMouthState.ACTIVE,
|
||||
0,100,0,2,approved)))
|
||||
val clips = listOf(clip("idle",SafeClipRole.IDLE,"closed","closed"),clip("opening",SafeClipRole.OPENING,"closed","open"),
|
||||
clip("talk",SafeClipRole.TALK,"open","open"),clip("closing",SafeClipRole.CLOSING,"open","closed"),
|
||||
clip("waiting",SafeClipRole.WAITING,"closed","closed")).associateBy { it.id }
|
||||
fun edge(from: String,to: String) = SafeAvatarEdge("${from}_$to",from,"exit",to,"entry",approved,latestWaitMs=100)
|
||||
return SafeAvatarGraph(clips,anchors,listOf(edge("idle","opening"),edge("opening","talk"),edge("talk","closing"),
|
||||
edge("closing","idle"),edge("idle","waiting")),"idle","entry",approved)
|
||||
}
|
||||
private class Driver(val graph: SafeAvatarGraph = syntheticGraph(), initial: String = "idle") {
|
||||
val planner = SafeTransitionPlanner(graph,initial)
|
||||
private var serial=0L
|
||||
fun observation(position: Long,now: Long=position,loop: Long=0) =
|
||||
ClipObservation(planner.snapshot(now).actualClip,position,(position/50).toInt(),loop,++serial,now)
|
||||
fun tick(position: Long,now: Long=position,loop: Long=0) = planner.tick(observation(position,now,loop),now)
|
||||
fun stage(position: Long=100,now: Long=100): TransitionAction.Stage = tick(position,now).single() as TransitionAction.Stage
|
||||
fun ready(stage: TransitionAction.Stage, position: Long=0) = StagedFrame(stage.ticket,position,(position/50).toInt(),true,true,true)
|
||||
fun cut(stage: TransitionAction.Stage,now: Long): TransitionAction.Reveal {
|
||||
check(planner.targetReady(ready(stage)))
|
||||
val offer = tick(820,now).single() as TransitionAction.OfferCut
|
||||
return planner.commit(offer.ticket,observation(830,now+10),ready(stage),now+10).single() as TransitionAction.Reveal
|
||||
}
|
||||
}
|
||||
fun checkSafePlanner() {
|
||||
val d=Driver(); val p=d.planner
|
||||
check(p.request(MouthIntent(1,1,42,SafeClipRole.TALK),0).isEmpty())
|
||||
check(p.snapshot(10).actualRole == SafeClipRole.IDLE)
|
||||
val stage=d.stage()
|
||||
for (bad in listOf(d.ready(stage).copy(paused=false),d.ready(stage).copy(seekComplete=false),
|
||||
d.ready(stage).copy(textureReady=false),d.ready(stage,150))) check(!p.targetReady(bad))
|
||||
check(d.tick(820).single() == TransitionAction.Hold(TransitionReason.TARGET_NOT_READY))
|
||||
check(p.targetReady(d.ready(stage)))
|
||||
val late=d.tick(830).single() as TransitionAction.OfferCut
|
||||
check(p.commit(late.ticket,d.observation(910,910),d.ready(stage),910).single() is TransitionAction.Hold)
|
||||
check(p.snapshot(910).actualClip == "idle")
|
||||
check(d.tick(920).single() == TransitionAction.Hold(TransitionReason.WAIT_BUDGET_EXCEEDED))
|
||||
// Expired offer cannot reveal; next approved wrap permits a fresh offer.
|
||||
val wrap=d.tick(820,1820,1).single() as TransitionAction.OfferCut
|
||||
check(p.commit(wrap.ticket,d.observation(830,1830,1),d.ready(stage),1830).single() is TransitionAction.Reveal)
|
||||
check(p.snapshot(1830).actualClip == "opening")
|
||||
// Visible bridge finishes on approved graph edges using the latest desired idle.
|
||||
p.request(MouthIntent(2,1,null,SafeClipRole.IDLE,VisualIntentReason.ABORT),1840)
|
||||
val bridge=d.stage(100,1900); check(bridge.ticket.target == "talk")
|
||||
d.cut(bridge,2000)
|
||||
check(p.snapshot(2010).desired == SafeClipRole.IDLE) // callback never restores old talk intent
|
||||
val closing=d.stage(100,2100); check(closing.ticket.target == "closing"); d.cut(closing,2200)
|
||||
val idle=d.stage(100,2300); d.cut(idle,2400)
|
||||
check(p.snapshot(2410).actualRole == SafeClipRole.IDLE && p.snapshot(2410).closedMouthLagMs == 570L)
|
||||
val staleIntent=p.request(MouthIntent(1,9,42,SafeClipRole.TALK),2500)
|
||||
check(staleIntent.single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
p.request(MouthIntent(2,2,null,SafeClipRole.WAITING,VisualIntentReason.HANGUP),2500)
|
||||
check(p.snapshot(2600).exitPending)
|
||||
val waiting=d.stage(100,2600); d.cut(waiting,2700)
|
||||
check(!p.snapshot(2710).exitPending)
|
||||
check(p.background().last() == TransitionAction.Release)
|
||||
check(!p.targetReady(d.ready(waiting)))
|
||||
val startup=checkNotNull(p.stageForeground(3))
|
||||
val startupFrame=d.ready(startup)
|
||||
check(!p.foreground(3,"idle",startup.entry.copy(endMs=999),startupFrame,3000))
|
||||
check(!p.foreground(3,"idle",startup.entry,startupFrame.copy(textureReady=false),3000))
|
||||
check(p.foreground(3,"idle",startup.entry,startupFrame,3000))
|
||||
check(!p.foreground(3,"idle",startup.entry,startupFrame,3001))
|
||||
|
||||
val reversal=Driver(); reversal.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val retired=reversal.stage(); reversal.planner.targetReady(reversal.ready(retired))
|
||||
val offered=reversal.tick(820).single() as TransitionAction.OfferCut
|
||||
check(reversal.planner.request(MouthIntent(1,2,5,SafeClipRole.IDLE),825).single() is TransitionAction.Cancel)
|
||||
check(!reversal.planner.targetReady(reversal.ready(retired)))
|
||||
check(reversal.planner.commit(offered.ticket,reversal.observation(830),reversal.ready(retired),830).single() is TransitionAction.Hold)
|
||||
check(reversal.planner.request(MouthIntent(1,3,6,SafeClipRole.TALK),840).single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
check(reversal.planner.request(MouthIntent(1,4,4,SafeClipRole.IDLE,VisualIntentReason.ABORT),841).single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
check(reversal.planner.snapshot(840).actualRole == SafeClipRole.IDLE)
|
||||
|
||||
val g=syntheticGraph()
|
||||
val noEdge=Driver(g.copy(edges=emptyList()),"talk")
|
||||
noEdge.planner.request(MouthIntent(1,1,null,SafeClipRole.IDLE,VisualIntentReason.DISCONNECT),0)
|
||||
check(noEdge.tick(100).single() == TransitionAction.Hold(TransitionReason.NO_REVIEWED_EDGE))
|
||||
check(noEdge.planner.snapshot(5000).visualWaitMs == 5000L)
|
||||
val unreviewed=Driver(g.copy(clips=g.clips + ("idle" to g.clips.getValue("idle").copy(loopSeamReview=AnchorReview.PENDING))))
|
||||
unreviewed.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
check(unreviewed.tick(100,1100,1).single() == TransitionAction.Hold(TransitionReason.LOOP_UNREVIEWED))
|
||||
val held=Driver(g.copy(edges=g.edges.map { it.copy(missedWindowPolicy=MissedWindowPolicy.HOLD) }))
|
||||
held.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val hs=held.stage(); held.planner.targetReady(held.ready(hs))
|
||||
check(held.tick(950).single() is TransitionAction.Hold)
|
||||
check(held.tick(820,1820,1).single() == TransitionAction.Hold(TransitionReason.WINDOW_MISSED))
|
||||
val stale=Driver(); stale.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
check(stale.planner.tick(stale.observation(100,100).copy(continuous=false),100).single() == TransitionAction.Hold(TransitionReason.STALE_POSITION))
|
||||
check(stale.planner.tick(stale.observation(100,100),141).single() == TransitionAction.Hold(TransitionReason.STALE_POSITION))
|
||||
val eos=Driver(); eos.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val es=eos.stage(); eos.planner.targetReady(eos.ready(es))
|
||||
val eo=eos.tick(820).single() as TransitionAction.OfferCut
|
||||
check(eos.planner.commit(eo.ticket,eos.observation(830).copy(ended=true),eos.ready(es),830).single() == TransitionAction.Hold(TransitionReason.LATE_CUT))
|
||||
check(eos.planner.tick(eos.observation(850).copy(ended=true),850).single() == TransitionAction.Hold(TransitionReason.WINDOW_MISSED))
|
||||
|
||||
val cursor=ActualClipCursor(); val clip=g.clips.getValue("idle")
|
||||
check(cursor.observe(clip,950,19,100).continuous)
|
||||
check(cursor.observe(clip,0,0,150).loop == 1L)
|
||||
check(!cursor.observe(clip,500,10,1200).continuous) // may have missed a whole loop
|
||||
cursor.reset(); cursor.observe(clip,500,10,0)
|
||||
check(!cursor.observe(clip,450,9,20).continuous) // seek/jitter is not a seam
|
||||
val diag=TransitionDiagnostics()
|
||||
check(diag.summary(p.snapshot(4000),AssetEmotion(),4000)?.contains("wait_ms=") == true)
|
||||
check(diag.summary(p.snapshot(4999),AssetEmotion(),4999) == null)
|
||||
check(diag.summary(p.snapshot(5000),AssetEmotion(),5000) != null)
|
||||
println("PASS: safe planner reviewed graph/bridge, paused seek+texture gate, fresh second sample, missed/late/noedge/unreviewed loop, latest intent/old turn, abort closing/hangup exit, background/new foreground, cursor continuity, bounded diagnostics; synthetic anchors only")
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private val fakeSha = "a".repeat(64)
|
||||
fun syntheticManifest(): Map<String,Any?> {
|
||||
val g=syntheticGraph()
|
||||
fun interval(i: AnchorInterval): Map<String,Any?> = mapOf("id" to i.id,"anchorId" to i.anchorId,
|
||||
"startMs" to i.startMs,"endMs" to i.endMs,"startFrame" to i.startFrame,"endFrame" to i.endFrame,"reviewStatus" to "approved")
|
||||
return mapOf("schemaVersion" to 1,"assets" to g.clips.values.map { mapOf("id" to it.id,"path" to it.path) },
|
||||
"safeTransitions" to mapOf("version" to 1,"reviewStatus" to "approved","initialAssetId" to g.initialClip,"initialEntryId" to g.initialEntry,
|
||||
"anchors" to g.anchors.values.map { mapOf("id" to it.id,"closedMouth" to it.closedMouth,"reviewStatus" to "approved") },
|
||||
"clips" to g.clips.values.map { mapOf("assetId" to it.id,"role" to it.role.name.lowercase(),
|
||||
"durationMs" to it.durationMs,"frameCount" to it.frameCount,"fpsNumerator" to it.fpsNumerator,"fpsDenominator" to it.fpsDenominator,
|
||||
"entryAnchors" to it.entryAnchors.map(::interval),"safeExitWindows" to it.safeExitWindows.map(::interval),
|
||||
"mouthStateWindows" to it.mouthStateWindows.map { w -> mapOf("state" to w.state.name.lowercase(),
|
||||
"startMs" to w.startMs,"endMs" to w.endMs,"startFrame" to w.startFrame,"endFrame" to w.endFrame,"reviewStatus" to "approved") },
|
||||
"loop" to it.loop,"reviewStatus" to "approved","loopSeamReviewStatus" to "approved","seekReviewStatus" to "approved") },
|
||||
"transitions" to g.edges.map { mapOf("id" to it.id,"sourceAssetId" to it.source,"sourceWindowId" to it.sourceWindow,
|
||||
"targetAssetId" to it.target,"targetEntryId" to it.targetEntry,"reviewStatus" to "approved",
|
||||
"earliestPolicy" to "next_safe_window","latestPolicy" to "next_reviewed_loop","earliestWaitMs" to 0L,"latestWaitMs" to 100L) }))
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkSafetyManifest() {
|
||||
val root=syntheticManifest()
|
||||
val extension=root["safeTransitions"] as Map<String,Any?>
|
||||
fun modifiedExtension(change: Map<String,Any?>) = root + ("safeTransitions" to (extension + change))
|
||||
fun status(value: Map<String,Any?>) = SafeAvatarManifest.read(value,fakeSha,setOf(fakeSha)).status
|
||||
check(status(root - "safeTransitions") == SafetyManifestStatus.LEGACY_UNANNOTATED)
|
||||
// a01-v2's draft annotations are not this reviewed schema and grant no safety.
|
||||
check(status((root - "safeTransitions") + mapOf("approvedEdges" to emptyList<Any>(),"safeExits" to emptyList<Any>())) == SafetyManifestStatus.LEGACY_UNANNOTATED)
|
||||
check(status(modifiedExtension(mapOf("reviewStatus" to "pending","anchors" to emptyList<Any>(),"clips" to emptyList<Any>()))) == SafetyManifestStatus.REVIEW_PENDING)
|
||||
check(SafeAvatarManifest.read(root,fakeSha).status == SafetyManifestStatus.HASH_NOT_APPROVED)
|
||||
check(SafeAvatarManifest.read(root,"not-a-sha",setOf("not-a-sha")).status == SafetyManifestStatus.HASH_NOT_APPROVED)
|
||||
val approved=SafeAvatarManifest.read(root,fakeSha,setOf(fakeSha))
|
||||
check(approved.status == SafetyManifestStatus.APPROVED && approved.graph?.nextEdge("idle",SafeClipRole.TALK) != null)
|
||||
check(approved.graph?.clips?.getValue("idle")?.mouthStateWindows?.single()?.state == ReviewedMouthState.CLOSED_STABLE)
|
||||
check(status(root + ("schemaVersion" to 1.0)) == SafetyManifestStatus.INVALID)
|
||||
check(status(modifiedExtension(mapOf("version" to 2))) == SafetyManifestStatus.INVALID)
|
||||
check(status(modifiedExtension(mapOf("reviewStatus" to "almost_approved"))) == SafetyManifestStatus.INVALID)
|
||||
val clips=extension["clips"] as List<Map<String,Any?>>
|
||||
val closingAlias=clips.map { if (it["role"] == "closing") it + ("role" to "end-talk") else it }
|
||||
check(status(modifiedExtension(mapOf("clips" to closingAlias))) == SafetyManifestStatus.APPROVED)
|
||||
val badMouth=clips.first() + ("mouthStateWindows" to listOf(mapOf("state" to "active","startMs" to 0L,
|
||||
"endMs" to 9999L,"startFrame" to 0,"endFrame" to 1,"reviewStatus" to "approved")))
|
||||
check(status(modifiedExtension(mapOf("clips" to listOf(badMouth)+clips.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
for (change in listOf(mapOf("durationMs" to 4000.5),mapOf("durationMs" to -1L),mapOf("frameCount" to 1),mapOf("frameCount" to 3600),
|
||||
mapOf("assetId" to "missing"),mapOf("entryAnchors" to emptyList<Any>()),mapOf("fpsDenominator" to 0))) {
|
||||
check(status(modifiedExtension(mapOf("clips" to listOf(clips.first()+change)+clips.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
}
|
||||
val edges=extension["transitions"] as List<Map<String,Any?>>
|
||||
for (change in listOf(mapOf("targetEntryId" to "missing"),mapOf("sourceWindowId" to "missing"),
|
||||
mapOf("bridgeAssetId" to "closing"),mapOf("latestPolicy" to "force_cut"),mapOf("latestWaitMs" to -1))) {
|
||||
check(status(modifiedExtension(mapOf("transitions" to listOf(edges.first()+change)+edges.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
}
|
||||
val unreviewed=SafeAvatarManifest.read(modifiedExtension(mapOf("transitions" to edges.map { it + ("reviewStatus" to "pending") })),fakeSha,setOf(fakeSha))
|
||||
check(unreviewed.graph?.nextEdge("idle",SafeClipRole.TALK) == null)
|
||||
check(status(root + ("assets" to List(33) { mapOf("id" to "a$it","path" to "videos/a.mp4") })) == SafetyManifestStatus.INVALID)
|
||||
check(status(root + ("assets" to listOf(mapOf("id" to "idle","path" to "../private.mp4")) +
|
||||
(root["assets"] as List<Map<String,Any?>>).drop(1))) == SafetyManifestStatus.INVALID)
|
||||
println("PASS: manifest legacy/draft unsafe, pending unknown allowed without invented windows, hash allowlist, strict bounded metadata/frame/pose/reference/policy validation; fixture approval only")
|
||||
}
|
||||
@@ -44,6 +44,20 @@ fun checkCallControls() {
|
||||
val frame = session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
|
||||
frame.invoke(session,DownlinkFrame(11)); activity(PlaybackActivity(11,7,true,960,1920)); Handler.drain()
|
||||
check(AudioPlayback.enqueued == enqueued && states.last().playbackActivity == null)
|
||||
// New automatic UX can reopen a session while preserving mute, without a single
|
||||
// capture start before applying it. Permission pause sends safe stop/abort controls.
|
||||
dialogue.setField("socket",socket); dialogue.setField("ready",true)
|
||||
set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
|
||||
val mutedStarts = AudioCapture.starts
|
||||
session.startVoice(microphoneMuted=true)
|
||||
check(states.last().voiceActive && states.last().microphoneMuted && AudioCapture.starts == mutedStarts)
|
||||
session.background(keepConnectionForPermission=true)
|
||||
check(!states.last().voiceActive && states.last().playbackActivity == null)
|
||||
check(socket.sent.takeLast(2).any { it.contains("abort") })
|
||||
session.foreground(connectAutomatically=false)
|
||||
check(!states.last().voiceActive && AudioCapture.starts == mutedStarts)
|
||||
session.resetConnection()
|
||||
check(states.last().connection == ConnectionStatus.DISCONNECTED)
|
||||
session.release(); AudioPlayback.activityFence = null
|
||||
println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user