Support bounded 720x1280 avatar shapes through GLES and production gates

This commit is contained in:
zenord
2026-10-13 17:32:21 +08:00
parent 62dce32bb7
commit ddd75fc571
18 changed files with 352 additions and 83 deletions
+5 -3
View File
@@ -22,7 +22,8 @@ static void texture(GLuint id,int w,int h,const char *path) {
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_RGBA,GL_UNSIGNED_BYTE,data);free(data);
}
int main(int argc,char **v) {
assert(argc==14);
assert(argc==16);
int bw=atoi(v[14]),bh=atoi(v[15]);assert(bw>0&&bh>0);
int pw=atoi(v[6]),ph=atoi(v[7]),w=atoi(v[11]),h=atoi(v[12]);float x=atof(v[8]),y=atof(v[9]),opacity=atof(v[10]);
PFNEGLGETPLATFORMDISPLAYEXTPROC platform=(void*)eglGetProcAddress("eglGetPlatformDisplayEXT");assert(platform);
EGLDisplay d=platform(EGL_PLATFORM_SURFACELESS_MESA,EGL_DEFAULT_DISPLAY,NULL);assert(d!=EGL_NO_DISPLAY);
@@ -34,9 +35,10 @@ int main(int argc,char **v) {
assert(eglMakeCurrent(d,surface,surface,c));
GLuint vertex=shader(GL_VERTEX_SHADER,v[1]),fragment=shader(GL_FRAGMENT_SHADER,v[2]);GLuint p=glCreateProgram();glAttachShader(p,vertex);glAttachShader(p,fragment);glLinkProgram(p);
GLint linked;glGetProgramiv(p,GL_LINK_STATUS,&linked);assert(linked);glUseProgram(p);
GLuint ids[2];glGenTextures(2,ids);glActiveTexture(GL_TEXTURE0);texture(ids[0],480,848,v[3]);glUniform1i(glGetUniformLocation(p,"uBody"),0);
GLuint ids[2];glGenTextures(2,ids);glActiveTexture(GL_TEXTURE0);texture(ids[0],bw,bh,v[3]);glUniform1i(glGetUniformLocation(p,"uBody"),0);
glActiveTexture(GL_TEXTURE1);texture(ids[1],pw,ph,v[4]);glUniform1i(glGetUniformLocation(p,"uPatch"),1);
float scale=fminf(w/480.f,h/848.f),mw=480*scale,mh=848*scale,left=(w-mw)/2,top=(h-mh)/2;
glUniform2f(glGetUniformLocation(p,"uBodySize"),bw,bh);
float scale=fminf((float)w/bw,(float)h/bh),mw=bw*scale,mh=bh*scale,left=(w-mw)/2,top=(h-mh)/2;
GLfloat pos[]={left/w*2-1,1-(top+mh)/h*2,(left+mw)/w*2-1,1-(top+mh)/h*2,left/w*2-1,1-top/h*2,(left+mw)/w*2-1,1-top/h*2};
GLfloat uv[]={0,0,1,0,0,1,1,1};
GLint a=glGetAttribLocation(p,"aPosition"),b=glGetAttribLocation(p,"aUv");glVertexAttribPointer(a,2,GL_FLOAT,GL_FALSE,0,pos);glEnableVertexAttribArray(a);glVertexAttribPointer(b,2,GL_FLOAT,GL_FALSE,0,uv);glEnableVertexAttribArray(b);
+1
View File
@@ -16,6 +16,7 @@ fun main() {
emotionActionCheck()
conversationPackageCheck()
actualMediaViewCheck()
actualMediaViewCheck(720,1280)
mediaBoundaryCheck()
idleVariantCheck()
fullActionGraphCheck()
+3 -2
View File
@@ -5,6 +5,7 @@ import java.nio.ByteBuffer
/** Deterministic API doubles exercise production codec control; no Android decoder claim. */
object CodecFixture {
var width=480;var height=848
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
@@ -13,7 +14,7 @@ object CodecFixture {
val timelines=mutableMapOf<String,List<Long>>()
val audioPaths=mutableSetOf<String>()
fun reset() {
frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false
width=480;height=848;frames=20; fps=20; gop=4; firstPtsUs=0; timestampOffsetUs=0; outputEnabled=true; configureFails=false
seeks.clear(); releases=0; flushes=0; rendered.clear(); onRender=null
emitNativeSurface=false;timelines.clear();audioPaths.clear()
}
@@ -21,7 +22,7 @@ object CodecFixture {
class MediaFormat(private val mime: String="video/avc") {
companion object { const val KEY_MIME="mime"; const val KEY_WIDTH="width"; const val KEY_HEIGHT="height" }
fun getString(key: String): String? = mime
fun getInteger(key: String): Int = if (key == KEY_WIDTH) 480 else 848
fun getInteger(key: String): Int = if (key == KEY_WIDTH) CodecFixture.width else CodecFixture.height
}
class MediaExtractor {
private var av=false
+37 -4
View File
@@ -8,7 +8,7 @@ import android.os.TestScheduler
import android.opengl.GLFixture
@Suppress("UNCHECKED_CAST")
fun dynamicRuntimeFixture(count: Int=121,fpsN: Int=30,fpsD: Int=1,sha: String="c".repeat(64)): Map<String,Any?> {
fun dynamicRuntimeFixture(count: Int=121,fpsN: Int=30,fpsD: Int=1,sha: String="c".repeat(64),width: Int=480,height: Int=848): Map<String,Any?> {
val old=continuousFixture()
val pts=List(count) { it*1_000_000L*fpsD/fpsN }
val base=(old["patches"] as List<Map<String,Any?>>).first()
@@ -21,13 +21,13 @@ fun dynamicRuntimeFixture(count: Int=121,fpsN: Int=30,fpsD: Int=1,sha: String="c
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<String,Any?>)+mapOf("sha256" to sha,"frameCount" to count,
"body" to (old["body"] as Map<String,Any?>)+mapOf("sha256" to sha,"width" to width,"height" to height,"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/"))
fun dynamicPack(count: Int,fps: Int,sha: String,width: Int=480,height: Int=848): ContinuousAvatarPack = checkNotNull(
ContinuousAvatarManifest.read(dynamicRuntimeFixture(count,fps,1,sha,width,height),sha,sha,true,"dynamic/"))
@Suppress("UNCHECKED_CAST")
fun dynamicBodyCheck() {
@@ -101,6 +101,39 @@ fun dynamicBodyCheck() {
val patches=(root["patches"] as List<Map<String,Any?>>).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)
// Run the production decoder/shader driver with 720 format, not a copied state model.
run {
val large=dynamicRuntimeFixture(97,24,1,sha,720,1280)
val rows=large["patches"] as List<Map<String,Any?>>
val moved=large+("patches" to rows.map { it+mapOf("x" to 650.25f,"y" to 1200.5f) })
val pack=checkNotNull(ContinuousAvatarManifest.read(moved,sha,sha,true,"large/"))
check(pack.patches.all { it.x>480 && it.y>848 })
fun rejected(meta: Map<String,Any?>) { check(ContinuousAvatarManifest.read(meta,sha,sha,true,"large/")==null) }
rejected(moved+("patches" to rows.map { it+("x" to 690f) }))
rejected(moved+("patches" to rows.map { it+("y" to 1260f) }))
rejected(moved+("body" to (large["body"] as Map<String,Any?>)+mapOf("width" to 720,"height" to 848)))
rejected(moved+("body" to (large["body"] as Map<String,Any?>)+mapOf("width" to 1080,"height" to 1920)))
val legacy=continuousFixture()
rejected(legacy+("body" to (legacy["body"] as Map<String,Any?>)+mapOf("width" to 720,"height" to 1280)))
val fit=bodyFit(360,800,720,1280)
check(fit.left==0f && fit.top==80f && fit.width==360f && fit.height==640f)
fun render(codecW: Int,codecH: Int): Pair<List<ComposedBodyFrame>,List<String>> {
TestScheduler.reset();CodecFixture.reset();GLFixture.reset()
CodecFixture.width=codecW;CodecFixture.height=codecH;CodecFixture.frames=97;CodecFixture.fps=24
CodecFixture.onRender={ t -> SurfaceTexture.lastCreated?.emit(t*1000) }
val frames=mutableListOf<ComposedBodyFrame>();val errors=mutableListOf<String>()
val renderer=ContinuousBodyRenderer(android.content.Context(),pack,Surface(SurfaceTexture(0)),360,800,
{ frame,_ -> frames+=frame },errors::add)
renderer.intent(true,1,1);TestScheduler.advanceBy(8500)
if(errors.isEmpty()) check(GLFixture.bodySize==720f to 1280f && frames.size>97 && frames[97].key.loopOrdinal==1L)
renderer.close();TestScheduler.advanceBy(100);check(CodecFixture.releases==1 || errors.isNotEmpty())
val count=frames.size;SurfaceTexture.lastCreated?.emit(0);TestScheduler.advanceBy(100);check(frames.size==count)
return frames to errors
}
val ok=render(720,1280);check(ok.second.isEmpty() && ok.first.all { it.patch==pack.patches[it.key.index] })
val wrong=render(480,848);check(wrong.first.isEmpty() && wrong.second.isNotEmpty())
println("PASS: schema2 720x1280 production codec/render/uniform/wrap/release, pixel bounds/Fit, mismatched decoder and legacy/unsupported shape rejection; GPU/device not claimed")
}
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)
+24 -5
View File
@@ -1,14 +1,16 @@
import com.gorios.lanvoice.avatar.*
/** Expected five bodies/eight TALK bridges/two dances, synthetic metadata only. */
@Suppress("UNCHECKED_CAST")
fun fullActionGraphCheck() {
for((width,height) in listOf(480 to 848,720 to 1280)) {
val pin="b".repeat(64)
val bodies=listOf("neutral","happy","sad","idle-breathe","idle-shift").associateWith { id->
val sha=java.security.MessageDigest.getInstance("SHA-256").digest(id.toByteArray()).joinToString("") { "%02x".format(it) }
dynamicPack(if(id=="sad") 49 else 97,24,sha)
dynamicPack(if(id=="sad") 49 else 97,24,sha,width,height)
}
fun clip(pack: ContinuousAvatarPack,path: String,audio: Boolean=false)=mapOf<String,Any?>(
"path" to path,"sha256" to pack.body.sha256,"width" to 480,"height" to 848,"hasAudio" to audio,
"path" to path,"sha256" to pack.body.sha256,"width" to pack.body.width,"height" to pack.body.height,"hasAudio" to audio,
"frameCount" to pack.body.frameCount,"ptsUs" to pack.body.ptsUs,"durationUs" to pack.body.durationUs,
"fpsNumerator" to pack.body.fpsNumerator,"fpsDenominator" to pack.body.fpsDenominator)
val rows=bodies.map { (id,body)->mapOf<String,Any?>("id" to id,
@@ -21,13 +23,13 @@ fun fullActionGraphCheck() {
"fromAnchor" to "A","toAnchor" to "A","nativeLoop" to true,"clip" to clip(body,"$id/body.mp4")) }
val bridges=bodies.keys.filter { it!="neutral" }.flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)->
val name="$from-$to";val sha=java.security.MessageDigest.getInstance("SHA-256").digest(name.toByteArray()).joinToString("") { "%02x".format(it) }
val own=dynamicPack(25,24,sha);mouths[name]=own
val own=dynamicPack(25,24,sha,width,height);mouths[name]=own
mapOf<String,Any?>("id" to name,"from" to from,"to" to to,"fromFrame" to bodies.getValue(from).body.frameCount-1,
"fromPtsUs" to bodies.getValue(from).body.ptsUs.last(),"toFrame" to 0,"toPtsUs" to 0L,"fromAnchor" to "A","toAnchor" to "A",
"mouthAllowed" to true,"mouthRuntimeManifest" to mapOf("path" to "$name/manifest.json","sha256" to own.manifestSha),
"clip" to clip(own,"$name/body.mp4"))
} }
val dance=dynamicPack(241,24,"f".repeat(64))
val dance=dynamicPack(241,24,"f".repeat(64),width,height)
val actions=listOf("asset_01","asset_02").map { id->mapOf<String,Any?>("id" to id,"kind" to "dance",
"mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A",
"sourcePackageId" to "neutral","sourceFrame" to 0,"sourcePtsUs" to 0L,
@@ -52,7 +54,24 @@ fun fullActionGraphCheck() {
val wrong=mouths.getValue(name).copy(body=mouths.getValue(name).body.copy(sha256=bodies.getValue("neutral").body.sha256))
check(read(bridgeData=mouths+(name to wrong))==null);assertions++
}
check(index.packages.values.all { it.body.width==width && it.body.height==height } &&
index.edges.all { it.clip.width==width && it.clip.height==height } &&
index.actionPack!!.assets.all { it.media!!.width==width && it.media.height==height });assertions++
val otherWidth=if(width==480) 720 else 480;val otherHeight=if(height==848) 1280 else 848
val wrongShape=bodies.getValue("happy").let { it.copy(body=it.body.copy(width=otherWidth,height=otherHeight)) }
check(read(bodyData=bodies+("happy" to wrongShape))==null);assertions++
for(i in (loops+bridges).indices) {
val changed=(loops+bridges).mapIndexed { j,e -> if(j==i) e+("clip" to (e["clip"] as Map<String,Any?>)+
mapOf("width" to otherWidth,"height" to otherHeight)) else e }
check(read(root+("edges" to changed))==null);assertions++
}
for(i in actions.indices) {
val changed=actions.mapIndexed { j,a -> if(j==i) a+("clip" to (a["clip"] as Map<String,Any?>)+
mapOf("width" to otherWidth,"height" to otherHeight)) else a }
check(read(root+("actions" to changed))==null);assertions++
}
val inflated=bodies.mapValues { (_,body)->body.copy(patches=body.patches.map { it.copy(width=80,height=44) }) }
check(inflated.values.all { it.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES } && read(bodyData=inflated)==null);assertions++
println("PASS: $assertions full5-body/13-edge/8-own-bridge/two241-frame-action parser assertions; RGBA=$bytes bytes, source0/return96/4s binding and total-cache rejection; fixtures only")
println("PASS: $assertions ${width}x$height full5-body/13-edge/8-own-bridge/two241-frame-action parser assertions; RGBA=$bytes bytes, source0/return96/4s binding and total-cache rejection; fixtures only")
}
}
+3 -1
View File
@@ -3,9 +3,10 @@ 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 bodySize=0f to 0f
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() }
fun reset() { swaps=0;draws=0;deleted=0;terminated=0;swapFails=false;shaderFails=false;alpha=0f;patchTexture=0;activeUnit=0;rendered.clear();bodySize=0f to 0f }
}
class EGLDisplay
class EGLContext
@@ -60,6 +61,7 @@ object GLES20 {
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 glUniform2f(location: Int,x: Float,y: Float) { GLFixture.bodySize=x to y }
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 }
+16 -16
View File
@@ -7,20 +7,20 @@ import android.graphics.BitmapFactory
import android.opengl.GLFixture
import android.view.TextureView
fun mediaFixtureIndex(): EmotionActionIndex {
val packs=linkedMapOf("neutral" to dynamicPack(97,24,"c".repeat(64)).copy(root="neutral/"),
"happy" to dynamicPack(49,24,"d".repeat(64)).copy(root="happy/"),
"sad" to dynamicPack(121,30,"e".repeat(64)).copy(root="sad/"))
fun mediaFixtureIndex(width: Int=480,height: Int=848): EmotionActionIndex {
val packs=linkedMapOf("neutral" to dynamicPack(97,24,"c".repeat(64),width,height).copy(root="neutral/"),
"happy" to dynamicPack(49,24,"d".repeat(64),width,height).copy(root="happy/"),
"sad" to dynamicPack(121,30,"e".repeat(64),width,height).copy(root="sad/"))
val visuals=packs.map { (id,p)->TalkPackage(id,RoleEmotion.entries.single { it.wire==id },p.body.sha256,p.body.sha256,p.body.ptsUs,p.body.ptsUs,true) }
val bridges=packs.map { (id,p)->ConversationEdge("$id-loop",id,id,p.body.frameCount-1,0,p.body,true) }+
listOf("happy","sad").flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)->
ConversationEdge("$from-$to",from,to,packs.getValue(from).body.frameCount-1,0,
ContinuousBodyAsset("clips/$from-$to.mp4","f".repeat(64),480,848,3,125000,List(3) { it*1_000_000L/24 }),
mouthRuntime=dynamicPack(3,24,"f".repeat(64)).copy(root="bridge-$from-$to/"))
ContinuousBodyAsset("clips/$from-$to.mp4","f".repeat(64),width,height,3,125000,List(3) { it*1_000_000L/24 }),
mouthRuntime=dynamicPack(3,24,"f".repeat(64),width,height).copy(root="bridge-$from-$to/"))
} }
val musicPts=List(24) { it*1_000_000L/24 }
val actions=ReviewedActionPack("a".repeat(64),listOf("asset_01","asset_02").map {
ActionAsset(it,1000,ActionMedia("clips/$it.mp4","a".repeat(64),"",musicPts,1_000_000,480,848,"neutral",96,"neutral",0,950_000))
ActionAsset(it,1000,ActionMedia("clips/$it.mp4","a".repeat(64),"",musicPts,1_000_000,width,height,"neutral",96,"neutral",0,950_000))
})
return EmotionActionIndex("neutral",packs,visuals,actions,bridges)
}
@@ -28,13 +28,13 @@ fun mediaFixtureIndex(): EmotionActionIndex {
fun mediaReply(emotion: RoleEmotion,turn: Long=7,seq: Long=2,intensity: Int=if(emotion==RoleEmotion.NEUTRAL) 0 else 1)=
ReplyEmotion(emotion,intensity,EmotionSource.MODEL,turn,seq)
fun actualMediaViewCheck() {
fun actualMediaViewCheck(width: Int=480,height: Int=848) {
var cases=0
fun reset() {
TestScheduler.reset();CodecFixture.reset();GLFixture.reset();BitmapFactory.wrongSize=false;MediaPlayer.created.clear()
CodecFixture.emitNativeSurface=true
CodecFixture.emitNativeSurface=true;CodecFixture.width=width;CodecFixture.height=height
}
fun rig(index: EmotionActionIndex=mediaFixtureIndex()): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<VideoPresentation>> {
fun rig(index: EmotionActionIndex=mediaFixtureIndex(width,height)): Triple<EmotionActionAvatarView,AvatarMediaBinding,MutableList<VideoPresentation>> {
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.filterNot { it.nativeLoop }.forEach { CodecFixture.timelines[(it.mouthRuntime?.root ?: index.root)+(it.mouthRuntime?.body?.path ?: it.clip.path)]=it.clip.ptsUs }
index.actionPack?.assets?.mapNotNull { it.media }?.forEach { CodecFixture.timelines[it.root+it.path]=it.ptsUs;CodecFixture.audioPaths.add(it.root+it.path) }
@@ -93,7 +93,7 @@ fun actualMediaViewCheck() {
reset();val (cancelView,cancelBinding,_)=rig()
var stop: ((Boolean)->Unit)?=null;var resumed=0
val statuses=mutableListOf<ActionStatus>()
val controller=ActionController(mediaFixtureIndex().actionPack,cancelBinding,{TestScheduler.now},{stop=it},statuses::add,
val controller=ActionController(mediaFixtureIndex(width,height).actionPack,cancelBinding,{TestScheduler.now},{stop=it},statuses::add,
{ active->if(!active) resumed++ })
check(controller.offer(ActionPlan("p".repeat(24),7,"a".repeat(64),15000)))
controller.cancel();TestScheduler.advanceBy(100)
@@ -105,7 +105,7 @@ fun actualMediaViewCheck() {
}
for(mode in listOf("complete","cancel","failed","background","late_final_frame")) {
reset();val index=mediaFixtureIndex();val (actionView,actionBinding,trace)=rig(index)
reset();val index=mediaFixtureIndex(width,height);val (actionView,actionBinding,trace)=rig(index)
var stopped: ((Boolean)->Unit)?=null
val statuses=mutableListOf<ActionStatus>()
val controller=ActionController(index.actionPack,actionBinding,{TestScheduler.now},{stopped=it},statuses::add)
@@ -143,7 +143,7 @@ fun actualMediaViewCheck() {
// the movie TextureView. Native/codec/record ports remain deterministic doubles.
for(mode in listOf("complete", "cancel", "failed", "background", "newturn")) {
reset()
val base=mediaFixtureIndex()
val base=mediaFixtureIndex(width,height)
val original=base.actionPack!!.assets.first()
val media=original.media!!.copy(ptsUs=List(241) { it*1_000_000L/24 },durationUs=10_041_667,
sourceFrame=0,returnFrame=96,audioEndUs=10_000_000)
@@ -188,7 +188,7 @@ fun actualMediaViewCheck() {
// New idle rows use the actual view/renderer/codec path and reviewed graph.
reset()
val idleIndex=mediaFixtureIndex().let { it.copy(actionPack=null,visuals=it.visuals.map { p->p.copy(emotion=RoleEmotion.NEUTRAL) }) }
val idleIndex=mediaFixtureIndex(width,height).let { it.copy(actionPack=null,visuals=it.visuals.map { p->p.copy(emotion=RoleEmotion.NEUTRAL) }) }
val (idleView,idleBinding,idleTrace)=rig(idleIndex)
TestScheduler.advanceBy(3000)
check(idleTrace.all { it.actual=="body_neutral" });cases++
@@ -211,7 +211,7 @@ fun actualMediaViewCheck() {
// Real renderer path over a25-frame own-mouth bridge, no loop or endpoint patches.
reset()
val ownBridge=dynamicPack(25,24,"f".repeat(64)).copy(root="bridge25/")
val ownBridge=dynamicPack(25,24,"f".repeat(64),width,height).copy(root="bridge25/")
CodecFixture.timelines[ownBridge.root+ownBridge.body.path]=ownBridge.body.ptsUs
val clock=ConversationMouthClock();val prior=Any()
clock.intent(prior,ownBridge.curves,true,1,1,0);clock.sample(prior,0)
@@ -229,5 +229,5 @@ fun actualMediaViewCheck() {
renderer.close();TestScheduler.advanceBy(50)
check(GLFixture.deleted>=126 && CodecFixture.releases==1);cases++
CodecFixture.reset();MediaPlayer.created.clear()
println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback assertions: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run")
println("PASS: $cases ${width}x$height actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback assertions: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run")
}
+11 -2
View File
@@ -31,9 +31,10 @@ fun startupCacheCheck() {
fun startupViewCheck() {
var cases=0
fun rig(): Triple<StartupAvatarView,ContinuousAvatarPack,AvatarPack> {
fun rig(width: Int=480,height: Int=848): Triple<StartupAvatarView,ContinuousAvatarPack,AvatarPack> {
TestScheduler.reset();CodecFixture.reset();CodecFixture.emitNativeSurface=true
val index=mediaFixtureIndex();val neutral=index.packages.getValue(index.fallbackId)
CodecFixture.width=width;CodecFixture.height=height
val index=mediaFixtureIndex(width,height);val neutral=index.packages.getValue(index.fallbackId)
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.mapNotNull {it.mouthRuntime}.forEach {CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs}
return Triple(StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{}),neutral.copy(patches=emptyList(),curves=emptyMap()),AvatarPack(fallback="fixture.png",emotionAction=index))
@@ -64,5 +65,13 @@ fun startupViewCheck() {
retrying.update(b4,p4,true,"failed");CodecFixture.configureFails=false
retrying.update(b4,p4,true,"preparing");TestScheduler.until(6000) { recovered==1 };cases++
retrying.dispose();TestScheduler.advanceBy(100)
val (large,largeBase,largeFull)=rig(720,1280)
large.update(largeBase,null,true);TestScheduler.advanceBy(250)
large.update(largeBase,largeFull,true);TestScheduler.advanceBy(100)
check((large.children.last() as EmotionActionAvatarView).alpha==0f);cases++
TestScheduler.until(6000) { (large.children.last() as EmotionActionAvatarView).alpha==1f }
TestScheduler.until(100) { CodecFixture.releases>=1 }
check(android.opengl.GLFixture.bodySize==720f to 1280f);cases++
large.dispose();TestScheduler.advanceBy(100)
println("PASS: $cases production startup host renderer callback cases: held exact target0/source0, decoderrelease before capability, persistent host, lifecycle and bodySHA mismatch")
}
+126
View File
@@ -0,0 +1,126 @@
"""Real procedural H264/PNG gates: no portrait, provider, network or activation."""
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
spec=importlib.util.spec_from_file_location('shape_packager',ROOT/'scripts/package-avatar-emotion.py')
packager=importlib.util.module_from_spec(spec);spec.loader.exec_module(packager)
gate=packager.runtime_gate
class AvatarShapeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
from PIL import Image
cls.tmp=tempfile.TemporaryDirectory(prefix='avatar-shape-fixtures-')
cls.root=Path(cls.tmp.name)
cls.runtimes={}
for w,h in [(480,848),(720,1280)]:
folder=cls.root/f'{w}x{h}'/'runtime';(folder/'body').mkdir(parents=True);(folder/'patches').mkdir()
movie=folder/'body/idle.mp4'
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i',
f'testsrc2=size={w}x{h}:rate=24','-frames:v','12','-an','-c:v','libx264','-pix_fmt','yuv420p',
'-threads','1',str(movie)],check=True,capture_output=True,timeout=30)
measured=packager.probe_clip(movie);digest=packager.file_sha(movie)
body=dict(path='body/idle.mp4',sha256=digest,width=w,height=h,hasAudio=False,frameCount=12,
ptsUs=measured['ptsUs'],durationUs=measured['durationUs'],fpsNumerator=24,fpsDenominator=1)
patches=[]
for i,t in enumerate(body['ptsUs']):
levels=[]
for l in range(5):
name=f'patches/f{i}-l{l}.png'
Image.new('RGBA',(40,22),(200,80,50,l*60)).save(folder/name)
levels.append(dict(levelIndex=l,aperture=l/4,path=name,sha256=packager.file_sha(folder/name)))
patches.append(dict(frameIndex=i,ptsUs=t,path=levels[4]['path'],sha256=levels[4]['sha256'],
x=w-40,y=h-22,width=40,height=22,levels=levels))
states=[]
curves={'idle':[0]*12,'opening':[0,.2,.4,.6,.8,1],
'talk1':[1,.75,.5,.25,0,.25,.5,.75,1,.75,.5,1],
'talk2':[1,.5,.25,0,.25,.5,.75,1,.75,.5,.75,1],
'end-talk':[1,.8,.6,.4,.2,0]}
for name,alpha in curves.items():
n=len(alpha)
states.append(dict(id=name,frameCount=n,ptsUs=[i*1000000//24 for i in range(n)],
durationMs=n*1000//24,fpsNumerator=24,fpsDenominator=1,globalAlphaByFrame=alpha,
entryMouthAnchor='A' if name in ('idle','opening') else 'B',
exitMouthAnchor='A' if name in ('idle','end-talk') else 'B'))
runtime=dict(schemaVersion=2,packId='a01-expression-action-v1-test-runtime-04',identityId='a01',
publishApproval=False,runtimeReady=True,body=body,patches=patches,mouthStates=states,
patchFormat=dict(bodySha256=digest,format='PNG RGBA 8bit',alphaEncoding='straight_unassociated',
apertureLevels=[0,.25,.5,.75,1],requiresRendererExtension=True),
stateRouting=dict(idle=['idle','opening'],opening=['talk1','talk2','end-talk'],
talk1=['talk1','talk2','end-talk'],talk2=['talk1','talk2','end-talk'],**{'end-talk':['idle']}))
cls.write(folder/'manifest.json',runtime);cls.runtimes[(w,h)]=(folder,runtime)
cls.music=cls.root/'music.mp4'
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i',
'testsrc2=size=720x1280:rate=24','-f','lavfi','-i','sine=frequency=440:sample_rate=48000',
'-t','1','-c:v','libx264','-pix_fmt','yuv420p','-c:a','aac','-threads','1',str(cls.music)],
check=True,capture_output=True,timeout=30)
@classmethod
def tearDownClass(cls): cls.tmp.cleanup()
@staticmethod
def write(path,data): path.write_text(json.dumps(data)+'\n')
def test_actual_body_shapes_and_own_pixel_bounds(self):
for shape,(folder,_) in self.runtimes.items():
path=folder/'manifest.json'
result,_=gate.check_runtime(path,packager.file_sha(path),kotlin=False)
self.assertEqual(result['body_shape'],list(shape));self.assertEqual(result['patch_images'],60)
self.assertEqual(result['rgba_cache_bytes'],12*40*22*4*5)
def test_declared_shape_must_match_actual_codec(self):
folder,runtime=self.runtimes[(720,1280)]
invalid=copy.deepcopy(runtime);invalid['body'].update(width=480,height=848)
path=folder/'wrong-shape.json';self.write(path,invalid)
with self.assertRaisesRegex(ValueError,'codec/shape mismatch'):
gate.check_runtime(path,packager.file_sha(path),kotlin=False)
def test_legacy_schema_does_not_inherit_larger_shape(self):
folder,runtime=self.runtimes[(720,1280)]
invalid=copy.deepcopy(runtime);invalid.update(schemaVersion=1,packId='a01-neutral-graph-v1-runtime-04')
path=folder/'wrong-schema.json';self.write(path,invalid)
with self.assertRaisesRegex(ValueError,'codec/shape mismatch'):
gate.check_runtime(path,packager.file_sha(path),kotlin=False)
def test_large_patch_bounds_remain_strict(self):
folder,runtime=self.runtimes[(720,1280)]
invalid=copy.deepcopy(runtime);invalid['patches'][0]['x']=681
path=folder/'wrong-patch.json';self.write(path,invalid)
with self.assertRaisesRegex(ValueError,'patch pixel bounds'):
gate.check_runtime(path,packager.file_sha(path),kotlin=False)
def test_actual_720_music_decode_shape(self):
result=packager.probe_music_clip(self.music)
self.assertEqual(result['shape'],(720,1280));self.assertEqual(len(result['ptsUs']),24)
self.assertEqual(result['humanListening'],'not_run')
def test_full_720_bundle_uses_production_kotlin_parser(self):
folder,runtime=self.runtimes[(720,1280)];root=folder.parent;body=runtime['body']
def index(clip):
return dict(schemaVersion=2,identityId='a01',packId='a01-expression-action-v1',fallbackPackageId='neutral',
conversationPackages=[dict(id='neutral',emotion='neutral',visualIntensity=0,mouthBodySha256=body['sha256'],
runtimeManifest=dict(path='runtime/manifest.json',sha256=packager.file_sha(folder/'manifest.json')),
entryAnchor='A',exitAnchor='A',legalExitFrames=[11],loopEdge='neutral-loop')],
edges=[dict(id='neutral-loop',**{'from':'neutral','to':'neutral'},fromFrame=11,toFrame=0,
fromPtsUs=body['ptsUs'][-1],toPtsUs=0,fromAnchor='A',toAnchor='A',nativeLoop=True,clip=clip)],
actions=[],files=[dict(path=str(p.relative_to(root)),sha256=packager.file_sha(p),bytes=p.stat().st_size)
for p in folder.rglob('*') if p.is_file() and p.name not in ('wrong-patch.json','wrong-schema.json','wrong-shape.json')])
clip=body|dict(path='runtime/body/idle.mp4')
path=root/'manifest.json';self.write(path,index(clip));output=self.root/'gate';output.mkdir()
result=packager.check_bundle(path,packager.file_sha(path),output)
self.assertEqual(result['production_kotlin_index'],'passed');self.assertEqual(result['referenced_files'],63)
self.assertFalse(result['dance_available'])
self.write(path,index(clip|dict(width=480,height=848)));output=self.root/'bad-gate';output.mkdir()
with self.assertRaisesRegex(ValueError,'decoded clip shape mismatch'):
packager.check_bundle(path,packager.file_sha(path),output)
if __name__=='__main__': unittest.main()