Support bounded 720x1280 avatar shapes through GLES and production gates
This commit is contained in:
@@ -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<Map<String,Any?>>).also { require(it.size==5) }.mapIndexed { level,row ->
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Map<String,Any?>>
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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-<edgeId>-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.
|
||||
|
||||
@@ -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 <runtime>/manifest.json --sha256 <exact-sha> --output <new-evidence.json>
|
||||
python3 scripts/package-avatar-emotion.py --manifest <index>/manifest.json --sha256 <exact-index-sha> --output <new-evidence-directory>
|
||||
```
|
||||
|
||||
均为只读检查,不激活未知包。
|
||||
|
||||
## 验证
|
||||
|
||||
- 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未变,本轮无需重启或额外推理调用。
|
||||
@@ -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
|
||||
|
||||
@@ -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<bw)&(py>=0)&(py<bh)
|
||||
bx=px*(.98 if crop else 1)+(bw*.01 if crop else 0)-.5
|
||||
by=py*(.98 if crop else 1)+(bh*.01 if crop else 0)-.5
|
||||
b=bilinear(body.astype(float),bx,by)
|
||||
localx=px-x;localy=py-y;ph,pw=patch.shape[:2]
|
||||
p=bilinear(patch.astype(float),localx-.5,localy-.5)
|
||||
@@ -27,9 +28,11 @@ def golden(body,patch,x,y,opacity,w,h,crop):
|
||||
return np.clip(np.floor(out+.5),0,255).astype(np.uint8)
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--runtime',type=Path,required=True);parser.add_argument('--output',type=Path,required=True)
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--runtime',type=Path);parser.add_argument('--synthetic-shape',choices=['480x848','720x1280'],default='720x1280');parser.add_argument('--output',type=Path,required=True)
|
||||
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
||||
m=json.loads((args.runtime/'manifest.json').read_text());source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
|
||||
m=json.loads((args.runtime/'manifest.json').read_text()) if args.runtime else None
|
||||
bw,bh=(m['body']['width'],m['body']['height']) if m else map(int,args.synthetic_shape.split('x'))
|
||||
source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
|
||||
vertex=re.search(r'const val VERTEX="""([\s\S]*?)"""',source)[1]
|
||||
fragment=re.search(r'const val FRAGMENT="""([\s\S]*?)"""',source)[1]
|
||||
fragment=fragment.replace('#extension GL_OES_EGL_image_external : require','').replace('samplerExternalOES','sampler2D')
|
||||
@@ -40,38 +43,44 @@ def main():
|
||||
env=dict(os.environ,EGL_PLATFORM='surfaceless',LIBGL_ALWAYS_SOFTWARE='1')
|
||||
def check(body,patch,x,y,opacity,w,h,label,crop=0):
|
||||
(tmp/'body.rgba').write_bytes(body.tobytes());(tmp/'patch.rgba').write_bytes(patch.tobytes())
|
||||
p=subprocess.run([str(tmp/'golden'),str(tmp/'vertex'),str(tmp/'fragment'),str(tmp/'body.rgba'),str(tmp/'patch.rgba'),str(tmp/'out.rgba'),str(patch.shape[1]),str(patch.shape[0]),str(x),str(y),str(opacity),str(w),str(h),str(crop)],env=env,capture_output=True,text=True)
|
||||
p=subprocess.run([str(tmp/'golden'),str(tmp/'vertex'),str(tmp/'fragment'),str(tmp/'body.rgba'),str(tmp/'patch.rgba'),str(tmp/'out.rgba'),str(patch.shape[1]),str(patch.shape[0]),str(x),str(y),str(opacity),str(w),str(h),str(crop),str(body.shape[1]),str(body.shape[0])],env=env,capture_output=True,text=True)
|
||||
assert p.returncode==0,p.stderr
|
||||
actual=np.frombuffer((tmp/'out.rgba').read_bytes(),np.uint8).reshape(h,w,4)[::-1,:,:3]
|
||||
expected=golden(body,patch,x,y,opacity,w,h,crop);diff=np.abs(actual.astype(int)-expected.astype(int))
|
||||
row={'case':label,'maxAbsRGB':int(diff.max()),'meanAbsRGB':float(diff.mean()),'viewport':[w,h],'bodyTransformCrop':crop,'gl':p.stdout.strip()}
|
||||
row={'case':label,'maxAbsRGB':int(diff.max()),'meanAbsRGB':float(diff.mean()),'viewport':[w,h],'bodyShape':[body.shape[1],body.shape[0]],'bodyTransformCrop':crop,'gl':p.stdout.strip()}
|
||||
results.append(row)
|
||||
assert diff.max()<=2,row
|
||||
if opacity==0 and w==480 and h==848 and not crop:assert np.array_equal(actual,body[:,:,:3]),'Level0 must be exact decoded body'
|
||||
if opacity==0 and w==body.shape[1] and h==body.shape[0] and not crop:assert np.array_equal(actual,body[:,:,:3]),'Level0 must be exact decoded body'
|
||||
if label=='frame43-level2':Image.fromarray(actual[94:150,193:263]).resize((560,448)).save(args.output/'gles-frame43-level2-mouth.png')
|
||||
yy,xx=np.mgrid[:848,:480];body=np.empty((848,480,4),np.uint8)
|
||||
yy,xx=np.mgrid[:bh,:bw];body=np.empty((bh,bw,4),np.uint8)
|
||||
body[:,:,0]=xx%256;body[:,:,1]=yy%256;body[:,:,2]=((xx//16+yy//16)%2)*255;body[:,:,3]=255
|
||||
patch=np.zeros((22,40,4),np.uint8);patch[:,:,:3]=[211,70,39];patch[:,:,3]=np.arange(40,dtype=np.uint8)[None,:]*6
|
||||
for w,h in [(480,848),(360,800),(800,480)]:
|
||||
for w,h in [(bw,bh),(360,800),(800,480)]:
|
||||
for opacity in [0,.5,1]:check(body,patch,211.25,112.5,opacity,w,h,f'synthetic-{w}x{h}-opacity{opacity}')
|
||||
check(body,patch,211.25,112.5,1,480,848,'synthetic-transform-crop',1)
|
||||
pipe=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(args.runtime/m['body']['path']),'-f','rawvideo','-pix_fmt','rgba','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
try:
|
||||
for i,row in enumerate(m['patches']):
|
||||
raw=pipe.stdout.read(480*848*4);assert len(raw)==480*848*4
|
||||
fixed=(0,26,43,52,69,96) if len(m['patches'])==97 else tuple(sorted({round(k*(len(m['patches'])-1)/5) for k in range(6)}))
|
||||
if i not in fixed:continue
|
||||
body=np.frombuffer(raw,np.uint8).reshape(848,480,4)
|
||||
for level in (0,1,2,3,4):
|
||||
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
|
||||
check(body,patch,row['x'],row['y'],0 if level==0 else 1,480,848,f'frame{i}-level{level}')
|
||||
assert pipe.stdout.read(1)==b'';assert pipe.wait(timeout=10)==0
|
||||
finally:
|
||||
if pipe.poll() is None:pipe.kill();pipe.wait()
|
||||
check(body,patch,211.25,112.5,1,bw,bh,'synthetic-transform-crop',1)
|
||||
if m is None:
|
||||
# Pixel-space beyond the legacy bounds, both edges and fractional origin.
|
||||
for x,y in [(bw-40.0,bh-22.0),(bw-40.25,bh-22.25),(0,0),(0.25,0.25)]:
|
||||
for opacity in [0,.25,.5,.75,1]:
|
||||
check(body,patch,x,y,opacity,bw,bh,f'edge-{x}-{y}-opacity{opacity}')
|
||||
else:
|
||||
pipe=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(args.runtime/m['body']['path']),'-f','rawvideo','-pix_fmt','rgba','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
try:
|
||||
for i,row in enumerate(m['patches']):
|
||||
raw=pipe.stdout.read(bw*bh*4);assert len(raw)==bw*bh*4
|
||||
fixed=(0,26,43,52,69,96) if len(m['patches'])==97 else tuple(sorted({round(k*(len(m['patches'])-1)/5) for k in range(6)}))
|
||||
if i not in fixed:continue
|
||||
body=np.frombuffer(raw,np.uint8).reshape(bh,bw,4)
|
||||
for level in (0,1,2,3,4):
|
||||
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
|
||||
check(body,patch,row['x'],row['y'],0 if level==0 else 1,bw,bh,f'frame{i}-level{level}')
|
||||
assert pipe.stdout.read(1)==b'';assert pipe.wait(timeout=10)==0
|
||||
finally:
|
||||
if pipe.poll() is None:pipe.kill();pipe.wait()
|
||||
report={'status':'passed','shaderSourceSha':hashlib.sha256(source.encode()).hexdigest(),
|
||||
'harnessSha':hashlib.sha256((ROOT/'tests/avatar-pixels/gles-golden.c').read_bytes()).hexdigest(),
|
||||
'scope':'Production shader strings; body OES sampler substituted by2D, decoded ffmpeg/PIL straight bytes. Does not test Android Bitmap/OES/YUV/physicaldisplay.','cases':results}
|
||||
(args.output/'shader-golden.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print('PASS:',len(results),'real offline EGL/GLES pixel golden cases: UV/top-bottom/Fit/nontrivial body transform/straight blend/alpha0/6fixedframes x5levels; Android device pending')
|
||||
print('PASS:',len(results),'real offline EGL/GLES pixel golden cases: UV/top-bottom/Fit/nontrivial body transform/straight blend/alpha0; '+('6 fixed frames x5 levels' if m else 'procedural edge/fractional-coordinate cases')+'; Android device pending')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
|
||||
@@ -68,10 +68,10 @@ def probe_clip(path):
|
||||
data=json.loads(result.stdout)
|
||||
require(len(data['streams'])==1,'conversation/bridge must be silent video')
|
||||
v=data['streams'][0]
|
||||
require(v['codec_type']=='video' and v['codec_name']=='h264' and (v['width'],v['height'])==(480,848),'clip codec/shape')
|
||||
require(v['codec_type']=='video' and v['codec_name']=='h264' and (v['width'],v['height']) in runtime_gate.SUPPORTED_SHAPES,'clip codec/shape')
|
||||
us=lambda value:int((Decimal(value)*1_000_000).to_integral_value())
|
||||
measured={'ptsUs':[us(f['best_effort_timestamp_time']) for f in data['frames']],
|
||||
'durationUs':us(v['duration']),'fps':Fraction(v['r_frame_rate'])}
|
||||
'durationUs':us(v['duration']),'fps':Fraction(v['r_frame_rate']),'shape':(v['width'],v['height'])}
|
||||
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60)
|
||||
return measured
|
||||
|
||||
@@ -84,7 +84,7 @@ def probe_music_clip(path):
|
||||
require(len(streams)==2 and sorted(s['codec_type'] for s in streams)==['audio','video'],
|
||||
'dance requires exactly video+audio, no attached cover')
|
||||
v=next(s for s in streams if s['codec_type']=='video');a=next(s for s in streams if s['codec_type']=='audio')
|
||||
require(v['codec_name']=='h264' and (v['width'],v['height'])==(480,848) and
|
||||
require(v['codec_name']=='h264' and (v['width'],v['height']) in runtime_gate.SUPPORTED_SHAPES and
|
||||
not v.get('disposition',{}).get('attached_pic',0),'dance video codec/shape/cover')
|
||||
require(a['codec_name']=='aac' and a['channels'] in (1,2) and 8000<=int(a['sample_rate'])<=96000,'dance AAC format')
|
||||
us=lambda value:int((Decimal(value)*1_000_000).to_integral_value())
|
||||
@@ -110,7 +110,7 @@ def probe_music_clip(path):
|
||||
require(rms>0.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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -16,6 +16,7 @@ fun main() {
|
||||
emotionActionCheck()
|
||||
conversationPackageCheck()
|
||||
actualMediaViewCheck()
|
||||
actualMediaViewCheck(720,1280)
|
||||
mediaBoundaryCheck()
|
||||
idleVariantCheck()
|
||||
fullActionGraphCheck()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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 }
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user