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 52e2f90..0edbb87 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt @@ -15,6 +15,12 @@ data class ContinuousAvatarPack(val body: ContinuousBodyAsset,val patches: List< val rgbaBytes: Long get() = patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) } } +/** Deliberately bounded schema2 shapes; schema1 keeps its original pixel contract. */ +object AvatarShape { + fun supported(width: Int,height: Int): Boolean = + (width==480 && height==848) || (width==720 && height==1280) +} + /** Metadata validation only; importer must additionally verify decoded frame PTS. */ object BodyTimeline { const val MAX_TALK_FRAMES = 720 @@ -63,7 +69,8 @@ object ContinuousAvatarManifest { val body=ContinuousBodyAsset(b["path"] as String,hash(b["sha256"]),smallInt(b["width"]),smallInt(b["height"]), 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 && b["hasAudio"]==false) + field="body.width/height" + require((if(dynamic) AvatarShape.supported(body.width,body.height) else 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) @@ -85,7 +92,7 @@ object ContinuousAvatarManifest { 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) + patch.x+patch.width<=body.width && patch.y+patch.height<=body.height) if(apertureMode) { field="patches[$index].levels" val levels=(p["levels"] as List>).also { require(it.size==5) }.mapIndexed { level,row -> 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 64782a2..4a2c11b 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt @@ -61,7 +61,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont put(floatArrayOf(0f,0f,1f,0f,0f,1f,1f,1f));position(0) } private var aPosition=0; private var aUv=0; private var uTextureMatrix=0 - private var uBody=0; private var uPatch=0; private var uRect=0; private var uOpacity=0 + private var uBodySize=0; private var uBody=0; private var uPatch=0; private var uRect=0; private var uOpacity=0 private var startedMs=SystemClock.elapsedRealtime() private var progressMs=startedMs private val timeout=Runnable { fail("frame_timeout") } @@ -93,6 +93,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont continueBody() } } } } private fun initialize() { + check(AvatarShape.supported(pack.body.width,pack.body.height)) check(pack.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES && (!mouthEnabled || pack.patches.size==pack.body.frameCount)) check(startFrame in pack.body.ptsUs.indices) display=EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);check(display!=EGL14.EGL_NO_DISPLAY) @@ -109,8 +110,9 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont aPosition=GLES20.glGetAttribLocation(program,"aPosition");aUv=GLES20.glGetAttribLocation(program,"aUv") uTextureMatrix=GLES20.glGetUniformLocation(program,"uTextureMatrix") uBody=GLES20.glGetUniformLocation(program,"uBody");uPatch=GLES20.glGetUniformLocation(program,"uPatch") + uBodySize=GLES20.glGetUniformLocation(program,"uBodySize") uRect=GLES20.glGetUniformLocation(program,"uRect");uOpacity=GLES20.glGetUniformLocation(program,"uOpacity") - check(listOf(aPosition,aUv,uTextureMatrix,uBody,uPatch,uRect,uOpacity).all { it>=0 }) + check(listOf(aPosition,aUv,uTextureMatrix,uBodySize,uBody,uPatch,uRect,uOpacity).all { it>=0 }) val texture=IntArray(1);GLES20.glGenTextures(1,texture,0);bodyTexture=texture[0] GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture) configureTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES) @@ -148,7 +150,7 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont video } else { check(ex.trackCount==1);0 } val format=ex.getTrackFormat(track);check(format.getString(MediaFormat.KEY_MIME)=="video/avc") - check(format.getInteger(MediaFormat.KEY_WIDTH)==480 && format.getInteger(MediaFormat.KEY_HEIGHT)==848) + check(format.getInteger(MediaFormat.KEY_WIDTH)==pack.body.width && format.getInteger(MediaFormat.KEY_HEIGHT)==pack.body.height) ex.selectTrack(track);check(ex.sampleTime==0L) codec=MediaCodec.createDecoderByType("video/avc").also { it.configure(format,checkNotNull(inputSurface),null,0);it.start() } progressMs=SystemClock.elapsedRealtime() @@ -229,13 +231,14 @@ class ContinuousBodyRenderer(private val context: Context,private val pack: Cont private fun draw(frame: ComposedBodyFrame) { check(width>0 && height>0) GLES20.glViewport(0,0,width,height);GLES20.glClearColor(1f,1f,1f,1f);GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) - val rect=bodyFit(width,height) + val rect=bodyFit(width,height,pack.body.width,pack.body.height) val left=rect.left/width*2-1;val right=(rect.left+rect.width)/width*2-1 val top=1-rect.top/height*2;val bottom=1-(rect.top+rect.height)/height*2 positions.clear();positions.put(floatArrayOf(left,bottom,right,bottom,left,top,right,top));positions.position(0);uv.position(0) GLES20.glUseProgram(program) GLES20.glVertexAttribPointer(aPosition,2,GLES20.GL_FLOAT,false,0,positions);GLES20.glEnableVertexAttribArray(aPosition) GLES20.glVertexAttribPointer(aUv,2,GLES20.GL_FLOAT,false,0,uv);GLES20.glEnableVertexAttribArray(aUv) + GLES20.glUniform2f(uBodySize,pack.body.width.toFloat(),pack.body.height.toFloat()) GLES20.glUniformMatrix4fv(uTextureMatrix,1,false,textureMatrix,0) GLES20.glActiveTexture(GLES20.GL_TEXTURE0);GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,bodyTexture);GLES20.glUniform1i(uBody,0) GLES20.glActiveTexture(GLES20.GL_TEXTURE1);GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, @@ -297,11 +300,11 @@ internal object AvatarLayerShader { #extension GL_OES_EGL_image_external : require precision highp float; uniform samplerExternalOES uBody; uniform sampler2D uPatch; - uniform vec4 uRect; uniform float uOpacity; + uniform vec2 uBodySize; uniform vec4 uRect; uniform float uOpacity; varying vec2 vBody; varying vec2 vLogical; void main() { vec4 body=texture2D(uBody,vBody); - vec2 pixel=vec2(vLogical.x*480.0,(1.0-vLogical.y)*848.0); + vec2 pixel=vec2(vLogical.x,1.0-vLogical.y)*uBodySize; vec2 local=(pixel-uRect.xy)/uRect.zw; if(uOpacity<=0.0 || local.x<0.0 || local.y<0.0 || local.x>=1.0 || local.y>=1.0) { gl_FragColor=vec4(body.rgb,1.0); 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 fdb5bec..9ebfbf3 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt @@ -56,6 +56,10 @@ object EmotionActionManifest { field="conversationPackages.cacheBytes/fallbackPackageId" require(packages.values.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES) require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL) + field="conversationPackages.width/height" + val shape=packages.getValue(fallback).body + require(AvatarShape.supported(shape.width,shape.height) && + packages.values.all { it.body.width==shape.width && it.body.height==shape.height }) field="edges" val edges=root["edges"] as List> require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size) @@ -71,7 +75,7 @@ object EmotionActionManifest { require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A") field="$edgeField.clip" val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"]) - require(clip["hasAudio"]==false && integer(clip["width"])==480L && integer(clip["height"])==848L) + require(clip["hasAudio"]==false && integer(clip["width"])==shape.width.toLong() && integer(clip["height"])==shape.height.toLong()) val count=boundedInt(clip["frameCount"],BodyTimeline.MAX_TALK_FRAMES) val pts=(clip["ptsUs"] as List<*>).also { require(it.size==count) }.map(::integer) require(BodyTimeline.valid(pts,count,integer(clip["durationUs"]), @@ -109,7 +113,7 @@ object EmotionActionManifest { require(mouthRuntime==null || edge["mouthAllowed"]!=false) 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, + ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),shape.width,shape.height,pts.size, integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop,mouthRuntime) } field="combinedRuntimeCacheBytes" @@ -144,7 +148,7 @@ object EmotionActionManifest { require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration) val count=boundedInt(clip["frameCount"],5400) val pts=(clip["ptsUs"] as List<*>).also { require(it.size==count) }.map(::integer) - require(integer(clip["width"])==480L && integer(clip["height"])==848L) + require(integer(clip["width"])==shape.width.toLong() && integer(clip["height"])==shape.height.toLong()) 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) @@ -159,7 +163,7 @@ object EmotionActionManifest { require(integer(action["sourcePtsUs"])==runtime.body.ptsUs[sourceFrame.toInt()] && integer(action["returnPtsUs"])==runtime.body.ptsUs[returnFrame.toInt()]) ActionAsset(action["id"] as String,(duration+999)/1000,ActionMedia(path(clip["path"]),hash(clip["sha256"]),pathRoot, - pts,duration,480,848,fallback,sourceFrame.toInt(),fallback,returnFrame.toInt(),integer(action["audioEndUs"]), + pts,duration,shape.width,shape.height,fallback,sourceFrame.toInt(),fallback,returnFrame.toInt(),integer(action["audioEndUs"]), boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000))) } ReviewedActionPack(actualSha,assets) diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt index 0898568..e8b34c5 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt @@ -30,7 +30,7 @@ object StartupAvatarRepository { val app=context.applicationContext val info=app.packageManager.getPackageInfo(app.packageName,0) val key=StartupAssetKey(info.versionCode.toLong(),info.lastUpdateTime,BuildConfig.EMOTION_MANIFEST_SHA, - "avatar/a01-expression-action-v1/",1) + "avatar/a01-expression-action-v1/",2) var cancelled=false var basicFailed=false // Both requests use one serial IO worker: the tiny baseline is prioritized. @@ -45,9 +45,9 @@ object StartupAvatarRepository { val bytes=readBounded(app.assets.open(path),64_000_000);check(bytes.size<=64_000_000 && sha(bytes)==b.getString("sha256")) val poster=readBounded(app.assets.open(ROOT+"poster.png"),100_000);check(poster.size<=100_000 && sha(poster)==json.getString("posterSha256")) val pts=b.getJSONArray("ptsUs");val timeline=List(pts.length()) { pts.getLong(it) } - check(b.getInt("width")==480 && b.getInt("height")==848 && + check(AvatarShape.supported(b.getInt("width"),b.getInt("height")) && BodyTimeline.valid(timeline,b.getInt("frameCount"),b.getLong("durationUs"),b.getInt("fpsNumerator"),b.getInt("fpsDenominator"))) - val body=ContinuousBodyAsset(path,b.getString("sha256"),480,848,timeline.size,b.getLong("durationUs"), + val body=ContinuousBodyAsset(path,b.getString("sha256"),b.getInt("width"),b.getInt("height"),timeline.size,b.getLong("durationUs"), timeline,b.getInt("fpsNumerator"),b.getInt("fpsDenominator")) StartupTrace.mark(StartupTrace.Phase.BASIC_VERIFY,start) ContinuousAvatarPack(body,emptyList(),emptyMap(),"",BASIC_SHA) diff --git a/docs/AVATAR_PACK_V2_CONTRACT.md b/docs/AVATAR_PACK_V2_CONTRACT.md index 30ca00d..1825380 100644 --- a/docs/AVATAR_PACK_V2_CONTRACT.md +++ b/docs/AVATAR_PACK_V2_CONTRACT.md @@ -67,7 +67,20 @@ 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). +Schema2 supports exactly **480×848 or720×1280**. Declare actual `body.width/height` +and every edge/action `clip.width/height`; the full index must use one common shape, +including native loops, own-mouth bridges and music actions. Mixed/undeclared shapes +are rejected. Legacy schema1 stays480×848. No schemaVersion3 is needed. +Coordinates `patches.x/y/width/height` are pixels of that exact decoded body, +not normalized UVs or480-reference coordinates. GLES receives the admitted body size +for Fit, logical pixel→patch UV and decoder/SurfaceTexture dimensions. Patch bitmaps +are uploaded at their authored size without automatic scaling. Track each new body +independently:720/480=1.5 but1280/848≈1.509434, so a blanket1.5× transform of old +coordinates is neither sufficient nor an own-body binding. Existing128px/8MB/32MB +limits remain in force; larger portraits do not authorize larger mouth caches. +New shape support is code admission only, not a new pin or device/naturalness review. +The currently frozen white480×848 pack stays unchanged; new720 assets need their +own machine gate and independent exact index pin before any capability activation. 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. @@ -139,7 +152,7 @@ Bridge TALK extension (2026-10-13, stable optional field): `edge.mouthRuntimeManifest:{path,sha256}` references a bridge-own schema2 runtime04. Use packId `a01-expression-action-v1--runtime-04`; relative runtime paths resolve under its own manifest directory. Its body SHA/N/actual ptsUs/duration/fps/ -480×848 shape must equal edge.clip exactly; the body path can resolve to a copy of +width/height (the common index shape) must equal edge.clip exactly; the body path can resolve to a copy of that unchanged bridge video. Every one of its N frames has five own source patches (1.1 sourcepx candidate) and own coords/curves, never either endpoint's patches. For the current four bridges N=25:125 own PNGs each, measured independently. diff --git a/docs/GLES_720_SUPPORT.md b/docs/GLES_720_SUPPORT.md new file mode 100644 index 0000000..51df991 --- /dev/null +++ b/docs/GLES_720_SUPPORT.md @@ -0,0 +1,35 @@ +# GLES 720×1280 支持 + +本次从 clean `62dce32bb7c0f50f7873c906017cd0b80fe63586` 实施尺寸扩展。支持代码不等于新素材发布或真机性能认证。本轮不生成/导入新角色素材,不修改时间、LLM/provider/TTS、摄像头检测或 gateway 部署。 + +## 生产实现 + +- `ContinuousBodyRenderer` 从已准入 `body.width/height` 设置 SurfaceTexture、核对 MediaExtractor 实际 H264 尺寸、计算 Fit 和传递 `uBodySize`。嘴层 shader 将 logical UV 转换为自身 body 像素坐标,保留 OES textureMatrix 只作用于 body 的规则。PNG 按自身 width/height 上传,无隐式放大。 +- schema2 明确只接受480×848、720×1280。完整 index 的 conversation bodies、native loops、桥 clip/own-mouth runtime、音乐动作使用同一尺寸;混合尺寸拒绝。旧 schema1 仍固定480×848。schema2 字段足够,不升级schema。 +- `check-avatar-runtime.py` 和 `package-avatar-emotion.py` 核实际解码尺寸与声明值;复用已测视频时也必须核 shape,不能只复用 SHA/PTS 测量绕过维度绑定。实际 N/PTS、独立 body/patch SHA、音轨/cover、五档嘴层等原校验保留。 +- 启动 repository 的 body 构造使用校验后的尺寸;immutable APK 校验 receipt 的 validator 更新为2,旧 receipt 不复用。现 bootstrap 的路径/独立 SHA/poster/旧pin仍冻结;将来换720包需重新制作并审核匹配 bootstrap,当前不能只换pin就启新包。 +- 每patch≤128×128、每runtime≤8,000,000 RGBA bytes、全部≤32,000,000 bytes,不提高上限。高分辨率 decoder/native body texture 的额外开销不在这个 mouth RGBA 上限中,需真机测量。 + +## 素材 owner 合同 + +完整字段见 `docs/AVATAR_PACK_V2_CONTRACT.md`。新720 body 独立解码并声明实际 width=720、height=1280/N/PTS;逐帧重新 tracking/export 自身五档 patch,坐标以自身720×1280像素为准。不能沿用旧480 body 的 mask/hash/coord;横向倍率1.5,纵向1280/848≈1.509434,因此一律1.5×坐标并不正确。body/桥/动作全部一致shape;mouth state curve clock 与 body clock 独立。新 exact index 必须重新 machine gate、Pi pin 和能力 registry 审核,旧白衣 pin 不批准新素材。 + +读取候选的入口保持不变: + +```sh +python3 scripts/check-avatar-runtime.py --manifest /manifest.json --sha256 --output +python3 scripts/package-avatar-emotion.py --manifest /manifest.json --sha256 --output +``` + +均为只读检查,不激活未知包。 + +## 验证 + +- 9 JVM/UI入口回归;双尺寸分别重放实际 `EmotionActionAvatarView`/renderer/music/record-confirm callback 路径,每种1288断言(Android API doubles)。包括 happy/sad、own桥、idle轮换、10s动作层独占/自然结束/取消/旧epoch/恢复A,非手抄状态机。 +- 双尺寸完整5body/13edge/8ownmouth/2action生产 parser,每种34断言;混合package/edge/action shape及总缓存越界拒绝。720 production renderer 另测越旧坐标范围、越界拒绝、codec尺寸不符、循环、uniform、释放后旧callback。启动720基本loop→full等待真实source/target0和基础decoder释放。 +- 40包装测试:新增6项使用本地临时 procedural H264/PNG及合成正弦AAC。实际720 index 经生产 Kotlin parser、全decode、PTS/PNG/own-body/hash gate;旧schema1扩尺寸、声明/实际尺寸不符、patch越界、edge复用测量尺寸不符拒绝。没有人物生成或付费API。 +- GLES2/Mesa llvmpipe:旧冻结五包重跑200像素goldens;720 procedural30项,覆盖三viewport/Fit、上下方向、body texture crop与独立patch坐标、alpha0精确body、fractional origin和四边界。使用生产shader字符串,OES sampler替换2D surrogate;不证明Android OES/YUV/Bitmap/手机GPU。 +- 旧 exact pin `987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887` 全包生产 gate仍通过:5body/13edge/8ownmouth/2action,3222引用文件,RGBA10,911,120 bytes。 +- Gradle assembleDebug及instrumentation Kotlin编译通过。编译核验包未发布/安装;其全部3819 asset文件与已发布code24逐字节一致,同arm64/min26/target34/debug证书。实际APK后台repository cold/receipt回放 main_asset_reads=0、cold3185patch检查、receipt0patch检查,同进程不重复load。 + +证据保存在 ignored `logs/avatar-shape-720/`、`logs/avatar-safe-061/`;源代码/合同/测试进入Git,媒体、报告和二进制不进入Git。没有发布新720 APK,没有修改已发布code24/旧回退包或live allowlist。真机720解码、GPU对齐、startup/内存/温度/自然效果、instrumentation运行均未测;gateway未变,本轮无需重启或额外推理调用。 diff --git a/scripts/check-avatar-runtime.py b/scripts/check-avatar-runtime.py index 6fddabe..3759709 100644 --- a/scripts/check-avatar-runtime.py +++ b/scripts/check-avatar-runtime.py @@ -13,6 +13,7 @@ import sys from PIL import Image ROOT=Path(__file__).resolve().parents[1] +SUPPORTED_SHAPES={(480,848),(720,1280)} def require(value,reason): if not value: raise ValueError(reason) @@ -49,7 +50,7 @@ def check_runtime(manifest_path, expected_sha, kotlin=True): 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(stream['codec_name']=='h264' and (stream['width'],stream['height'])==(body['width'],body['height']) and (body['width'],body['height']) in (SUPPORTED_SHAPES if dynamic else {(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] @@ -65,6 +66,8 @@ def check_runtime(manifest_path, expected_sha, kotlin=True): 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') + require(all(isinstance(patch[k],(int,float)) and not isinstance(patch[k],bool) for k in ('x','y')) and + 0<=patch['x']<=body['width']-width and 0<=patch['y']<=body['height']-height,'patch pixel bounds') levels=patch['levels'] if aperture else [patch] require(len(levels)==(5 if aperture else 1),'five own levels required') for level in levels: @@ -82,7 +85,7 @@ def check_runtime(manifest_path, expected_sha, kotlin=True): 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, + 'body_sha256':body['sha256'],'schema_version':manifest['schemaVersion'],'body_shape':[body['width'],body['height']],'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' if kotlin else 'checked_by_bundle_parser','naturalness':'pending','real_device':'not_run'} return evidence, verified diff --git a/scripts/check-avatar-shader.py b/scripts/check-avatar-shader.py index 90d1c0a..d021cf1 100644 --- a/scripts/check-avatar-shader.py +++ b/scripts/check-avatar-shader.py @@ -13,11 +13,12 @@ def bilinear(image,x,y): return (image[iy,ix]*(1-fx)+image[iy,jx]*fx)*(1-fy)+(image[jy,ix]*(1-fx)+image[jy,jx]*fx)*fy def golden(body,patch,x,y,opacity,w,h,crop): - scale=min(w/480,h/848);left=(w-480*scale)/2;top=(h-848*scale)/2 + bh,bw=body.shape[:2] + scale=min(w/bw,h/bh);left=(w-bw*scale)/2;top=(h-bh*scale)/2 yy,xx=np.mgrid[:h,:w];px=(xx+.5-left)/scale;py=(yy+.5-top)/scale - inside=(px>=0)&(px<480)&(py>=0)&(py<848) - bx=px*(.98 if crop else 1)+(4.8 if crop else 0)-.5 - by=py*(.98 if crop else 1)+(8.48 if crop else 0)-.5 + inside=(px>=0)&(px=0)&(py0.00001 and peak<=1.001,'dance silent/out-of-range audio') return {'ptsUs':[us(f['best_effort_timestamp_time']) for f in frames], 'durationUs':duration,'fps':Fraction(v['r_frame_rate']),'audioEndUs':audio_end, - 'decodedAudioEndUs':decoded_end,'pcmFrames':len(samples)//2,'audioRms':rms,'audioPeak':peak, + 'shape':(v['width'],v['height']),'decodedAudioEndUs':decoded_end,'pcmFrames':len(samples)//2,'audioRms':rms,'audioPeak':peak, 'nearFullScaleSamples':sum(abs(x)>=0.999 for x in samples),'humanListening':'not_run'} @@ -140,7 +140,7 @@ def check_bundle(manifest,expected,output): m=read_json(path);prefix=PurePosixPath(ref['path']).parent for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000) body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])], - 'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])} + 'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator']),'shape':(body['width'],body['height'])} runtimes.append({'package_id':runtime_id,**evidence}) rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound') require(len(index['edges'])<=100,'edge count bound') @@ -149,6 +149,7 @@ def check_bundle(manifest,expected,output): require(clip['hasAudio'] is False,'conversation edge cannot have audio') measured=measurements.get(name) if measured is None: measured=measurements[name]=probe_clip(path) + require(measured['shape']==(clip['width'],clip['height']),'decoded clip shape mismatch: '+name) require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name) require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name) require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name) @@ -157,6 +158,7 @@ def check_bundle(manifest,expected,output): clip=action['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],128_000_000) require(clip['hasAudio'] is True,'dance requires actual audio') measured=probe_music_clip(path) + require(measured['shape']==(clip['width'],clip['height']),'decoded clip shape mismatch: '+name) require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'], 'dance decoded N mismatch: '+name) require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'dance decoded PTS mismatch: '+name) require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'dance decoded timing mismatch: '+name) diff --git a/tests/avatar-pixels/gles-golden.c b/tests/avatar-pixels/gles-golden.c index bf54175..81efe1c 100644 --- a/tests/avatar-pixels/gles-golden.c +++ b/tests/avatar-pixels/gles-golden.c @@ -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); diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index 4c15417..9d31736 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -16,6 +16,7 @@ fun main() { emotionActionCheck() conversationPackageCheck() actualMediaViewCheck() + actualMediaViewCheck(720,1280) mediaBoundaryCheck() idleVariantCheck() fullActionGraphCheck() diff --git a/tests/avatar/CodecMedia.kt b/tests/avatar/CodecMedia.kt index f3c4bf6..a9fd597 100644 --- a/tests/avatar/CodecMedia.kt +++ b/tests/avatar/CodecMedia.kt @@ -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(); var releases=0; var flushes=0 @@ -13,7 +14,7 @@ object CodecFixture { val timelines=mutableMapOf>() val audioPaths=mutableSetOf() 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 diff --git a/tests/avatar/DynamicBodyCheck.kt b/tests/avatar/DynamicBodyCheck.kt index ecdf856..71bab07 100644 --- a/tests/avatar/DynamicBodyCheck.kt +++ b/tests/avatar/DynamicBodyCheck.kt @@ -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 { +fun dynamicRuntimeFixture(count: Int=121,fpsN: Int=30,fpsD: Int=1,sha: String="c".repeat(64),width: Int=480,height: Int=848): Map { val old=continuousFixture() val pts=List(count) { it*1_000_000L*fpsD/fpsN } val base=(old["patches"] as List>).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)+mapOf("sha256" to sha,"frameCount" to count, + "body" to (old["body"] as Map)+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>).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> + 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) { 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)+mapOf("width" to 720,"height" to 848))) + rejected(moved+("body" to (large["body"] as Map)+mapOf("width" to 1080,"height" to 1920))) + val legacy=continuousFixture() + rejected(legacy+("body" to (legacy["body"] as Map)+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> { + 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();val errors=mutableListOf() + 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) diff --git a/tests/avatar/FullActionGraphCheck.kt b/tests/avatar/FullActionGraphCheck.kt index 3e1060b..037a418 100644 --- a/tests/avatar/FullActionGraphCheck.kt +++ b/tests/avatar/FullActionGraphCheck.kt @@ -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( - "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("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("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("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)+ + 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)+ + 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") + } } diff --git a/tests/avatar/GL.kt b/tests/avatar/GL.kt index 0ec5d11..55378be 100644 --- a/tests/avatar/GL.kt +++ b/tests/avatar/GL.kt @@ -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>() - 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 } diff --git a/tests/avatar/MediaWiringCheck.kt b/tests/avatar/MediaWiringCheck.kt index 1d09620..b6ab6ed 100644 --- a/tests/avatar/MediaWiringCheck.kt +++ b/tests/avatar/MediaWiringCheck.kt @@ -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> { + fun rig(index: EmotionActionIndex=mediaFixtureIndex(width,height)): Triple> { 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() - 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() 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") } diff --git a/tests/avatar/StartupCheck.kt b/tests/avatar/StartupCheck.kt index e8817c4..14afe5d 100644 --- a/tests/avatar/StartupCheck.kt +++ b/tests/avatar/StartupCheck.kt @@ -31,9 +31,10 @@ fun startupCacheCheck() { fun startupViewCheck() { var cases=0 - fun rig(): Triple { + fun rig(width: Int=480,height: Int=848): Triple { 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") } diff --git a/tests/packaging/test_avatar_shape.py b/tests/packaging/test_avatar_shape.py new file mode 100644 index 0000000..dab785b --- /dev/null +++ b/tests/packaging/test_avatar_shape.py @@ -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()