Support bridge-owned TALK layers and recover free P4a candidate
This commit is contained in:
+4
-1
@@ -31,6 +31,7 @@ if (avatarUiCandidate && !avatarNatural) {
|
|||||||
def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?: ''
|
def naturalManifestSha = providers.gradleProperty('naturalManifestSha').orNull ?: ''
|
||||||
def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: ''
|
def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?: ''
|
||||||
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
|
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
|
||||||
|
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
|
||||||
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
|
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
|
||||||
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
|
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
|
||||||
}
|
}
|
||||||
@@ -66,6 +67,7 @@ def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) {
|
|||||||
from('src/main/assets')
|
from('src/main/assets')
|
||||||
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
|
exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**'
|
||||||
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
|
if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**'
|
||||||
|
if (!emotionManifestSha) exclude 'avatar/a01-expression-action-v1/**'
|
||||||
into(packagedAssets)
|
into(packagedAssets)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +88,8 @@ android {
|
|||||||
buildFeatures { compose true; buildConfig true }
|
buildFeatures { compose true; buildConfig true }
|
||||||
buildTypes {
|
buildTypes {
|
||||||
debug {
|
debug {
|
||||||
if (avatarActionCandidate) versionNameSuffix '-stage-dev'
|
if (emotionManifestSha) versionNameSuffix '-emotion-stage-dev'
|
||||||
|
else if (avatarActionCandidate) versionNameSuffix '-stage-dev'
|
||||||
else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
|
else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
|
||||||
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
|
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
|
||||||
else if (avatarNatural) versionNameSuffix '-natural-dev'
|
else if (avatarNatural) versionNameSuffix '-natural-dev'
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion
|
|||||||
|
|
||||||
/** One Activity-owned binding shared by VoiceSession and its persistent avatar view. */
|
/** One Activity-owned binding shared by VoiceSession and its persistent avatar view. */
|
||||||
class AvatarMediaBinding : ActionPlayer {
|
class AvatarMediaBinding : ActionPlayer {
|
||||||
|
val currentPackageId: String? get() = driver?.currentPackageId
|
||||||
|
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
|
||||||
|
val selection: RoleVisualSelection? get() = driver?.selection
|
||||||
private var driver: ConversationMediaDriver?=null
|
private var driver: ConversationMediaDriver?=null
|
||||||
private var prepared: ReplyEmotion?=null
|
private var prepared: ReplyEmotion?=null
|
||||||
private var reply: ReplyEmotion?=null
|
private var reply: ReplyEmotion?=null
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
|||||||
LaunchedEffect(state.voiceActive,pack) {
|
LaunchedEffect(state.voiceActive,pack) {
|
||||||
if(state.voiceActive) while(true) {
|
if(state.voiceActive) while(true) {
|
||||||
val selected=latestAvatar
|
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}")
|
DiagnosticLog.record("avatar","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} current_visual=${mediaBinding?.currentPackageId ?: "unavailable"} visual_status=${mediaBinding?.visualStatus ?: "legacy_neutral"}")
|
||||||
delay(1_000)
|
delay(1_000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -127,7 +127,10 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
|||||||
Text("角色:${state.roleLabel}",fontSize=13.sp)
|
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)
|
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) }
|
state.previousReplyEmotion?.let { Text("上一轮:${it.label}",fontSize=12.sp) }
|
||||||
Text("解析素材:中立0 · ${video.actual};意图 ${avatar.desiredMode.name.lowercase()}"+if(avatar.emotionFallback) "(素材缺失,回退中立)" else "",fontSize=12.sp)
|
val visualId=mediaBinding?.currentPackageId
|
||||||
|
val visualEmotion=pack?.emotionAction?.visuals?.firstOrNull { it.id==visualId }?.emotion
|
||||||
|
Text("当前画面:${visualEmotion?.label ?: if(pack?.emotionAction!=null) "过渡或未呈现" else "中立"} · ${video.actual}",fontSize=12.sp)
|
||||||
|
Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp)
|
||||||
AvatarDiagnostics(pack,video)
|
AvatarDiagnostics(pack,video)
|
||||||
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
|
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
|
||||||
Row {
|
Row {
|
||||||
@@ -175,6 +178,8 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
|
|||||||
var override by remember { mutableStateOf<AvatarMode?>(null) }
|
var override by remember { mutableStateOf<AvatarMode?>(null) }
|
||||||
var restart by remember { mutableStateOf(0L) }
|
var restart by remember { mutableStateOf(0L) }
|
||||||
var video by remember { mutableStateOf(VideoPresentation()) }
|
var video by remember { mutableStateOf(VideoPresentation()) }
|
||||||
|
val offlineBinding=remember(pack) { AvatarMediaBinding() }
|
||||||
|
var emotionLabel by remember { mutableStateOf("") }
|
||||||
DisposableEffect(activity) {
|
DisposableEffect(activity) {
|
||||||
val observer=LifecycleEventObserver { _,event ->
|
val observer=LifecycleEventObserver { _,event ->
|
||||||
if(event==Lifecycle.Event.ON_RESUME) resumed=true
|
if(event==Lifecycle.Event.ON_RESUME) resumed=true
|
||||||
@@ -183,19 +188,32 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted
|
|||||||
activity.lifecycle.addObserver(observer)
|
activity.lifecycle.addObserver(observer)
|
||||||
onDispose { activity.lifecycle.removeObserver(observer) }
|
onDispose { activity.lifecycle.removeObserver(observer) }
|
||||||
}
|
}
|
||||||
LaunchedEffect(resumed,restart) {
|
LaunchedEffect(resumed,restart,override) {
|
||||||
if(resumed) {
|
if(resumed) {
|
||||||
val start=android.os.SystemClock.elapsedRealtime()
|
val start=android.os.SystemClock.elapsedRealtime()
|
||||||
while(true) { trace=OfflineAvatarTrace.at(android.os.SystemClock.elapsedRealtime()-start);delay(20) }
|
val emotionSequence=OfflineEmotionSequence(1000+restart)
|
||||||
|
if(pack?.emotionAction!=null) offlineBinding.beginTurn(1000+restart)
|
||||||
|
while(true) {
|
||||||
|
val elapsed=android.os.SystemClock.elapsedRealtime()-start
|
||||||
|
trace=OfflineAvatarTrace.at(elapsed)
|
||||||
|
if(pack?.emotionAction!=null) {
|
||||||
|
val visual=pack.emotionAction.visuals.firstOrNull { it.id==offlineBinding.currentPackageId }?.emotion
|
||||||
|
val sample=emotionSequence.at(elapsed,visual)
|
||||||
|
offlineBinding.intent(sample.reply,when(override) { AvatarMode.TALK->true;AvatarMode.IDLE->false;else->sample.talking })
|
||||||
|
emotionLabel=sample.label
|
||||||
|
if(elapsed>=60_000) break
|
||||||
|
}
|
||||||
|
delay(20)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
CleanAvatarScaffold(avatar={
|
CleanAvatarScaffold(avatar={
|
||||||
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize()) { video=it }
|
AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize(),if(pack?.emotionAction!=null) offlineBinding else null) { video=it }
|
||||||
},settings={
|
},settings={
|
||||||
Text("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp)
|
Text("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp)
|
||||||
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
|
Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp)
|
||||||
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
|
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
|
||||||
Text("合成意图:${override?.name ?: trace.label}",fontSize=12.sp)
|
Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp)
|
||||||
AvatarDiagnostics(pack,video)
|
AvatarDiagnostics(pack,video)
|
||||||
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
|
Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
|
||||||
TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") }
|
TextButton(onClick={override=AvatarMode.IDLE}) { Text("Idle") }
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
|||||||
private val output: Surface,private var width: Int,private var height: Int,
|
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 presented: (ComposedBodyFrame,Long)->Unit,private val failure: (String)->Unit,
|
||||||
private val automatic: Boolean=true,private val startFrame: Int=0,private val mayLoop: Boolean=true,
|
private val automatic: Boolean=true,private val startFrame: Int=0,private val mayLoop: Boolean=true,
|
||||||
private val mouthEnabled: Boolean=true,private val ended: ()->Unit={}) {
|
private val mouthEnabled: Boolean=true,private val sharedMouth: ConversationMouthClock?=null,private val ended: ()->Unit={}) {
|
||||||
private val alive=AtomicBoolean(true)
|
private val alive=AtomicBoolean(true)
|
||||||
private val releaseLock=Any()
|
private val releaseLock=Any()
|
||||||
private val releaseCallbacks=mutableListOf<()->Unit>()
|
private val releaseCallbacks=mutableListOf<()->Unit>()
|
||||||
@@ -37,7 +37,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
|||||||
private val thread=HandlerThread("avatar-body-gl").apply { start() }
|
private val thread=HandlerThread("avatar-body-gl").apply { start() }
|
||||||
private val worker=Handler(thread.looper)
|
private val worker=Handler(thread.looper)
|
||||||
private val main=Handler(Looper.getMainLooper())
|
private val main=Handler(Looper.getMainLooper())
|
||||||
private val gate=ContinuousFramePresenter(pack,mouthEnabled=mouthEnabled,startFrame=startFrame)
|
private val gate=ContinuousFramePresenter(pack,mouthEnabled=mouthEnabled,startFrame=startFrame,sharedMouth=sharedMouth)
|
||||||
private var display: EGLDisplay=EGL14.EGL_NO_DISPLAY
|
private var display: EGLDisplay=EGL14.EGL_NO_DISPLAY
|
||||||
private var eglContext: EGLContext=EGL14.EGL_NO_CONTEXT
|
private var eglContext: EGLContext=EGL14.EGL_NO_CONTEXT
|
||||||
private var window: EGLSurface=EGL14.EGL_NO_SURFACE
|
private var window: EGLSurface=EGL14.EGL_NO_SURFACE
|
||||||
@@ -77,6 +77,13 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont
|
|||||||
|
|
||||||
init { worker.post { guarded { initialize(); pump() } } }
|
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 intent(talk: Boolean,generation: Long,revision: Long) { worker.post { if(alive.get()) gate.intent(talk,generation,revision,SystemClock.elapsedRealtime()) } }
|
||||||
|
fun activateMouth(talk: Boolean,generation: Long,revision: Long,ready: ()->Unit) {
|
||||||
|
worker.post { guarded {
|
||||||
|
gate.intent(talk,generation,revision,SystemClock.elapsedRealtime())
|
||||||
|
val value=gate.recompose(SystemClock.elapsedRealtime()) { draw(it) } ?: return@guarded
|
||||||
|
main.post { if(alive.get()) { presented(value,SystemClock.elapsedRealtime()-startedMs);ready() } }
|
||||||
|
} }
|
||||||
|
}
|
||||||
fun resize(w: Int,h: Int) { worker.post { if(alive.get()) { width=w; height=h } } }
|
fun resize(w: Int,h: Int) { worker.post { if(alive.get()) { width=w; height=h } } }
|
||||||
fun advance() { worker.post { guarded { if(held) {
|
fun advance() { worker.post { guarded { if(held) {
|
||||||
held=false;worker.removeCallbacks(heldTick)
|
held=false;worker.removeCallbacks(heldTick)
|
||||||
|
|||||||
@@ -13,12 +13,12 @@ data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPat
|
|||||||
/** The real EGL renderer uses this gate immediately around updateTexImage + draw/swap.
|
/** 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. */
|
* No other thread can choose a patch or change body phase. close() fences stale output. */
|
||||||
class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,
|
class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,
|
||||||
private val mouthEnabled: Boolean=true,startFrame: Int=0,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
|
private val mouthEnabled: Boolean=true,startFrame: Int=0,private val sharedMouth: ConversationMouthClock?=null,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
|
||||||
private val clock=ContinuousFrameClock(pack.body.frameCount,pack.body.ptsUs,startFrame)
|
private val clock=ContinuousFrameClock(pack.body.frameCount,pack.body.ptsUs,startFrame)
|
||||||
private val mouth=ContinuousMouth(pack.curves,choose)
|
private val mouth=ContinuousMouth(pack.curves,choose)
|
||||||
private var active=true
|
private var active=true
|
||||||
private var heldKey: BodyFrameKey?=null
|
private var heldKey: BodyFrameKey?=null
|
||||||
fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && mouth.request(talk && mouthEnabled,generation,revision,nowMs)
|
fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && if(sharedMouth!=null && mouthEnabled) sharedMouth.intent(this,pack.curves,talk,generation,revision,nowMs ?: 0) else mouth.request(talk && mouthEnabled,generation,revision,nowMs)
|
||||||
fun decoded(ptsUs: Long): BodyFrameKey { check(active); return clock.decoded(ptsUs) }
|
fun decoded(ptsUs: Long): BodyFrameKey { check(active); return clock.decoded(ptsUs) }
|
||||||
fun present(timestampNs: Long,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? {
|
fun present(timestampNs: Long,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame? {
|
||||||
if(!active) return null
|
if(!active) return null
|
||||||
@@ -31,12 +31,12 @@ class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,
|
|||||||
return compose(heldKey ?: return null,nowMs,drawAndSwap)
|
return compose(heldKey ?: return null,nowMs,drawAndSwap)
|
||||||
}
|
}
|
||||||
private fun compose(key: BodyFrameKey,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame {
|
private fun compose(key: BodyFrameKey,nowMs: Long,drawAndSwap: (ComposedBodyFrame)->Unit): ComposedBodyFrame {
|
||||||
val sample=mouth.sample(nowMs)
|
val sample=if(sharedMouth!=null && mouthEnabled) sharedMouth.sample(this,nowMs) else mouth.sample(nowMs)
|
||||||
val frame=if(mouthEnabled) ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha))
|
val frame=if(mouthEnabled) ComposedBodyFrame(key,pack.patches[key.index],sample,selectMouthPatch(pack,key.index,sample.alpha))
|
||||||
else ComposedBodyFrame(key,RegisteredMouthPatch(key.index,key.ptsUs,"","",0f,0f,1,1),sample,MouthPatchSelection(-1,0,0f))
|
else ComposedBodyFrame(key,RegisteredMouthPatch(key.index,key.ptsUs,"","",0f,0f,1,1),sample,MouthPatchSelection(-1,0,0f))
|
||||||
drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented.
|
drawAndSwap(frame) // Exactly one atomic composition; failed swap is not presented.
|
||||||
return frame
|
return frame
|
||||||
}
|
}
|
||||||
fun wrap() { check(active); clock.wrap() }
|
fun wrap() { check(active); clock.wrap() }
|
||||||
fun close() { active=false }
|
fun close() { active=false;sharedMouth?.release(this) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ data class MouthLayerSample(val phase: String, val alpha: Float, val generation:
|
|||||||
val phaseWaitMs: Long=0)
|
val phaseWaitMs: Long=0)
|
||||||
|
|
||||||
/** Body-independent authored phase controller. No perceived-mouth SLA is inferred. */
|
/** 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) }) {
|
class ContinuousMouth(private var curves: Map<String,MouthCurve>, private val choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) {
|
||||||
private var desired = false
|
private var desired = false
|
||||||
private var generation = -1L
|
private var generation = -1L
|
||||||
private var revision = -1L
|
private var revision = -1L
|
||||||
@@ -16,6 +16,17 @@ class ContinuousMouth(private val curves: Map<String,MouthCurve>, private val ch
|
|||||||
private var initialized = false
|
private var initialized = false
|
||||||
private var previousTalk: String? = null
|
private var previousTalk: String? = null
|
||||||
private var requestedAt: Long? = null
|
private var requestedAt: Long? = null
|
||||||
|
fun rebind(next: Map<String,MouthCurve>,nowMs: Long) {
|
||||||
|
if(curves==next) return
|
||||||
|
if(initialized && phase!="idle") {
|
||||||
|
sample(nowMs)
|
||||||
|
if(phase!="idle") {
|
||||||
|
val fraction=(nowMs-startedAt).toDouble()/curves.getValue(phase).durationMs
|
||||||
|
startedAt=nowMs-(fraction*next.getValue(phase).durationMs).toLong()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
curves=next
|
||||||
|
}
|
||||||
fun request(talk: Boolean, generation: Long, revision: Long,nowMs: Long?=null): Boolean {
|
fun request(talk: Boolean, generation: Long, revision: Long,nowMs: Long?=null): Boolean {
|
||||||
if (generation < this.generation || generation == this.generation && revision <= this.revision) return false
|
if (generation < this.generation || generation == this.generation && revision <= this.revision) return false
|
||||||
this.generation=generation; this.revision=revision; desired=talk
|
this.generation=generation; this.revision=revision; desired=talk
|
||||||
@@ -101,3 +112,34 @@ fun composeMouthChannel(body: Float,patch: Float,mask: Float,global: Float): Flo
|
|||||||
val a=mask*global
|
val a=mask*global
|
||||||
return body*(1-a)+patch*a
|
return body*(1-a)+patch*a
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Shared phase only: every presenter still indexes its own body/patch/UV data.
|
||||||
|
* Hidden surfaces never advance this clock. Global generation/revision fences also
|
||||||
|
* prevent a retired worker from taking ownership back after a boundary switch. */
|
||||||
|
class ConversationMouthClock {
|
||||||
|
private var owner: Any?=null
|
||||||
|
private val lastSamples=java.util.IdentityHashMap<Any,MouthLayerSample>()
|
||||||
|
private var controller: ContinuousMouth?=null
|
||||||
|
private var generation=-1L
|
||||||
|
private var revision=-1L
|
||||||
|
private var time=0L
|
||||||
|
@Synchronized fun intent(token: Any,curves: Map<String,MouthCurve>,talk: Boolean,generation: Long,revision: Long,nowMs: Long): Boolean {
|
||||||
|
if(generation<this.generation || generation==this.generation && revision<=this.revision) return false
|
||||||
|
time=maxOf(time,nowMs)
|
||||||
|
val current=controller ?: ContinuousMouth(curves).also { controller=it }
|
||||||
|
current.rebind(curves,time)
|
||||||
|
current.request(talk,generation,revision,time)
|
||||||
|
owner=token;this.generation=generation;this.revision=revision
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
@Synchronized fun sample(token: Any,nowMs: Long): MouthLayerSample {
|
||||||
|
if(token!==owner) return lastSamples[token] ?: MouthLayerSample("idle",0f,generation,revision)
|
||||||
|
time=maxOf(time,nowMs)
|
||||||
|
return checkNotNull(controller).sample(time).also { lastSamples[token]=it }
|
||||||
|
}
|
||||||
|
@Synchronized fun release(token: Any) {
|
||||||
|
lastSamples.remove(token);if(owner===token) owner=null
|
||||||
|
if(owner==null && lastSamples.isEmpty()) controller=null // No expired phase across background restart.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ interface CompositeMediaPort {
|
|||||||
frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit)
|
frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit)
|
||||||
fun advance()
|
fun advance()
|
||||||
fun mouth(talk: Boolean,generation: Long,revision: Long)
|
fun mouth(talk: Boolean,generation: Long,revision: Long)
|
||||||
|
fun activateMouth(talk: Boolean,generation: Long,revision: Long,ready: ()->Unit) {
|
||||||
|
mouth(talk,generation,revision);ready()
|
||||||
|
}
|
||||||
fun close(released: ()->Unit)
|
fun close(released: ()->Unit)
|
||||||
}
|
}
|
||||||
interface MusicMediaPort {
|
interface MusicMediaPort {
|
||||||
@@ -21,16 +24,27 @@ interface MusicMediaPort {
|
|||||||
* New intent during a bridge finishes that edge and then routes the latest target. */
|
* New intent during a bridge finishes that edge and then routes the latest target. */
|
||||||
class ConversationMediaDriver(private val index: EmotionActionIndex,
|
class ConversationMediaDriver(private val index: EmotionActionIndex,
|
||||||
private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort,
|
private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort,
|
||||||
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> }) : ActionPlayer {
|
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> },
|
||||||
|
private val allowSilentEdges: Boolean=false) : ActionPlayer {
|
||||||
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
|
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
|
||||||
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
|
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
|
||||||
private val slots=mutableListOf<Slot>()
|
private val slots=mutableListOf<Slot>()
|
||||||
private var visible: Slot?=null
|
private var visible: Slot?=null
|
||||||
|
private var revealing: Slot?=null
|
||||||
private var target: Slot?=null
|
private var target: Slot?=null
|
||||||
private var bridge: Slot?=null
|
private var bridge: Slot?=null
|
||||||
private var edge: ConversationEdge?=null
|
private var edge: ConversationEdge?=null
|
||||||
private var selectedId=index.fallbackId
|
private var selectedId=index.fallbackId
|
||||||
var selection: RoleVisualSelection?=null;private set
|
var selection: RoleVisualSelection?=null;private set
|
||||||
|
val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId
|
||||||
|
val visualStatus: String get() = when {
|
||||||
|
!active -> "renderer_stopped"
|
||||||
|
actionStarted -> "action_mouth_disabled"
|
||||||
|
inBridge -> "bridge_own_mouth"
|
||||||
|
edge!=null || revealing!=null -> "queued_emotion_safe_exit_or_prepared_surface"
|
||||||
|
visible?.packageId!=selectedId -> "queued_emotion_path_or_layer_unavailable"
|
||||||
|
else -> selection?.reason ?: "no_model_expression"
|
||||||
|
}
|
||||||
private var turn: Long?=null
|
private var turn: Long?=null
|
||||||
private var seq=-1L
|
private var seq=-1L
|
||||||
private var generation=0L
|
private var generation=0L
|
||||||
@@ -49,9 +63,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private val releaseWaiters=mutableListOf<()->Unit>()
|
private val releaseWaiters=mutableListOf<()->Unit>()
|
||||||
fun beginTurn(id: Long?) {
|
fun beginTurn(id: Long?) {
|
||||||
if(id==turn) return
|
if(id==turn) return
|
||||||
turn=id;seq=-1;generation++;revision=0;talk=false
|
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null
|
||||||
selectedId=visible?.packageId ?: index.fallbackId
|
selectedId=visible?.packageId ?: index.fallbackId
|
||||||
if(!inBridge) discardRoute()
|
if(!inBridge && revealing==null) discardRoute()
|
||||||
applyMouth()
|
applyMouth()
|
||||||
}
|
}
|
||||||
fun start() {
|
fun start() {
|
||||||
@@ -82,7 +96,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
if(active && !inBridge && !actionStarted) plan()
|
if(active && !inBridge && !actionStarted) plan()
|
||||||
}
|
}
|
||||||
private fun applyMouth() {
|
private fun applyMouth() {
|
||||||
visible?.port?.mouth(talk && action==null && !inBridge && edge==null && visible?.packageId==selectedId,generation,++revision)
|
val current=revealing ?: visible
|
||||||
|
current?.port?.mouth(talk && action==null && current.pack.apertureMode,generation,++revision)
|
||||||
}
|
}
|
||||||
private fun loopEdge(id: String)=index.edges.first { it.from==id && it.to==id && (index.loopIds[id]==null || it.id==index.loopIds[id]) }
|
private fun loopEdge(id: String)=index.edges.first { it.from==id && it.to==id && (index.loopIds[id]==null || it.id==index.loopIds[id]) }
|
||||||
private fun prepare(id: String,frame: Int): Slot = prepare(index.packages.getValue(id),frame,true,loopEdge(id).nativeLoop,id)
|
private fun prepare(id: String,frame: Int): Slot = prepare(index.packages.getValue(id),frame,true,loopEdge(id).nativeLoop,id)
|
||||||
@@ -106,7 +121,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
} else if(returning) restoreAction(slot) else plan()
|
} else if(returning) restoreAction(slot) else plan()
|
||||||
}
|
}
|
||||||
},{
|
},{
|
||||||
if(active && visible===slot && inBridge) finishBridge()
|
if(active && slot.live && visible===slot && inBridge && revealing==null) {
|
||||||
|
if(slot.key?.index==slot.pack.body.frameCount-1) finishBridge() else fail()
|
||||||
|
}
|
||||||
},{ if(active && slot.live && slot in slots) fail() })
|
},{ if(active && slot.live && slot in slots) fail() })
|
||||||
return slot
|
return slot
|
||||||
}
|
}
|
||||||
@@ -116,7 +133,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private fun plan() {
|
private fun plan() {
|
||||||
val source=visible ?: return
|
val source=visible ?: return
|
||||||
val key=source.key ?: return
|
val key=source.key ?: return
|
||||||
if(inBridge || !active || returning || actionStarted) return
|
if(inBridge || revealing!=null || !active || returning || actionStarted) return
|
||||||
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else selectedId
|
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else selectedId
|
||||||
var reviewedLoop: ConversationEdge?=null
|
var reviewedLoop: ConversationEdge?=null
|
||||||
if(source.packageId==wanted) {
|
if(source.packageId==wanted) {
|
||||||
@@ -138,18 +155,23 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
visualIntensity=0,packageId=index.fallbackId,degraded=true,reason="whole_package_path_unavailable")
|
visualIntensity=0,packageId=index.fallbackId,degraded=true,reason="whole_package_path_unavailable")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if(next.mouthRuntime==null && !allowSilentEdges) {
|
||||||
|
report("queued_emotion_bridge_has_no_own_mouth",key);return
|
||||||
|
}
|
||||||
if(target!=null && (target?.packageId!=next.to || target?.entry!=next.toFrame)) { discardTarget();return }
|
if(target!=null && (target?.packageId!=next.to || target?.entry!=next.toFrame)) { discardTarget();return }
|
||||||
if(slots.size+(if(target==null) 2 else 1)>3) return
|
if(slots.size+(if(target==null) 2 else 1)>3) return
|
||||||
edge=next
|
edge=next
|
||||||
if(target==null) target=prepare(next.to,next.toFrame)
|
if(target==null) target=prepare(next.to,next.toFrame)
|
||||||
bridge=prepare(ContinuousAvatarPack(next.clip,emptyList(),emptyMap(),index.root,"",false),0,false,false,null)
|
bridge=prepare(next.mouthRuntime ?: ContinuousAvatarPack(next.clip,emptyList(),emptyMap(),index.root,"",false),0,next.mouthRuntime!=null,false,null)
|
||||||
applyMouth()
|
applyMouth()
|
||||||
}
|
}
|
||||||
val current=edge ?: return
|
val current=edge ?: return
|
||||||
if(source.closedMouth && key.index==current.fromFrame && target?.key?.index==current.toFrame && bridge?.key?.index==0) {
|
if((current.mouthRuntime!=null || source.closedMouth) && key.index==current.fromFrame && target?.key?.index==current.toFrame && bridge?.key?.index==0) {
|
||||||
val destination=checkNotNull(bridge)
|
val destination=checkNotNull(bridge)
|
||||||
inBridge=true;visible=destination;closeSlot(source);reveal(destination.number)
|
activate(destination) {
|
||||||
report("bridge",destination.key);destination.port.advance()
|
inBridge=true;visible=destination;closeSlot(source);reveal(destination.number)
|
||||||
|
report("bridge",destination.key);destination.port.advance()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private fun finishBridge() {
|
private fun finishBridge() {
|
||||||
@@ -157,9 +179,20 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
val destination=target ?: return fail()
|
val destination=target ?: return fail()
|
||||||
val current=edge ?: return fail()
|
val current=edge ?: return fail()
|
||||||
if(destination.key?.index!=current.toFrame) return fail()
|
if(destination.key?.index!=current.toFrame) return fail()
|
||||||
visible=destination;target=null;bridge=null;edge=null;inBridge=false
|
activate(destination) {
|
||||||
closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key)
|
visible=destination;target=null;bridge=null;edge=null;inBridge=false
|
||||||
applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance()
|
closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key)
|
||||||
|
applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun activate(destination: Slot,ready: ()->Unit) {
|
||||||
|
if(revealing!=null) return
|
||||||
|
revealing=destination
|
||||||
|
destination.port.activateMouth(talk && action==null && destination.pack.apertureMode,generation,++revision) {
|
||||||
|
if(active && destination.live && revealing===destination) {
|
||||||
|
revealing=null;ready()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
private fun discardTarget() { target?.let(::closeSlot);target=null }
|
private fun discardTarget() { target?.let(::closeSlot);target=null }
|
||||||
private fun discardRoute() { bridge?.let(::closeSlot);bridge=null;edge=null;discardTarget() }
|
private fun discardRoute() { bridge?.let(::closeSlot);bridge=null;edge=null;discardTarget() }
|
||||||
@@ -202,7 +235,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false
|
musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false
|
||||||
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
|
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
|
||||||
reveal(null);releaseWaiters.add(released)
|
reveal(null);releaseWaiters.add(released)
|
||||||
active=false;visible=null;target=null;bridge=null;edge=null;inBridge=false
|
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
|
||||||
closing++ // Music barrier exists before any synchronous port release callback.
|
closing++ // Music barrier exists before any synchronous port release callback.
|
||||||
slots.toList().forEach(::closeSlot)
|
slots.toList().forEach(::closeSlot)
|
||||||
music.close { closing--;releasedIfDone() }
|
music.close { closing--;releasedIfDone() }
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
|||||||
private fun start() {
|
private fun start() {
|
||||||
if(!active || released || driver!=null || textures.any { !it.isAvailable }) return
|
if(!active || released || driver!=null || textures.any { !it.isAvailable }) return
|
||||||
val index=checkNotNull(pack.emotionAction)
|
val index=checkNotNull(pack.emotionAction)
|
||||||
|
val mouthClock=ConversationMouthClock()
|
||||||
val music=AndroidMusicPort(context,textures[3]);movie=music
|
val music=AndroidMusicPort(context,textures[3]);movie=music
|
||||||
val current=ConversationMediaDriver(index,{ slot ->
|
val current=ConversationMediaDriver(index,{ slot ->
|
||||||
object: CompositeMediaPort {
|
object: CompositeMediaPort {
|
||||||
@@ -52,11 +53,14 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
|||||||
renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(textures[slot].surfaceTexture)),
|
renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(textures[slot].surfaceTexture)),
|
||||||
textures[slot].width,textures[slot].height,{ value,_->
|
textures[slot].width,textures[slot].height,{ value,_->
|
||||||
frame(value.key,value.mouth.phase=="idle" && value.selection.opacity==0f)
|
frame(value.key,value.mouth.phase=="idle" && value.selection.opacity==0f)
|
||||||
},{ reason->report(VideoPresentation(reason=reason));failed() },automatic=false,startFrame=entryFrame,mayLoop=loop,mouthEnabled=mouth,ended=ended)
|
},{ reason->report(VideoPresentation(reason=reason));failed() },automatic=false,startFrame=entryFrame,mayLoop=loop,mouthEnabled=mouth,sharedMouth=mouthClock,ended=ended)
|
||||||
renderers[slot]=renderer
|
renderers[slot]=renderer
|
||||||
}
|
}
|
||||||
override fun advance() { renderer?.advance() }
|
override fun advance() { renderer?.advance() }
|
||||||
override fun mouth(talk: Boolean,generation: Long,revision: Long) { renderer?.intent(talk,generation,revision) }
|
override fun mouth(talk: Boolean,generation: Long,revision: Long) { renderer?.intent(talk,generation,revision) }
|
||||||
|
override fun activateMouth(talk: Boolean,generation: Long,revision: Long,ready: ()->Unit) {
|
||||||
|
renderer?.activateMouth(talk,generation,revision,ready)
|
||||||
|
}
|
||||||
override fun close(released: ()->Unit) { val old=renderer;renderer=null
|
override fun close(released: ()->Unit) { val old=renderer;renderer=null
|
||||||
if(renderers[slot]===old) renderers[slot]=null
|
if(renderers[slot]===old) renderers[slot]=null
|
||||||
old?.close(released) ?: released()
|
old?.close(released) ?: released()
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ data class EmotionActionIndex(val fallbackId: String, val packages: Map<String,C
|
|||||||
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?, val edges: List<ConversationEdge> = emptyList(),val root: String="",
|
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?, val edges: List<ConversationEdge> = emptyList(),val root: String="",
|
||||||
val loopIds: Map<String,String> = emptyMap())
|
val loopIds: Map<String,String> = emptyMap())
|
||||||
data class ConversationEdge(val id: String,val from: String,val to: String,val fromFrame: Int,val toFrame: Int,
|
data class ConversationEdge(val id: String,val from: String,val to: String,val fromFrame: Int,val toFrame: Int,
|
||||||
val clip: ContinuousBodyAsset,val nativeLoop: Boolean=false)
|
val clip: ContinuousBodyAsset,val nativeLoop: Boolean=false,val mouthRuntime: ContinuousAvatarPack?=null)
|
||||||
|
|
||||||
/** Exact external manifest pin admits the whole graph. Self-approval fields have no effect.
|
/** Exact external manifest pin admits the whole graph. Self-approval fields have no effect.
|
||||||
* loadRuntime must hash-check exact bytes and all body/patch files before returning a pack.
|
* loadRuntime must hash-check exact bytes and all body/patch files before returning a pack.
|
||||||
@@ -70,11 +70,29 @@ object EmotionActionManifest {
|
|||||||
if(nativeLoop) require(edge["from"]==edge["to"] && integer(edge["fromFrame"])==from.body.frameCount-1L &&
|
if(nativeLoop) require(edge["from"]==edge["to"] && integer(edge["fromFrame"])==from.body.frameCount-1L &&
|
||||||
integer(edge["toFrame"])==0L && hash(clip["sha256"])==from.body.sha256 && pts==from.body.ptsUs &&
|
integer(edge["toFrame"])==0L && hash(clip["sha256"])==from.body.sha256 && pts==from.body.ptsUs &&
|
||||||
integer(clip["durationUs"])==from.body.durationUs)
|
integer(clip["durationUs"])==from.body.durationUs)
|
||||||
|
val mouthRuntime=edge["mouthRuntimeManifest"]?.let { value ->
|
||||||
|
require(!nativeLoop) // Native loops already use their exact package layer.
|
||||||
|
val reference=obj(value)
|
||||||
|
val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"])))
|
||||||
|
require(runtime.apertureMode && runtime.patches.size==count && runtime.patches.all { it.levels.size==5 })
|
||||||
|
require(runtime.body.sha256==clip["sha256"] && runtime.body.frameCount==count &&
|
||||||
|
runtime.body.ptsUs==pts && runtime.patches.map { it.ptsUs }==pts &&
|
||||||
|
runtime.body.width==integer(clip["width"]).toInt() && runtime.body.height==integer(clip["height"]).toInt() &&
|
||||||
|
runtime.body.durationUs==integer(clip["durationUs"]) &&
|
||||||
|
runtime.body.fpsNumerator==integer(clip["fpsNumerator"]).toInt() &&
|
||||||
|
runtime.body.fpsDenominator==integer(clip["fpsDenominator"]).toInt())
|
||||||
|
runtime
|
||||||
|
}
|
||||||
|
require(edge["mouthAllowed"]==null || edge["mouthAllowed"] is Boolean)
|
||||||
|
require(edge["mouthAllowed"]!=true || nativeLoop || mouthRuntime!=null)
|
||||||
|
require(mouthRuntime==null || edge["mouthAllowed"]!=false)
|
||||||
ConversationEdge(edge["id"] as String,edge["from"] as String,edge["to"] as String,
|
ConversationEdge(edge["id"] as String,edge["from"] as String,edge["to"] as String,
|
||||||
integer(edge["fromFrame"]).toInt(),integer(edge["toFrame"]).toInt(),
|
integer(edge["fromFrame"]).toInt(),integer(edge["toFrame"]).toInt(),
|
||||||
ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size,
|
ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size,
|
||||||
integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop)
|
integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop,mouthRuntime)
|
||||||
}
|
}
|
||||||
|
require(packages.values.sumOf { it.rgbaBytes }+
|
||||||
|
admittedEdges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES)
|
||||||
val admitted=visuals.map { visual ->
|
val admitted=visuals.map { visual ->
|
||||||
val row=rows.single { it["id"]==visual.id }
|
val row=rows.single { it["id"]==visual.id }
|
||||||
require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A")
|
require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A")
|
||||||
|
|||||||
@@ -23,3 +23,29 @@ object OfflineAvatarTrace {
|
|||||||
return Intent(mode,cycle*2+if(time>=15_000) 2 else 1,epoch,label)
|
return Intent(mode,cycle*2+if(time>=15_000) 2 else 1,epoch,label)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** A finite sequence gated by actual rendered body identity, never assumed bridge time. */
|
||||||
|
class OfflineEmotionSequence(private val turn: Long) {
|
||||||
|
private val steps=listOf(com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL,
|
||||||
|
com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY,com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL,
|
||||||
|
com.gorios.lanvoice.dialogue.RoleEmotion.SAD,com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL)
|
||||||
|
private var step=0
|
||||||
|
private var arrivedAt: Long?=null
|
||||||
|
private var finished=false
|
||||||
|
data class Sample(val reply: com.gorios.lanvoice.dialogue.ReplyEmotion,val talking: Boolean,val label: String)
|
||||||
|
fun at(elapsedMs: Long,visualEmotion: com.gorios.lanvoice.dialogue.RoleEmotion?): Sample {
|
||||||
|
if(visualEmotion==steps[step] && arrivedAt==null) arrivedAt=elapsedMs
|
||||||
|
if(visualEmotion!=steps[step]) arrivedAt=null
|
||||||
|
val arrived=arrivedAt
|
||||||
|
if(!finished && arrived!=null && elapsedMs-arrived>=2000) {
|
||||||
|
if(step<steps.lastIndex) { step++;arrivedAt=null } else finished=true
|
||||||
|
}
|
||||||
|
if(elapsedMs>=60_000) finished=true // Bound failed/unavailable asset traces, no fabricated arrival.
|
||||||
|
val emotion=steps[step]
|
||||||
|
val talk=!finished && arrivedAt!=null && elapsedMs-checkNotNull(arrivedAt) in 200..1400
|
||||||
|
return Sample(com.gorios.lanvoice.dialogue.ReplyEmotion(emotion,if(emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL) 0 else 2,
|
||||||
|
com.gorios.lanvoice.dialogue.EmotionSource.MODEL,turn,step.toLong()+1),talk,
|
||||||
|
if(finished) "emotion trace ended" else "synthetic ${emotion.wire} / actual-body gate")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -238,3 +238,74 @@ p4a-combined-01-gate/}`, `logs/action-emotion/media-wiring/sad-v2-gate.json`.
|
|||||||
No asset import/activation, APK build/publication, gateway deployment/restart,
|
No asset import/activation, APK build/publication, gateway deployment/restart,
|
||||||
new live probe or paid call. Code16 rollback remains intact. Handoff marker:
|
new live probe or paid call. Code16 rollback remains intact. Handoff marker:
|
||||||
**PARTIAL_EMOTION_PACKER_READY_INDEX_MACHINE_PASSED_AWAIT_EXACT_PI_PIN**.
|
**PARTIAL_EMOTION_PACKER_READY_INDEX_MACHINE_PASSED_AWAIT_EXACT_PI_PIN**.
|
||||||
|
|
||||||
|
### Bridge TALK recovery milestone (2026-10-13)
|
||||||
|
|
||||||
|
Baseline `fcc55b8370d212570fa1d2884bed789f5238eb4f`. The coordinator chose bridge-own
|
||||||
|
TALK layers; live conversations continue to traverse reviewed expression bridges.
|
||||||
|
`edge.mouthRuntimeManifest:{path,sha256}` is optional for old metadata, but a voice
|
||||||
|
session cannot enter an edge lacking its own layer. New edges bind bridge SHA,
|
||||||
|
actual N/PTS/fps/duration/shape and five patches per frame. Native loops keep the
|
||||||
|
same body layer; actual bridges are one-shot. All runtimes together remain32MB,
|
||||||
|
each runtime8MB. Queuing an expression no longer mutes the current body's mouth.
|
||||||
|
A shared, generation-fenced phase clock carries TALK across own body→own bridge→
|
||||||
|
own target; hidden bodies do not advance it. The destination is recomposed before
|
||||||
|
reveal, stale workers cannot reclaim its clock, and released presenters remove
|
||||||
|
cached samples. Audio/TTS never waits on these transitions. Settings distinguish
|
||||||
|
model requested expression, selected slight visual, actual body and queued reason.
|
||||||
|
The sensor/network-free preview now traverses neutral→happy→neutral→sad→neutral,
|
||||||
|
waiting on actual presented package identity, with a60s failure bound.
|
||||||
|
|
||||||
|
After the asset worker's reported transport failure, user authorized **only free
|
||||||
|
four-bridge offline recovery**. Output is isolated at
|
||||||
|
`.runtime/avatar-imports/a01-expression-action-v1/code-recovery-bridge-mouth-01/`.
|
||||||
|
No original owner directory, reference or movie was modified. All1244 old indexed
|
||||||
|
files and old exact index `000d04ea2137748e42a762e170a739c0ea5648fe14703d4980c2cc5811bc5008`
|
||||||
|
retain their hashes. New four bridge runtimes each have25 actual PTS and125 own
|
||||||
|
RGBA patches at1.1 sourcepx. Lip localization, cheek/nose tracking and each-frame
|
||||||
|
seam deformation reuse the owner's documented CPU runtime04 method; no endpoint
|
||||||
|
patch pixels are reused. Scalar phase control is shared; each runtime serializes
|
||||||
|
its own curve data. Export script is `scripts/export-bridge-own-mouth.py`.
|
||||||
|
An interrupted final metadata write (missing new docs directory) was corrected;
|
||||||
|
explicit finish verifies existing source/own hashes, without overwriting exports.
|
||||||
|
|
||||||
|
Candidate index SHA:
|
||||||
|
`e73f336123bf5e2dec2d82b97eb22cc632a4ee75bcf7f4bd0052b1ff42d95cd7`.
|
||||||
|
This is **not a new Pi pin**. Exact metadata is archived at
|
||||||
|
`manifests/a01-expression-action-v1/recovery-bridge-talk-index.json`.
|
||||||
|
Production gate passes1773 inventory files/1734 runtime references; three body
|
||||||
|
runtimes97/97/49 plus four25-frame bridge runtimes. Total RGBA5,804,040 bytes.
|
||||||
|
Seven graph edges remain three native loops/four bridges; actions empty, no dance.
|
||||||
|
|
||||||
|
Review download:
|
||||||
|
`http://192.168.31.124:8080/avatar-bridge-talk-review-e73f336123bf/code-recovery-bridge-mouth-01.tar.gz`
|
||||||
|
SHA `204a04c7ed7928da401afc0d87203075f980c567dc3a91f503f7297e1259c8bd`,
|
||||||
|
58,767,872 bytes; HTTP bytes and standalone index SHA verified. The adjacent
|
||||||
|
`review/` provides20.167s clean/annotated/mouth MP4s, all25×5 levels and both
|
||||||
|
junctions with dense face/full-body PNGs for every bridge. These are four explicitly
|
||||||
|
separate five-second synthetic TALK windows, **no real PCM**, not a full live
|
||||||
|
conversation/GL/device capture. Inherited old continuous graph preview is retained.
|
||||||
|
`machine-gate.json` and provenance contain only this task's role asset metadata.
|
||||||
|
No chat/capture/credential logs are published.
|
||||||
|
|
||||||
|
Validation:9 JVM entry points plus UI contracts;51 actual-view/binding/renderer/
|
||||||
|
MediaPlayer fixtures,15 prior driver boundaries and289 bridge timing/phase/abort/
|
||||||
|
resource assertions;14 new bridge binding/cache rejection cases,15 prior graph
|
||||||
|
rejections and2361 dynamic N×5 checks. Packaging safety17 tests includes known
|
||||||
|
previous import backup, unknown/drift/symlink preservation. Gateway archive98:
|
||||||
|
97 pass,1 existing excluded Silero model skip. Offline GLES40 base goldens plus
|
||||||
|
40 for each of four actual bridge runtimes (200 total), production shader with
|
||||||
|
2D sampler substitution. Android/app instrumentation Kotlin compilation passes;
|
||||||
|
instrumentation execution, physical GPU/AudioRecord and perceived SLA are not_run.
|
||||||
|
Naturalness and comprehensive dynamic human review are not certified; rights unknown.
|
||||||
|
|
||||||
|
No new APK built/published or bridge pack activated in this milestone. Code17 is
|
||||||
|
still free; code16 stays rollback. New exact coord pin is required before verified
|
||||||
|
replacement of the old1226-file code-owned import, backup and candidate publication.
|
||||||
|
Gateway0.8/Qwen/TTS/provider parameters and containers are unchanged; no deploy,
|
||||||
|
restart or paid/model request. Recovery's additional AI calls/known fee both0.
|
||||||
|
Original batch11 calls/knownvideo$1.44/image unknown is an earlier owner snapshot,
|
||||||
|
not a claim about later P4b/P5 production. No recovery exporter/checker remains
|
||||||
|
running. Owner resumed independent P4b/P5; recovery directory remains isolated.
|
||||||
|
|
||||||
|
Handoff: **BRIDGE_TALK_CODE_AND_FREE_INDEX_READY_AWAIT_NEW_EXACT_COORD_PIN**.
|
||||||
|
|||||||
@@ -133,3 +133,22 @@ Next pin / asset handoff (media-wiring stage, no activation):
|
|||||||
- Supply full index bytes SHA, all referenced files plus SHA/bytes, preview paths
|
- Supply full index bytes SHA, all referenced files plus SHA/bytes, preview paths
|
||||||
and Pi's independent exact index approval. A runtime-only SHA is not the index pin.
|
and Pi's independent exact index approval. A runtime-only SHA is not the index pin.
|
||||||
Do not fabricate bridges, exits, audio, naturalness or dance capability to fill gaps.
|
Do not fabricate bridges, exits, audio, naturalness or dance capability to fill gaps.
|
||||||
|
|
||||||
|
|
||||||
|
Bridge TALK extension (2026-10-13, stable optional field):
|
||||||
|
`edge.mouthRuntimeManifest:{path,sha256}` references a bridge-own schema2 runtime04.
|
||||||
|
Use packId `a01-expression-action-v1-<edgeId>-runtime-04`; relative runtime paths
|
||||||
|
resolve under its own manifest directory. Its body SHA/N/actual ptsUs/duration/fps/
|
||||||
|
480×848 shape must equal edge.clip exactly; the body path can resolve to a copy of
|
||||||
|
that unchanged bridge video. Every one of its N frames has five own source patches
|
||||||
|
(1.1 sourcepx candidate) and own coords/curves, never either endpoint's patches.
|
||||||
|
For the current four bridges N=25:125 own PNGs each, measured independently.
|
||||||
|
Optional `mouthAllowed:true` requires this runtime; missing runtime means no live
|
||||||
|
voice-session entry into that edge. Native loops reuse their existing body's layer
|
||||||
|
and must not declare another mouthRuntimeManifest. Non-native bridges are one-shot,
|
||||||
|
not looped regardless of runtime routing metadata. All conversation and bridge
|
||||||
|
runtime RGBA counts sum under32MB; each runtime remains bounded8MB/N720.
|
||||||
|
`actions:[]` remains no dance capability; ACTION mouthAllowed:false is unchanged.
|
||||||
|
The new p4a-combined-02 index, all runtime references and files inventory require a
|
||||||
|
new exact Pi pin; old000d04ea…5008 is only the old silent-bridge candidate pin.
|
||||||
|
Offline processing does not require new AI/body generation or paid calls.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -59,7 +59,8 @@ def main():
|
|||||||
try:
|
try:
|
||||||
for i,row in enumerate(m['patches']):
|
for i,row in enumerate(m['patches']):
|
||||||
raw=pipe.stdout.read(480*848*4);assert len(raw)==480*848*4
|
raw=pipe.stdout.read(480*848*4);assert len(raw)==480*848*4
|
||||||
if i not in (0,26,43,52,69,96):continue
|
fixed=(0,26,43,52,69,96) if len(m['patches'])==97 else tuple(sorted({round(k*(len(m['patches'])-1)/5) for k in range(6)}))
|
||||||
|
if i not in fixed:continue
|
||||||
body=np.frombuffer(raw,np.uint8).reshape(848,480,4)
|
body=np.frombuffer(raw,np.uint8).reshape(848,480,4)
|
||||||
for level in (0,1,2,3,4):
|
for level in (0,1,2,3,4):
|
||||||
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
|
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
|
||||||
|
|||||||
@@ -73,8 +73,10 @@ for name, main, real in suites:
|
|||||||
index_path=args.index_manifest.resolve(strict=True)
|
index_path=args.index_manifest.resolve(strict=True)
|
||||||
raw=index_path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
raw=index_path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
||||||
data=json.loads(raw);runtimes={};hashes={}
|
data=json.loads(raw);runtimes={};hashes={}
|
||||||
for row in data['conversationPackages']:
|
references=[row['runtimeManifest'] for row in data['conversationPackages']]
|
||||||
reference=row['runtimeManifest'];path=reference['path']
|
references += [edge['mouthRuntimeManifest'] for edge in data['edges'] if 'mouthRuntimeManifest' in edge]
|
||||||
|
for reference in references:
|
||||||
|
path=reference['path']
|
||||||
runtime_path=(index_path.parent/path).resolve(strict=True)
|
runtime_path=(index_path.parent/path).resolve(strict=True)
|
||||||
if not runtime_path.is_relative_to(index_path.parent): raise ValueError('Runtime path escape')
|
if not runtime_path.is_relative_to(index_path.parent): raise ValueError('Runtime path escape')
|
||||||
runtime_raw=runtime_path.read_bytes();runtime_hash=hashlib.sha256(runtime_raw).hexdigest()
|
runtime_raw=runtime_path.read_bytes();runtime_hash=hashlib.sha256(runtime_raw).hexdigest()
|
||||||
|
|||||||
@@ -0,0 +1,350 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Bounded CPU-only recovery export; no AI, no models, never edits the source pack."""
|
||||||
|
import argparse
|
||||||
|
import copy
|
||||||
|
from decimal import Decimal
|
||||||
|
from fractions import Fraction
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
FFMPEG = '/home/ubuntu/gori-bin/ffmpeg'
|
||||||
|
FFPROBE = '/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe'
|
||||||
|
LEVELS = np.array([0, .25, .5, .75, 1.])
|
||||||
|
|
||||||
|
|
||||||
|
def require(condition, reason):
|
||||||
|
if not condition:
|
||||||
|
raise ValueError(reason)
|
||||||
|
|
||||||
|
|
||||||
|
def digest(path):
|
||||||
|
with Path(path).open('rb') as stream:
|
||||||
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def write_json(path, data):
|
||||||
|
with path.open('x') as stream:
|
||||||
|
json.dump(data, stream, indent=2)
|
||||||
|
stream.write('\n')
|
||||||
|
|
||||||
|
|
||||||
|
def safe_file(root, name):
|
||||||
|
require(isinstance(name, str) and not name.startswith('/') and
|
||||||
|
all(part not in ('', '.', '..') for part in name.split('/')), 'relative file required')
|
||||||
|
path = (root/name).resolve(strict=True)
|
||||||
|
require(path.is_relative_to(root.resolve()) and path.is_file(), 'file escape')
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def decode(path, body):
|
||||||
|
probe = json.loads(subprocess.check_output([FFPROBE, '-v', 'error', '-show_streams',
|
||||||
|
'-show_frames', '-of', 'json', str(path)], timeout=60))
|
||||||
|
require(len(probe['streams']) == 1, 'silent single video track required')
|
||||||
|
stream = probe['streams'][0]
|
||||||
|
require(stream['codec_name'] == 'h264' and (stream['width'], stream['height']) == (480, 848), 'body shape/codec')
|
||||||
|
us = lambda value: int((Decimal(value)*1_000_000).to_integral_value())
|
||||||
|
pts = [us(frame['best_effort_timestamp_time']) for frame in probe['frames']]
|
||||||
|
require(pts == body['ptsUs'] and len(pts) == body['frameCount'], 'actual N/PTS mismatch')
|
||||||
|
require(us(stream['duration']) == body['durationUs'] and
|
||||||
|
Fraction(stream['r_frame_rate']) == Fraction(body['fpsNumerator'], body['fpsDenominator']), 'actual timing mismatch')
|
||||||
|
require(digest(path) == body['sha256'], 'body bytes changed')
|
||||||
|
raw = subprocess.check_output([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path),
|
||||||
|
'-map', '0:v:0', '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-'], timeout=60)
|
||||||
|
frames = np.frombuffer(raw, np.uint8).reshape(-1, 848, 480, 3)
|
||||||
|
require(len(frames) == body['frameCount'], 'full decode N')
|
||||||
|
return frames
|
||||||
|
|
||||||
|
|
||||||
|
def make_patches(frames, pts, destination):
|
||||||
|
"""Same source-seam deformation method as owner runtime04, local ROI arithmetic."""
|
||||||
|
first = frames[0].astype(float)
|
||||||
|
roi = first[103:137, 202:265]
|
||||||
|
score = roi[:, :, 0]-roi[:, :, 1]+.20*(255-roi.mean(axis=2))
|
||||||
|
ys, xs = np.where(score > np.percentile(score, 88))
|
||||||
|
cx, cy = float(np.median(xs)+202), float(np.median(ys)+103)
|
||||||
|
require(210 < cx < 252 and 111 < cy < 133, 'own first-frame lip center outside fixture bounds')
|
||||||
|
x0, x1, y0, y1 = int(cx-31), int(cx+32), int(cy-30), int(cy+17)
|
||||||
|
reference = first[y0:y1, x0:x1].mean(axis=2)
|
||||||
|
yy, xx = np.mgrid[y0:y1, x0:x1]
|
||||||
|
tracking_mask = ((yy < cy-9) | (xx < cx-22) | (xx > cx+23)) & (yy < cy+12)
|
||||||
|
patches, tracks = [], []
|
||||||
|
for i, frame in enumerate(frames):
|
||||||
|
f = frame.astype(float)
|
||||||
|
gray = f.mean(axis=2)
|
||||||
|
scores = {}
|
||||||
|
for dy in range(-8, 9):
|
||||||
|
for dx in range(-14, 15):
|
||||||
|
diff = gray[y0+dy:y1+dy, x0+dx:x1+dx]-reference
|
||||||
|
diff -= diff[tracking_mask].mean()
|
||||||
|
scores[dx, dy] = float((diff[tracking_mask]**2).mean())
|
||||||
|
dx, dy = min(scores, key=scores.get)
|
||||||
|
require(abs(dx) < 14 and abs(dy) < 8, 'tracking hit search boundary; manual review required')
|
||||||
|
cxi, cyi = cx+dx, cy+dy
|
||||||
|
left, right = int(round(cxi-15)), int(round(cxi+15))
|
||||||
|
curve = []
|
||||||
|
for x in range(left, right+1):
|
||||||
|
rows = np.arange(int(round(cyi-4)), int(round(cyi+5)))
|
||||||
|
pixels = f[rows, x]
|
||||||
|
darkness = pixels.mean(axis=1)-.6*(pixels[:, 0]-pixels[:, 1])
|
||||||
|
curve.append(float(rows[np.argmin(darkness)]))
|
||||||
|
curve = np.convolve(np.pad(curve, 2, mode='edge'), np.ones(5)/5, mode='valid')
|
||||||
|
# These bounds contain the same mask>.005 support as the owner's full-frame computation.
|
||||||
|
Y, X = np.mgrid[int(cyi)-22:int(cyi)+23, int(cxi)-19:int(cxi)+20]
|
||||||
|
seam = np.interp(X, np.arange(left, right+1), curve)
|
||||||
|
dist = Y-seam
|
||||||
|
taper = np.clip(1-((X-cxi)/17)**2, 0, 1)**1.5
|
||||||
|
vertical = np.exp(-(dist/5)**2)
|
||||||
|
mask = taper*vertical
|
||||||
|
support_y, support_x = np.where(mask > .005)
|
||||||
|
ys = slice(support_y.min(), support_y.max()+1)
|
||||||
|
xs = slice(support_x.min(), support_x.max()+1)
|
||||||
|
bx, by = int(X[ys, xs].min()), int(Y[ys, xs].min())
|
||||||
|
height, width = mask[ys, xs].shape
|
||||||
|
require(width <= 128 and height <= 128, 'patch shape cap')
|
||||||
|
levels = []
|
||||||
|
for li, aperture in enumerate(LEVELS):
|
||||||
|
gap = aperture*1.1*taper
|
||||||
|
source_y = np.clip(Y-np.where(dist >= 0, gap*.65, -gap*.35)*vertical, 0, 847)
|
||||||
|
j0 = np.floor(source_y).astype(int)
|
||||||
|
j1 = np.minimum(j0+1, 847)
|
||||||
|
fraction = (source_y-j0)[..., None]
|
||||||
|
warped = f[j0, X]*(1-fraction)+f[j1, X]*fraction
|
||||||
|
seam_rows = np.clip(np.rint(seam).astype(int), 0, 847)
|
||||||
|
interior = f[seam_rows, X]*.65
|
||||||
|
inside = np.clip((gap*.55-np.abs(dist-.05*aperture))/.6, 0, 1)*taper
|
||||||
|
warped = warped*(1-inside[..., None])+interior*inside[..., None]
|
||||||
|
if li == 0:
|
||||||
|
warped = f[Y, X]
|
||||||
|
rgba = np.dstack([np.rint(warped[ys, xs]).astype(np.uint8),
|
||||||
|
np.rint(mask[ys, xs]*255).astype(np.uint8)])
|
||||||
|
name = f'patches/{i:03d}-l{li}.png'
|
||||||
|
Image.fromarray(rgba).save(destination/name)
|
||||||
|
levels.append({'levelIndex': li, 'aperture': float(aperture), 'path': name,
|
||||||
|
'sha256': digest(destination/name)})
|
||||||
|
patches.append({'frameIndex': i, 'ptsUs': pts[i], 'x': bx, 'y': by,
|
||||||
|
'width': width, 'height': height, 'path': levels[4]['path'], 'sha256': levels[4]['sha256'],
|
||||||
|
'levels': levels, 'observedLipSeamPixels': curve.tolist(), 'seamSourceXRange': [left, right+1]})
|
||||||
|
tracks.append({'frameIndex': i, 'ptsUs': pts[i], 'dx': dx, 'dy': dy,
|
||||||
|
'ssd': scores[dx, dy], 'searchBoundary': False})
|
||||||
|
return patches, tracks, [cx, cy]
|
||||||
|
|
||||||
|
|
||||||
|
def compose(frame, patch, runtime, level):
|
||||||
|
if level == 0:
|
||||||
|
return frame
|
||||||
|
rgba = np.asarray(Image.open(runtime/patch['levels'][level]['path']).convert('RGBA'))
|
||||||
|
x, y, w, h = (patch[k] for k in ('x', 'y', 'width', 'height'))
|
||||||
|
output = frame.copy()
|
||||||
|
alpha = rgba[:, :, 3:4]/255.
|
||||||
|
output[y:y+h, x:x+w] = np.clip(np.rint(frame[y:y+h, x:x+w]*(1-alpha)+rgba[:, :, :3]*alpha), 0, 255).astype(np.uint8)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def encode(frames, path, width=480, height=848):
|
||||||
|
proc = subprocess.Popen([FFMPEG, '-nostdin', '-n', '-v', 'error', '-xerror', '-f', 'rawvideo',
|
||||||
|
'-pix_fmt', 'rgb24', '-s', f'{width}x{height}', '-r', '24', '-i', '-', '-an', '-c:v',
|
||||||
|
'libx264', '-threads', '2', '-crf', '16', '-pix_fmt', 'yuv420p', '-g', '12', '-movflags', '+faststart', str(path)], stdin=subprocess.PIPE)
|
||||||
|
try:
|
||||||
|
for frame in frames:
|
||||||
|
proc.stdin.write(frame.tobytes())
|
||||||
|
finally:
|
||||||
|
proc.stdin.close()
|
||||||
|
require(proc.wait() == 0, 'preview encoder failed')
|
||||||
|
subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path), '-f', 'null', '-'], check=True, timeout=60)
|
||||||
|
|
||||||
|
|
||||||
|
def previews(index, output, bodies, runtimes):
|
||||||
|
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 13)
|
||||||
|
all_items, trace = [], []
|
||||||
|
for edge in index['edges']:
|
||||||
|
if edge.get('nativeLoop'):
|
||||||
|
continue
|
||||||
|
own = runtimes['bridge:'+edge['id']]
|
||||||
|
source = runtimes[edge['from']]
|
||||||
|
target = runtimes[edge['to']]
|
||||||
|
items = [(edge['from'], (edge['fromFrame']-k) % len(bodies[edge['from']])) for k in range(47, -1, -1)]
|
||||||
|
items += [('bridge:'+edge['id'], i) for i in range(len(bodies['bridge:'+edge['id']]))]
|
||||||
|
items += [(edge['to'], (edge['toFrame']+k) % len(bodies[edge['to']])) for k in range(48)]
|
||||||
|
start = len(all_items)
|
||||||
|
all_items.extend(items)
|
||||||
|
trace.append({'edgeId': edge['id'], 'startFrame': start, 'bridgeStartFrame': start+48,
|
||||||
|
'bridgeEndFrameExclusive': start+48+25, 'endFrameExclusive': len(all_items),
|
||||||
|
'syntheticTalk': True, 'realPCM': False, 'realDevice': 'not_run'})
|
||||||
|
# Both junctions, own layers kept at the same fixed aperture for seam review.
|
||||||
|
dense = items[36:60]+items[61:85]
|
||||||
|
require(len(dense) == 48, 'dense junction inventory')
|
||||||
|
for view, box, width in [('face', (170, 45, 295, 165), 250), ('full', (0, 0, 480, 848), 180)]:
|
||||||
|
height = round((box[3]-box[1])*width/(box[2]-box[0]))
|
||||||
|
sheet = Image.new('RGB', (4*width, 12*(height+24)+26), (20, 20, 25))
|
||||||
|
draw = ImageDraw.Draw(sheet)
|
||||||
|
draw.text((3, 3), edge['id']+' own mouths at level3 / candidate', font=font, fill='white')
|
||||||
|
for k, (key, i) in enumerate(dense):
|
||||||
|
root, manifest = runtimes[key]
|
||||||
|
frame = compose(bodies[key][i], manifest['patches'][i], root, 3)
|
||||||
|
x, y = k % 4*width, k//4*(height+24)+26
|
||||||
|
sheet.paste(Image.fromarray(frame).crop(box).resize((width, height)), (x, y))
|
||||||
|
draw.text((x+3, y+height+2), f'{key[:19]} f{i}', font=font, fill='white')
|
||||||
|
sheet.save(output/'review'/f'{edge["id"]}-{view}-talk-junctions.png')
|
||||||
|
# All25 frames and all5 levels: engineering localization/shape evidence.
|
||||||
|
sheet = Image.new('RGB', (5*180, 25*144), (20, 20, 25))
|
||||||
|
draw = ImageDraw.Draw(sheet)
|
||||||
|
for i in range(25):
|
||||||
|
for level in range(5):
|
||||||
|
frame = compose(bodies['bridge:'+edge['id']][i], own[1]['patches'][i], own[0], level)
|
||||||
|
sheet.paste(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((180, 110)), (level*180, i*144))
|
||||||
|
draw.text((level*180+2, i*144+112), f'f{i} L{level} / own1.1px', font=font, fill='white')
|
||||||
|
sheet.save(output/'review'/f'{edge["id"]}-all25-fivelevels.png')
|
||||||
|
# Four isolated five-second windows, each has true source→bridge→target cursors.
|
||||||
|
# Between windows the cut is explicitly a new independent fixture, not a graph edge.
|
||||||
|
require(len(all_items) == 484, '20.167s preview frame count')
|
||||||
|
def render(annotated=False, mouth=False):
|
||||||
|
for k, (key, i) in enumerate(all_items):
|
||||||
|
root, manifest = runtimes[key]
|
||||||
|
# Synthetic TALK crosses every bridge; one phase per window, not reset at boundaries.
|
||||||
|
local = k % 121
|
||||||
|
alpha = .5-.5*math.cos(math.pi*local/5) if local < 6 else 1-.88*math.sin(2*math.pi*((local-6) % 12)/11)**2
|
||||||
|
level = int(np.argmin(np.abs(LEVELS-alpha)))
|
||||||
|
frame = compose(bodies[key][i], manifest['patches'][i], root, level)
|
||||||
|
if annotated:
|
||||||
|
image = Image.fromarray(frame.copy())
|
||||||
|
draw = ImageDraw.Draw(image)
|
||||||
|
draw.rectangle((0, 0, 479, 58), fill=(20, 20, 25))
|
||||||
|
draw.text((3, 3), 'SYNTHETIC TALK / NO PCM / NOT DEVICE', font=font, fill='white')
|
||||||
|
draw.text((3, 21), f'window{k//121+1} t{k/24:.3f}s {key[:31]} f{i} L{level}', font=font, fill='white')
|
||||||
|
draw.text((3, 39), 'independent windows; ownbody/ownbridge; pending Pi', font=font, fill='white')
|
||||||
|
frame = np.asarray(image)
|
||||||
|
if mouth:
|
||||||
|
frame = np.asarray(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((656, 400)))
|
||||||
|
yield frame
|
||||||
|
encode(render(), output/'review/bridge-talk-20s-clean.mp4')
|
||||||
|
encode(render(annotated=True), output/'review/bridge-talk-20s-annotated.mp4')
|
||||||
|
encode(render(mouth=True), output/'review/bridge-talk-20s-mouth.mp4', 656, 400)
|
||||||
|
write_json(output/'review/synthetic-intent-trace.json', {'fps': 24, 'frames': len(all_items), 'durationSeconds': len(all_items)/24,
|
||||||
|
'windowCuts': 'four independent fixtures, not continuous graph edges', 'windows': trace,
|
||||||
|
'TTSintentOnly': True, 'audio': False, 'naturalness': 'not_certified'})
|
||||||
|
|
||||||
|
|
||||||
|
def finalize(source, source_sha, output, old):
|
||||||
|
index=copy.deepcopy(old)
|
||||||
|
bridge_reports=[]
|
||||||
|
for edge in index['edges']:
|
||||||
|
if edge.get('nativeLoop'): continue
|
||||||
|
path=output/'runtime-bridges'/edge['id']/'manifest.json'
|
||||||
|
runtime=json.loads(path.read_bytes());body=runtime['body']
|
||||||
|
require(body['sha256']==edge['clip']['sha256'] and body['ptsUs']==edge['clip']['ptsUs'],'recovery binding drift')
|
||||||
|
require(digest(path.parent/body['path'])==body['sha256'],'recovery body drift')
|
||||||
|
for patch in runtime['patches']:
|
||||||
|
for level in patch['levels']:
|
||||||
|
require(digest(path.parent/level['path'])==level['sha256'],'recovery patch drift')
|
||||||
|
edge['mouthRuntimeManifest']={'path':str(path.relative_to(output)),'sha256':digest(path)}
|
||||||
|
edge['mouthAllowed']=True
|
||||||
|
bridge_reports.append({'edgeId':edge['id'],'bodySha256':body['sha256'],'N':body['frameCount'],'ptsUs':body['ptsUs'],'runtimeSha256':digest(path),'ownPatchCount':len(runtime['patches'])*5,'rgbaBytes':sum(p['width']*p['height']*4*5 for p in runtime['patches']),'firstFrameLipCenter':runtime['sourceSpecificLipLocalization']['firstFrameCenter']})
|
||||||
|
for row in old['files']:
|
||||||
|
require(digest(safe_file(output,row['path']))==row['sha256'],'copied source payload drift')
|
||||||
|
for name in ('bridge-talk-20s-clean.mp4','bridge-talk-20s-annotated.mp4','bridge-talk-20s-mouth.mp4'):
|
||||||
|
require((output/'review'/name).stat().st_size>0,'preview absent')
|
||||||
|
(output/'docs').mkdir(exist_ok=True)
|
||||||
|
write_json(output/'docs/free-recovery-provenance.json', {'sourceIndexSha256': source_sha,
|
||||||
|
'exportScriptSha256': digest(Path(__file__)), 'methodReusedFrom': 'asset owner build_own_mouth_current.py',
|
||||||
|
'methodSourceSha256': digest(source.parent.parent/'docs/build_own_mouth_current.py'),
|
||||||
|
'sourcePayloadUnmodified': True, 'reusedPixelsFromEndpoint': False,
|
||||||
|
'controlCurves': 'same authored scalar phase contract; every bridge has own serialized state PTS; only control timing reused',
|
||||||
|
'sourceVideosUnchanged': True, 'AIcalls': 0, 'knownFeeUSD': 0, 'bridgeReports': bridge_reports,
|
||||||
|
'naturalness': 'pending_independent_Pi', 'realDevice': 'not_run'})
|
||||||
|
index['reviewStatus'] = 'recovery_bridge_own_mouth_pending_new_exact_Pi_pin'
|
||||||
|
index['advancedGateKeep'] = False
|
||||||
|
index['publishApproval'] = False
|
||||||
|
index['sceneTimeline'] = 'See review/synthetic-intent-trace.json; four separate TALK windows, not full graph execution'
|
||||||
|
index['files'] = [{'path': str(path.relative_to(output)), 'sha256': digest(path), 'bytes': path.stat().st_size}
|
||||||
|
for path in sorted(output.rglob('*')) if path.is_file() and path != output/'manifest.json']
|
||||||
|
write_json(output/'manifest.json', index)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--source-manifest', type=Path, required=True)
|
||||||
|
parser.add_argument('--source-sha', required=True)
|
||||||
|
parser.add_argument('--output', type=Path, required=True)
|
||||||
|
parser.add_argument('--finish-existing',action='store_true',help='Finish metadata only after an interrupted export; all original/own file hashes still verified')
|
||||||
|
args = parser.parse_args()
|
||||||
|
source = args.source_manifest.resolve(strict=True)
|
||||||
|
output = args.output.resolve()
|
||||||
|
require(digest(source) == args.source_sha, 'old index drift')
|
||||||
|
require(not output.is_relative_to(source.parent) and not (output/'manifest.json').exists(), 'new independent index required')
|
||||||
|
require(args.finish_existing or not output.exists(),'existing output preserved; explicit metadata finish only')
|
||||||
|
old = json.loads(source.read_bytes())
|
||||||
|
require(old['actions'] == [] and len(old['edges']) == 7, 'only current partial P4a recovery')
|
||||||
|
for row in old['files']:
|
||||||
|
path = safe_file(source.parent, row['path'])
|
||||||
|
require(digest(path) == row['sha256'] and path.stat().st_size == row['bytes'], 'old indexed file drift')
|
||||||
|
if args.finish_existing:
|
||||||
|
finalize(source,args.source_sha,output,old)
|
||||||
|
require(digest(source)==args.source_sha,'old index drift')
|
||||||
|
print('RECOVERY_BRIDGE_INDEX_READY',digest(output/'manifest.json'),flush=True)
|
||||||
|
return
|
||||||
|
output.mkdir(parents=True)
|
||||||
|
for row in old['files']:
|
||||||
|
destination = output/row['path']
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(safe_file(source.parent, row['path']), destination)
|
||||||
|
index = copy.deepcopy(old)
|
||||||
|
bodies, runtimes = {}, {}
|
||||||
|
for row in index['conversationPackages']:
|
||||||
|
path = output/row['runtimeManifest']['path']
|
||||||
|
runtime = json.loads(path.read_bytes())
|
||||||
|
bodies[row['id']] = decode(path.parent/runtime['body']['path'], runtime['body'])
|
||||||
|
runtimes[row['id']] = (path.parent, runtime)
|
||||||
|
template = runtimes[index['fallbackPackageId']][1]
|
||||||
|
bridge_reports = []
|
||||||
|
for edge in index['edges']:
|
||||||
|
if edge.get('nativeLoop'):
|
||||||
|
continue
|
||||||
|
clip = edge['clip']
|
||||||
|
require(clip['frameCount'] == 25, 'current bridge actual25 required')
|
||||||
|
frames = decode(output/clip['path'], clip)
|
||||||
|
destination = output/'runtime-bridges'/edge['id']
|
||||||
|
for folder in ('body', 'patches', 'docs'):
|
||||||
|
(destination/folder).mkdir(parents=True)
|
||||||
|
shutil.copyfile(output/clip['path'], destination/'body/bridge.mp4')
|
||||||
|
patches, tracking, center = make_patches(frames, clip['ptsUs'], destination)
|
||||||
|
body = dict(clip, path='body/bridge.mp4')
|
||||||
|
runtime = {'schemaVersion': 2, 'identityId': 'a01', 'packId': 'a01-expression-action-v1-'+edge['id']+'-runtime-04',
|
||||||
|
'publishApproval': False, 'runtimeReady': True, 'naturalQualityStatus': 'pending_independent_Pi',
|
||||||
|
'advancedGateKeep': False, 'rightsStatus': 'unknown', 'deviceTestStatus': 'not_run',
|
||||||
|
'playbackMode': 'one_shot', 'body': body, 'patchFormat': {
|
||||||
|
'bodySha256': body['sha256'], 'format': 'PNG RGBA 8bit', 'alphaEncoding': 'straight_unassociated',
|
||||||
|
'apertureLevels': LEVELS.tolist(), 'requiresRendererExtension': True,
|
||||||
|
'loopMapping': 'actual displayed bridge frame index only; no wrap'},
|
||||||
|
'patches': patches, 'mouthStates': copy.deepcopy(template['mouthStates']),
|
||||||
|
'stateRouting': copy.deepcopy(template['stateRouting']), 'amplitudeSourcePx': 1.1,
|
||||||
|
'sourceSpecificLipLocalization': {'firstFrameCenter': center, 'method': 'own first-frame red/dark lip ROI; own cheek/nose SSD; own per-frame lip seam',
|
||||||
|
'neutralPatchReuse': False, 'trackingBoundaryFrames': []},
|
||||||
|
'additionalAICalls': 0, 'knownAdditionalFeeUSD': 0}
|
||||||
|
write_json(destination/'manifest.json', runtime)
|
||||||
|
write_json(destination/'docs/tracking.json', tracking)
|
||||||
|
edge['mouthRuntimeManifest'] = {'path': str((destination/'manifest.json').relative_to(output)), 'sha256': digest(destination/'manifest.json')}
|
||||||
|
edge['mouthAllowed'] = True
|
||||||
|
bodies['bridge:'+edge['id']] = frames
|
||||||
|
runtimes['bridge:'+edge['id']] = (destination, runtime)
|
||||||
|
bridge_reports.append({'edgeId': edge['id'], 'bodySha256': body['sha256'], 'N': len(frames), 'ptsUs': body['ptsUs'],
|
||||||
|
'runtimeSha256': digest(destination/'manifest.json'), 'ownPatchCount': len(patches)*5,
|
||||||
|
'rgbaBytes': sum(p['width']*p['height']*4*5 for p in patches), 'firstFrameLipCenter': center})
|
||||||
|
print('BRIDGE_OWN_MOUTH_EXPORTED', edge['id'], edge['mouthRuntimeManifest']['sha256'], flush=True)
|
||||||
|
previews(index, output, bodies, runtimes)
|
||||||
|
finalize(source,args.source_sha,output,old)
|
||||||
|
require(digest(source) == args.source_sha, 'old index changed during recovery')
|
||||||
|
for row in old['files']:
|
||||||
|
require(digest(safe_file(source.parent, row['path'])) == row['sha256'], 'old source payload changed during recovery')
|
||||||
|
print('RECOVERY_BRIDGE_INDEX_READY', digest(output/'manifest.json'), 'files', len(index['files']), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -87,14 +87,16 @@ def check_bundle(manifest,expected,output):
|
|||||||
files[name]=row
|
files[name]=row
|
||||||
require(sum(f['bytes'] for f in files.values())<=512_000_000,'bundle byte bound')
|
require(sum(f['bytes'] for f in files.values())<=512_000_000,'bundle byte bound')
|
||||||
return p
|
return p
|
||||||
for row in rows:
|
references=[(row['id'],row['runtimeManifest']) for row in rows]
|
||||||
ref=row['runtimeManifest'];path=add(ref['path'],ref['sha256'],2_000_000)
|
references += [('bridge:'+edge['id'],edge['mouthRuntimeManifest']) for edge in index['edges'] if 'mouthRuntimeManifest' in edge]
|
||||||
|
for runtime_id,ref in references:
|
||||||
|
path=add(ref['path'],ref['sha256'],2_000_000)
|
||||||
evidence,verified=runtime_gate.check_runtime(path,ref['sha256'],kotlin=False)
|
evidence,verified=runtime_gate.check_runtime(path,ref['sha256'],kotlin=False)
|
||||||
m=read_json(path);prefix=PurePosixPath(ref['path']).parent
|
m=read_json(path);prefix=PurePosixPath(ref['path']).parent
|
||||||
for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000)
|
for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000)
|
||||||
body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])],
|
body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])],
|
||||||
'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])}
|
'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])}
|
||||||
runtimes.append({'package_id':row['id'],**evidence})
|
runtimes.append({'package_id':runtime_id,**evidence})
|
||||||
rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound')
|
rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound')
|
||||||
require(len(index['edges'])<=100,'edge count bound')
|
require(len(index['edges'])<=100,'edge count bound')
|
||||||
for edge in index['edges']:
|
for edge in index['edges']:
|
||||||
@@ -149,6 +151,45 @@ def import_files(root,files,target):
|
|||||||
finally: os.unlink(tmp)
|
finally: os.unlink(tmp)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def replace_known_import(root,files,target,previous_report,previous_pin,backup):
|
||||||
|
"""Replace only a completely verified code-owned previous import; retain rollback."""
|
||||||
|
require(re.fullmatch('[0-9a-f]{64}',previous_pin or ''),'previous exact pin required')
|
||||||
|
require(not target.is_symlink() and target.is_dir(),'previous target directory')
|
||||||
|
old=read_json(previous_report)
|
||||||
|
require(old['status']=='passed' and old['manifest_sha256']==previous_pin,'previous report pin mismatch')
|
||||||
|
previous_manifest=target/'manifest.json'
|
||||||
|
require(file_sha(previous_manifest)==previous_pin,'previous import index drift')
|
||||||
|
inventory=read_json(previous_manifest)['files']
|
||||||
|
if isinstance(inventory,dict): inventory=[dict(row,path=name) for name,row in inventory.items()]
|
||||||
|
known={relative(row['path']):{'sha256':row['sha256'],'bytes':row['bytes']} for row in inventory}
|
||||||
|
known['manifest.json']={'sha256':previous_pin,'bytes':previous_manifest.stat().st_size}
|
||||||
|
previous=old['files']
|
||||||
|
require(all(known.get(relative(name))==row for name,row in previous.items()),'previous report not bound to pinned inventory')
|
||||||
|
require(not any(p.is_symlink() for p in target.rglob('*')),'previous import symlink preserved')
|
||||||
|
actual={str(p.relative_to(target)) for p in target.rglob('*') if p.is_file()}
|
||||||
|
require(actual==set(previous),'unknown import files preserved')
|
||||||
|
def verify_previous():
|
||||||
|
for name,row in previous.items():
|
||||||
|
p=locate(target,name)
|
||||||
|
require(p.stat().st_size==row['bytes'] and file_sha(p)==row['sha256'],'previous import bytes drift: '+name)
|
||||||
|
verify_previous()
|
||||||
|
require(not backup.exists() and not backup.is_symlink() and not backup.resolve().is_relative_to(target.resolve()),'new external backup required')
|
||||||
|
require(not backup.resolve().is_relative_to(root.resolve()),'backup must not modify asset owner directory')
|
||||||
|
target.parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
staging=Path(tempfile.mkdtemp(prefix='.emotion-stage-',dir=target.parent))
|
||||||
|
try:
|
||||||
|
import_files(root,files,staging)
|
||||||
|
verify_previous()
|
||||||
|
backup.parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
os.rename(target,backup)
|
||||||
|
try: os.rename(staging,target)
|
||||||
|
except BaseException:
|
||||||
|
os.rename(backup,target);raise
|
||||||
|
finally:
|
||||||
|
if staging.exists(): shutil.rmtree(staging)
|
||||||
|
|
||||||
|
|
||||||
def badging(path):
|
def badging(path):
|
||||||
return subprocess.check_output([str(TOOLS/'aapt'),'dump','badging',str(path)],text=True,stderr=subprocess.STDOUT)
|
return subprocess.check_output([str(TOOLS/'aapt'),'dump','badging',str(path)],text=True,stderr=subprocess.STDOUT)
|
||||||
|
|
||||||
@@ -162,7 +203,7 @@ def tested_source():
|
|||||||
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||||
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
|
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
|
||||||
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
|
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
|
||||||
evidence=json.loads((ROOT/'logs/action-emotion/media-wiring/delivery.json').read_text())
|
evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text())
|
||||||
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence')
|
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence')
|
||||||
for name,digest in evidence['source_hashes'].items():
|
for name,digest in evidence['source_hashes'].items():
|
||||||
if name.startswith('app/'): require(file_sha(ROOT/name)==digest,'media evidence drift: '+name)
|
if name.startswith('app/'): require(file_sha(ROOT/name)==digest,'media evidence drift: '+name)
|
||||||
@@ -175,6 +216,8 @@ def packaging_tests_current():
|
|||||||
|
|
||||||
|
|
||||||
def publish(report,output,requested):
|
def publish(report,output,requested):
|
||||||
|
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
|
||||||
|
'live emotion release needs bridge-own TALK runtimes')
|
||||||
tested_source();packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
tested_source();packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
||||||
version=next_version((ROOT/'artifacts').glob('*.apk'))
|
version=next_version((ROOT/'artifacts').glob('*.apk'))
|
||||||
if requested is not None:
|
if requested is not None:
|
||||||
@@ -183,7 +226,7 @@ def publish(report,output,requested):
|
|||||||
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
||||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version)],check=True,cwd=ROOT)
|
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version)],check=True,cwd=ROOT)
|
||||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
|
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
|
||||||
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-stage-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-emotion-stage-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||||
require(text in badge,'APK metadata: '+text)
|
require(text in badge,'APK metadata: '+text)
|
||||||
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
||||||
cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True)
|
cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True)
|
||||||
@@ -221,6 +264,9 @@ def main():
|
|||||||
parser.add_argument('--output',type=Path,required=True,help='New evidence directory outside owner storage')
|
parser.add_argument('--output',type=Path,required=True,help='New evidence directory outside owner storage')
|
||||||
parser.add_argument('--pi-pin',help='External exact Pi pin, required for import/publish')
|
parser.add_argument('--pi-pin',help='External exact Pi pin, required for import/publish')
|
||||||
mode=parser.add_mutually_exclusive_group();mode.add_argument('--import-only',action='store_true');mode.add_argument('--publish',action='store_true')
|
mode=parser.add_mutually_exclusive_group();mode.add_argument('--import-only',action='store_true');mode.add_argument('--publish',action='store_true')
|
||||||
|
parser.add_argument('--previous-import-report',type=Path,help='Verified previous bundle-gate.json; requires --previous-pin and fresh backup')
|
||||||
|
parser.add_argument('--previous-pin')
|
||||||
|
parser.add_argument('--backup',type=Path)
|
||||||
parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17')
|
parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17')
|
||||||
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
||||||
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
||||||
@@ -228,7 +274,13 @@ def main():
|
|||||||
output.mkdir(parents=True)
|
output.mkdir(parents=True)
|
||||||
report=check_bundle(manifest,args.sha256,output)
|
report=check_bundle(manifest,args.sha256,output)
|
||||||
if args.import_only or args.publish:
|
if args.import_only or args.publish:
|
||||||
import_files(manifest.parent,report['files'],ROOT/'app/src/main/assets'/ASSET_ROOT)
|
target=ROOT/'app/src/main/assets'/ASSET_ROOT
|
||||||
|
if args.previous_import_report:
|
||||||
|
require(args.previous_pin and args.backup,'previous replacement requires exact pin and backup')
|
||||||
|
replace_known_import(manifest.parent,report['files'],target,args.previous_import_report,args.previous_pin,args.backup)
|
||||||
|
else:
|
||||||
|
require(not args.previous_pin and not args.backup,'previous import report required')
|
||||||
|
import_files(manifest.parent,report['files'],target)
|
||||||
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
|
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
|
||||||
result=publish(report,output,args.version_code) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
result=publish(report,output,args.version_code) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||||
print(json.dumps(result,indent=2))
|
print(json.dumps(result,indent=2))
|
||||||
|
|||||||
@@ -52,6 +52,37 @@ fun conversationPackageCheck() {
|
|||||||
val oversized=listOf("neutral","happy","sad","idle1","idle2").associateWith { large }
|
val oversized=listOf("neutral","happy","sad","idle1","idle2").associateWith { large }
|
||||||
check(read(root(oversized),oversized)==null);rejected++
|
check(read(root(oversized),oversized)==null);rejected++
|
||||||
|
|
||||||
|
// Optional bridge-own runtime admission: own body SHA and every timing field.
|
||||||
|
val bridgeOwn=dynamicPack(12,24,pin)
|
||||||
|
val reference=mapOf("path" to "bridge/manifest.json","sha256" to bridgeOwn.manifestSha)
|
||||||
|
val talkGraph=graph.map { it+mapOf("mouthRuntimeManifest" to reference,"mouthAllowed" to true) }
|
||||||
|
fun bridgeRead(edges: List<Map<String,Any?>>,own: ContinuousAvatarPack=bridgeOwn)=
|
||||||
|
EmotionActionManifest.read(meta+("edges" to edges),pin,pin) { path,hash ->
|
||||||
|
(if(path=="bridge/manifest.json") own else packs[path.substringBefore('/')])?.takeIf { it.manifestSha==hash }
|
||||||
|
}
|
||||||
|
check(bridgeRead(talkGraph)?.edges?.all { it.mouthRuntime?.body?.frameCount==12 }==true)
|
||||||
|
var bridgeRejected=0
|
||||||
|
for(own in listOf(bridgeOwn.copy(body=bridgeOwn.body.copy(sha256="a".repeat(64))),
|
||||||
|
bridgeOwn.copy(body=bridgeOwn.body.copy(ptsUs=bridgeOwn.body.ptsUs.mapIndexed { i,t->t+if(i==1) 1 else 0 })),
|
||||||
|
bridgeOwn.copy(body=bridgeOwn.body.copy(durationUs=500001)),
|
||||||
|
bridgeOwn.copy(body=bridgeOwn.body.copy(fpsNumerator=30)),
|
||||||
|
bridgeOwn.copy(body=bridgeOwn.body.copy(frameCount=11)),
|
||||||
|
bridgeOwn.copy(body=bridgeOwn.body.copy(width=481)),
|
||||||
|
bridgeOwn.copy(apertureMode=false),bridgeOwn.copy(patches=bridgeOwn.patches.dropLast(1)))) {
|
||||||
|
check(bridgeRead(talkGraph,own)==null);bridgeRejected++
|
||||||
|
}
|
||||||
|
for(change in listOf(mapOf("mouthAllowed" to false),mapOf("nativeLoop" to true),
|
||||||
|
mapOf("mouthRuntimeManifest" to reference+("path" to "../bridge/manifest.json")),
|
||||||
|
mapOf("mouthRuntimeManifest" to reference+("sha256" to "a".repeat(64))))) {
|
||||||
|
check(bridgeRead(listOf(talkGraph[0]+change)+talkGraph.drop(1))==null);bridgeRejected++
|
||||||
|
}
|
||||||
|
check(read(meta+("edges" to graph.map { it+("mouthAllowed" to true) }))==null);bridgeRejected++
|
||||||
|
val inflated=bridgeOwn.copy(patches=bridgeOwn.patches.map { it.copy(width=128,height=128) })
|
||||||
|
// Each runtime remains below8MB; bridge resources together exceed32MB.
|
||||||
|
val overGraph=List(40) { i->talkGraph[0]+("id" to "extra-$i") }+talkGraph
|
||||||
|
check(inflated.rgbaBytes<BodyTimeline.MAX_RGBA_BYTES && bridgeRead(overGraph,inflated)==null);bridgeRejected++
|
||||||
|
println("PASS: bridge-own optional runtime binding and $bridgeRejected SHA/PTS/N/fps/duration/shape/path/flag/cache rejection cases; old silent graph compatible, no self approval")
|
||||||
|
|
||||||
val planner=ConversationPackagePlanner(index)
|
val planner=ConversationPackagePlanner(index)
|
||||||
planner.newTurn(10)
|
planner.newTurn(10)
|
||||||
fun expression(emotion: RoleEmotion,seq: Long=1,intensity: Int=1)=PreparedExpression(10,seq,emotion,intensity)
|
fun expression(emotion: RoleEmotion,seq: Long=1,intensity: Int=1)=PreparedExpression(10,seq,emotion,intensity)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.gorios.lanvoice.dialogue.RoleEmotion
|
|||||||
/** Callback-controlled ports test held exits and release fences, not physical playback. */
|
/** Callback-controlled ports test held exits and release fences, not physical playback. */
|
||||||
fun mediaBoundaryCheck() {
|
fun mediaBoundaryCheck() {
|
||||||
var cases=0
|
var cases=0
|
||||||
|
bridgeTalkBoundaryCheck()
|
||||||
class Port: CompositeMediaPort {
|
class Port: CompositeMediaPort {
|
||||||
lateinit var pack: ContinuousAvatarPack
|
lateinit var pack: ContinuousAvatarPack
|
||||||
lateinit var frame: (BodyFrameKey,Boolean)->Unit
|
lateinit var frame: (BodyFrameKey,Boolean)->Unit
|
||||||
@@ -29,7 +30,7 @@ fun mediaBoundaryCheck() {
|
|||||||
for(loopBridge in listOf(false,true)) {
|
for(loopBridge in listOf(false,true)) {
|
||||||
val edges=original.edges.map {
|
val edges=original.edges.map {
|
||||||
when {
|
when {
|
||||||
loopBridge && it.id=="neutral-loop" -> it.copy(clip=clip,nativeLoop=false)
|
loopBridge && it.id=="neutral-loop" -> it.copy(clip=clip,nativeLoop=false,mouthRuntime=original.edges.first { e->e.id=="neutral-happy" }.mouthRuntime)
|
||||||
!loopBridge && it.id=="neutral-happy" -> it.copy(fromFrame=0)
|
!loopBridge && it.id=="neutral-happy" -> it.copy(fromFrame=0)
|
||||||
else -> it
|
else -> it
|
||||||
}
|
}
|
||||||
@@ -74,3 +75,124 @@ fun mediaBoundaryCheck() {
|
|||||||
driver.stop {};ports.forEach { it.release?.invoke() }
|
driver.stop {};ports.forEach { it.release?.invoke() }
|
||||||
println("PASS: $cases production media driver boundary cases: frame0 exit held until target+bridge ready, actual non-native loop bridge, own-mouth whole fallback, exact frame/ordinal guards and retired callbacks; fixture only")
|
println("PASS: $cases production media driver boundary cases: frame0 exit held until target+bridge ready, actual non-native loop bridge, own-mouth whole fallback, exact frame/ordinal guards and retired callbacks; fixture only")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fun bridgeTalkBoundaryCheck() {
|
||||||
|
var cases=0
|
||||||
|
class Port: CompositeMediaPort {
|
||||||
|
lateinit var pack: ContinuousAvatarPack
|
||||||
|
lateinit var frame: (BodyFrameKey,Boolean)->Unit
|
||||||
|
lateinit var ended: ()->Unit
|
||||||
|
var talk=false;var enabled=false;var loop=false;var lastGeneration=-1L
|
||||||
|
var closed=false
|
||||||
|
var ready: (()->Unit)?=null
|
||||||
|
var holdActivation=false
|
||||||
|
override fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean,
|
||||||
|
frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) {
|
||||||
|
this.pack=pack;this.frame=frame;this.ended=ended;enabled=mouth;this.loop=loop
|
||||||
|
}
|
||||||
|
override fun advance() {}
|
||||||
|
override fun mouth(talk: Boolean,generation: Long,revision: Long) { this.talk=talk;lastGeneration=generation }
|
||||||
|
override fun activateMouth(talk: Boolean,generation: Long,revision: Long,ready: ()->Unit) {
|
||||||
|
mouth(talk,generation,revision);if(holdActivation) this.ready=ready else ready()
|
||||||
|
}
|
||||||
|
override fun close(released: ()->Unit) { closed=true;released() }
|
||||||
|
fun emit(i: Int,closedMouth: Boolean=false) { frame(BodyFrameKey(i,0,pack.body.ptsUs[i]),closedMouth) }
|
||||||
|
}
|
||||||
|
val music=object: MusicMediaPort {
|
||||||
|
override fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit) { error("not an action fixture") }
|
||||||
|
override fun start() { error("not an action fixture") }
|
||||||
|
override fun close(released: ()->Unit) { released() }
|
||||||
|
}
|
||||||
|
// Seeded public timings: audio before, at entry, inside and after each bridge.
|
||||||
|
for(audioAt in listOf(-1,0,1,12,24,25)) for(reverse in listOf(false,true)) {
|
||||||
|
val index=mediaFixtureIndex().let { old->old.copy(edges=old.edges.map { e->
|
||||||
|
if(e.nativeLoop) e else dynamicPack(25,24,e.clip.sha256).copy(root="bridge25-${e.id}/").let { own ->
|
||||||
|
e.copy(clip=own.body.copy(path=e.clip.path),mouthRuntime=own)
|
||||||
|
}
|
||||||
|
}) }
|
||||||
|
val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
|
||||||
|
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) })
|
||||||
|
driver.beginTurn(7);driver.start();val source=ports.single()
|
||||||
|
driver.intent(mediaReply(RoleEmotion.HAPPY),audioAt<0);source.emit(0)
|
||||||
|
val target=ports[1];val bridge=ports[2]
|
||||||
|
check(bridge.pack===index.edges.first { it.id=="neutral-happy" }.mouthRuntime && bridge.enabled && !bridge.loop);cases++
|
||||||
|
if(audioAt<0) { check(source.talk);cases++ } // Queued visual doesn't mute source's own layer.
|
||||||
|
(1..95).forEach { source.emit(it) }
|
||||||
|
source.emit(96)
|
||||||
|
check(trace.last()=="body_neutral");cases++ // Exact exit held until both surfaces ready.
|
||||||
|
bridge.emit(0);target.emit(0)
|
||||||
|
check(trace.last()=="bridge");cases++ // Open source can enter its own TALK bridge.
|
||||||
|
if(audioAt==0) driver.intent(mediaReply(RoleEmotion.HAPPY),true)
|
||||||
|
if(reverse) driver.intent(mediaReply(RoleEmotion.SAD,seq=3,intensity=2),audioAt<=0)
|
||||||
|
for(i in 1..24) {
|
||||||
|
if(audioAt==i) driver.intent(mediaReply(if(reverse) RoleEmotion.SAD else RoleEmotion.HAPPY,seq=4),true)
|
||||||
|
bridge.emit(i)
|
||||||
|
if(audioAt<=i) { check(bridge.talk);cases++ }
|
||||||
|
}
|
||||||
|
bridge.ended();check(trace.last()=="body_happy" && bridge.closed);cases++
|
||||||
|
if(audioAt==25) driver.intent(mediaReply(if(reverse) RoleEmotion.SAD else RoleEmotion.HAPPY,seq=5),true)
|
||||||
|
check(target.talk && !source.talk || target.talk && source.closed);cases++
|
||||||
|
driver.beginTurn(8);driver.intent(mediaReply(RoleEmotion.SAD,turn=7,seq=99),true)
|
||||||
|
check(!target.talk);cases++ // Old audio/reply cannot reopen after abort/new generation.
|
||||||
|
val before=trace.size;source.emit(96);bridge.ended()
|
||||||
|
check(trace.size==before);cases++
|
||||||
|
driver.stop {};check(ports.all { it.closed });cases++
|
||||||
|
}
|
||||||
|
// An asynchronously activated surface is not revealed until its own composition.
|
||||||
|
run {
|
||||||
|
val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
|
||||||
|
val index=mediaFixtureIndex().let { it.copy(edges=it.edges.map { e->if(e.id=="neutral-happy") e.copy(fromFrame=0) else e }) }
|
||||||
|
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) })
|
||||||
|
driver.beginTurn(7);driver.start();driver.intent(mediaReply(RoleEmotion.HAPPY),true);ports[0].emit(0)
|
||||||
|
ports[2].holdActivation=true;ports[1].emit(0);ports[2].emit(0)
|
||||||
|
check(trace.last()=="body_neutral");cases++
|
||||||
|
driver.beginTurn(8);driver.intent(mediaReply(RoleEmotion.SAD,turn=8),true)
|
||||||
|
check(ports[2].talk && ports[2].lastGeneration==ports[0].lastGeneration+1);cases++
|
||||||
|
val ready=checkNotNull(ports[2].ready);driver.stop {};val before=trace.size;ready()
|
||||||
|
check(trace.size==before && ports.all { it.closed });cases++
|
||||||
|
}
|
||||||
|
// Completion before actual final PTS is failure, never a target reveal.
|
||||||
|
run {
|
||||||
|
val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
|
||||||
|
val index=mediaFixtureIndex().let { it.copy(edges=it.edges.map { e->if(e.id=="neutral-happy") e.copy(fromFrame=0) else e }) }
|
||||||
|
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) })
|
||||||
|
driver.beginTurn(7);driver.start();driver.intent(mediaReply(RoleEmotion.HAPPY),true);ports[0].emit(0)
|
||||||
|
ports[1].emit(0);ports[2].emit(0);ports[2].ended()
|
||||||
|
check(trace.last()=="media_failed" && ports.all { it.closed });cases++
|
||||||
|
}
|
||||||
|
// Missing own layer: compatible metadata, but no voice-session bridge entry.
|
||||||
|
run {
|
||||||
|
val index=mediaFixtureIndex().let { it.copy(edges=it.edges.map { e->e.copy(mouthRuntime=null) }) }
|
||||||
|
val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
|
||||||
|
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) })
|
||||||
|
driver.beginTurn(7);driver.start();driver.intent(mediaReply(RoleEmotion.HAPPY,intensity=2),true);ports[0].emit(0)
|
||||||
|
check(ports.size==1 && ports[0].talk && trace.last()=="queued_emotion_bridge_has_no_own_mouth" && driver.selection?.selectedIntensity==2);cases++
|
||||||
|
driver.stop {}
|
||||||
|
}
|
||||||
|
// Body-independent phase crosses own97→bridge3→own49 without reopening.
|
||||||
|
val clock=ConversationMouthClock()
|
||||||
|
val a=dynamicPack(97,24,"c".repeat(64));val b=dynamicPack(3,24,"d".repeat(64))
|
||||||
|
val tokenA=Any();val tokenB=Any();val tokenC=Any()
|
||||||
|
check(clock.intent(tokenA,a.curves,true,1,1,0))
|
||||||
|
clock.sample(tokenA,0);val phase=clock.sample(tokenA,600)
|
||||||
|
check(phase.phase in setOf("talk1","talk2"));cases++
|
||||||
|
check(clock.intent(tokenB,b.curves,true,1,2,600) && clock.sample(tokenB,600).phase==phase.phase);cases++
|
||||||
|
check(!clock.intent(tokenA,a.curves,true,1,1,601));cases++
|
||||||
|
check(clock.intent(tokenC,a.curves,true,1,3,650) && clock.sample(tokenC,650).phase!="opening");cases++
|
||||||
|
check(clock.sample(tokenB,651).phase==phase.phase);cases++
|
||||||
|
clock.release(tokenB);check(clock.sample(tokenB,652).alpha==0f);cases++
|
||||||
|
clock.intent(tokenC,a.curves,false,2,1,660)
|
||||||
|
check(clock.sample(tokenC,2000).phase=="idle");cases++
|
||||||
|
clock.release(tokenA);clock.release(tokenC)
|
||||||
|
check(clock.intent(Any(),a.curves,false,3,1,120000));cases++
|
||||||
|
// Sensor-free sequence waits on actual rendered emotion; unavailable paths are bounded.
|
||||||
|
val sequence=OfflineEmotionSequence(42)
|
||||||
|
check(!sequence.at(0,null).talking && sequence.at(5000,null).reply.emotion==RoleEmotion.NEUTRAL);cases++
|
||||||
|
check(sequence.at(5001,RoleEmotion.NEUTRAL).reply.emotion==RoleEmotion.NEUTRAL);cases++
|
||||||
|
check(sequence.at(7001,RoleEmotion.NEUTRAL).reply.emotion==RoleEmotion.HAPPY);cases++
|
||||||
|
check(!sequence.at(12000,null).talking && sequence.at(12001,RoleEmotion.HAPPY).reply.intensity==2);cases++
|
||||||
|
check(sequence.at(12201,RoleEmotion.HAPPY).talking && sequence.at(14001,RoleEmotion.HAPPY).reply.emotion==RoleEmotion.NEUTRAL);cases++
|
||||||
|
check(!sequence.at(60000,null).talking);cases++
|
||||||
|
println("PASS: $cases bridge TALK timing/own-layer/latest-generation/async-composed-reveal/reversal/abort/resource/phase-continuation cases, deterministic fixtures only")
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ fun mediaFixtureIndex(): EmotionActionIndex {
|
|||||||
val bridges=packs.map { (id,p)->ConversationEdge("$id-loop",id,id,p.body.frameCount-1,0,p.body,true) }+
|
val bridges=packs.map { (id,p)->ConversationEdge("$id-loop",id,id,p.body.frameCount-1,0,p.body,true) }+
|
||||||
listOf("happy","sad").flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)->
|
listOf("happy","sad").flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)->
|
||||||
ConversationEdge("$from-$to",from,to,packs.getValue(from).body.frameCount-1,0,
|
ConversationEdge("$from-$to",from,to,packs.getValue(from).body.frameCount-1,0,
|
||||||
ContinuousBodyAsset("clips/$from-$to.mp4","f".repeat(64),480,848,3,125000,List(3) { it*1_000_000L/24 }))
|
ContinuousBodyAsset("clips/$from-$to.mp4","f".repeat(64),480,848,3,125000,List(3) { it*1_000_000L/24 }),
|
||||||
|
mouthRuntime=dynamicPack(3,24,"f".repeat(64)).copy(root="bridge-$from-$to/"))
|
||||||
} }
|
} }
|
||||||
val musicPts=List(24) { it*1_000_000L/24 }
|
val musicPts=List(24) { it*1_000_000L/24 }
|
||||||
val actions=ReviewedActionPack("a".repeat(64),listOf("asset_01","asset_02").map {
|
val actions=ReviewedActionPack("a".repeat(64),listOf("asset_01","asset_02").map {
|
||||||
@@ -35,7 +36,7 @@ fun actualMediaViewCheck() {
|
|||||||
}
|
}
|
||||||
fun rig(index: EmotionActionIndex=mediaFixtureIndex()): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<VideoPresentation>> {
|
fun rig(index: EmotionActionIndex=mediaFixtureIndex()): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<VideoPresentation>> {
|
||||||
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
|
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
|
||||||
index.edges.filterNot { it.nativeLoop }.forEach { CodecFixture.timelines[index.root+it.clip.path]=it.clip.ptsUs }
|
index.edges.filterNot { it.nativeLoop }.forEach { CodecFixture.timelines[(it.mouthRuntime?.root ?: index.root)+(it.mouthRuntime?.body?.path ?: it.clip.path)]=it.clip.ptsUs }
|
||||||
val binding=AvatarMediaBinding();binding.beginTurn(7)
|
val binding=AvatarMediaBinding();binding.beginTurn(7)
|
||||||
val reports=mutableListOf<VideoPresentation>()
|
val reports=mutableListOf<VideoPresentation>()
|
||||||
val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,reports::add)
|
val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,reports::add)
|
||||||
@@ -49,6 +50,15 @@ fun actualMediaViewCheck() {
|
|||||||
binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(200)
|
binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(200)
|
||||||
check(reports.none { it.actual=="body_happy" });cases++ // Header preloads hidden, never shows.
|
check(reports.none { it.actual=="body_happy" });cases++ // Header preloads hidden, never shows.
|
||||||
binding.intent(mediaReply(RoleEmotion.HAPPY,intensity=2),true)
|
binding.intent(mediaReply(RoleEmotion.HAPPY,intensity=2),true)
|
||||||
|
TestScheduler.until { reports.last().actual=="bridge" || reports.last().actual=="media_failed" }
|
||||||
|
check(reports.last().actual=="bridge")
|
||||||
|
val actualRenderers=view.javaClass.getDeclaredField("renderers").apply { isAccessible=true }.get(view) as Array<*>
|
||||||
|
val bridgeRenderer=actualRenderers.filterNotNull().first { value ->
|
||||||
|
value.javaClass.getDeclaredField("pack").apply { isAccessible=true }.get(value).let { (it as ContinuousAvatarPack).root=="bridge-neutral-happy/" }
|
||||||
|
}
|
||||||
|
check(bridgeRenderer.javaClass.getDeclaredField("mouthEnabled").apply { isAccessible=true }.getBoolean(bridgeRenderer));cases++
|
||||||
|
check(bridgeRenderer.javaClass.getDeclaredField("sharedMouth").apply { isAccessible=true }.get(bridgeRenderer)!=null);cases++
|
||||||
|
check(binding.currentPackageId==null && binding.visualStatus=="bridge_own_mouth");cases++
|
||||||
TestScheduler.until { reports.any { it.actual=="body_happy" } || reports.any { it.actual=="media_failed" } }
|
TestScheduler.until { reports.any { it.actual=="body_happy" } || reports.any { it.actual=="media_failed" } }
|
||||||
check(reports.none { it.actual=="media_failed" }) { reports.takeLast(6).toString() }
|
check(reports.none { it.actual=="media_failed" }) { reports.takeLast(6).toString() }
|
||||||
val selected=(driver as ConversationMediaDriver).selection
|
val selected=(driver as ConversationMediaDriver).selection
|
||||||
@@ -128,6 +138,25 @@ fun actualMediaViewCheck() {
|
|||||||
check(statuses.size==before);cases++
|
check(statuses.size==before);cases++
|
||||||
actionView.dispose();TestScheduler.advanceBy(100)
|
actionView.dispose();TestScheduler.advanceBy(100)
|
||||||
}
|
}
|
||||||
|
// Real renderer path over a25-frame own-mouth bridge, no loop or endpoint patches.
|
||||||
|
reset()
|
||||||
|
val ownBridge=dynamicPack(25,24,"f".repeat(64)).copy(root="bridge25/")
|
||||||
|
CodecFixture.timelines[ownBridge.root+ownBridge.body.path]=ownBridge.body.ptsUs
|
||||||
|
val clock=ConversationMouthClock();val prior=Any()
|
||||||
|
clock.intent(prior,ownBridge.curves,true,1,1,0);clock.sample(prior,0)
|
||||||
|
TestScheduler.advanceBy(600);val priorPhase=clock.sample(prior,600).phase
|
||||||
|
val composed=mutableListOf<ComposedBodyFrame>();var ended=false;val failures=mutableListOf<String>()
|
||||||
|
val renderer=ContinuousBodyRenderer(android.content.Context(),ownBridge,android.view.Surface(android.graphics.SurfaceTexture(5)),480,848,
|
||||||
|
{ frame,_->composed.add(frame) },failures::add,mayLoop=false,sharedMouth=clock,ended={ended=true})
|
||||||
|
renderer.intent(true,1,2)
|
||||||
|
TestScheduler.until { ended || failures.isNotEmpty() }
|
||||||
|
check(failures.isEmpty() && ended && composed.map { it.key.index }==(0..24).toList());cases++
|
||||||
|
check(composed.first().mouth.phase==priorPhase && composed.none { it.mouth.phase=="opening" });cases++
|
||||||
|
check(composed.all { it.patch===ownBridge.patches[it.key.index] && it.key.loopOrdinal==0L &&
|
||||||
|
it.selection.textureSlot/5==it.key.index });cases++
|
||||||
|
check(composed.any { it.selection.opacity==1f } && GLFixture.rendered.any { it.second==1f });cases++
|
||||||
|
renderer.close();TestScheduler.advanceBy(50)
|
||||||
|
check(GLFixture.deleted>=126 && CodecFixture.releases==1);cases++
|
||||||
CodecFixture.reset();MediaPlayer.created.clear()
|
CodecFixture.reset();MediaPlayer.created.clear()
|
||||||
println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback cases: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run")
|
println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback cases: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,6 +114,40 @@ class PackageTests(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ValueError,'source drift'): pack.import_files(source,files,target)
|
with self.assertRaisesRegex(ValueError,'source drift'): pack.import_files(source,files,target)
|
||||||
self.assertFalse(target.exists())
|
self.assertFalse(target.exists())
|
||||||
|
|
||||||
|
def replacement_fixture(self,name):
|
||||||
|
root=self.base/name;root.mkdir();target=root/'target';target.mkdir();source=root/'source';source.mkdir()
|
||||||
|
(target/'body').write_bytes(b'old');(source/'body').write_bytes(b'new')
|
||||||
|
oldrow={'sha256':pack.file_sha(target/'body'),'bytes':3}
|
||||||
|
(target/'manifest.json').write_text(json.dumps({'files':[dict(oldrow,path='body')]}))
|
||||||
|
pin=pack.file_sha(target/'manifest.json')
|
||||||
|
oldfiles={'body':oldrow,'manifest.json':{'sha256':pin,'bytes':(target/'manifest.json').stat().st_size}}
|
||||||
|
report=root/'report.json';report.write_text(json.dumps({'status':'passed','manifest_sha256':pin,'files':oldfiles}))
|
||||||
|
(source/'manifest.json').write_text('{"new":true}')
|
||||||
|
files={p.name:{'sha256':pack.file_sha(p),'bytes':p.stat().st_size} for p in source.iterdir()}
|
||||||
|
return source,files,target,report,pin,root/'backup'
|
||||||
|
|
||||||
|
def test_verified_previous_import_backup(self):
|
||||||
|
args=self.replacement_fixture('replace-valid');pack.replace_known_import(*args)
|
||||||
|
self.assertEqual((args[2]/'body').read_bytes(),b'new')
|
||||||
|
self.assertEqual((args[5]/'body').read_bytes(),b'old')
|
||||||
|
self.assertEqual(pack.file_sha(args[5]/'manifest.json'),args[4])
|
||||||
|
|
||||||
|
def test_previous_drift_and_unknown_preserved(self):
|
||||||
|
for kind in ('unknown','body_drift','manifest_drift','wrong_pin','symlink'):
|
||||||
|
args=list(self.replacement_fixture('replace-'+kind));target=args[2]
|
||||||
|
if kind=='unknown': (target/'unknown').write_bytes(b'preserve')
|
||||||
|
if kind=='body_drift': (target/'body').write_bytes(b'unknown')
|
||||||
|
if kind=='manifest_drift': (target/'manifest.json').write_text('{}')
|
||||||
|
if kind=='wrong_pin': args[4]='0'*64
|
||||||
|
if kind=='symlink': (target/'link').symlink_to(target/'body')
|
||||||
|
with self.subTest(kind=kind),self.assertRaises(ValueError): pack.replace_known_import(*args)
|
||||||
|
self.assertTrue(target.exists());self.assertFalse(args[5].exists())
|
||||||
|
|
||||||
|
def test_previous_report_not_pinned_inventory(self):
|
||||||
|
args=self.replacement_fixture('replace-forged');report=json.loads(args[3].read_text())
|
||||||
|
report['files']['body']['sha256']='0'*64;args[3].write_text(json.dumps(report))
|
||||||
|
with self.assertRaisesRegex(ValueError,'pinned inventory'): pack.replace_known_import(*args)
|
||||||
|
|
||||||
def test_version_increments_existing_apks(self):
|
def test_version_increments_existing_apks(self):
|
||||||
with patch.object(pack,'badging',side_effect=["versionCode='16'","versionCode='19'"]):
|
with patch.object(pack,'badging',side_effect=["versionCode='16'","versionCode='19'"]):
|
||||||
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)
|
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)
|
||||||
|
|||||||
Reference in New Issue
Block a user