Support bridge-owned TALK layers and recover free P4a candidate

This commit is contained in:
zenord
2026-10-13 04:35:33 +08:00
parent fcc55b8370
commit a53600db92
22 changed files with 18696 additions and 43 deletions
+31
View File
@@ -52,6 +52,37 @@ fun conversationPackageCheck() {
val oversized=listOf("neutral","happy","sad","idle1","idle2").associateWith { large }
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)
planner.newTurn(10)
fun expression(emotion: RoleEmotion,seq: Long=1,intensity: Int=1)=PreparedExpression(10,seq,emotion,intensity)
+123 -1
View File
@@ -4,6 +4,7 @@ import com.gorios.lanvoice.dialogue.RoleEmotion
/** Callback-controlled ports test held exits and release fences, not physical playback. */
fun mediaBoundaryCheck() {
var cases=0
bridgeTalkBoundaryCheck()
class Port: CompositeMediaPort {
lateinit var pack: ContinuousAvatarPack
lateinit var frame: (BodyFrameKey,Boolean)->Unit
@@ -29,7 +30,7 @@ fun mediaBoundaryCheck() {
for(loopBridge in listOf(false,true)) {
val edges=original.edges.map {
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)
else -> it
}
@@ -74,3 +75,124 @@ fun mediaBoundaryCheck() {
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")
}
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")
}
+31 -2
View File
@@ -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) }+
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,
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 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>> {
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 reports=mutableListOf<VideoPresentation>()
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)
check(reports.none { it.actual=="body_happy" });cases++ // Header preloads hidden, never shows.
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" } }
check(reports.none { it.actual=="media_failed" }) { reports.takeLast(6).toString() }
val selected=(driver as ConversationMediaDriver).selection
@@ -128,6 +138,25 @@ fun actualMediaViewCheck() {
check(statuses.size==before);cases++
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()
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")
}
+34
View File
@@ -114,6 +114,40 @@ class PackageTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError,'source drift'): pack.import_files(source,files,target)
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):
with patch.object(pack,'badging',side_effect=["versionCode='16'","versionCode='19'"]):
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)