import com.gorios.lanvoice.avatar.* import android.os.* /** Synthetic small graph, never a timestamp annotation for generated portraits. */ fun neutralGraphFixture(): SafeAvatarGraph { val ok=AnchorReview.APPROVED val anchors=listOf(VisualAnchor("A",true,ok),VisualAnchor("B",false,ok)).associateBy { it.id } fun clip(id: String,role: SafeClipRole,a: String,b: String,frames: Int): SafeAvatarClip { val duration=frames*50L val mouth=when (role) { SafeClipRole.IDLE -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,0,duration,0,frames,ok)) SafeClipRole.TALK -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,0,duration,0,frames,ok)) SafeClipRole.OPENING -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,100,duration,2,frames,ok)) else -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,100,duration,2,frames,ok)) } return SafeAvatarClip(id,"videos/$id.mp4",role,duration,frames,20,1, listOf(AnchorInterval("in",a,0,50,0,1,ok)), listOf(AnchorInterval("out",b,duration-50,duration,frames-1,frames,ok)),ok, role in setOf(SafeClipRole.IDLE,SafeClipRole.TALK),ok,ok,mouth) } val clips=listOf(clip("idle",SafeClipRole.IDLE,"A","A",10),clip("opening",SafeClipRole.OPENING,"A","B",3), clip("talk1",SafeClipRole.TALK,"B","B",10),clip("talk2",SafeClipRole.TALK,"B","B",10), clip("end-talk",SafeClipRole.CLOSING,"B","A",3)).associateBy { it.id } fun edge(a: String,b: String) = SafeAvatarEdge("${a}_$b",a,"out",b,"in",ok,latestWaitMs=1000) val edges=listOf(edge("idle","opening"),edge("opening","talk1"),edge("opening","talk2"), edge("talk1","talk2"),edge("talk2","talk1"),edge("talk1","end-talk"),edge("talk2","end-talk"),edge("end-talk","idle")) return SafeAvatarGraph(clips,anchors,edges,"idle","in",ok) } private class FramePort(private val readyDelay: Long = 0) : AnchorVideoPort { private val handler=Handler() lateinit var clip: SafeAvatarClip; lateinit var listener: AnchorVideoPort.Listener var last: DisplayedVideoFrame?=null; var held=false; var closed=false private var serial=0L override fun prepare(clip: SafeAvatarClip,entry: AnchorInterval,listener: AnchorVideoPort.Listener) { this.clip=clip; this.listener=listener handler.postDelayed({ emit(entry.startFrame,0) },readyDelay) } fun emit(frame: Int,loop: Long) { if (closed) return last=DisplayedVideoFrame(frame*50L,frame,loop,++serial); held=true; listener.frame(checkNotNull(last)) } override fun displayed() = if (held && !closed) last else null override fun advance() { val f=displayed() ?: return held=false handler.postDelayed({ if (!closed) { if (f.frame+1 < clip.frameCount) emit(f.frame+1,f.loop) else if (clip.mayLoop) emit(0,f.loop+1) else { held=true; listener.ended() } } },50) } override fun close() { closed=true; handler.removeCallbacksAndMessages(null) } } private class VideoRig(graph: SafeAvatarGraph = neutralGraphFixture(), delay: (Int) -> Long = { 0 }) { val ports=mutableListOf(); val reports=mutableListOf(); val visible=mutableListOf() val trace=mutableListOf>() var still=0; var maxPorts=0 private val random=kotlin.random.Random(7) val driver=SafeVideoDriver(graph,{ slot -> FramePort(delay(slot)).also { port -> ports += port; maxPorts=maxOf(maxPorts,ports.count { !it.closed }) } },{ visible += it },{ still++ },SystemClock::elapsedRealtime,{ reports += it; trace += SystemClock.elapsedRealtime() to it },random::nextInt) fun run(ms: Long) { TestScheduler.advanceBy(ms) } fun clip() = driver.sample().clipId } fun checkSafeDriver() { TestScheduler.reset() val graph=neutralGraphFixture() check(NeutralGraphContract.missing(graph).isEmpty()) val choices=mutableSetOf() for (seed in 0..15) { val random=kotlin.random.Random(seed) val p=SafeTransitionPlanner(graph,"opening",chooseVariant=random::nextInt) p.request(MouthIntent(1,1,1,SafeClipRole.TALK),0) val action=p.tick(ClipObservation("opening",0,0,0,1,0),0).single() as TransitionAction.Stage choices += action.ticket.target } check(choices==setOf("talk1","talk2")) for (edge in graph.edges) check(NeutralGraphContract.missing(graph.copy(edges=graph.edges-edge)).isNotEmpty()) val reversalEdge=SafeAvatarEdge("opening_end-talk","opening","out","end-talk","in",AnchorReview.APPROVED) val withReversal=graph.copy(edges=graph.edges+reversalEdge) check(NeutralGraphContract.missing(withReversal).isEmpty()) val reversing=SafeTransitionPlanner(withReversal,"opening") reversing.request(MouthIntent(1,1,null,SafeClipRole.IDLE,VisualIntentReason.ABORT),0) check((reversing.prepareNext().single() as TransitionAction.Stage).ticket.target=="end-talk") val shortcut=SafeAvatarEdge("idle_talk1","idle","out","talk1","in",AnchorReview.PENDING) // An unapproved shortcut never becomes runnable (anchor mismatch is rejected at construction). check(runCatching { graph.copy(edges=graph.edges+shortcut) }.isFailure) val open=graph.clips.getValue("opening") check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(open.id to open.copy(loop=true)))).isNotEmpty()) for (id in listOf("idle","talk1","talk2")) { val c=graph.clips.getValue(id) check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(id to c.copy(loopSeamReview=AnchorReview.PENDING)))).isNotEmpty()) } val rig=VideoRig(); rig.driver.desire(SafeClipRole.TALK,7) // newest startup intent must survive preroll rig.driver.start(); rig.run(2000) val talkSequence=rig.reports.map { it.clipId }.filter { it.startsWith("talk") }.fold(mutableListOf()) { acc,id -> if (acc.lastOrNull()!=id) acc+=id; acc } check(talkSequence.size >= 3 && talkSequence.zipWithNext().all { it.first != it.second }) check(rig.maxPorts==2 && rig.driver.sample().mouthActiveLagMs != null) rig.driver.desire(SafeClipRole.IDLE,null,true); rig.run(800) check(rig.clip()=="idle" && rig.driver.sample().closingLagMs in 0L..1000L) val traceFile=java.io.File("logs/avatar-safe-061/synthetic-player-trace.json") traceFile.parentFile.mkdirs() traceFile.writeText("{\"kind\":\"synthetic_control_trace_not_material_review\",\"fps\":20,\"seed\":7,\"events\":[" + rig.trace.joinToString(",") { (time,v) -> "{\"atMs\":$time,\"clip\":\"${v.clipId}\",\"reason\":\"${v.reason}\",\"waitMs\":${v.waitMs},\"mouthActiveLagMs\":${v.mouthActiveLagMs},\"closedStableLagMs\":${v.closingLagMs}}" } + "]}\n") // Old active/staged callbacks after stop cannot resurrect talk or reveal. val old=rig.ports.last(); rig.driver.stop(); val reveals=rig.visible.size old.listener.frame(DisplayedVideoFrame(0,0,0,999)); old.listener.ended(); old.listener.failed(VideoFailure.DECODE) check(rig.visible.size==reveals && rig.ports.all { it.closed }) rig.driver.desire(SafeClipRole.IDLE,null); rig.driver.start(); rig.run(100) check(rig.clip()=="idle") rig.driver.stop() TestScheduler.reset(); val reversal=VideoRig(); reversal.driver.start(); reversal.run(50) reversal.driver.desire(SafeClipRole.TALK,10); reversal.run(450) check(reversal.clip()=="opening") reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(800) check(reversal.clip()=="idle") // short opening completes, legal talk junction then closing reversal.driver.desire(SafeClipRole.TALK,11,true); reversal.run(10) val retiredTarget=reversal.ports.last() reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(500) check(reversal.clip()=="idle") // idle reversal cancels an obsolete hidden opening val count=reversal.visible.size retiredTarget.listener.frame(DisplayedVideoFrame(0,0,0,99)) retiredTarget.listener.failed(VideoFailure.DECODE) check(reversal.visible.size==count && reversal.clip()=="idle") reversal.driver.stop() TestScheduler.reset(); val delayed=VideoRig(delay={ 1100 }); delayed.driver.start(); delayed.run(1100) delayed.driver.desire(SafeClipRole.TALK,1); delayed.run(1100) check(delayed.clip()=="idle") // target arriving after a window cannot cause a late cut delayed.run(400); check(delayed.clip()=="opening") delayed.driver.stop() TestScheduler.reset(); val fail=VideoRig(); fail.driver.start(); fail.run(0) fail.ports.single().listener.failed(VideoFailure.DECODE) check(fail.ports.all { it.closed } && fail.reports.last().reason=="video_decode") // Presentation fitting preserves complete body on portrait/landscape/tablet canvases. for ((w,h) in listOf(320 to 640,1080 to 2400,2400 to 1080,1600 to 2560)) { val fit=fitVideo(w,h,480,848) check(fit.scaleX in 0f..1f && fit.scaleY in 0f..1f) check(kotlin.math.abs(w*fit.scaleX/(h*fit.scaleY)-480f/848)<0.0001) } // Unknown mouth evidence is never substituted with a role-name latency measurement. val noMouth=graph.copy(clips=graph.clips.mapValues { (_,c) -> c.copy(mouthStateWindows=emptyList()) }) TestScheduler.reset(); val unknown=VideoRig(noMouth); unknown.driver.start(); unknown.run(0) unknown.driver.desire(SafeClipRole.TALK,1); unknown.run(1500) check(unknown.driver.sample().mouthActiveLagMs==null && unknown.driver.sample().waitMs==1500L) unknown.driver.stop() println("PASS: production video driver with held-frame ports: complete fixed graph/all required edges, alternating legal variants, startup intent, stop/abort/reversal, target-not-ready/late-window wait, renderer epochs/background/failure, two-port bound, mouth evidence latency and fullbody Fit; synthetic materials/device pending") }