From 4ead34a944bbe27ba2acca602c9651ff8a16ef0b Mon Sep 17 00:00:00 2001 From: zenord Date: Tue, 13 Oct 2026 01:23:43 +0800 Subject: [PATCH] feat: validate per-body mouth timelines and reviewed conversation routes --- .../avatar/ContinuousAvatarManifest.kt | 71 ++++++++---- .../lanvoice/avatar/ContinuousBodyRenderer.kt | 5 +- .../avatar/ContinuousFramePresenter.kt | 2 +- .../gorios/lanvoice/avatar/ContinuousMouth.kt | 23 ++-- .../avatar/ConversationPackagePlanner.kt | 52 +++++++++ .../lanvoice/avatar/EmotionActionManifest.kt | 41 +++++-- .../lanvoice/avatar/RoleVisualSelection.kt | 3 +- docs/ACTION_EMOTION_STAGE_070.md | 68 ++++++++++-- docs/AVATAR_PACK_V2_CONTRACT.md | 49 ++++++++- gateway/SOURCE_MANIFEST.json | 4 +- gateway/tests/test_action_protocol.py | 83 ++++++++++++++ scripts/check-avatar-runtime.py | 101 ++++++++++++++++++ scripts/check-reply-regressions.py | 10 +- tests/avatar/AvatarCheck.kt | 2 + tests/avatar/ConversationPackageCheck.kt | 88 +++++++++++++++ tests/avatar/DynamicBodyCheck.kt | 101 ++++++++++++++++++ tests/avatar/EmotionActionCheck.kt | 4 +- 17 files changed, 646 insertions(+), 61 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/ConversationPackagePlanner.kt create mode 100644 scripts/check-avatar-runtime.py create mode 100644 tests/avatar/ConversationPackageCheck.kt create mode 100644 tests/avatar/DynamicBodyCheck.kt diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt index b6257f5..969ca94 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt @@ -4,12 +4,34 @@ data class MouthPatchLevel(val levelIndex: Int,val aperture: Float,val path: Str data class RegisteredMouthPatch(val frameIndex: Int,val ptsUs: Long,val path: String,val sha256: String, val x: Float,val y: Float,val width: Int,val height: Int,val levels: List = emptyList()) data class ContinuousBodyAsset(val path: String,val sha256: String,val width: Int,val height: Int, - val frameCount: Int,val durationUs: Long) + val frameCount: Int,val durationUs: Long, + val ptsUs: List = List(frameCount) { it*1_000_000L/24 }, + val fpsNumerator: Int = 24,val fpsDenominator: Int = 1) data class ContinuousAvatarPack(val body: ContinuousBodyAsset,val patches: List, val curves: Map,val root: String,val manifestSha: String,val apertureMode: Boolean=false) { val textureImages: List = patches.flatMap { p -> if(apertureMode) p.levels else listOf(MouthPatchLevel(0,1f,p.path,p.sha256)) } + val rgbaBytes: Long get() = patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) } +} + +/** Metadata validation only; importer must additionally verify decoded frame PTS. */ +object BodyTimeline { + const val MAX_TALK_FRAMES = 720 + const val MAX_RGBA_BYTES = 8_000_000L + const val MAX_PACK_CACHE_BYTES = 32_000_000L + fun valid(pts: List,count: Int,durationUs: Long,fpsNumerator: Int,fpsDenominator: Int, + maxFrames: Int = MAX_TALK_FRAMES,maxDurationUs: Long = 30_000_000): Boolean { + if(count !in 2..maxFrames || pts.size!=count || durationUs !in 100_000..maxDurationUs || + fpsNumerator !in 1..120_000 || fpsDenominator !in 1..10_000) return false + val fps=fpsNumerator.toDouble()/fpsDenominator + if(fps !in 1.0..60.0 || pts.first()!=0L || pts.last()>=durationUs || + pts.zipWithNext().any { (a,b)->a<0 || b<=a }) return false + val period=1_000_000.0/fps + return kotlin.math.abs(durationUs-count*period)<=period+2 && + durationUs-pts.last()<=period*2+2 && + pts.zipWithNext().all { (a,b)->b-a<=period*2+2 } + } } /** This parser admits only coordinator-selected debug runtime data; no production graph. */ @@ -23,34 +45,40 @@ object ContinuousAvatarManifest { fun smallInt(v: Any?): Int { val n=integer(v);require(n in 0..1_000_000);return n.toInt() } fun finite(v: Any?): Float { val f=(v as Number).toFloat(); require(f.isFinite()); return f } fun hash(v: Any?)=(v as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) } - val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" || - (root["packId"] as? String)?.matches(Regex("a01-expression-action-v1-[a-z0-9_-]+-runtime-04"))==true - require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" && + val dynamic=(root["packId"] as? String)?.matches(Regex("a01-expression-action-v1-[a-z0-9_-]+-runtime-04"))==true + val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" || dynamic + require(integer(root["schemaVersion"])==(if(dynamic) 2L else 1L) && root["identityId"]=="a01" && (apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03")) require(root["publishApproval"]==false && root["runtimeReady"]==true) val b=obj(root["body"]) + val count=smallInt(b["frameCount"]);require(count in 2..BodyTimeline.MAX_TALK_FRAMES) + val fpsN=smallInt(b["fpsNumerator"]);val fpsD=smallInt(b["fpsDenominator"]) + val pts=if(dynamic) (b["ptsUs"] as List<*>).also { require(it.size==count) }.map(::integer) else List(count) { it*1_000_000L/24 } val body=ContinuousBodyAsset(b["path"] as String,hash(b["sha256"]),smallInt(b["width"]),smallInt(b["height"]), - smallInt(b["frameCount"]),integer(b["durationUs"])) + count,integer(b["durationUs"]),pts,fpsN,fpsD) require(body.path.matches(Regex("body/[a-zA-Z0-9_.-]+\\.mp4"))) - require(body.width==480 && body.height==848 && body.frameCount==97 && kotlin.math.abs(body.durationUs-4_041_667)<=2) - require(integer(b["fpsNumerator"])==24L && integer(b["fpsDenominator"])==1L && b["hasAudio"]==false) - require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L) + require(body.width==480 && body.height==848 && b["hasAudio"]==false) + if(dynamic) require(BodyTimeline.valid(pts,count,body.durationUs,fpsN,fpsD)) else { + require(count==97 && kotlin.math.abs(body.durationUs-4_041_667)<=2 && fpsN==24 && fpsD==1) + require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L) + } val patchFormat=obj(root["patchFormat"]) require(patchFormat["alphaEncoding"]=="straight_unassociated" && patchFormat["format"]=="PNG RGBA 8bit") + if(dynamic) require(hash(patchFormat["bodySha256"])==body.sha256) if(apertureMode) { require((patchFormat["apertureLevels"] as List<*>).map(::finite)==listOf(0f,.25f,.5f,.75f,1f)) require(patchFormat["requiresRendererExtension"]==true) } - val rows=root["patches"] as List>; require(rows.size==97) + val rows=root["patches"] as List>; require(rows.size==count) val patches=rows.mapIndexed { index,p -> val patch=RegisteredMouthPatch(smallInt(p["frameIndex"]),integer(p["ptsUs"]),p["path"] as String,hash(p["sha256"]), finite(p["x"]),finite(p["y"]),smallInt(p["width"]),smallInt(p["height"])) - require(patch.frameIndex==index && kotlin.math.abs(patch.ptsUs-index*1_000_000L/24)<=2) + require(patch.frameIndex==index && if(dynamic) patch.ptsUs==pts[index] else kotlin.math.abs(patch.ptsUs-pts[index])<=2) require(patch.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png"))) require(patch.width in 1..128 && patch.height in 1..128 && patch.x>=0 && patch.y>=0 && patch.x+patch.width<=480 && patch.y+patch.height<=848) if(apertureMode) { - val levels=(p["levels"] as List>).mapIndexed { level,row -> + val levels=(p["levels"] as List>).also { require(it.size==5) }.mapIndexed { level,row -> require(level in 0..4 && smallInt(row["levelIndex"])==level && finite(row["aperture"])==level/4f) MouthPatchLevel(level,level/4f,row["path"] as String,hash(row["sha256"])).also { require(it.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png"))) @@ -64,19 +92,26 @@ object ContinuousAvatarManifest { } } val paths=patches.flatMap { if(apertureMode) it.levels.map { l -> l.path } else listOf(it.path) } - require(paths.distinct().size==if(apertureMode) 485 else 97) - require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=8_000_000) + require(paths.distinct().size==count*(if(apertureMode) 5 else 1)) + require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=BodyTimeline.MAX_RGBA_BYTES) val states=root["mouthStates"] as List> require(states.size==5) val c=states.associateBy { it["id"] as String } require(c.keys==setOf("idle","opening","talk1","talk2","end-talk")) val curves=c.mapValues { (id,v) -> val row=obj(v); val duration=integer(row["durationMs"]) - val alpha=(row["globalAlphaByFrame"] as List<*>).map(::finite) + val alpha=(row["globalAlphaByFrame"] as List<*>).also { require(it.size in 2..60) }.map(::finite) val bridge=id in setOf("opening","end-talk") - require(duration==if(bridge) 250L else 500L) - require(alpha.size==if(bridge) 6 else 12) - require(integer(row["frameCount"])==alpha.size.toLong() && integer(row["fpsNumerator"])==24L && integer(row["fpsDenominator"])==1L) + require(integer(row["frameCount"])==alpha.size.toLong()) + val curvePts=if(dynamic) (row["ptsUs"] as List<*>).also { require(it.size==alpha.size) }.map(::integer) else alpha.indices.map { it*1_000_000L/24 } + if(dynamic) { + require(duration in 100..1_000 && BodyTimeline.valid(curvePts,alpha.size,duration*1000, + smallInt(row["fpsNumerator"]),smallInt(row["fpsDenominator"]),60,1_000_000)) + } else { + require(duration==if(bridge) 250L else 500L) + require(alpha.size==if(bridge) 6 else 12) + require(integer(row["fpsNumerator"])==24L && integer(row["fpsDenominator"])==1L) + } require(alpha.all { it in 0f..1f }) require(row["entryMouthAnchor"]==if(id in setOf("idle","opening")) "A" else "B") require(row["exitMouthAnchor"]==if(id in setOf("idle","end-talk")) "A" else "B") @@ -86,7 +121,7 @@ object ContinuousAvatarManifest { "end-talk" -> require(alpha.first()==1f && alpha.last()==0f) else -> require(alpha.first()==1f && alpha.last()==1f && alpha.min()<.5f) } - MouthCurve(id,duration,alpha) + MouthCurve(id,duration,alpha,curvePts) } val routing=obj(root["stateRouting"]) val required=mapOf("idle" to setOf("idle","opening"),"opening" to setOf("talk1","talk2","end-talk"), diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt index 0217dee..e59c6a6 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt @@ -63,6 +63,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont fun intent(talk: Boolean,generation: Long,revision: Long) { worker.post { if(alive.get()) gate.intent(talk,generation,revision,SystemClock.elapsedRealtime()) } } fun resize(w: Int,h: Int) { worker.post { if(alive.get()) { width=w; height=h } } } private fun initialize() { + check(pack.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES && pack.patches.size==pack.body.frameCount) display=EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);check(display!=EGL14.EGL_NO_DISPLAY) val version=IntArray(2);check(EGL14.eglInitialize(display,version,0,version,1)) val configs=arrayOfNulls(1);val count=IntArray(1) @@ -149,7 +150,9 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont check(!(info.size==0 && info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM!=0)) { "early_eos" } val key=gate.decoded(info.presentationTimeUs) waiting=true;lastIndex=key.index - val step=if(key.index==0) 41L else key.index*1000L/24-(key.index-1)*1000L/24 + val pts=pack.body.ptsUs + val step=if(key.index==0) (pack.body.durationUs-pts.last())/1000 else + pts[key.index]/1000-pts[key.index-1]/1000 val delay=if(first) 0L else (lastPresentedMs+step-SystemClock.elapsedRealtime()).coerceAtLeast(0) worker.postDelayed({ guarded { worker.postDelayed(timeout,2_000) diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt index b7c1802..c3d36d6 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousFramePresenter.kt @@ -13,7 +13,7 @@ data class ComposedBodyFrame(val key: BodyFrameKey,val patch: RegisteredMouthPat /** The real EGL renderer uses this gate immediately around updateTexImage + draw/swap. * No other thread can choose a patch or change body phase. close() fences stale output. */ class ContinuousFramePresenter(private val pack: ContinuousAvatarPack,choose: (Int)->Int = { kotlin.random.Random.nextInt(it) }) { - private val clock=ContinuousFrameClock(pack.body.frameCount) + private val clock=ContinuousFrameClock(pack.body.frameCount,pack.body.ptsUs) private val mouth=ContinuousMouth(pack.curves,choose) private var active=true fun intent(talk: Boolean,generation: Long,revision: Long,nowMs: Long?=null): Boolean = active && mouth.request(talk,generation,revision,nowMs) diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt index 9b42205..08bbae6 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousMouth.kt @@ -1,6 +1,7 @@ package com.gorios.lanvoice.avatar -data class MouthCurve(val id: String, val durationMs: Long, val alpha: List) +data class MouthCurve(val id: String, val durationMs: Long, val alpha: List, + val ptsUs: List = alpha.indices.map { it*1_000_000L/24 }) data class MouthLayerSample(val phase: String, val alpha: Float, val generation: Long, val revision: Long, val phaseWaitMs: Long=0) @@ -43,11 +44,13 @@ class ContinuousMouth(private val curves: Map, private val ch val wait=if(satisfied) 0 else (nowMs-checkNotNull(requestedAt)).coerceAtLeast(0) if (phase=="idle") return MouthLayerSample(phase,0f,generation,revision,wait) val c=curves.getValue(phase) - // Authored endpoints are at (n-1)/24. Hold their value only for the last - // natural display interval; do not manufacture a body freeze or reverse. - val index=((nowMs-startedAt)*24.0/1000).coerceIn(0.0,(c.alpha.size-1).toDouble()) - val lower=index.toInt(); val upper=minOf(lower+1,c.alpha.lastIndex) - val alpha=c.alpha[lower]+(c.alpha[upper]-c.alpha[lower])*(index-lower).toFloat() + val elapsedUs=(nowMs-startedAt)*1000 + val found=c.ptsUs.binarySearch(elapsedUs) + val lower=if(found>=0) found else (-found-2).coerceAtLeast(0) + val upper=minOf(lower+1,c.alpha.lastIndex) + val fraction=if(lower==upper) 0f else ((elapsedUs-c.ptsUs[lower]).toDouble()/ + (c.ptsUs[upper]-c.ptsUs[lower])).coerceIn(0.0,1.0).toFloat() + val alpha=c.alpha[lower]+(c.alpha[upper]-c.alpha[lower])*fraction return MouthLayerSample(phase,alpha,generation,revision,wait) } private fun nextTalk(): String { @@ -59,14 +62,16 @@ class ContinuousMouth(private val curves: Map, private val ch data class BodyFrameKey(val index: Int, val loopOrdinal: Long, val ptsUs: Long) /** Decoder order and SurfaceTexture consumption are separately checked. */ -class ContinuousFrameClock(private val frames: Int=97) { +class ContinuousFrameClock(private val frames: Int=97, + private val pts: List = List(frames) { it*1_000_000L/24 }) { + init { require(pts.size==frames && frames>0) } private var expected=0 private var loop=0L private var pending: BodyFrameKey?=null fun decoded(ptsUs: Long): BodyFrameKey { check(pending==null) - val index=((ptsUs*24+500_000)/1_000_000).toInt() - check(index==expected && kotlin.math.abs(ptsUs-index*1_000_000L/24)<=2_000) + val index=expected + check(index in pts.indices && kotlin.math.abs(ptsUs-pts[index])<=2) return BodyFrameKey(index,loop,ptsUs).also { pending=it } } fun latched(timestampNs: Long): BodyFrameKey { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationPackagePlanner.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationPackagePlanner.kt new file mode 100644 index 0000000..f3dc98b --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationPackagePlanner.kt @@ -0,0 +1,52 @@ +package com.gorios.lanvoice.avatar + +import com.gorios.lanvoice.dialogue.RoleEmotion + +data class PreparedExpression(val turn: Long,val seq: Long,val emotion: RoleEmotion,val intensity: Int) +data class ConversationBridge(val serial: Long,val turn: Long,val edge: ConversationEdge) + +/** Preparation never changes selected/visible packages. A final reply authorizes + * routing; a driver must present every reviewed bridge before acknowledging it. */ +class ConversationPackagePlanner(private val index: EmotionActionIndex) { + var visiblePackage = index.fallbackId + private set + var selected: RoleVisualSelection? = null + private set + var prepared: PreparedExpression? = null + private set + private var turn = -1L + private var finalSeq = -1L + private var target = visiblePackage + private var inFlight: ConversationBridge? = null + private var bridgeSerial = 0L + private fun valid(value: PreparedExpression) = value.seq>=0 && value.intensity in + if(value.emotion==RoleEmotion.NEUTRAL) 0..0 else 1..2 + fun newTurn(id: Long) { + require(id>=0);turn=id;finalSeq=-1;prepared=null;selected=null;target=visiblePackage + inFlight=null + } + fun prepare(value: PreparedExpression): Boolean { + if(!valid(value) || value.turn!=turn || value.seq<=finalSeq || value.seq<=(prepared?.seq ?: -1)) return false + prepared=value;return true + } + fun cancelPrepare(id: Long) { if(id==turn) prepared=null } + fun commit(value: PreparedExpression): Boolean { + if(!valid(value) || value.turn!=turn || value.seq<=finalSeq) return false + finalSeq=value.seq;prepared=null + selected=RoleVisualSelector.select(value.emotion,value.intensity,index.visuals,index.fallbackId) + target=checkNotNull(selected).packageId + return true + } + fun nextEdge(frame: Int): ConversationBridge? { + if(inFlight!=null || visiblePackage==target) return null + val candidates=index.edges.filter { it.from==visiblePackage && it.fromFrame==frame } + val edge=candidates.firstOrNull { it.to==target } ?: candidates.firstOrNull { + visiblePackage!=index.fallbackId && it.to==index.fallbackId + } ?: return null + return ConversationBridge(++bridgeSerial,turn,edge).also { inFlight=it } + } + fun presented(bridge: ConversationBridge,targetFrame: Int): Boolean { + if(bridge!=inFlight || bridge.turn!=turn || bridge.edge.toFrame!=targetFrame) return false + visiblePackage=bridge.edge.to;inFlight=null;return true + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt index 847a3a1..5d9a006 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt @@ -3,7 +3,9 @@ package com.gorios.lanvoice.avatar import com.gorios.lanvoice.dialogue.RoleEmotion data class EmotionActionIndex(val fallbackId: String, val packages: Map, - val visuals: List, val actionPack: ReviewedActionPack?) + val visuals: List, val actionPack: ReviewedActionPack?, val edges: List = emptyList()) +data class ConversationEdge(val id: String,val from: String,val to: String,val fromFrame: Int,val toFrame: Int, + val clip: ContinuousBodyAsset) /** Exact external manifest pin admits the whole graph. Self-approval fields have no effect. * loadRuntime must hash-check exact bytes and all body/patch files before returning a pack. @@ -21,6 +23,7 @@ object EmotionActionManifest { } fun hash(value: Any?)=(value as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) } fun integer(value: Any?): Long { val n=value as Number;require(n.toDouble()==n.toLong().toDouble());return n.toLong() } + fun boundedInt(value: Any?, maximum: Int): Int = integer(value).also { require(it in 1..maximum.toLong()) }.toInt() val fallback=root["fallbackPackageId"] as String val rows=root["conversationPackages"] as List> require(rows.isNotEmpty() && rows.size<=12 && rows.map { it["id"] }.distinct().size==rows.size) @@ -28,28 +31,43 @@ object EmotionActionManifest { val visuals=rows.map { row -> val id=row["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}"))) val emotion=RoleEmotion.entries.single { it.wire==row["emotion"] } - require(emotion!=RoleEmotion.ANGRY && integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L) + require(emotion in setOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY,RoleEmotion.SAD) && + integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L) val reference=obj(row["runtimeManifest"]) val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"]))) require(runtime.apertureMode && runtime.body.sha256==hash(row["mouthBodySha256"])) require(runtime.patches.size==runtime.body.frameCount && runtime.patches.all { it.levels.size==5 }) + require(runtime.body.ptsUs==runtime.patches.map { it.ptsUs } && + BodyTimeline.valid(runtime.body.ptsUs,runtime.body.frameCount,runtime.body.durationUs, + runtime.body.fpsNumerator,runtime.body.fpsDenominator)) packages[id]=runtime val pts=runtime.patches.map { it.ptsUs } - TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),pts,pts,false) + TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),runtime.body.ptsUs,pts,false) } + require(packages.values.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES) require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL) val edges=root["edges"] as List> require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size) - edges.forEach { edge -> + val admittedEdges=edges.map { edge -> require(edge["from"] in packages && edge["to"] in packages) val from=checkNotNull(packages[edge["from"]]);val to=checkNotNull(packages[edge["to"]]) require(integer(edge["fromFrame"]) in 0 until from.body.frameCount.toLong()) require(integer(edge["toFrame"]) in 0 until to.body.frameCount.toLong()) require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A") val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"]) - require(clip["hasAudio"]==false && integer(clip["frameCount"])>0 && integer(clip["durationUs"])>0) - val pts=(clip["ptsUs"] as List<*>).map(::integer) - require(pts.size==integer(clip["frameCount"]).toInt() && pts.first()==0L && pts.zipWithNext().all { (a,b)->a).also { require(it.size==count) }.map(::integer) + require(BodyTimeline.valid(pts,count,integer(clip["durationUs"]), + boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000))) + val source=rows.single { it["id"]==edge["from"] } + require(integer(edge["fromFrame"]) in (source["legalExitFrames"] as List<*>).map(::integer)) + require(integer(edge["fromPtsUs"])==from.body.ptsUs[integer(edge["fromFrame"]).toInt()]) + require(integer(edge["toPtsUs"])==to.body.ptsUs[integer(edge["toFrame"]).toInt()]) + ConversationEdge(edge["id"] as String,edge["from"] as String,edge["to"] as String, + integer(edge["fromFrame"]).toInt(),integer(edge["toFrame"]).toInt(), + ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size, + integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000))) } val admitted=visuals.map { visual -> val row=rows.single { it["id"]==visual.id } @@ -73,13 +91,16 @@ object EmotionActionManifest { val clip=obj(action["clip"]);path(clip["path"]);hash(clip["sha256"]) val duration=integer(clip["durationUs"]) require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration) - val pts=(clip["ptsUs"] as List<*>).map(::integer) - require(pts.isNotEmpty() && pts.size==integer(clip["frameCount"]).toInt() && pts.zipWithNext().all { (a,b)->a).also { require(it.size==count) }.map(::integer) + require(integer(clip["width"])==480L && integer(clip["height"])==848L) + require(BodyTimeline.valid(pts,count,duration, + boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000),5400,90_000_000)) require(duration in 1_000_000..90_000_000) ActionAsset(action["id"] as String,(duration+999)/1000) } ReviewedActionPack(actualSha,assets) } - EmotionActionIndex(fallback,packages,admitted,actionPack) + EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges) } catch(_: Exception) { null } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/RoleVisualSelection.kt b/app/src/main/java/com/gorios/lanvoice/avatar/RoleVisualSelection.kt index 8317b88..099b4b4 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/RoleVisualSelection.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/RoleVisualSelection.kt @@ -13,7 +13,8 @@ data class TalkPackage(val id: String, val emotion: RoleEmotion, val bodySha: St object RoleVisualSelector { fun select(emotion: RoleEmotion, intensity: Int, packages: List, fallbackId: String): RoleVisualSelection { fun valid(p: TalkPackage) = p.bodySha.matches(Regex("[0-9a-f]{64}")) && - p.mouthBodySha == p.bodySha && p.framePtsUs.size == 97 && + p.mouthBodySha == p.bodySha && p.framePtsUs.size in 2..BodyTimeline.MAX_TALK_FRAMES && + p.framePtsUs.first()==0L && p.framePtsUs == p.mouthPtsUs && p.framePtsUs.zipWithNext().all { (a,b) -> a < b } && p.approvedEdges val usable = packages.filter(::valid) val same = usable.firstOrNull { it.emotion == emotion && emotion != RoleEmotion.ANGRY } diff --git a/docs/ACTION_EMOTION_STAGE_070.md b/docs/ACTION_EMOTION_STAGE_070.md index bc484ff..30fea17 100644 --- a/docs/ACTION_EMOTION_STAGE_070.md +++ b/docs/ACTION_EMOTION_STAGE_070.md @@ -22,18 +22,18 @@ Adjacent spoken assistant rows merge in provider context to preserve role orderi Android implements capture cleanup acknowledgement, action state/port, settings cancel, background cancellation, no-repeat variants, stale callbacks/frames fences, and expression preload callback separate from displayed expression. V2 metadata -parser and visual selector bind each own body-mouth SHA/97 PTS and slight-only +parser and visual selector bind each own body-mouth SHA/actual per-body PTS and slight-only visual intensity, requiring complete fallback packages and reviewed bridge graph. See [asset contract](AVATAR_PACK_V2_CONTRACT.md). -Pending: asset owner's mouth amplitude choice, happy/sad TALK packages and their +Pending: happy/sad TALK packages and their own mouths/bridges, Pi exact manifest review, idle variants, two real music dances, asset file/decode import gate and actual v2 bridge/media renderer integration. No new asset is admitted in this APK; default action capability remains absent. Existing neutral runtime04 bytes are preserved. No naturalness approval is inferred from hashes, tests or fixtures. Real device/GPU/music tail/≤1s perception: **not_run**. -Validation: full nine client JVM entry points + expression/UI source contracts; +Validation: nine JVM entry points (five client + four expression), UI source contracts; production parser on actual runtime04 97×5 metadata; 40 offline EGL/GLES pixel cases. 95 gateway tests pass in remote staging, including existing Silero; local archive also passes with that excluded-model test skipped. Android assemble and device-test @@ -65,7 +65,8 @@ Detailed numeric evidence (ignored, no raw replies/keys/user audio/face reports) `logs/action-emotion/{schema-probe.json,delivery.json,shader-golden/}`, client `logs/avatar-safe-061/`, gateway `logs/voice-investigation/gateway-emotion-staged.json`. Live gateway0.8.0 deployed from `e91354c9e8bd3a671bb8b02b3ff94c252559355d`. -Exact deployed hashes are in `gateway/SOURCE_MANIFEST.json`; before restart, source +Deployed runtime-module hashes are in `gateway/SOURCE_MANIFEST.json`; followup +test-file hashes describe the newer local tests, not a new deployment. Before restart, source and busy fences passed. Private environment and unit loading stayed hash-identical. Only `lan-voice-gateway.service` restarted. Backup: `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261013-004204`. @@ -80,8 +81,59 @@ protocol evidence, not proof of a person hearing playback. Numeric result: schema calls + this one pipeline call; paid/cloud calls by code owner: zero. Asset-owner update: P1 free amplitude previews completed in its own -`.runtime/avatar-imports/a01-expression-action-v1/p1-amplitude-01/`; Pi original-speed -selection remains pending. Nearest-level/opacity1/zero-bypass rendering stays intact. -P4a report: four generation calls (two expression edits + two 4s body videos), -known video fee $0.68, image fee unknown. Bodies/own-mouth/bridges are not admitted; +`.runtime/avatar-imports/a01-expression-action-v1/p1-amplitude-01/`; Pi selected1.1 +source pixels for candidate production based on fixed comparisons. Dynamic visual +review remains pending. Nearest-level/opacity1/zero-bypass rendering stays intact. +Latest coordinator ledger snapshot: **6 submitted**, known video fee **$0.96**, +image fee unknown (supersedes earlier4/$0.68 and5/$0.86 snapshots, not an all-time total). +sad001 idle rejected for visible opening/strong expression; sad0022s inspection +continues in `p4a-sad-revision-02`. Happy own mouth uses1.1 sourcepx and actual97 +source PTS; dynamic12s review pending. First real frame0-to-frame0 entry bridge +is in `bridge-review/neutral-happy-enter-001`; its gate determines later bridges. +Bodies/own-mouth/bridges are not admitted; this cost is the separate asset ledger, not code-owner paid usage. No P4b/P5 activation. + +Preparation semantics: four fixed probe rows record complete valid ordered header +availability before full response, and agreement with strict final parsing on those +four outputs. They cannot guarantee all future finals. `reply.emotion.prepare` is +**preload-only**, turn/seq scoped; it must not select visible expression or start +speech. The final `reply.emotion` event is authoritative. Duplicate/mismatched/ +truncated/extra-field finals cancel preparation; after_action emotion is excluded +from prefix preparation and is displayed only in its later speech turn. Current +MainActivity has no approved multi-pack preload implementation wired to this hook; +the protocol hook and deterministic planner are tested separately, not claimed as +actual new expression pixels on code16. The code16 APK remains unchanged/rollback. + +Post-code16 source milestone starts from clean/pushed +`4358fc9cae27bcad01b0098690c4a77fa4767d13`. New schema2 per-body parser, frame +presenter/renderer and mouth curves use actual N/PTS/fps/duration. Independent +97/121/49 and rational61-frame fixtures retain N×5 levels, exact own-body SHA and +frame binding. Runtime RGBA≤8MB, index≤32MB, N≤720; oversize numeric narrowing, +duplicate paths, malformed curves and invalid timelines fail admission. Only +legacy neutral schema1 keeps97@24; current happy/sad001 also happen to be97. + +New multi-package planner keeps prepare separate from final selection and actual +visible package. Sad→neutral→happy executes only reviewed source frames/bridges; +serial/turn fences reject stale/repeated presentation, and missing own mouth +falls back as a whole package. Index retains bridge clip metadata for its future +driver. It remains unwired to MainActivity until asset/bridge admission is complete. + +Followup validation: 2,361 dynamic frame/level/rejection checks, 15 invalid graph/ +cache cases; all nine JVM entries + UI checks; 40 offline real EGL/GLES goldens; +Android debug/application-instrumentation Kotlin compilation passed, no new APK +published. Local gateway archive98 tests:97 passed,1 existing Silero model test +skipped (no model artifact provided); three added tests cover actual generate/ +synthesize/drain/action cancel/failure/new-turn abort and prepare-final cancellation. +Mock action normal completion still proves1 LLM/2 TTS across two speech turns, +after speech history only upon drain, with no model/TTS provider changes. + +Read-only Gate1 on retained neutral runtime04 verified486 files,97 body PTS, +485 RGBA patches,1,646,400 cache bytes, full decode and actual production parser. +Current unapproved happy draft was rejected with nonzero exit for old schema; +owner files/previews were not changed. Evidence: +`logs/action-emotion/dynamic-n/{avatar-tests.txt,neutral-gate.json,happy-draft-rejection.json,shader-golden/}`, +`logs/avatar-safe-061/`; gateway98-test and compile summaries are in the same +dynamic-n evidence directory. No new live probes, paid calls, deployments, +service restarts or code16 replacement in this milestone. Whole visual/action +release remains pending approved own-mouth/bridges/index and media integration; +device/AudioRecord/GPU/perceptual≤1s remain not_run. diff --git a/docs/AVATAR_PACK_V2_CONTRACT.md b/docs/AVATAR_PACK_V2_CONTRACT.md index 657b098..f8983fc 100644 --- a/docs/AVATAR_PACK_V2_CONTRACT.md +++ b/docs/AVATAR_PACK_V2_CONTRACT.md @@ -14,15 +14,18 @@ Self-authored approved/status fields never enable runtime capabilities. Each conversation package: unique `id`, `emotion:neutral|happy|sad`, `visualIntensity:0|1`, `mouthBodySha256`, `runtimeManifest:{path,sha256}` referencing runtime04 format -(continuous body + own 97 PTS registered frames × five RGBA aperture levels, +(continuous body + own actual N PTS registered frames × five RGBA aperture levels, own curves/anchors/coordinates). Body SHA, frame count and decoded PTS bind every mouth track to that exact body; no cross-body patches/masks/coordinates reuse. Happy/sad are slightly only, including model intensity2. Body is silent. No layer means whole-package fallback, never a neutral mouth over another body. -Provide 0.9/1.1/1.2 aperture previews; Pi chooses before import. +Pi selected **1.1 source pixels for the candidate**, based on fixed comparisons; +dynamic naturalness review is still pending. Do not treat a numeric gap as approval. Edges: `id`, `from`, `to`, `fromAnchor`, `toAnchor`, `fromFrame`, `toFrame`, -`clip:{path,sha256,width,height,frameCount,ptsUs,durationUs,hasAudio:false}`. +`clip:{path,sha256,width,height,frameCount,ptsUs,durationUs,fpsNumerator,fpsDenominator,hasAudio:false}`. +Edges also bind `fromPtsUs` and `toPtsUs` to the exact source/target body frame; +`fromFrame` must be in that source package's `legalExitFrames`. Each package declares `entryAnchor`, `exitAnchor`, `legalExitFrames`, `loopEdge`. Frame indices/PTS are actual decoded values. Every changed body phase requires a reviewed edge, no arbitrary alpha cut. Supply dense seam frames, real-speed loops @@ -58,6 +61,44 @@ camera cues are independent and never select these role packages. Production runtime04 parser: `app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt`; v2 index parser: `app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt`. Each package should use `packId:a01-expression-action-v1--runtime-04`; -runtime04 body/patchFormat/patches/mouthStates/stateRouting field shapes stay intact. +New per-package runtime manifests use **schemaVersion:2**; only the old neutral +runtime03/04 schemaVersion1 retains its fixed97@24 constraints. Each new body's +`frameCount:N`, `durationUs`, `fpsNumerator/fpsDenominator`, **`ptsUs:[actual decoded +presentation timestamps]`** are mandatory. No truncation/padding to97, no neutral +track reuse. Counts121/49 and rational frame rates are supported independently. +Current GLES shape remains480×848 (new shapes require renderer extension). +N is bounded2..720, fps1..60, duration0.1..30s; body PTS starts0, strictly increases, +remains below duration and agrees with measured duration/nominal fps within one +nominal frame. Nonuniform actual PTS is accepted within two nominal frame intervals. +Machine gate must compare decoded PTS/duration to declarations, not infer PTS. +`patchFormat.bodySha256` must equal `body.sha256`; `patches` has exactlyN entries, +each `frameIndex:i`, `ptsUs:body.ptsUs[i]`, own coordinates/mask and five independent +level paths/hashes. Patch format remains straight RGBA8, [0,.25,.5,.75,1]; nearest +level, nonzero opacity1, zero bypass. Each patch≤128×128, totalRGBA≤8MB/runtime; +all packages combined≤32MB, ≤12packages. These are admission bounds, not GPU proof. +Each of the five mouth states supplies own actual `ptsUs`, `frameCount`, fps ratio, +`durationMs` (100..1000), alpha values and A/B anchors; curve timing no longer +assumes24fps. Runtime04 mouthStates/stateRouting names and anchor rules stay intact. Entry/return bridges carry actual decoded frame PTS; `audioEndUs` records measured last audio timestamp, completion also waits actual media stop and restored A. + +Current asset snapshot: happy/sad001 sources each actually97 frames; sad002 must +be measured independently. 121/49 are compatibility test counts, not a claim about +those files. The happy-01 draft hash +`518865589fcff36259b864226cdc9651f742d6f56f3b58eeb98f241ef03d48e3` +still used schema1/`a01-slight-happy-01`/`body.framePTSUs` at the read-only check; +it is rejected, not silently relabeled or modified. Export schema2, packId +`a01-expression-action-v1-happy-01-runtime-04`, `body.ptsUs`, +`patchFormat.bodySha256`, and each mouth state's `ptsUs`. Use the same format for +sad/neutral, independently measured. A frame0 enter bridge is legal only when +its source declares frame0 in `legalExitFrames`; do not inherit old last-frame exits. + +Read-only handoff check (new evidence file, does not import/activate): +`python3 scripts/check-avatar-runtime.py --manifest /manifest.json --sha256 --output logs/action-emotion/.json`. +It checks file hashes, complete video decode, actual PTS/duration/fps, PNG RGBA +shape/cache and production Kotlin admission. It rejects concurrent file drift. +Deliver corrected runtime paths/hashes plus complete index hash, reviewed loop/ +enter/return clip paths/hashes, timed seam previews and Pi's external exact pin. +Conversation planning retains clip metadata and assigns each bridge execution a +unique serial; stale completion cannot authorize a later bridge with the same id. +Playback driver integration and capability activation remain separate work. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json index 889c22b..e2d94f3 100644 --- a/gateway/SOURCE_MANIFEST.json +++ b/gateway/SOURCE_MANIFEST.json @@ -341,8 +341,8 @@ }, "tests/test_action_protocol.py": { "source": "workspace:gateway/tests/test_action_protocol.py", - "sha256": "2e19bb1471a2bab67bfb7adca1630151d466e50d9ebc103e54c2f92566f63b63", - "bytes": 9776, + "sha256": "fdc6c6206a6a0478166bc49b062c2981158cf1a6a8cdcf3e0d0df57a86fa4020", + "bytes": 15127, "upstream_sha256": "ae564b6a6e51620a33250e160df2ae0ba6619c5ea6d1063e96bfcd8baa144a79" }, "tests/test_action_reply.py": { diff --git a/gateway/tests/test_action_protocol.py b/gateway/tests/test_action_protocol.py index 93e914e..ec93f72 100644 --- a/gateway/tests/test_action_protocol.py +++ b/gateway/tests/test_action_protocol.py @@ -66,6 +66,89 @@ class ActionProtocolTests(unittest.TestCase): class ActionDialogueTests(unittest.IsolatedAsyncioTestCase): + async def prepare_fixture_action(self, d): + d.action_capability=PACK;d.playback_waiting=True + queue=asyncio.Queue(2);metrics={} + await d.generate(0,'公开合成请求',queue,metrics,time.perf_counter()) + await d.synthesize(0,queue,metrics,time.perf_counter()) + await d.drained() + ticket=d.action_plans.ticket + self.assertTrue(ticket and d.action_holding) + start={'action_id':ticket.id,'turn_id':0,'status':'started','asset_id':'asset_01','mic_stopped':True} + await d.action_status(start);ticket.started-=1.1 + return {**start,'status':'completed','video_ended':True,'audio_stopped':True,'idle_restored':True} + + async def test_full_fixture_cancel_and_failure_never_synthesize_after(self): + for status in ('cancelled','failed'): + with self.subTest(status=status): + calls=[] + def backend(request): + calls.append(request.url.port) + if request.url.port==8888: + return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':RAW},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n') + return httpx.Response(200,content=wav(b'\x10\x02'*4800,48000)) + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + socket=Socket();d=Dialogue(socket,FakeModel(),client) + complete=await self.prepare_fixture_action(d) + before=len(socket.frames) + await d.action_status({**complete,'status':status}) + await d.action_status(complete) + self.assertEqual(calls,[8888,5002]) + self.assertEqual(len(socket.frames),before) + self.assertIsNone(d.task);self.assertIsNone(d.action_plans.ticket) + self.assertFalse(any(e['type']=='speech.start' for e in socket.events)) + self.assertFalse(d.action_holding) + await d.close() + + async def test_full_fixture_new_turn_aborts_inflight_after_generator(self): + calls=[];entered=asyncio.Event();release=asyncio.Event() + async def backend(request): + calls.append(request.url.port) + if request.url.port==8888: + return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':RAW},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n') + if calls.count(5002)==2: + entered.set();await release.wait() + return httpx.Response(200,content=wav(b'\x10\x02'*4800,48000)) + with tempfile.TemporaryDirectory() as folder: + h=History(Path(folder)/'h.db');await h.initialize();cid=await h.conversation() + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + socket=Socket();d=Dialogue(socket,FakeModel(),client,h,cid) + complete=await self.prepare_fixture_action(d) + before=len(socket.frames) + await d.action_status(complete) + task=d.task;await asyncio.wait_for(entered.wait(),2) + self.assertEqual(d.turn,1) + await d.invalidate('new_turn');release.set() + with self.assertRaises(asyncio.CancelledError): await task + await d.request_drained(1);await d.action_status(complete) + self.assertEqual(calls,[8888,5002,5002]) + self.assertEqual(len(socket.frames),before) + self.assertIsNone(d.followup_pending) + self.assertEqual(await h.rows(cid),[]) + self.assertEqual(await h.context(cid,'next'),[]) + await d.close() + + async def test_actual_generate_speculative_prepare_final_cancel_and_no_second_llm(self): + for tail,finish in [(',"emotion":"sad"}', 'stop'),(',"extra":1}', 'stop'),('', 'length')]: + with self.subTest(tail=tail,finish=finish): + raw=RAW[:-1]+tail;calls=[] + def backend(request): + calls.append(request.url.port) + chunks=[raw[i:i+1] for i in range(len(raw))] + data=''.join('data: '+json.dumps({'choices':[{'delta':{'content':chunk}}]})+'\n\n' for chunk in chunks) + return httpx.Response(200,text=data+'data: '+json.dumps({'choices':[{'finish_reason':finish,'delta':{}}]})+'\n\ndata: [DONE]\n\n') + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + socket=Socket();d=Dialogue(socket,FakeModel(),client);d.action_capability=PACK + queue=asyncio.Queue(2) + await d.generate(0,'公开合成请求',queue,{},time.perf_counter()) + types=[e['type'] for e in socket.events] + self.assertLess(types.index('reply.emotion.prepare'),types.index('reply.emotion.prepare.cancel')) + self.assertLess(types.index('reply.emotion.prepare.cancel'),types.index('reply.emotion')) + self.assertEqual(calls,[8888]);self.assertIsNone(d.action_plans.ticket) + self.assertFalse((await queue.get()).startswith('{')) + self.assertIsNone(await queue.get()) + await d.close() + async def test_single_llm_then_drained_music_then_single_followup_and_history(self): calls=[] def backend(request): diff --git a/scripts/check-avatar-runtime.py b/scripts/check-avatar-runtime.py new file mode 100644 index 0000000..c980ea7 --- /dev/null +++ b/scripts/check-avatar-runtime.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Read-only Gate1 plus production Kotlin admission; never imports or approves assets.""" +import argparse +from decimal import Decimal +from fractions import Fraction +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys + +from PIL import Image + +ROOT=Path(__file__).resolve().parents[1] +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--manifest',type=Path,required=True) +parser.add_argument('--sha256',required=True,help='Exact candidate hash; this is not a publication approval') +parser.add_argument('--output',type=Path,required=True,help='New evidence file outside owner asset directory') +args=parser.parse_args() + +def require(value,reason): + if not value: raise ValueError(reason) + +def main(): + source=args.manifest.resolve(strict=True);directory=source.parent + output=args.output.resolve() + require(not output.exists() and not output.is_relative_to(directory),'evidence must be new and outside owner directory') + require(source.stat().st_size<=2_000_000,'manifest byte bound') + raw=source.read_bytes();digest=hashlib.sha256(raw).hexdigest() + require(re.fullmatch('[0-9a-f]{64}',args.sha256) and digest==args.sha256,'candidate manifest drift') + def unique(pairs): + result={} + for key,value in pairs: + require(key not in result,'duplicate manifest key');result[key]=value + return result + manifest=json.loads(raw,object_pairs_hook=unique) + body=manifest['body'];count=body['frameCount'] + require(type(count) is int and 2<=count<=720,'body frame bound') + dynamic=manifest['schemaVersion']==2 + require(dynamic or manifest['packId'] in ('a01-neutral-graph-v1-runtime-03','a01-neutral-graph-v1-runtime-04'),'new bodies require schema2') + if dynamic: + require(manifest['patchFormat']['bodySha256']==body['sha256'],'own-mouth body binding') + verified={} + def file(row,pattern,bound): + name=row['path'];require(re.fullmatch(pattern,name),'asset path shape') + path=(directory/name).resolve(strict=True) + require(path.is_relative_to(directory),'asset path escape') + require(path.stat().st_size<=bound,'asset file byte bound') + sha=hashlib.sha256(path.read_bytes()).hexdigest() + require(sha==row['sha256'],'asset file hash mismatch') + verified[name]=sha + return path + video=file(body,r'body/[A-Za-z0-9_.-]+\.mp4',64_000_000) + probe=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',str(video)],capture_output=True,check=True,timeout=60) + decoded=json.loads(probe.stdout);streams=decoded['streams'];frames=decoded['frames'] + require(len(streams)==1 and streams[0]['codec_type']=='video' and body['hasAudio'] is False,'conversation must be silent video') + stream=streams[0] + require(stream['codec_name']=='h264' and (stream['width'],stream['height'])==(body['width'],body['height'])==(480,848),'codec/shape mismatch') + require(Fraction(stream['r_frame_rate'])==Fraction(body['fpsNumerator'],body['fpsDenominator']),'measured nominal fps mismatch') + require(len(frames)==count,'decoded actual N mismatch') + pts=[int((Decimal(frame['best_effort_timestamp_time'])*1_000_000).to_integral_value()) for frame in frames] + expected=body['ptsUs'] if dynamic else [i*1_000_000//24 for i in range(count)] + require(len(expected)==count and all(abs(a-b)<=2 for a,b in zip(pts,expected)),'decoded actual PTS mismatch') + duration=int((Decimal(stream['duration'])*1_000_000).to_integral_value()) + require(abs(duration-body['durationUs'])<=2,'decoded duration mismatch') + subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(video),'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60) + patches=manifest['patches'];require(len(patches)==count,'N patches required') + rgba=0;paths=[];aperture=manifest['packId'].endswith('runtime-04') + for i,patch in enumerate(patches): + require(patch['frameIndex']==i and abs(patch['ptsUs']-pts[i])<=2,'own-frame patch binding') + if dynamic: require(patch['ptsUs']==expected[i],'schema2 exact patch PTS binding') + width,height=patch['width'],patch['height'] + require(type(width) is int and type(height) is int and 1<=width<=128 and 1<=height<=128,'patch shape bound') + levels=patch['levels'] if aperture else [patch] + require(len(levels)==(5 if aperture else 1),'five own levels required') + for level in levels: + image=file(level,r'patches/[A-Za-z0-9_.-]+\.png',256_000);paths.append(level['path']) + with Image.open(image) as bitmap: + require(bitmap.format=='PNG' and bitmap.mode=='RGBA' and bitmap.size==(width,height),'decoded PNG RGBA/shape mismatch') + bitmap.load() + rgba+=width*height*4 + require(len(set(paths))==len(paths) and rgba<=8_000_000,'unique N levels/cache bound') + result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--runtime-manifest',str(source)],capture_output=True,text=True,timeout=120) + require(result.returncode==0,'production Kotlin admission failed (candidate format or metadata)') + require('PASS: actual exported runtime manifest parsed' in result.stdout,'actual parser evidence absent') + require(source.read_bytes()==raw,'manifest changed during gate') + for name,sha in verified.items(): + require(hashlib.sha256((directory/name).read_bytes()).hexdigest()==sha,'asset changed during gate') + evidence={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':digest, + 'body_sha256':body['sha256'],'schema_version':manifest['schemaVersion'],'actual_frame_count':count, + 'actual_pts_count':len(pts),'actual_duration_us':duration,'patch_images':len(paths),'rgba_cache_bytes':rgba, + 'verified_files':len(verified),'full_decode':'passed','production_kotlin_parser':'passed','naturalness':'pending','real_device':'not_run'} + output.parent.mkdir(parents=True,exist_ok=True) + with output.open('x') as target: json.dump(evidence,target,indent=2);target.write('\n') + print(json.dumps(evidence)) + +try: main() +except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error: + print('FAIL: runtime gate: '+str(error),file=sys.stderr) + raise SystemExit(1) diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index b847ba0..21f6a24 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -27,7 +27,7 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice' suites = [ ('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']), - ('avatar','AvatarCheckKt', [source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), + ('avatar','AvatarCheckKt', [source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), ('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ] @@ -50,7 +50,7 @@ for name, main, real in suites: if isinstance(value,(list,dict)): result=('listOf('+','.join(map(kotlin,value))+')' if isinstance(value,list) else 'mapOf('+','.join(kotlin(k)+' to '+kotlin(v) for k,v in value.items())+')') - # Actual97x5 metadata exceeds a single JVM method. Preserve every + # Actual N×5 metadata can exceed a single JVM method. Preserve every # field while splitting literal construction into bounded helpers. method='metadata'+str(len(definitions)) kind='List' if isinstance(value,list) else 'Map' @@ -63,9 +63,9 @@ for name, main, real in suites: literal=kotlin(json.loads(raw)) extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+'fun main() {\nval root='+literal+'\n'+ 'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+ - 'check(pack.patches.size==97 && pack.body.frameCount==97 && pack.curves.size==5)\n'+ - ('check(pack.apertureMode && pack.textureImages.size==485 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==97)\n')+ - 'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; 97 body/patch frames and five authored curves/routing")\n}\n') + 'check(pack.patches.size==pack.body.frameCount && pack.curves.size==5)\n'+ + ('check(pack.apertureMode && pack.textureImages.size==pack.body.frameCount*5 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==pack.body.frameCount)\n')+ + 'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; per-body actual frame count/PTS and five authored curves/routing")\n}\n') files.append(extra) subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib', '-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT) diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index 4106a73..a80a3ac 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -6,8 +6,10 @@ import android.media.MediaPlayer import android.view.TextureView fun main() { + dynamicBodyCheck() actionCheck() emotionActionCheck() + conversationPackageCheck() checkContinuous() checkEngineering() checkSafeDriver() diff --git a/tests/avatar/ConversationPackageCheck.kt b/tests/avatar/ConversationPackageCheck.kt new file mode 100644 index 0000000..a2b8711 --- /dev/null +++ b/tests/avatar/ConversationPackageCheck.kt @@ -0,0 +1,88 @@ +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.dialogue.RoleEmotion + +/** Synthetic metadata invokes production admission/routing, never asset approval. */ +@Suppress("UNCHECKED_CAST") +fun conversationPackageCheck() { + val pin="b".repeat(64) + val packs=linkedMapOf("neutral" to dynamicPack(97,24,"c".repeat(64)), + "happy" to dynamicPack(121,30,"d".repeat(64)),"sad" to dynamicPack(49,24,"e".repeat(64))) + fun row(id: String,pack: ContinuousAvatarPack)=mapOf("id" to id, + "emotion" to if(id=="neutral") "neutral" else if(id=="sad") "sad" else "happy", + "visualIntensity" to if(id=="neutral") 0 else 1,"mouthBodySha256" to pack.body.sha256, + "runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to pack.manifestSha), + "entryAnchor" to "A","exitAnchor" to "A","legalExitFrames" to listOf(pack.body.frameCount-1),"loopEdge" to "$id-loop") + val clip=mapOf("path" to "clips/bridge.mp4","sha256" to pin,"hasAudio" to false, + "width" to 480,"height" to 848,"fpsNumerator" to 24,"fpsDenominator" to 1, + "frameCount" to 12,"ptsUs" to List(12) { it*1_000_000L/24 },"durationUs" to 500_000L) + fun edges(data: Map): List> { + fun edge(id: String,from: String,to: String)=mapOf("id" to id,"from" to from,"to" to to, + "fromAnchor" to "A","toAnchor" to "A","fromFrame" to data.getValue(from).body.frameCount-1,"toFrame" to 0, + "fromPtsUs" to data.getValue(from).body.ptsUs.last(),"toPtsUs" to 0L,"clip" to clip) + return data.keys.map { edge("$it-loop",it,it) }+data.keys.filter { it!="neutral" }.flatMap { + listOf(edge("neutral-$it","neutral",it),edge("$it-neutral",it,"neutral")) + } + } + fun root(data: Map)=mapOf("schemaVersion" to 2,"identityId" to "a01", + "packId" to "a01-expression-action-v1","fallbackPackageId" to "neutral", + "conversationPackages" to data.map { row(it.key,it.value) },"edges" to edges(data),"actions" to emptyList()) + fun read(meta: Map,data: Map = packs)=EmotionActionManifest.read(meta,pin,pin) { path,hash -> + data[path.substringBefore('/')]?.takeIf { it.manifestSha==hash } + } + val meta=root(packs);val index=checkNotNull(read(meta)) + check(index.packages.values.map { it.body.frameCount }==listOf(97,121,49) && index.actionPack==null) + check(index.edges.size==7 && index.edges.all { it.clip.ptsUs.size==12 && it.clip.sha256==pin }) + val graph=edges(packs) + var rejected=0 + fun invalid(change: Map) { check(read(meta+change)==null);rejected++ } + invalid(mapOf("edges" to graph.filterNot { it["id"]=="sad-neutral" })) + for(change in listOf(mapOf("fromFrame" to 1),mapOf("fromPtsUs" to 99L),mapOf("toPtsUs" to 1L), + mapOf("toFrame" to 49),mapOf("clip" to clip+("hasAudio" to true)), + mapOf("clip" to clip+("frameCount" to 4_294_967_308L)),mapOf("clip" to clip+("fpsNumerator" to 4_294_967_320L)), + mapOf("clip" to clip+("path" to "../bridge.mp4")),mapOf("clip" to clip+("ptsUs" to listOf(0L))))) { + invalid(mapOf("edges" to listOf(graph[0]+change)+graph.drop(1))) + } + val rows=packs.map { row(it.key,it.value) } + for(change in listOf(mapOf("mouthBodySha256" to pin),mapOf("emotion" to "angry"),mapOf("emotion" to "curious"), + mapOf("visualIntensity" to 2))) invalid(mapOf("conversationPackages" to listOf(rows[0],rows[1]+change,rows[2]))) + val largeRoot=dynamicRuntimeFixture(100,24,1,"f".repeat(64)) + val largePatches=(largeRoot["patches"] as List>).map { it+mapOf("width" to 80,"height" to 44) } + val large=checkNotNull(ContinuousAvatarManifest.read(largeRoot+("patches" to largePatches),"f".repeat(64),"f".repeat(64),true,"large/")) + check(large.rgbaBytes { + val old=continuousFixture() + val pts=List(count) { it*1_000_000L*fpsD/fpsN } + val base=(old["patches"] as List>).first() + val patches=pts.mapIndexed { i,t -> + val levels=List(5) { l -> mapOf("levelIndex" to l,"aperture" to l/4f,"path" to "patches/f$i-l$l.png","sha256" to sha) } + base+mapOf("frameIndex" to i,"ptsUs" to t,"levels" to levels,"path" to levels[4]["path"],"sha256" to sha) + } + val states=(old["mouthStates"] as List>).map { state -> + val n=(state["globalAlphaByFrame"] as List<*>).size + state+("ptsUs" to List(n) { it*1_000_000L/24 }) + } + return old+mapOf("schemaVersion" to 2,"packId" to "a01-expression-action-v1-test-runtime-04", + "body" to (old["body"] as Map)+mapOf("sha256" to sha,"frameCount" to count, + "fpsNumerator" to fpsN,"fpsDenominator" to fpsD,"ptsUs" to pts,"durationUs" to (count*1_000_000L*fpsD+fpsN/2)/fpsN), + "patches" to patches,"mouthStates" to states,"patchFormat" to mapOf("bodySha256" to sha, + "format" to "PNG RGBA 8bit","alphaEncoding" to "straight_unassociated","apertureLevels" to listOf(0f,.25f,.5f,.75f,1f),"requiresRendererExtension" to true)) +} +fun dynamicPack(count: Int,fps: Int,sha: String): ContinuousAvatarPack = checkNotNull( + ContinuousAvatarManifest.read(dynamicRuntimeFixture(count,fps,1,sha),sha,sha,true,"dynamic/")) + +@Suppress("UNCHECKED_CAST") +fun dynamicBodyCheck() { + var boundaries=0 + for((count,fpsN,fpsD) in listOf(Triple(121,30,1),Triple(49,24,1),Triple(61,30000,1001))) { + val sha="c".repeat(64);val root=dynamicRuntimeFixture(count,fpsN,fpsD,sha) + fun read(data: Map)=ContinuousAvatarManifest.read(data,sha,sha,true,"fixture/") + val pack=checkNotNull(read(root));check(pack.body.frameCount==count && pack.textureImages.size==count*5) + val presenter=ContinuousFramePresenter(pack) { 0 } + repeat(2) { loop -> + for(i in 0 until count) { + val pts=pack.body.ptsUs[i];presenter.decoded(pts) + val frame=checkNotNull(presenter.present(pts*1000,loop*10000L+pts/1000) {}) + check(frame.key.index==i && frame.patch.ptsUs==pts && frame.key.loopOrdinal==loop.toLong()) + for(level in 0..4) { + val s=selectMouthPatch(pack,i,level/4f) + check(s.textureSlot==i*5+level && s.opacity==if(level==0) 0f else 1f) + boundaries++ + } + } + presenter.wrap() + } + val body=root["body"] as Map;val patches=root["patches"] as List> + fun invalid(data: Map) { check(read(data)==null);boundaries++ } + invalid(root+("body" to body+("frameCount" to 97))) + invalid(root+("body" to body+("durationUs" to 100_000_000L))) + invalid(root+("body" to body+("fpsDenominator" to 0))) + invalid(root+("body" to body+("ptsUs" to pack.body.ptsUs.dropLast(1)))) + invalid(root+("body" to body+("ptsUs" to listOf(1L)+pack.body.ptsUs.drop(1)))) + invalid(root+("patches" to listOf(patches[0]+("ptsUs" to 1L))+patches.drop(1))) + invalid(root+("patches" to patches.dropLast(1))) + invalid(root+("patches" to patches.map { it+mapOf("width" to 128,"height" to 128) })) + invalid(root+("patchFormat" to (root["patchFormat"] as Map)+("bodySha256" to "b".repeat(64)))) + invalid(root+("schemaVersion" to 1)) + invalid(root+("body" to body+("frameCount" to 721))) + invalid(root+("body" to body+("frameCount" to 4_294_967_417L))) + invalid(root+("body" to body+("fpsNumerator" to 61))) + invalid(root+("body" to body+("ptsUs" to listOf(0L,0L)+pack.body.ptsUs.drop(2)))) + val levels=patches[0]["levels"] as List> + invalid(root+("patches" to listOf(patches[0]+("levels" to levels.dropLast(1)))+patches.drop(1))) + invalid(root+("patches" to listOf(patches[0]+("levels" to listOf(levels[0],levels[1]+("path" to levels[0]["path"]))+levels.drop(2)))+patches.drop(1))) + val states=root["mouthStates"] as List> + invalid(root+("mouthStates" to listOf(states[0]+("ptsUs" to listOf(0L)))+states.drop(1))) + check(runCatching { ContinuousFramePresenter(pack).decoded(pack.body.ptsUs[1]) }.isFailure) + check(runCatching { selectMouthPatch(pack,count,.5f) }.isFailure) + if(fpsD==1) { + TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false + CodecFixture.frames=count;CodecFixture.fps=fpsN + CodecFixture.onRender={ pts -> SurfaceTexture.lastCreated?.emit(pts*1000) } + val frames=mutableListOf();val errors=mutableListOf() + val renderer=ContinuousBodyRenderer(android.content.Context(),pack,Surface(SurfaceTexture(0)),480,848, + { frame,_ -> frames.add(frame) },errors::add) + renderer.intent(true,1,1);TestScheduler.advanceBy((pack.body.durationUs/1000)*2+100) + check(errors.isEmpty() && frames.size>count && frames[count].key.index==0 && frames[count].key.loopOrdinal==1L) { + "dynamic renderer count=$count fps=$fpsN errors=$errors frames=${frames.size} wrap=${frames.getOrNull(count)?.key}" + } + check(frames.all { it.patch.ptsUs==pack.body.ptsUs[it.key.index] && it.selection.textureSlot in pack.textureImages.indices }) + renderer.close();TestScheduler.advanceBy(100) + } + } + val sha="c".repeat(64);val root=dynamicRuntimeFixture();val body=root["body"] as Map + val pts=(body["ptsUs"] as List).mapIndexed { i,t -> t+if(i%2==1) 1000 else 0 } + val patches=(root["patches"] as List>).mapIndexed { i,p -> p+("ptsUs" to pts[i]) } + val variable=root+mapOf("body" to body+("ptsUs" to pts),"patches" to patches) + check(ContinuousAvatarManifest.read(variable,sha,sha,true,"variable/")!=null) + val curve=MouthCurve("opening",400,listOf(0f,.25f,1f),listOf(0L,100_000L,300_000L)) + val mouth=ContinuousMouth(continuousPack().curves+("opening" to curve)) + mouth.request(true,1,1);mouth.sample(0) + check(kotlin.math.abs(mouth.sample(200).alpha-.625f)<.0001f) + println("PASS: dynamic121/49/61 bodies + rational/nonuniform actual PTS, $boundaries frame/level/rejection checks; production decoder/render wrap on121@30/49@24, per-curve timing, SHA/cache/schema fences; fixtures only") +} diff --git a/tests/avatar/EmotionActionCheck.kt b/tests/avatar/EmotionActionCheck.kt index ec37bcc..c613eb7 100644 --- a/tests/avatar/EmotionActionCheck.kt +++ b/tests/avatar/EmotionActionCheck.kt @@ -6,9 +6,9 @@ fun emotionActionCheck() { patch.copy(levels=List(5) { MouthPatchLevel(it,it/4f,"patches/${patch.frameIndex}-$it.png",sha) }) }) } fun clip(audio: Boolean)=mapOf("path" to "clips/bridge.mp4","sha256" to sha,"hasAudio" to audio, - "frameCount" to 48,"ptsUs" to List(48) { it*1_000_000L/24 },"durationUs" to 2_000_000L) + "width" to 480,"height" to 848,"fpsNumerator" to 24,"fpsDenominator" to 1,"frameCount" to 48,"ptsUs" to List(48) { it*1_000_000L/24 },"durationUs" to 2_000_000L) fun edge(id: String,from: String,to: String)=mapOf("id" to id,"from" to from,"to" to to, - "fromAnchor" to "A","toAnchor" to "A","fromFrame" to 96,"toFrame" to 0,"clip" to clip(false)) + "fromPtsUs" to 4_000_000L,"toPtsUs" to 0L,"fromAnchor" to "A","toAnchor" to "A","fromFrame" to 96,"toFrame" to 0,"clip" to clip(false)) fun conversation(id: String)=mapOf("id" to id,"emotion" to if(id=="neutral") "neutral" else "happy", "visualIntensity" to if(id=="neutral") 0 else 1,"mouthBodySha256" to sha, "runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to sha),"entryAnchor" to "A","exitAnchor" to "A",