feat: deliver clean avatar home in 0.6.2 UI debug candidate
Keep the avatar mounted while all connection, permission, privacy and diagnostic controls live in a settings sheet. Save the tested continuous-body renderer, safe transition driver and foreground HELLO/permission workflow from this session. Pin runtime03 for the code14 UI-only candidate; mouth deformation remains unresolved. Add source UI contracts, an optional sensor-free device probe, exact asset import and candidate packaging checks. Portrait binaries and diagnostics remain private and untracked.
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
fun checkAutoConversation() {
|
||||
val flow=AutoConversation()
|
||||
check(flow.drive(false,false,false,0).isEmpty()) // not in actual foreground
|
||||
flow.enter()
|
||||
check(flow.drive(false,false,false,0) == listOf(EntryEffect.Connect))
|
||||
check(flow.drive(false,false,false,1).isEmpty()) // duplicate entry/pump never reconnects
|
||||
flow.connection(false,true,2)
|
||||
check(flow.drive(false,false,false,2).isEmpty()) // health/open socket isn't HELLO
|
||||
flow.connection(true,false,10)
|
||||
check(flow.drive(false,false,false,10) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
check(flow.drive(false,false,false,11).isEmpty()) // one dialog at a time
|
||||
flow.leave(); check(flow.permissionPending == EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.CAMERA,true) // wrong callback cannot clear MIC
|
||||
check(flow.permissionPending == EntryPermission.MICROPHONE)
|
||||
flow.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(flow.drive(true,false,false,12).isEmpty()) // permission result in background starts no sensor
|
||||
flow.enter()
|
||||
check(flow.drive(true,false,false,13) == listOf(EntryEffect.StartVoice,EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
flow.leave(); flow.permissionResult(EntryPermission.CAMERA,true)
|
||||
check(flow.drive(true,true,false,14).isEmpty())
|
||||
flow.enter()
|
||||
check(flow.drive(true,true,false,15) == listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
check(flow.drive(true,true,true,16).isEmpty() && flow.phase == EntryPhase.ACTIVE)
|
||||
flow.cameraOff(); flow.leave(); flow.enter()
|
||||
check(flow.drive(true,true,false,20) == listOf(EntryEffect.StartVoice))
|
||||
// Denial survives reentry and never loops a system permission request.
|
||||
val denied=AutoConversation(); denied.enter(); denied.drive(false,false,false,0); denied.connection(true,false,1)
|
||||
denied.drive(false,false,false,1); denied.permissionResult(EntryPermission.MICROPHONE,false)
|
||||
check(denied.drive(false,false,false,2) == listOf(EntryEffect.RequestPermission(EntryPermission.CAMERA)))
|
||||
denied.permissionResult(EntryPermission.CAMERA,false)
|
||||
denied.leave(); denied.enter(); denied.connection(true,false,3)
|
||||
check(denied.drive(false,false,false,3).isEmpty() && denied.phase == EntryPhase.AWAITING_PERMISSION)
|
||||
check(!denied.requestPermission(EntryPermission.MICROPHONE,true)) // UI must open settings
|
||||
check(denied.requestPermission(EntryPermission.MICROPHONE,false))
|
||||
check(denied.drive(false,false,false,4) == listOf(EntryEffect.RequestPermission(EntryPermission.MICROPHONE)))
|
||||
denied.permissionResult(EntryPermission.MICROPHONE,true)
|
||||
check(denied.drive(true,false,false,5) == listOf(EntryEffect.StartVoice)) // camera refusal does not block audio
|
||||
check(denied.drive(true,false,true,6).isEmpty() && denied.phase == EntryPhase.ACTIVE)
|
||||
// Three finite transport attempts: 1s and 3s backoff; no inference effects.
|
||||
val retry=AutoConversation(); retry.enter(); check(retry.drive(false,false,false,0).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,100); check(retry.phase == EntryPhase.ERROR && retry.retryAtMs == 1100L)
|
||||
check(!retry.retry(101))
|
||||
check(retry.drive(false,false,false,1099).isEmpty())
|
||||
check(retry.drive(false,false,false,1100).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,1200); check(retry.retryAtMs == 4200L)
|
||||
check(retry.drive(false,false,false,4200).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,4300); check(retry.retryAtMs == null && retry.attempts == 3)
|
||||
check(retry.drive(false,false,false,900000).isEmpty())
|
||||
check(retry.retry(900001)); check(retry.drive(false,false,false,900001).single() == EntryEffect.Connect)
|
||||
retry.connection(false,false,900002,busy=true)
|
||||
check(retry.retryAtMs == null && retry.drive(false,false,false,910000).isEmpty())
|
||||
retry.leave(); check(retry.drive(true,true,false,1000000).isEmpty())
|
||||
val persisted=AutoConversation(true,true,cameraInitiallyWanted=false); persisted.enter()
|
||||
persisted.drive(true,true,false,0); persisted.connection(true,false,1)
|
||||
check(persisted.drive(true,true,false,1) == listOf(EntryEffect.StartVoice))
|
||||
check(persisted.drive(true,true,false,2).isEmpty() && persisted.phase == EntryPhase.ERROR) // failed audio start isn't retried forever
|
||||
// Opening/closing in-Activity settings has no enter/leave transition or effects.
|
||||
// Recomposition while ACTIVE must never reconnect, restart capture or request permission.
|
||||
val settings=AutoConversation(true,true);settings.enter()
|
||||
settings.drive(true,true,false,0);settings.connection(true,false,1)
|
||||
check(settings.drive(true,true,false,1)==listOf(EntryEffect.StartVoice,EntryEffect.StartCamera))
|
||||
repeat(20) { check(settings.drive(true,true,true,2L+it).isEmpty() && settings.phase==EntryPhase.ACTIVE) }
|
||||
settings.cameraOff();check(settings.drive(true,true,true,30).isEmpty())
|
||||
settings.leave();check(settings.drive(true,true,true,31).isEmpty())
|
||||
println("PASS: automatic foreground connection/real HELLO/sequential permission continuations, denial/settings/camera-off, audio independent of camera/video, finite retry and busy stop, failed audio-start bound; no device permission granted by tests")
|
||||
}
|
||||
+20
-32
@@ -6,16 +6,27 @@ import android.media.MediaPlayer
|
||||
import android.view.TextureView
|
||||
|
||||
fun main() {
|
||||
checkContinuous()
|
||||
checkEngineering()
|
||||
checkSafeDriver()
|
||||
checkCodecPort()
|
||||
checkAutoConversation()
|
||||
checkSafePlanner()
|
||||
checkSafetyManifest()
|
||||
val unannotated = AvatarVideoView(Context(),AvatarPack("idle.mp4","talk.mp4","static.png","waiting.png"))
|
||||
unannotated.render(AvatarMode.IDLE,true); unannotated.render(AvatarMode.TALK,true)
|
||||
check(MediaPlayer.created.isEmpty()) // no implicit hard-cut path for unreviewed metadata
|
||||
unannotated.dispose()
|
||||
val controller = AvatarController()
|
||||
for (emotion in RoleEmotion.entries) for (intensity in if (emotion == RoleEmotion.NEUTRAL) listOf(0) else listOf(1,2)) {
|
||||
val request = ReplyEmotion(emotion, intensity, EmotionSource.MODEL,7L,2)
|
||||
val selected = controller.select(true,request,PlaybackActivity(7,3,true,960,1920))
|
||||
check(selected.mode == AvatarMode.TALK && selected.requestedEmotion == request)
|
||||
check(selected.desiredMode == AvatarMode.TALK && selected.requestedEmotion == request)
|
||||
check(selected.resolvedAssetEmotion == AssetEmotion())
|
||||
check(selected.emotionFallback == (emotion != RoleEmotion.NEUTRAL))
|
||||
check(controller.select(false,request,PlaybackActivity(7,3,true,960,1920)).mode == AvatarMode.WAITING)
|
||||
check(controller.select(true,request,PlaybackActivity(6,2,true,960,1920)).mode == AvatarMode.IDLE)
|
||||
check(controller.select(true,request,null).mode == AvatarMode.IDLE)
|
||||
check(controller.select(false,request,PlaybackActivity(7,3,true,960,1920)).desiredMode == AvatarMode.WAITING)
|
||||
check(controller.select(true,request,PlaybackActivity(6,2,true,960,1920)).desiredMode == AvatarMode.IDLE)
|
||||
check(controller.select(true,request,null).desiredMode == AvatarMode.IDLE)
|
||||
}
|
||||
val call = CallIntent()
|
||||
check(!call.consumeStart(true,true,true))
|
||||
@@ -32,33 +43,10 @@ fun main() {
|
||||
check(call.consumeStart(true,true,true))
|
||||
check(call.dial(false,true)); call.background(); check(!call.pending)
|
||||
|
||||
val view = AvatarVideoView(Context(),AvatarPack("idle.mp4","talk.mp4","static.png","waiting.png"))
|
||||
view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 2)
|
||||
val players = MediaPlayer.created.toList()
|
||||
check(players.all { it.looping && it.volume == 0f })
|
||||
val textures = view.children.filterIsInstance<TextureView>()
|
||||
players.forEach { it.prepared?.invoke(it) }
|
||||
players[0].info?.invoke(players[0],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
view.render(AvatarMode.TALK,true)
|
||||
check(textures.all { it.alpha == 0f }) // first-frame gate, static stays visible
|
||||
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
check(textures[1].alpha == 1f && textures[0].alpha == 0f)
|
||||
repeat(10) { view.render(if (it%2==0) AvatarMode.IDLE else AvatarMode.TALK,true) }
|
||||
check(MediaPlayer.created.size == 2) // switches don't recreate or seek players
|
||||
view.render(AvatarMode.WAITING,true)
|
||||
check(players.all { it.released } && textures.all { it.alpha == 0f })
|
||||
view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 4)
|
||||
players[1].info?.invoke(players[1],MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START,0)
|
||||
check(textures.all { it.alpha == 0f }) // stale callbacks can't show old talk
|
||||
val latest = MediaPlayer.created.takeLast(2)
|
||||
latest[0].error?.invoke(latest[0],1,0)
|
||||
check(latest.all { it.released } && textures.all { it.alpha == 0f })
|
||||
view.render(AvatarMode.TALK,true); check(MediaPlayer.created.size == 4) // fail to static for the current run
|
||||
view.render(AvatarMode.IDLE,false); view.render(AvatarMode.IDLE,true)
|
||||
check(MediaPlayer.created.size == 6)
|
||||
view.dispose(); check(MediaPlayer.created.all { it.released })
|
||||
val still = AvatarVideoView(Context(),AvatarPack(fallback="standing.png"))
|
||||
still.render(AvatarMode.TALK,true,5,1)
|
||||
check(MediaPlayer.created.isEmpty()) // metadata absence cannot activate arbitrary switching
|
||||
still.render(AvatarMode.IDLE,false); still.dispose()
|
||||
AvatarVideoView(Context(),null).render(AvatarMode.TALK,true)
|
||||
println("PASS: seven requested labels preserved/neutral resolved fallback, old-turn fence; explicit dial/permission/cancel/background; actual video view two muted loops/first-frame gate/switch reuse/stale callback/failure/static/missing pack/lifecycle")
|
||||
println("PASS: seven requested labels preserved/neutral resolved fallback, old-turn fence; explicit dial/permission/cancel/background; static standing view/missing graph never allocates legacy players")
|
||||
}
|
||||
|
||||
+35
-1
@@ -1,2 +1,36 @@
|
||||
package android.os
|
||||
object SystemClock { fun elapsedRealtime() = System.nanoTime()/1000000 }
|
||||
|
||||
object SystemClock { fun elapsedRealtime() = TestScheduler.now }
|
||||
class Looper { companion object { private val main = Looper(); fun getMainLooper() = main } }
|
||||
class HandlerThread(name: String) { val looper = Looper(); fun start() {} ; fun quitSafely() {} }
|
||||
class Handler(val looper: Looper = Looper.getMainLooper()) {
|
||||
fun post(action: Runnable): Boolean = postDelayed(action,0)
|
||||
fun postDelayed(action: Runnable, delay: Long): Boolean { TestScheduler.add(this,action,delay); return true }
|
||||
fun removeCallbacks(action: Runnable) { TestScheduler.remove(this,action) }
|
||||
fun removeCallbacksAndMessages(token: Any?) { TestScheduler.remove(this,null) }
|
||||
}
|
||||
object TestScheduler {
|
||||
var now = 0L; private set
|
||||
private var serial = 0L
|
||||
private data class Task(val handler: Handler,val action: Runnable,val due: Long,val serial: Long)
|
||||
private val tasks = java.util.PriorityQueue<Task>(compareBy<Task> { it.due }.thenBy { it.serial })
|
||||
fun add(handler: Handler,action: Runnable,delay: Long) { tasks.add(Task(handler,action,now+delay,++serial)) }
|
||||
fun remove(handler: Handler,action: Runnable?) { tasks.removeIf { it.handler === handler && (action == null || it.action === action) } }
|
||||
fun reset() { tasks.clear(); now=0; serial=0 }
|
||||
fun until(limitMs: Long = 10_000,condition: () -> Boolean) {
|
||||
val end=now+limitMs
|
||||
var count=0
|
||||
while (!condition()) {
|
||||
val task=tasks.poll() ?: error("No scheduled task before condition")
|
||||
check(task.due <= end && ++count <= 100_000) { "Scheduler bound exceeded" }
|
||||
now=task.due; task.action.run()
|
||||
}
|
||||
}
|
||||
fun advanceBy(ms: Long) {
|
||||
val end=now+ms; var count=0
|
||||
while (tasks.peek()?.due?.let { it <= end } == true) {
|
||||
val task=tasks.poll(); now=task.due; task.action.run(); check(++count < 100_000)
|
||||
}
|
||||
now=end
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package android.media
|
||||
|
||||
import android.view.Surface
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/** Deterministic API doubles exercise production codec control; no Android decoder claim. */
|
||||
object CodecFixture {
|
||||
var frames=20; var fps=20; var gop=4; var firstPtsUs=0L
|
||||
var timestampOffsetUs=0L; var outputEnabled=true; var configureFails=false
|
||||
var seeks=mutableListOf<Long>(); var releases=0; var flushes=0
|
||||
var rendered=mutableListOf<Long>(); var onRender: ((Long) -> Unit)? = null
|
||||
fun reset() {
|
||||
frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false
|
||||
seeks.clear(); releases=0; flushes=0; rendered.clear(); onRender=null
|
||||
}
|
||||
}
|
||||
class MediaFormat {
|
||||
companion object { const val KEY_MIME="mime"; const val KEY_WIDTH="width"; const val KEY_HEIGHT="height" }
|
||||
fun getString(key: String): String? = "video/avc"
|
||||
fun getInteger(key: String): Int = if (key == KEY_WIDTH) 480 else 848
|
||||
}
|
||||
class MediaExtractor {
|
||||
val trackCount=1; private var frame=0
|
||||
val sampleTime: Long get() = if (frame >= CodecFixture.frames) -1L else CodecFixture.firstPtsUs+frame*1_000_000L/CodecFixture.fps
|
||||
fun setDataSource(fd: java.io.FileDescriptor,offset: Long,length: Long) {}
|
||||
fun getTrackFormat(index: Int) = MediaFormat()
|
||||
fun selectTrack(index: Int) {}
|
||||
fun seekTo(time: Long,mode: Int) { CodecFixture.seeks += time; frame=(time*CodecFixture.fps/1_000_000).toInt()/CodecFixture.gop*CodecFixture.gop }
|
||||
fun readSampleData(buffer: ByteBuffer,offset: Int): Int = if (frame >= CodecFixture.frames) -1 else 1
|
||||
fun advance() { frame++ }
|
||||
fun release() {}
|
||||
companion object { const val SEEK_TO_PREVIOUS_SYNC=0 }
|
||||
}
|
||||
class MediaCodec {
|
||||
class BufferInfo { var presentationTimeUs=0L; var flags=0; var size=0 }
|
||||
private data class Output(val pts: Long,val flags: Int,val size: Int)
|
||||
private val queue=java.util.ArrayDeque<Output>(); private var current: Output? = null
|
||||
companion object {
|
||||
const val BUFFER_FLAG_END_OF_STREAM=4
|
||||
fun createDecoderByType(mime: String) = MediaCodec()
|
||||
}
|
||||
fun configure(format: MediaFormat,surface: Surface,crypto: Any?,flags: Int) { check(!CodecFixture.configureFails) }
|
||||
fun start() {}
|
||||
fun dequeueInputBuffer(timeout: Long) = 0
|
||||
fun getInputBuffer(index: Int): ByteBuffer = ByteBuffer.allocate(32)
|
||||
fun queueInputBuffer(index: Int,offset: Int,size: Int,pts: Long,flags: Int) { queue.add(Output(pts+CodecFixture.timestampOffsetUs,flags,size)) }
|
||||
fun dequeueOutputBuffer(info: BufferInfo,timeout: Long): Int {
|
||||
if (!CodecFixture.outputEnabled || queue.isEmpty()) return -1
|
||||
val out=queue.removeFirst(); current=out
|
||||
info.presentationTimeUs=out.pts; info.flags=out.flags; info.size=out.size
|
||||
return 0
|
||||
}
|
||||
fun releaseOutputBuffer(index: Int,render: Boolean) {
|
||||
if (render) { val pts=checkNotNull(current).pts; CodecFixture.rendered += pts; CodecFixture.onRender?.invoke(pts) }
|
||||
}
|
||||
fun flush() { queue.clear(); CodecFixture.flushes++ }
|
||||
fun stop() {}
|
||||
fun release() { CodecFixture.releases++ }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.content.Context
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.CodecFixture
|
||||
import android.os.*
|
||||
import android.view.Surface
|
||||
|
||||
private class CodecRig(val clip: SafeAvatarClip = syntheticGraph().clips.getValue("idle"),
|
||||
val entry: AnchorInterval = clip.entryAnchors.single(), latch: Boolean = true, wrongTimestamp: Boolean = false) {
|
||||
val port = CodecAnchorVideoPort(Context(),Surface(SurfaceTexture()),"fixture/",Looper()) { w,h -> check(w==480 && h==848) }
|
||||
val frames=mutableListOf<DisplayedVideoFrame>(); val failures=mutableListOf<VideoFailure>()
|
||||
var ended=0; var autoAdvance=false
|
||||
init {
|
||||
if (latch) CodecFixture.onRender = { pts -> Handler().post {
|
||||
port.textureLatched(pts*1000 + if (wrongTimestamp) 10_000 else 0)
|
||||
} }
|
||||
port.prepare(clip,entry,object : AnchorVideoPort.Listener {
|
||||
override fun frame(frame: DisplayedVideoFrame) { frames += frame; if (autoAdvance) port.advance() }
|
||||
override fun ended() { ended++ }
|
||||
override fun failed(reason: VideoFailure) { failures += reason }
|
||||
})
|
||||
}
|
||||
fun first() { TestScheduler.until { frames.isNotEmpty() || failures.isNotEmpty() } }
|
||||
fun close() { port.close(); TestScheduler.advanceBy(10) }
|
||||
}
|
||||
fun checkCodecPort() {
|
||||
fun reset() { TestScheduler.reset(); CodecFixture.reset() }
|
||||
reset()
|
||||
val idle=syntheticGraph().clips.getValue("idle")
|
||||
val entry=AnchorInterval("mid","closed",450,500,9,10,AnchorReview.APPROVED)
|
||||
val staged=CodecRig(idle,entry); staged.first()
|
||||
check(staged.frames.single().frame==9 && CodecFixture.seeks.single()==450_000L)
|
||||
check(CodecFixture.rendered==listOf(450_000L)) // preroll outputs discarded until entry
|
||||
TestScheduler.advanceBy(1_000); check(staged.frames.size==1) // hidden phase never advances
|
||||
val before=SystemClock.elapsedRealtime(); staged.port.advance()
|
||||
check(staged.port.displayed()==null) // old texture is not a fresh sample during flight
|
||||
TestScheduler.until { staged.frames.size==2 }
|
||||
check(SystemClock.elapsedRealtime()-before >= 50 && staged.frames.last().frame==10)
|
||||
staged.autoAdvance=true; staged.port.advance()
|
||||
TestScheduler.until { staged.frames.any { it.loop==1L } }
|
||||
check(staged.frames.last().frame==0 && CodecFixture.flushes==1 && staged.failures.isEmpty())
|
||||
staged.close(); val n=staged.frames.size; staged.port.textureLatched(0); TestScheduler.advanceBy(100)
|
||||
check(staged.frames.size==n && CodecFixture.releases==1)
|
||||
|
||||
reset(); CodecFixture.fps=24; CodecFixture.frames=12
|
||||
val c24=idle.copy(durationMs=500,frameCount=12,fpsNumerator=24,
|
||||
entryAnchors=listOf(AnchorInterval("entry","closed",0,42,0,1,AnchorReview.APPROVED)),
|
||||
safeExitWindows=listOf(AnchorInterval("exit","closed",458,500,11,12,AnchorReview.APPROVED)),mouthStateWindows=emptyList())
|
||||
val fps24=CodecRig(c24); fps24.autoAdvance=true; fps24.first()
|
||||
TestScheduler.until { fps24.frames.any { it.loop==1L } }
|
||||
check(fps24.frames.take(12).map { it.frame }==(0..11).toList() && fps24.failures.isEmpty())
|
||||
check(fps24.frames[11].positionMs==458L)
|
||||
fps24.close()
|
||||
|
||||
reset(); val bridge=CodecRig(syntheticGraph().clips.getValue("opening")); bridge.autoAdvance=true; bridge.first()
|
||||
TestScheduler.until { bridge.ended==1 }
|
||||
check(bridge.frames.size==20 && bridge.frames.last().frame==19 && CodecFixture.flushes==0)
|
||||
check(bridge.port.displayed()?.frame==19); bridge.close()
|
||||
|
||||
reset(); val timestamp=CodecRig(wrongTimestamp=true); timestamp.first()
|
||||
check(timestamp.failures==listOf(VideoFailure.TIMESTAMP)); timestamp.close()
|
||||
reset(); val noLatch=CodecRig(latch=false)
|
||||
TestScheduler.until { noLatch.failures.isNotEmpty() }
|
||||
check(noLatch.failures==listOf(VideoFailure.FRAME_TIMEOUT)); noLatch.close()
|
||||
reset(); CodecFixture.outputEnabled=false; val stuck=CodecRig()
|
||||
TestScheduler.until { stuck.failures.isNotEmpty() }
|
||||
check(stuck.failures==listOf(VideoFailure.FRAME_TIMEOUT)); stuck.close()
|
||||
reset(); CodecFixture.configureFails=true; val resource=CodecRig(); resource.first()
|
||||
check(resource.failures==listOf(VideoFailure.DECODE)); resource.close()
|
||||
reset(); CodecFixture.firstPtsUs=50_000; val origin=CodecRig(); origin.first()
|
||||
check(origin.failures==listOf(VideoFailure.DECODE)); origin.close()
|
||||
reset(); CodecFixture.timestampOffsetUs=10_000; val cfr=CodecRig(); cfr.first()
|
||||
check(cfr.failures==listOf(VideoFailure.FORMAT)); cfr.close()
|
||||
reset(); CodecFixture.frames=10; val truncated=CodecRig(); truncated.autoAdvance=true; truncated.first()
|
||||
TestScheduler.until { truncated.failures.isNotEmpty() }
|
||||
check(truncated.failures==listOf(VideoFailure.FORMAT)); truncated.close()
|
||||
reset(); val canceled=CodecRig(); canceled.close(); TestScheduler.advanceBy(10_000)
|
||||
check(canceled.frames.isEmpty() && canceled.failures.isEmpty())
|
||||
println("PASS: production codec control with deterministic Android API doubles: seek/preroll, latched entry/held phase, in-flight sample fence, frame pacing, approved wrap, nonloop tail, timestamp/decode/resource/early-EOS errors, watchdogs and canceled callbacks; hardware decoder/device pending")
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.content.Context
|
||||
import android.graphics.*
|
||||
import android.media.CodecFixture
|
||||
import android.opengl.GLFixture
|
||||
import android.os.TestScheduler
|
||||
import android.view.Surface
|
||||
|
||||
private val runtimeSha="b".repeat(64)
|
||||
fun continuousFixture(): Map<String,Any?> {
|
||||
val ids=listOf("idle","opening","talk1","talk2","end-talk")
|
||||
return mapOf("schemaVersion" to 1,"packId" to "a01-neutral-graph-v1-runtime-03","identityId" to "a01","publishApproval" to false,"runtimeReady" to true,
|
||||
"body" to mapOf("path" to "body/idle.mp4","sha256" to runtimeSha,"width" to 480,"height" to 848,"frameCount" to 97,
|
||||
"durationUs" to 4041667,"fpsNumerator" to 24,"fpsDenominator" to 1,"hasAudio" to false,
|
||||
"frameDurationUsNumerator" to 1000000,"frameDurationUsDenominator" to 24),
|
||||
"patchFormat" to mapOf("format" to "PNG RGBA 8bit","alphaEncoding" to "straight_unassociated"),
|
||||
"patches" to (0..96).map { mapOf("frameIndex" to it,"ptsUs" to it*1000000L/24,"path" to "patches/$it.png","sha256" to runtimeSha,
|
||||
"x" to 211,"y" to 112,"width" to 40,"height" to 22) },
|
||||
"mouthStates" to ids.map { id ->
|
||||
val bridge=id in setOf("opening","end-talk")
|
||||
val alpha=when(id) {
|
||||
"idle" -> List(12) { 0f }
|
||||
"opening" -> listOf(0f,.1f,.35f,.65f,.9f,1f)
|
||||
"end-talk" -> listOf(1f,.9f,.65f,.35f,.1f,0f)
|
||||
else -> listOf(1f,.8f,.4f,.1f,.4f,.8f,.8f,.4f,.1f,.4f,.8f,1f)
|
||||
}
|
||||
mapOf("id" to id,"durationMs" to if(bridge) 250 else 500,"frameCount" to alpha.size,"fpsNumerator" to 24,"fpsDenominator" to 1,
|
||||
"entryMouthAnchor" to if(id in setOf("idle","opening")) "A" else "B",
|
||||
"exitMouthAnchor" to if(id in setOf("idle","end-talk")) "A" else "B","globalAlphaByFrame" to alpha)
|
||||
},"stateRouting" to mapOf("idle" to listOf("idle","opening"),"opening" to listOf("talk1","talk2","end-talk"),
|
||||
"talk1" to listOf("talk1","talk2","end-talk"),"talk2" to listOf("talk1","talk2","end-talk"),"end-talk" to listOf("idle")))
|
||||
}
|
||||
fun continuousPack(): ContinuousAvatarPack = checkNotNull(ContinuousAvatarManifest.read(continuousFixture(),runtimeSha,runtimeSha,true,"runtime/"))
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkContinuous() {
|
||||
val root=continuousFixture();val pack=continuousPack()
|
||||
check(ContinuousAvatarManifest.read(root,runtimeSha,runtimeSha,false,"runtime/")==null)
|
||||
check(ContinuousAvatarManifest.read(root,"c".repeat(64),runtimeSha,true,"runtime/")==null)
|
||||
fun invalid(r: Map<String,Any?>) { check(ContinuousAvatarManifest.read(r,runtimeSha,runtimeSha,true,"runtime/")==null) }
|
||||
val patches=root["patches"] as List<Map<String,Any?>>
|
||||
for(c in listOf(mapOf("x" to -1),mapOf("x" to 479),mapOf("width" to 129),mapOf("path" to "../secret.png"),mapOf("ptsUs" to 90000),mapOf("frameIndex" to 2),mapOf("y" to Double.NaN)))
|
||||
invalid(root+("patches" to listOf(patches.first()+c)+patches.drop(1)))
|
||||
invalid(root+("patches" to patches.drop(1)))
|
||||
invalid(root+("publishApproval" to true))
|
||||
invalid(root+("patchFormat" to mapOf("format" to "PNG RGBA 8bit","alphaEncoding" to "premultiplied")))
|
||||
val routing=root["stateRouting"] as Map<String,Any?>
|
||||
invalid(root+("stateRouting" to routing+("end-talk" to listOf("talk1"))))
|
||||
val states=root["mouthStates"] as List<Map<String,Any?>>
|
||||
invalid(root+("mouthStates" to listOf(states.first()+("globalAlphaByFrame" to List(12){1f}))+states.drop(1)))
|
||||
|
||||
val mouth=ContinuousMouth(pack.curves) {0}
|
||||
check(mouth.sample(0).alpha==0f)
|
||||
check(mouth.request(true,1,1));check(mouth.sample(100).phase=="opening")
|
||||
check(!mouth.request(false,0,99));check(!mouth.request(false,1,1))
|
||||
check(mouth.sample(350).phase=="talk1")
|
||||
check(mouth.sample(850).phase=="talk2")
|
||||
check(mouth.request(false,2,1));check(!mouth.request(true,1,999))
|
||||
check(mouth.sample(1000).phase=="talk2") // stop finishes current small unit
|
||||
check(mouth.sample(1350).phase=="end-talk")
|
||||
check(mouth.request(true,2,2))
|
||||
check(mouth.sample(1500).phase=="end-talk")
|
||||
check(mouth.sample(1600).phase=="opening" && mouth.sample(1600).alpha==0f)
|
||||
val reversal=ContinuousMouth(pack.curves){0}
|
||||
reversal.request(true,1,1);reversal.sample(0);reversal.request(false,1,2)
|
||||
check(reversal.sample(250).phase=="end-talk");check(reversal.sample(500).phase=="idle")
|
||||
val seed=kotlin.random.Random(7);val random=ContinuousMouth(pack.curves,seed::nextInt)
|
||||
random.request(true,1,1);random.sample(0);var last=""
|
||||
repeat(20) { val p=random.sample(250+it*500L).phase;check(p in setOf("talk1","talk2") && p!=last);last=p }
|
||||
|
||||
val gate=ContinuousFramePresenter(pack){0};gate.intent(true,1,1)
|
||||
val observed=mutableListOf<ComposedBodyFrame>()
|
||||
repeat(2) { loop ->
|
||||
repeat(97) { index ->
|
||||
val pts=index*1_000_000L/24;gate.decoded(pts)
|
||||
gate.present(pts*1000,(loop*97L+index)*42) { observed+=it }
|
||||
check(observed.last().key==BodyFrameKey(index,loop.toLong(),pts))
|
||||
check(observed.last().patch.frameIndex==index)
|
||||
if(index==20) gate.intent(false,2,1)
|
||||
}
|
||||
gate.wrap()
|
||||
}
|
||||
gate.close();check(gate.present(0,9000){ error("stale callback drawn") }==null)
|
||||
check(runCatching { ContinuousFrameClock().decoded(41666) }.isFailure)
|
||||
val clock=ContinuousFrameClock();clock.decoded(0)
|
||||
check(runCatching { clock.latched(9999999) }.isFailure)
|
||||
check(runCatching { ContinuousFrameClock().wrap() }.isFailure)
|
||||
for((w,h) in listOf(480 to 848,1080 to 1920,1920 to 1080,800 to 1280,1200 to 800)) {
|
||||
val rect=bodyFit(w,h);check(rect.left>=0 && rect.top>=0 && rect.width<=w+.01f && rect.height<=h+.01f)
|
||||
check(kotlin.math.abs(rect.width/rect.height-480f/848)<.0001f)
|
||||
}
|
||||
val p=pack.patches.first();check(patchUv(p.x+20,p.y+11,p)==(.5f to .5f));check(patchUv(p.x-1,p.y,p)==null)
|
||||
for(b in listOf(0f,.123f,1f)) for(a in listOf(0f,.5f,1f)) check(composeMouthChannel(b,.8f,a,0f)==b)
|
||||
check(kotlin.math.abs(composeMouthChannel(.2f,.8f,.5f,.5f)-.35f)<.00001)
|
||||
checkContinuousRenderer(pack)
|
||||
println("PASS: continuous runtime strict hash/bounds/97frame/routing/alpha parser; independent mouth state/latest generation/abort/reversal/random continuation; actual decoded-latched frame+loop indexing; Fit/patch mapping/alpha-zero; atomic presenter lifecycle and failure fences")
|
||||
}
|
||||
private fun checkContinuousRenderer(pack: ContinuousAvatarPack) {
|
||||
fun reset() { TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false;CodecFixture.frames=97;CodecFixture.fps=24 }
|
||||
fun rig(): Triple<ContinuousBodyRenderer,MutableList<ComposedBodyFrame>,MutableList<String>> {
|
||||
val frames=mutableListOf<ComposedBodyFrame>();val errors=mutableListOf<String>()
|
||||
CodecFixture.onRender={ pts -> SurfaceTexture.lastCreated?.emit(pts*1000) }
|
||||
val renderer=ContinuousBodyRenderer(Context(),pack,Surface(SurfaceTexture()),1080,1920,{f,_->frames+=f},{errors+=it})
|
||||
return Triple(renderer,frames,errors)
|
||||
}
|
||||
reset();val (renderer,frames,errors)=rig()
|
||||
renderer.intent(true,1,1);TestScheduler.advanceBy(2000);renderer.intent(false,2,1)
|
||||
TestScheduler.advanceBy(2500)
|
||||
check(errors.isEmpty() && frames.size>97 && frames[97].key.index==0 && frames[97].key.loopOrdinal==1L)
|
||||
check(GLFixture.swaps==frames.size && GLFixture.draws==frames.size)
|
||||
check(frames.map { it.key.index+1 }==GLFixture.rendered.map { it.first })
|
||||
check(frames.last().mouth.phase=="idle")
|
||||
val before=frames.size;renderer.close();TestScheduler.advanceBy(1000)
|
||||
check(frames.size==before && CodecFixture.releases==1 && GLFixture.deleted==98 && GLFixture.terminated==1)
|
||||
reset();val (timestamp,_,timestampErrors)=rig();CodecFixture.onRender={pts->SurfaceTexture.lastCreated?.emit(pts*1000+100000)}
|
||||
TestScheduler.advanceBy(100);check(timestampErrors.size==1);timestamp.close()
|
||||
reset();GLFixture.swapFails=true;val (swap,swapFrames,swapErrors)=rig();TestScheduler.advanceBy(100)
|
||||
check(swapFrames.isEmpty() && swapErrors.size==1 && CodecFixture.releases==1);swap.close()
|
||||
reset();BitmapFactory.wrongSize=true;val (size,sizeFrames,sizeErrors)=rig();TestScheduler.advanceBy(100)
|
||||
check(sizeFrames.isEmpty() && sizeErrors.size==1);size.close();BitmapFactory.wrongSize=false
|
||||
reset();CodecFixture.onRender=null;val (timeout,_,timeoutErrors)=rig();CodecFixture.onRender=null
|
||||
TestScheduler.advanceBy(2100);check(timeoutErrors.size==1);timeout.close()
|
||||
reset();val (cancel,cancelFrames,_)=rig();cancel.close();TestScheduler.advanceBy(100)
|
||||
check(cancelFrames.isEmpty())
|
||||
println("PASS: real ContinuousBodyRenderer with deterministic Android MediaCodec/EGL doubles: one atomic draw/swap per decoded+latched body frame, 97frame wrap, patch selection, stop body continuity, timestamp/swap/size/timeout failures and resource teardown; actual GPU/device pending")
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private class TestPort : AnchorVideoPort {
|
||||
private lateinit var listener: AnchorVideoPort.Listener
|
||||
private var held: DisplayedVideoFrame? = null
|
||||
private var serial=0L
|
||||
override fun prepare(clip: SafeAvatarClip, entry: AnchorInterval, listener: AnchorVideoPort.Listener) { this.listener=listener }
|
||||
fun frame(ms: Long, index: Int) { held=DisplayedVideoFrame(ms,index,0,++serial); listener.frame(checkNotNull(held)) }
|
||||
override fun displayed()=held
|
||||
override fun advance() { held=null }
|
||||
override fun close() { held=null }
|
||||
}
|
||||
|
||||
fun engineeringFixture(): Map<String,Any?> {
|
||||
val ids=listOf("idle","opening","talk1","talk2","end-talk")
|
||||
val rows=ids.map { id ->
|
||||
val bridge=id in setOf("opening","end-talk")
|
||||
mapOf("id" to id,"path" to "controlled-01/delivery/$id.mp4","frameCount" to if(bridge) 6 else 12,
|
||||
"durationMs" to if(bridge) 250.0 else 500.0,"fpsNumerator" to 24,"fpsDenominator" to 1,
|
||||
"width" to 480,"height" to 848,"hasAudio" to false,
|
||||
"entryAnchor" to if(id in setOf("idle","opening")) "A" else "B",
|
||||
"exitAnchor" to if(id in setOf("idle","end-talk")) "A" else "B")
|
||||
}
|
||||
val pairs=listOf("idle" to "idle","idle" to "opening","opening" to "talk1","opening" to "talk2",
|
||||
"opening" to "end-talk","talk1" to "talk1","talk1" to "talk2","talk2" to "talk1",
|
||||
"talk2" to "talk2","talk1" to "end-talk","talk2" to "end-talk","end-talk" to "idle")
|
||||
return mapOf("schemaVersion" to 1,"packId" to "a01-neutral-graph-v1-controlled-01","identityId" to "a01",
|
||||
"publishApproval" to false,"naturalQualityStatus" to "not_approved",
|
||||
"safeTransitions" to mapOf("version" to 1,"reviewStatus" to "pending","transitions" to emptyList<Any>()),"assets" to rows,
|
||||
"candidateGraph" to mapOf("exitPolicy" to "complete_candidate_node_at_shared_rendered_anchor",
|
||||
"earliestExitFrames" to ids.associateWith { if(it in setOf("opening","end-talk")) 5 else 11 },
|
||||
"edges" to pairs.map { (s,t) -> mapOf("source" to s,"target" to t,"anchor" to if(s in setOf("idle","end-talk")) "A" else "B") }))
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkEngineering() {
|
||||
val root=engineeringFixture(); val hash=EngineeringGraphAdmission.MANIFEST_SHA
|
||||
check(EngineeringGraphAdmission.read(root,hash,false)==null)
|
||||
check(EngineeringGraphAdmission.read(root,"0".repeat(64),true)==null)
|
||||
val graph=checkNotNull(EngineeringGraphAdmission.read(root,hash,true))
|
||||
check(graph.review==AnchorReview.TECHNICAL_DEBUG && NeutralGraphContract.missing(graph).isEmpty())
|
||||
check(graph.clips.values.all { it.mouthStateWindows.isEmpty() })
|
||||
check(NeutralGraphContract.missing(graph.copy(review=AnchorReview.APPROVED)).isNotEmpty())
|
||||
check(!graph.copy(review=AnchorReview.APPROVED).approved(graph.edges.first()))
|
||||
check(SafeAvatarManifest.read(root,hash,setOf(hash)).status==SafetyManifestStatus.REVIEW_PENDING)
|
||||
for(edge in graph.edges) check(NeutralGraphContract.missing(graph.copy(edges=graph.edges-edge)).isNotEmpty() || edge.source=="opening" && edge.target=="end-talk")
|
||||
val candidate=root["candidateGraph"] as Map<String,Any?>
|
||||
fun changed(c: Map<String,Any?>) = EngineeringGraphAdmission.read(root+("candidateGraph" to (candidate+c)),hash,true)
|
||||
check(changed(mapOf("earliestExitFrames" to mapOf("idle" to 10)))==null)
|
||||
check(changed(mapOf("edges" to (candidate["edges"] as List<*>).drop(1)))==null)
|
||||
check(changed(mapOf("exitPolicy" to "force_cut"))==null)
|
||||
val assets=root["assets"] as List<Map<String,Any?>>
|
||||
for(change in listOf(mapOf("path" to "../other.mp4"),mapOf("hasAudio" to true),mapOf("durationMs" to 500.5),mapOf("entryAnchor" to "B")))
|
||||
check(EngineeringGraphAdmission.read(root+("assets" to listOf(assets.first()+change)+assets.drop(1)),hash,true)==null)
|
||||
// Real driver with held-frame ports uses the exact technical graph, not a mock planner.
|
||||
var now=0L; val created=mutableListOf<TestPort>(); val shown=mutableListOf<Int>()
|
||||
val driver=SafeVideoDriver(graph,{ TestPort().also { created+=it } },{shown+=it},{},{now},{},chooseVariant={0})
|
||||
driver.start(); created.first().frame(0,0)
|
||||
driver.desire(SafeClipRole.TALK,1)
|
||||
created.last().frame(0,0)
|
||||
created.first().frame(417,10); check(shown.size==1)
|
||||
now=458; created.first().frame(458,11); check(shown.size==2 && driver.sample().clipId=="opening")
|
||||
driver.stop(); check(driver.sample().mouthActiveLagMs==null)
|
||||
check(OfflineAvatarTrace.at(0).mode==AvatarMode.IDLE)
|
||||
check(OfflineAvatarTrace.at(1200).mode==AvatarMode.TALK)
|
||||
check(OfflineAvatarTrace.at(7100).mode==AvatarMode.IDLE)
|
||||
check(OfflineAvatarTrace.at(12500).generation>OfflineAvatarTrace.at(12499).generation)
|
||||
check(OfflineAvatarTrace.at(20000).generation>OfflineAvatarTrace.at(19999).generation)
|
||||
println("PASS: pinned debug-only admission, production pending preserved, last-frame gates, all edges, no forged perceived mouth evidence, offline synthetic reversal/abort generations")
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package android.opengl
|
||||
|
||||
import java.nio.Buffer
|
||||
object GLFixture {
|
||||
var swaps=0;var draws=0;var deleted=0;var terminated=0;var swapFails=false;var shaderFails=false
|
||||
var alpha=0f;var patchTexture=0;var activeUnit=0
|
||||
val rendered=mutableListOf<Pair<Int,Float>>()
|
||||
fun reset() { swaps=0;draws=0;deleted=0;terminated=0;swapFails=false;shaderFails=false;alpha=0f;patchTexture=0;activeUnit=0;rendered.clear() }
|
||||
}
|
||||
class EGLDisplay
|
||||
class EGLContext
|
||||
class EGLSurface
|
||||
class EGLConfig
|
||||
object EGL14 {
|
||||
val EGL_NO_DISPLAY=EGLDisplay();val EGL_NO_CONTEXT=EGLContext();val EGL_NO_SURFACE=EGLSurface()
|
||||
const val EGL_DEFAULT_DISPLAY=0;const val EGL_RENDERABLE_TYPE=1;const val EGL_OPENGL_ES2_BIT=2
|
||||
const val EGL_SURFACE_TYPE=3;const val EGL_WINDOW_BIT=4;const val EGL_RED_SIZE=5;const val EGL_GREEN_SIZE=6
|
||||
const val EGL_BLUE_SIZE=7;const val EGL_ALPHA_SIZE=8;const val EGL_NONE=9;const val EGL_CONTEXT_CLIENT_VERSION=10
|
||||
fun eglGetDisplay(id: Int)=EGLDisplay()
|
||||
fun eglInitialize(d: EGLDisplay,v: IntArray,o: Int,v2: IntArray,o2: Int)=true
|
||||
fun eglChooseConfig(d: EGLDisplay,attrs: IntArray,o: Int,configs: Array<EGLConfig?>,co: Int,size: Int,count: IntArray,no: Int): Boolean { configs[0]=EGLConfig();count[0]=1;return true }
|
||||
fun eglCreateContext(d: EGLDisplay,c: EGLConfig?,share: EGLContext,attrs: IntArray,o: Int)=EGLContext()
|
||||
fun eglCreateWindowSurface(d: EGLDisplay,c: EGLConfig?,native: Any,attrs: IntArray,o: Int)=EGLSurface()
|
||||
fun eglMakeCurrent(d: EGLDisplay,draw: EGLSurface,read: EGLSurface,c: EGLContext)=true
|
||||
fun eglSwapBuffers(d: EGLDisplay,s: EGLSurface): Boolean { GLFixture.swaps++;return !GLFixture.swapFails }
|
||||
fun eglDestroySurface(d: EGLDisplay,s: EGLSurface)=true
|
||||
fun eglDestroyContext(d: EGLDisplay,c: EGLContext)=true
|
||||
fun eglTerminate(d: EGLDisplay): Boolean { GLFixture.terminated++;return true }
|
||||
fun eglReleaseThread()=true
|
||||
}
|
||||
object GLES11Ext { const val GL_TEXTURE_EXTERNAL_OES=100 }
|
||||
object GLES20 {
|
||||
const val GL_TEXTURE_2D=101;const val GL_TEXTURE_MIN_FILTER=102;const val GL_TEXTURE_MAG_FILTER=103
|
||||
const val GL_LINEAR=104;const val GL_TEXTURE_WRAP_S=105;const val GL_TEXTURE_WRAP_T=106;const val GL_CLAMP_TO_EDGE=107
|
||||
const val GL_RGBA=108;const val GL_UNSIGNED_BYTE=109;const val GL_NO_ERROR=0;const val GL_VERTEX_SHADER=110
|
||||
const val GL_FRAGMENT_SHADER=111;const val GL_COMPILE_STATUS=112;const val GL_TRUE=1;const val GL_LINK_STATUS=113
|
||||
const val GL_COLOR_BUFFER_BIT=114;const val GL_FLOAT=115;const val GL_TEXTURE0=116;const val GL_TEXTURE1=117;const val GL_TRIANGLE_STRIP=118
|
||||
fun glGetAttribLocation(p: Int,name: String)=if(name=="aPosition") 1 else 2
|
||||
fun glGetUniformLocation(p: Int,name: String)=when(name) { "uAlpha"->3;"uRect"->4;else->5 }
|
||||
fun glGenTextures(n: Int,ids: IntArray,o: Int) { repeat(n) { ids[o+it]=it+1 } }
|
||||
fun glBindTexture(target: Int,id: Int) { if(target==GL_TEXTURE_2D && GLFixture.activeUnit==GL_TEXTURE1) GLFixture.patchTexture=id }
|
||||
fun glTexParameteri(target: Int,name: Int,value: Int) {}
|
||||
fun glTexImage2D(target: Int,level: Int,format: Int,w: Int,h: Int,border: Int,format2: Int,type: Int,data: Buffer) {}
|
||||
fun glGetError()=GL_NO_ERROR
|
||||
fun glCreateShader(type: Int)=1
|
||||
fun glShaderSource(id: Int,source: String) {}
|
||||
fun glCompileShader(id: Int) {}
|
||||
fun glGetShaderiv(id: Int,p: Int,status: IntArray,o: Int) { status[o]=if(GLFixture.shaderFails) 0 else GL_TRUE }
|
||||
fun glDeleteShader(id: Int) {}
|
||||
fun glCreateProgram()=1
|
||||
fun glAttachShader(program: Int,shader: Int) {}
|
||||
fun glLinkProgram(program: Int) {}
|
||||
fun glGetProgramiv(id: Int,p: Int,status: IntArray,o: Int) { status[o]=GL_TRUE }
|
||||
fun glViewport(x: Int,y: Int,w: Int,h: Int) {}
|
||||
fun glClearColor(r: Float,g: Float,b: Float,a: Float) {}
|
||||
fun glClear(mask: Int) {}
|
||||
fun glUseProgram(p: Int) {}
|
||||
fun glVertexAttribPointer(location: Int,size: Int,type: Int,normalized: Boolean,stride: Int,data: Buffer) {}
|
||||
fun glEnableVertexAttribArray(location: Int) {}
|
||||
fun glUniformMatrix4fv(location: Int,count: Int,transpose: Boolean,value: FloatArray,o: Int) {}
|
||||
fun glActiveTexture(id: Int) { GLFixture.activeUnit=id }
|
||||
fun glUniform1i(location: Int,value: Int) {}
|
||||
fun glUniform4f(location: Int,a: Float,b: Float,c: Float,d: Float) {}
|
||||
fun glUniform1f(location: Int,value: Float) { if(location==3) GLFixture.alpha=value }
|
||||
fun glDrawArrays(mode: Int,first: Int,count: Int) { GLFixture.draws++;GLFixture.rendered+=GLFixture.patchTexture to GLFixture.alpha }
|
||||
fun glDeleteTextures(n: Int,textures: IntArray,o: Int) { GLFixture.deleted+=n }
|
||||
fun glDeleteProgram(p: Int) {}
|
||||
}
|
||||
@@ -1,4 +1,23 @@
|
||||
package android.graphics
|
||||
class Matrix { fun setScale(x: Float,y: Float,px: Float,py: Float) {} }
|
||||
class SurfaceTexture
|
||||
object BitmapFactory { fun decodeStream(input: java.io.InputStream): Any? = Any() }
|
||||
class SurfaceTexture(textureName: Int=0) {
|
||||
var timestamp = 0L
|
||||
private var listener: ((SurfaceTexture)->Unit)?=null
|
||||
private var handler: android.os.Handler?=null
|
||||
init { lastCreated=this }
|
||||
fun setDefaultBufferSize(w: Int,h: Int) {}
|
||||
fun setOnFrameAvailableListener(listener: (SurfaceTexture)->Unit,handler: android.os.Handler) { this.listener=listener;this.handler=handler }
|
||||
fun emit(ptsNs: Long) { timestamp=ptsNs;handler?.post { listener?.invoke(this) } }
|
||||
fun updateTexImage() {}
|
||||
fun getTransformMatrix(matrix: FloatArray) { matrix.fill(0f);listOf(0,5,10,15).forEach { matrix[it]=1f } }
|
||||
fun release() { released++ }
|
||||
companion object { var lastCreated: SurfaceTexture?=null;var released=0 }
|
||||
}
|
||||
class Bitmap(val width: Int=40,val height: Int=22) {
|
||||
fun getPixels(pixels: IntArray,offset: Int,stride: Int,x: Int,y: Int,w: Int,h: Int) { pixels.fill(0x80aa6644.toInt()) }
|
||||
fun recycle() { BitmapFactory.recycled++ }
|
||||
}
|
||||
object BitmapFactory {
|
||||
var recycled=0;var wrongSize=false
|
||||
fun decodeStream(input: java.io.InputStream): Bitmap = Bitmap(if(wrongSize) 41 else 40,22)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
package com.gorios.lanvoice.avatar
|
||||
// File loading is separately verified against imported APK bytes; no Android assets here.
|
||||
data class AvatarPack(val idle: String,val talk: String,val fallback: String,val waiting: String)
|
||||
// Loader has independent byte/hash verification; no real portrait bytes in JVM fixtures.
|
||||
data class AvatarPack(val idle: String = "",val talk: String = "",val fallback: String,val waiting: String = fallback,
|
||||
val safeGraph: SafeAvatarGraph? = null,val pathRoot: String = "",val motionStatus: String = "anchor_review_pending")
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
import android.os.*
|
||||
|
||||
/** Synthetic small graph, never a timestamp annotation for generated portraits. */
|
||||
fun neutralGraphFixture(): SafeAvatarGraph {
|
||||
val ok=AnchorReview.APPROVED
|
||||
val anchors=listOf(VisualAnchor("A",true,ok),VisualAnchor("B",false,ok)).associateBy { it.id }
|
||||
fun clip(id: String,role: SafeClipRole,a: String,b: String,frames: Int): SafeAvatarClip {
|
||||
val duration=frames*50L
|
||||
val mouth=when (role) {
|
||||
SafeClipRole.IDLE -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,0,duration,0,frames,ok))
|
||||
SafeClipRole.TALK -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,0,duration,0,frames,ok))
|
||||
SafeClipRole.OPENING -> listOf(MouthStateWindow(ReviewedMouthState.ACTIVE,100,duration,2,frames,ok))
|
||||
else -> listOf(MouthStateWindow(ReviewedMouthState.CLOSED_STABLE,100,duration,2,frames,ok))
|
||||
}
|
||||
return SafeAvatarClip(id,"videos/$id.mp4",role,duration,frames,20,1,
|
||||
listOf(AnchorInterval("in",a,0,50,0,1,ok)),
|
||||
listOf(AnchorInterval("out",b,duration-50,duration,frames-1,frames,ok)),ok,
|
||||
role in setOf(SafeClipRole.IDLE,SafeClipRole.TALK),ok,ok,mouth)
|
||||
}
|
||||
val clips=listOf(clip("idle",SafeClipRole.IDLE,"A","A",10),clip("opening",SafeClipRole.OPENING,"A","B",3),
|
||||
clip("talk1",SafeClipRole.TALK,"B","B",10),clip("talk2",SafeClipRole.TALK,"B","B",10),
|
||||
clip("end-talk",SafeClipRole.CLOSING,"B","A",3)).associateBy { it.id }
|
||||
fun edge(a: String,b: String) = SafeAvatarEdge("${a}_$b",a,"out",b,"in",ok,latestWaitMs=1000)
|
||||
val edges=listOf(edge("idle","opening"),edge("opening","talk1"),edge("opening","talk2"),
|
||||
edge("talk1","talk2"),edge("talk2","talk1"),edge("talk1","end-talk"),edge("talk2","end-talk"),edge("end-talk","idle"))
|
||||
return SafeAvatarGraph(clips,anchors,edges,"idle","in",ok)
|
||||
}
|
||||
private class FramePort(private val readyDelay: Long = 0) : AnchorVideoPort {
|
||||
private val handler=Handler()
|
||||
lateinit var clip: SafeAvatarClip; lateinit var listener: AnchorVideoPort.Listener
|
||||
var last: DisplayedVideoFrame?=null; var held=false; var closed=false
|
||||
private var serial=0L
|
||||
override fun prepare(clip: SafeAvatarClip,entry: AnchorInterval,listener: AnchorVideoPort.Listener) {
|
||||
this.clip=clip; this.listener=listener
|
||||
handler.postDelayed({ emit(entry.startFrame,0) },readyDelay)
|
||||
}
|
||||
fun emit(frame: Int,loop: Long) {
|
||||
if (closed) return
|
||||
last=DisplayedVideoFrame(frame*50L,frame,loop,++serial); held=true; listener.frame(checkNotNull(last))
|
||||
}
|
||||
override fun displayed() = if (held && !closed) last else null
|
||||
override fun advance() {
|
||||
val f=displayed() ?: return
|
||||
held=false
|
||||
handler.postDelayed({
|
||||
if (!closed) {
|
||||
if (f.frame+1 < clip.frameCount) emit(f.frame+1,f.loop)
|
||||
else if (clip.mayLoop) emit(0,f.loop+1)
|
||||
else { held=true; listener.ended() }
|
||||
}
|
||||
},50)
|
||||
}
|
||||
override fun close() { closed=true; handler.removeCallbacksAndMessages(null) }
|
||||
}
|
||||
private class VideoRig(graph: SafeAvatarGraph = neutralGraphFixture(), delay: (Int) -> Long = { 0 }) {
|
||||
val ports=mutableListOf<FramePort>(); val reports=mutableListOf<VideoPresentation>(); val visible=mutableListOf<Int>()
|
||||
val trace=mutableListOf<Pair<Long,VideoPresentation>>()
|
||||
var still=0; var maxPorts=0
|
||||
private val random=kotlin.random.Random(7)
|
||||
val driver=SafeVideoDriver(graph,{ slot -> FramePort(delay(slot)).also { port ->
|
||||
ports += port; maxPorts=maxOf(maxPorts,ports.count { !it.closed })
|
||||
} },{ visible += it },{ still++ },SystemClock::elapsedRealtime,{ reports += it; trace += SystemClock.elapsedRealtime() to it },random::nextInt)
|
||||
fun run(ms: Long) { TestScheduler.advanceBy(ms) }
|
||||
fun clip() = driver.sample().clipId
|
||||
}
|
||||
fun checkSafeDriver() {
|
||||
TestScheduler.reset()
|
||||
val graph=neutralGraphFixture()
|
||||
check(NeutralGraphContract.missing(graph).isEmpty())
|
||||
val choices=mutableSetOf<String>()
|
||||
for (seed in 0..15) {
|
||||
val random=kotlin.random.Random(seed)
|
||||
val p=SafeTransitionPlanner(graph,"opening",chooseVariant=random::nextInt)
|
||||
p.request(MouthIntent(1,1,1,SafeClipRole.TALK),0)
|
||||
val action=p.tick(ClipObservation("opening",0,0,0,1,0),0).single() as TransitionAction.Stage
|
||||
choices += action.ticket.target
|
||||
}
|
||||
check(choices==setOf("talk1","talk2"))
|
||||
for (edge in graph.edges) check(NeutralGraphContract.missing(graph.copy(edges=graph.edges-edge)).isNotEmpty())
|
||||
val reversalEdge=SafeAvatarEdge("opening_end-talk","opening","out","end-talk","in",AnchorReview.APPROVED)
|
||||
val withReversal=graph.copy(edges=graph.edges+reversalEdge)
|
||||
check(NeutralGraphContract.missing(withReversal).isEmpty())
|
||||
val reversing=SafeTransitionPlanner(withReversal,"opening")
|
||||
reversing.request(MouthIntent(1,1,null,SafeClipRole.IDLE,VisualIntentReason.ABORT),0)
|
||||
check((reversing.prepareNext().single() as TransitionAction.Stage).ticket.target=="end-talk")
|
||||
val shortcut=SafeAvatarEdge("idle_talk1","idle","out","talk1","in",AnchorReview.PENDING)
|
||||
// An unapproved shortcut never becomes runnable (anchor mismatch is rejected at construction).
|
||||
check(runCatching { graph.copy(edges=graph.edges+shortcut) }.isFailure)
|
||||
val open=graph.clips.getValue("opening")
|
||||
check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(open.id to open.copy(loop=true)))).isNotEmpty())
|
||||
for (id in listOf("idle","talk1","talk2")) {
|
||||
val c=graph.clips.getValue(id)
|
||||
check(NeutralGraphContract.missing(graph.copy(clips=graph.clips+(id to c.copy(loopSeamReview=AnchorReview.PENDING)))).isNotEmpty())
|
||||
}
|
||||
val rig=VideoRig(); rig.driver.desire(SafeClipRole.TALK,7) // newest startup intent must survive preroll
|
||||
rig.driver.start(); rig.run(2000)
|
||||
val talkSequence=rig.reports.map { it.clipId }.filter { it.startsWith("talk") }.fold(mutableListOf<String>()) { acc,id ->
|
||||
if (acc.lastOrNull()!=id) acc+=id; acc
|
||||
}
|
||||
check(talkSequence.size >= 3 && talkSequence.zipWithNext().all { it.first != it.second })
|
||||
check(rig.maxPorts==2 && rig.driver.sample().mouthActiveLagMs != null)
|
||||
rig.driver.desire(SafeClipRole.IDLE,null,true); rig.run(800)
|
||||
check(rig.clip()=="idle" && rig.driver.sample().closingLagMs in 0L..1000L)
|
||||
val traceFile=java.io.File("logs/avatar-safe-061/synthetic-player-trace.json")
|
||||
traceFile.parentFile.mkdirs()
|
||||
traceFile.writeText("{\"kind\":\"synthetic_control_trace_not_material_review\",\"fps\":20,\"seed\":7,\"events\":[" +
|
||||
rig.trace.joinToString(",") { (time,v) -> "{\"atMs\":$time,\"clip\":\"${v.clipId}\",\"reason\":\"${v.reason}\",\"waitMs\":${v.waitMs},\"mouthActiveLagMs\":${v.mouthActiveLagMs},\"closedStableLagMs\":${v.closingLagMs}}" } + "]}\n")
|
||||
// Old active/staged callbacks after stop cannot resurrect talk or reveal.
|
||||
val old=rig.ports.last(); rig.driver.stop(); val reveals=rig.visible.size
|
||||
old.listener.frame(DisplayedVideoFrame(0,0,0,999)); old.listener.ended(); old.listener.failed(VideoFailure.DECODE)
|
||||
check(rig.visible.size==reveals && rig.ports.all { it.closed })
|
||||
rig.driver.desire(SafeClipRole.IDLE,null); rig.driver.start(); rig.run(100)
|
||||
check(rig.clip()=="idle")
|
||||
rig.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val reversal=VideoRig(); reversal.driver.start(); reversal.run(50)
|
||||
reversal.driver.desire(SafeClipRole.TALK,10); reversal.run(450)
|
||||
check(reversal.clip()=="opening")
|
||||
reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(800)
|
||||
check(reversal.clip()=="idle") // short opening completes, legal talk junction then closing
|
||||
reversal.driver.desire(SafeClipRole.TALK,11,true); reversal.run(10)
|
||||
val retiredTarget=reversal.ports.last()
|
||||
reversal.driver.desire(SafeClipRole.IDLE,null,true); reversal.run(500)
|
||||
check(reversal.clip()=="idle") // idle reversal cancels an obsolete hidden opening
|
||||
val count=reversal.visible.size
|
||||
retiredTarget.listener.frame(DisplayedVideoFrame(0,0,0,99))
|
||||
retiredTarget.listener.failed(VideoFailure.DECODE)
|
||||
check(reversal.visible.size==count && reversal.clip()=="idle")
|
||||
reversal.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val delayed=VideoRig(delay={ 1100 }); delayed.driver.start(); delayed.run(1100)
|
||||
delayed.driver.desire(SafeClipRole.TALK,1); delayed.run(1100)
|
||||
check(delayed.clip()=="idle") // target arriving after a window cannot cause a late cut
|
||||
delayed.run(400); check(delayed.clip()=="opening")
|
||||
delayed.driver.stop()
|
||||
|
||||
TestScheduler.reset(); val fail=VideoRig(); fail.driver.start(); fail.run(0)
|
||||
fail.ports.single().listener.failed(VideoFailure.DECODE)
|
||||
check(fail.ports.all { it.closed } && fail.reports.last().reason=="video_decode")
|
||||
// Presentation fitting preserves complete body on portrait/landscape/tablet canvases.
|
||||
for ((w,h) in listOf(320 to 640,1080 to 2400,2400 to 1080,1600 to 2560)) {
|
||||
val fit=fitVideo(w,h,480,848)
|
||||
check(fit.scaleX in 0f..1f && fit.scaleY in 0f..1f)
|
||||
check(kotlin.math.abs(w*fit.scaleX/(h*fit.scaleY)-480f/848)<0.0001)
|
||||
}
|
||||
// Unknown mouth evidence is never substituted with a role-name latency measurement.
|
||||
val noMouth=graph.copy(clips=graph.clips.mapValues { (_,c) -> c.copy(mouthStateWindows=emptyList()) })
|
||||
TestScheduler.reset(); val unknown=VideoRig(noMouth); unknown.driver.start(); unknown.run(0)
|
||||
unknown.driver.desire(SafeClipRole.TALK,1); unknown.run(1500)
|
||||
check(unknown.driver.sample().mouthActiveLagMs==null && unknown.driver.sample().waitMs==1500L)
|
||||
unknown.driver.stop()
|
||||
println("PASS: production video driver with held-frame ports: complete fixed graph/all required edges, alternating legal variants, startup intent, stop/abort/reversal, target-not-ready/late-window wait, renderer epochs/background/failure, two-port bound, mouth evidence latency and fullbody Fit; synthetic materials/device pending")
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private val approved = AnchorReview.APPROVED
|
||||
// Entirely synthetic, 20fps/1s fixture. No real avatar annotations or approval claims.
|
||||
fun syntheticGraph(): SafeAvatarGraph {
|
||||
val anchors = listOf(VisualAnchor("closed",true,approved),VisualAnchor("open",false,approved)).associateBy { it.id }
|
||||
fun interval(id: String,anchor: String,start: Long,end: Long) = AnchorInterval(id,anchor,start,end,(start/50).toInt(),(end/50).toInt(),approved)
|
||||
fun clip(id: String,role: SafeClipRole,entry: String,exit: String) = SafeAvatarClip(id,"videos/$id.mp4",role,1000,20,20,1,
|
||||
listOf(interval("entry",entry,0,100)),listOf(interval("exit",exit,800,900)),approved,
|
||||
loop=role in setOf(SafeClipRole.IDLE,SafeClipRole.TALK),loopSeamReview=approved,seekReview=approved,
|
||||
mouthStateWindows=listOf(MouthStateWindow(if (entry == "closed") ReviewedMouthState.CLOSED_STABLE else ReviewedMouthState.ACTIVE,
|
||||
0,100,0,2,approved)))
|
||||
val clips = listOf(clip("idle",SafeClipRole.IDLE,"closed","closed"),clip("opening",SafeClipRole.OPENING,"closed","open"),
|
||||
clip("talk",SafeClipRole.TALK,"open","open"),clip("closing",SafeClipRole.CLOSING,"open","closed"),
|
||||
clip("waiting",SafeClipRole.WAITING,"closed","closed")).associateBy { it.id }
|
||||
fun edge(from: String,to: String) = SafeAvatarEdge("${from}_$to",from,"exit",to,"entry",approved,latestWaitMs=100)
|
||||
return SafeAvatarGraph(clips,anchors,listOf(edge("idle","opening"),edge("opening","talk"),edge("talk","closing"),
|
||||
edge("closing","idle"),edge("idle","waiting")),"idle","entry",approved)
|
||||
}
|
||||
private class Driver(val graph: SafeAvatarGraph = syntheticGraph(), initial: String = "idle") {
|
||||
val planner = SafeTransitionPlanner(graph,initial)
|
||||
private var serial=0L
|
||||
fun observation(position: Long,now: Long=position,loop: Long=0) =
|
||||
ClipObservation(planner.snapshot(now).actualClip,position,(position/50).toInt(),loop,++serial,now)
|
||||
fun tick(position: Long,now: Long=position,loop: Long=0) = planner.tick(observation(position,now,loop),now)
|
||||
fun stage(position: Long=100,now: Long=100): TransitionAction.Stage = tick(position,now).single() as TransitionAction.Stage
|
||||
fun ready(stage: TransitionAction.Stage, position: Long=0) = StagedFrame(stage.ticket,position,(position/50).toInt(),true,true,true)
|
||||
fun cut(stage: TransitionAction.Stage,now: Long): TransitionAction.Reveal {
|
||||
check(planner.targetReady(ready(stage)))
|
||||
val offer = tick(820,now).single() as TransitionAction.OfferCut
|
||||
return planner.commit(offer.ticket,observation(830,now+10),ready(stage),now+10).single() as TransitionAction.Reveal
|
||||
}
|
||||
}
|
||||
fun checkSafePlanner() {
|
||||
val d=Driver(); val p=d.planner
|
||||
check(p.request(MouthIntent(1,1,42,SafeClipRole.TALK),0).isEmpty())
|
||||
check(p.snapshot(10).actualRole == SafeClipRole.IDLE)
|
||||
val stage=d.stage()
|
||||
for (bad in listOf(d.ready(stage).copy(paused=false),d.ready(stage).copy(seekComplete=false),
|
||||
d.ready(stage).copy(textureReady=false),d.ready(stage,150))) check(!p.targetReady(bad))
|
||||
check(d.tick(820).single() == TransitionAction.Hold(TransitionReason.TARGET_NOT_READY))
|
||||
check(p.targetReady(d.ready(stage)))
|
||||
val late=d.tick(830).single() as TransitionAction.OfferCut
|
||||
check(p.commit(late.ticket,d.observation(910,910),d.ready(stage),910).single() is TransitionAction.Hold)
|
||||
check(p.snapshot(910).actualClip == "idle")
|
||||
check(d.tick(920).single() == TransitionAction.Hold(TransitionReason.WAIT_BUDGET_EXCEEDED))
|
||||
// Expired offer cannot reveal; next approved wrap permits a fresh offer.
|
||||
val wrap=d.tick(820,1820,1).single() as TransitionAction.OfferCut
|
||||
check(p.commit(wrap.ticket,d.observation(830,1830,1),d.ready(stage),1830).single() is TransitionAction.Reveal)
|
||||
check(p.snapshot(1830).actualClip == "opening")
|
||||
// Visible bridge finishes on approved graph edges using the latest desired idle.
|
||||
p.request(MouthIntent(2,1,null,SafeClipRole.IDLE,VisualIntentReason.ABORT),1840)
|
||||
val bridge=d.stage(100,1900); check(bridge.ticket.target == "talk")
|
||||
d.cut(bridge,2000)
|
||||
check(p.snapshot(2010).desired == SafeClipRole.IDLE) // callback never restores old talk intent
|
||||
val closing=d.stage(100,2100); check(closing.ticket.target == "closing"); d.cut(closing,2200)
|
||||
val idle=d.stage(100,2300); d.cut(idle,2400)
|
||||
check(p.snapshot(2410).actualRole == SafeClipRole.IDLE && p.snapshot(2410).closedMouthLagMs == 570L)
|
||||
val staleIntent=p.request(MouthIntent(1,9,42,SafeClipRole.TALK),2500)
|
||||
check(staleIntent.single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
p.request(MouthIntent(2,2,null,SafeClipRole.WAITING,VisualIntentReason.HANGUP),2500)
|
||||
check(p.snapshot(2600).exitPending)
|
||||
val waiting=d.stage(100,2600); d.cut(waiting,2700)
|
||||
check(!p.snapshot(2710).exitPending)
|
||||
check(p.background().last() == TransitionAction.Release)
|
||||
check(!p.targetReady(d.ready(waiting)))
|
||||
val startup=checkNotNull(p.stageForeground(3))
|
||||
val startupFrame=d.ready(startup)
|
||||
check(!p.foreground(3,"idle",startup.entry.copy(endMs=999),startupFrame,3000))
|
||||
check(!p.foreground(3,"idle",startup.entry,startupFrame.copy(textureReady=false),3000))
|
||||
check(p.foreground(3,"idle",startup.entry,startupFrame,3000))
|
||||
check(!p.foreground(3,"idle",startup.entry,startupFrame,3001))
|
||||
|
||||
val reversal=Driver(); reversal.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val retired=reversal.stage(); reversal.planner.targetReady(reversal.ready(retired))
|
||||
val offered=reversal.tick(820).single() as TransitionAction.OfferCut
|
||||
check(reversal.planner.request(MouthIntent(1,2,5,SafeClipRole.IDLE),825).single() is TransitionAction.Cancel)
|
||||
check(!reversal.planner.targetReady(reversal.ready(retired)))
|
||||
check(reversal.planner.commit(offered.ticket,reversal.observation(830),reversal.ready(retired),830).single() is TransitionAction.Hold)
|
||||
check(reversal.planner.request(MouthIntent(1,3,6,SafeClipRole.TALK),840).single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
check(reversal.planner.request(MouthIntent(1,4,4,SafeClipRole.IDLE,VisualIntentReason.ABORT),841).single() == TransitionAction.Hold(TransitionReason.OLD_INTENT))
|
||||
check(reversal.planner.snapshot(840).actualRole == SafeClipRole.IDLE)
|
||||
|
||||
val g=syntheticGraph()
|
||||
val noEdge=Driver(g.copy(edges=emptyList()),"talk")
|
||||
noEdge.planner.request(MouthIntent(1,1,null,SafeClipRole.IDLE,VisualIntentReason.DISCONNECT),0)
|
||||
check(noEdge.tick(100).single() == TransitionAction.Hold(TransitionReason.NO_REVIEWED_EDGE))
|
||||
check(noEdge.planner.snapshot(5000).visualWaitMs == 5000L)
|
||||
val unreviewed=Driver(g.copy(clips=g.clips + ("idle" to g.clips.getValue("idle").copy(loopSeamReview=AnchorReview.PENDING))))
|
||||
unreviewed.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
check(unreviewed.tick(100,1100,1).single() == TransitionAction.Hold(TransitionReason.LOOP_UNREVIEWED))
|
||||
val held=Driver(g.copy(edges=g.edges.map { it.copy(missedWindowPolicy=MissedWindowPolicy.HOLD) }))
|
||||
held.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val hs=held.stage(); held.planner.targetReady(held.ready(hs))
|
||||
check(held.tick(950).single() is TransitionAction.Hold)
|
||||
check(held.tick(820,1820,1).single() == TransitionAction.Hold(TransitionReason.WINDOW_MISSED))
|
||||
val stale=Driver(); stale.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
check(stale.planner.tick(stale.observation(100,100).copy(continuous=false),100).single() == TransitionAction.Hold(TransitionReason.STALE_POSITION))
|
||||
check(stale.planner.tick(stale.observation(100,100),141).single() == TransitionAction.Hold(TransitionReason.STALE_POSITION))
|
||||
val eos=Driver(); eos.planner.request(MouthIntent(1,1,5,SafeClipRole.TALK),0)
|
||||
val es=eos.stage(); eos.planner.targetReady(eos.ready(es))
|
||||
val eo=eos.tick(820).single() as TransitionAction.OfferCut
|
||||
check(eos.planner.commit(eo.ticket,eos.observation(830).copy(ended=true),eos.ready(es),830).single() == TransitionAction.Hold(TransitionReason.LATE_CUT))
|
||||
check(eos.planner.tick(eos.observation(850).copy(ended=true),850).single() == TransitionAction.Hold(TransitionReason.WINDOW_MISSED))
|
||||
|
||||
val cursor=ActualClipCursor(); val clip=g.clips.getValue("idle")
|
||||
check(cursor.observe(clip,950,19,100).continuous)
|
||||
check(cursor.observe(clip,0,0,150).loop == 1L)
|
||||
check(!cursor.observe(clip,500,10,1200).continuous) // may have missed a whole loop
|
||||
cursor.reset(); cursor.observe(clip,500,10,0)
|
||||
check(!cursor.observe(clip,450,9,20).continuous) // seek/jitter is not a seam
|
||||
val diag=TransitionDiagnostics()
|
||||
check(diag.summary(p.snapshot(4000),AssetEmotion(),4000)?.contains("wait_ms=") == true)
|
||||
check(diag.summary(p.snapshot(4999),AssetEmotion(),4999) == null)
|
||||
check(diag.summary(p.snapshot(5000),AssetEmotion(),5000) != null)
|
||||
println("PASS: safe planner reviewed graph/bridge, paused seek+texture gate, fresh second sample, missed/late/noedge/unreviewed loop, latest intent/old turn, abort closing/hangup exit, background/new foreground, cursor continuity, bounded diagnostics; synthetic anchors only")
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
private val fakeSha = "a".repeat(64)
|
||||
fun syntheticManifest(): Map<String,Any?> {
|
||||
val g=syntheticGraph()
|
||||
fun interval(i: AnchorInterval): Map<String,Any?> = mapOf("id" to i.id,"anchorId" to i.anchorId,
|
||||
"startMs" to i.startMs,"endMs" to i.endMs,"startFrame" to i.startFrame,"endFrame" to i.endFrame,"reviewStatus" to "approved")
|
||||
return mapOf("schemaVersion" to 1,"assets" to g.clips.values.map { mapOf("id" to it.id,"path" to it.path) },
|
||||
"safeTransitions" to mapOf("version" to 1,"reviewStatus" to "approved","initialAssetId" to g.initialClip,"initialEntryId" to g.initialEntry,
|
||||
"anchors" to g.anchors.values.map { mapOf("id" to it.id,"closedMouth" to it.closedMouth,"reviewStatus" to "approved") },
|
||||
"clips" to g.clips.values.map { mapOf("assetId" to it.id,"role" to it.role.name.lowercase(),
|
||||
"durationMs" to it.durationMs,"frameCount" to it.frameCount,"fpsNumerator" to it.fpsNumerator,"fpsDenominator" to it.fpsDenominator,
|
||||
"entryAnchors" to it.entryAnchors.map(::interval),"safeExitWindows" to it.safeExitWindows.map(::interval),
|
||||
"mouthStateWindows" to it.mouthStateWindows.map { w -> mapOf("state" to w.state.name.lowercase(),
|
||||
"startMs" to w.startMs,"endMs" to w.endMs,"startFrame" to w.startFrame,"endFrame" to w.endFrame,"reviewStatus" to "approved") },
|
||||
"loop" to it.loop,"reviewStatus" to "approved","loopSeamReviewStatus" to "approved","seekReviewStatus" to "approved") },
|
||||
"transitions" to g.edges.map { mapOf("id" to it.id,"sourceAssetId" to it.source,"sourceWindowId" to it.sourceWindow,
|
||||
"targetAssetId" to it.target,"targetEntryId" to it.targetEntry,"reviewStatus" to "approved",
|
||||
"earliestPolicy" to "next_safe_window","latestPolicy" to "next_reviewed_loop","earliestWaitMs" to 0L,"latestWaitMs" to 100L) }))
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun checkSafetyManifest() {
|
||||
val root=syntheticManifest()
|
||||
val extension=root["safeTransitions"] as Map<String,Any?>
|
||||
fun modifiedExtension(change: Map<String,Any?>) = root + ("safeTransitions" to (extension + change))
|
||||
fun status(value: Map<String,Any?>) = SafeAvatarManifest.read(value,fakeSha,setOf(fakeSha)).status
|
||||
check(status(root - "safeTransitions") == SafetyManifestStatus.LEGACY_UNANNOTATED)
|
||||
// a01-v2's draft annotations are not this reviewed schema and grant no safety.
|
||||
check(status((root - "safeTransitions") + mapOf("approvedEdges" to emptyList<Any>(),"safeExits" to emptyList<Any>())) == SafetyManifestStatus.LEGACY_UNANNOTATED)
|
||||
check(status(modifiedExtension(mapOf("reviewStatus" to "pending","anchors" to emptyList<Any>(),"clips" to emptyList<Any>()))) == SafetyManifestStatus.REVIEW_PENDING)
|
||||
check(SafeAvatarManifest.read(root,fakeSha).status == SafetyManifestStatus.HASH_NOT_APPROVED)
|
||||
check(SafeAvatarManifest.read(root,"not-a-sha",setOf("not-a-sha")).status == SafetyManifestStatus.HASH_NOT_APPROVED)
|
||||
val approved=SafeAvatarManifest.read(root,fakeSha,setOf(fakeSha))
|
||||
check(approved.status == SafetyManifestStatus.APPROVED && approved.graph?.nextEdge("idle",SafeClipRole.TALK) != null)
|
||||
check(approved.graph?.clips?.getValue("idle")?.mouthStateWindows?.single()?.state == ReviewedMouthState.CLOSED_STABLE)
|
||||
check(status(root + ("schemaVersion" to 1.0)) == SafetyManifestStatus.INVALID)
|
||||
check(status(modifiedExtension(mapOf("version" to 2))) == SafetyManifestStatus.INVALID)
|
||||
check(status(modifiedExtension(mapOf("reviewStatus" to "almost_approved"))) == SafetyManifestStatus.INVALID)
|
||||
val clips=extension["clips"] as List<Map<String,Any?>>
|
||||
val closingAlias=clips.map { if (it["role"] == "closing") it + ("role" to "end-talk") else it }
|
||||
check(status(modifiedExtension(mapOf("clips" to closingAlias))) == SafetyManifestStatus.APPROVED)
|
||||
val badMouth=clips.first() + ("mouthStateWindows" to listOf(mapOf("state" to "active","startMs" to 0L,
|
||||
"endMs" to 9999L,"startFrame" to 0,"endFrame" to 1,"reviewStatus" to "approved")))
|
||||
check(status(modifiedExtension(mapOf("clips" to listOf(badMouth)+clips.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
for (change in listOf(mapOf("durationMs" to 4000.5),mapOf("durationMs" to -1L),mapOf("frameCount" to 1),mapOf("frameCount" to 3600),
|
||||
mapOf("assetId" to "missing"),mapOf("entryAnchors" to emptyList<Any>()),mapOf("fpsDenominator" to 0))) {
|
||||
check(status(modifiedExtension(mapOf("clips" to listOf(clips.first()+change)+clips.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
}
|
||||
val edges=extension["transitions"] as List<Map<String,Any?>>
|
||||
for (change in listOf(mapOf("targetEntryId" to "missing"),mapOf("sourceWindowId" to "missing"),
|
||||
mapOf("bridgeAssetId" to "closing"),mapOf("latestPolicy" to "force_cut"),mapOf("latestWaitMs" to -1))) {
|
||||
check(status(modifiedExtension(mapOf("transitions" to listOf(edges.first()+change)+edges.drop(1)))) == SafetyManifestStatus.INVALID)
|
||||
}
|
||||
val unreviewed=SafeAvatarManifest.read(modifiedExtension(mapOf("transitions" to edges.map { it + ("reviewStatus" to "pending") })),fakeSha,setOf(fakeSha))
|
||||
check(unreviewed.graph?.nextEdge("idle",SafeClipRole.TALK) == null)
|
||||
check(status(root + ("assets" to List(33) { mapOf("id" to "a$it","path" to "videos/a.mp4") })) == SafetyManifestStatus.INVALID)
|
||||
check(status(root + ("assets" to listOf(mapOf("id" to "idle","path" to "../private.mp4")) +
|
||||
(root["assets"] as List<Map<String,Any?>>).drop(1))) == SafetyManifestStatus.INVALID)
|
||||
println("PASS: manifest legacy/draft unsafe, pending unknown allowed without invented windows, hash allowlist, strict bounded metadata/frame/pose/reference/policy validation; fixture approval only")
|
||||
}
|
||||
@@ -44,6 +44,20 @@ fun checkCallControls() {
|
||||
val frame = session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
|
||||
frame.invoke(session,DownlinkFrame(11)); activity(PlaybackActivity(11,7,true,960,1920)); Handler.drain()
|
||||
check(AudioPlayback.enqueued == enqueued && states.last().playbackActivity == null)
|
||||
// New automatic UX can reopen a session while preserving mute, without a single
|
||||
// capture start before applying it. Permission pause sends safe stop/abort controls.
|
||||
dialogue.setField("socket",socket); dialogue.setField("ready",true)
|
||||
set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
|
||||
val mutedStarts = AudioCapture.starts
|
||||
session.startVoice(microphoneMuted=true)
|
||||
check(states.last().voiceActive && states.last().microphoneMuted && AudioCapture.starts == mutedStarts)
|
||||
session.background(keepConnectionForPermission=true)
|
||||
check(!states.last().voiceActive && states.last().playbackActivity == null)
|
||||
check(socket.sent.takeLast(2).any { it.contains("abort") })
|
||||
session.foreground(connectAutomatically=false)
|
||||
check(!states.last().voiceActive && AudioCapture.starts == mutedStarts)
|
||||
session.resetConnection()
|
||||
check(states.last().connection == ConnectionStatus.DISCONNECTED)
|
||||
session.release(); AudioPlayback.activityFence = null
|
||||
println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user