Files
baji-vc/scripts/check-avatar-shader.py

91 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Offline real GLES2 shader pixel golden; surrogate body texture, no Android/device claim."""
from pathlib import Path
import argparse,hashlib,json,os,re,subprocess,tempfile
import numpy as np
from PIL import Image
ROOT=Path(__file__).resolve().parents[1]
def bilinear(image,x,y):
h,w=image.shape[:2];x=np.clip(x,0,w-1);y=np.clip(y,0,h-1)
ix=np.floor(x).astype(int);iy=np.floor(y).astype(int);jx=np.minimum(ix+1,w-1);jy=np.minimum(iy+1,h-1)
fx=(x-ix)[...,None];fy=(y-iy)[...,None]
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,zoom=1,center_y=.5):
bh,bw=body.shape[:2]
scale=min(w/bw,h/bh)*zoom;left=(w-bw*scale)/2;top=h/2-bh*scale*center_y
yy,xx=np.mgrid[:h,:w];px=(xx+.5-left)/scale;py=(yy+.5-top)/scale
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)
mask=(opacity*p[:,:,3:4]/255)*((localx>=0)&(localy>=0)&(localx<pw)&(localy<ph))[...,None]
out=b[:,:,:3]*(1-mask)+p[:,:,:3]*mask
out[~inside]=255
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);parser.add_argument('--synthetic-shape',choices=['480x848','720x1280'],default='720x1280');parser.add_argument('--output',type=Path,required=True)
parser.add_argument('--framing-preset',choices=['legacy','square540-headchest'],default='legacy')
parser.add_argument('--zoom',type=float,default=1);parser.add_argument('--center-y',type=float,default=.5)
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
assert (args.framing_preset=='legacy' and 1<=args.zoom<=2 and .4<=args.center_y<=.6) or (args.framing_preset=='square540-headchest' and abs(args.zoom-32/9)<1e-7 and args.center_y==.128125)
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')
results=[]
with tempfile.TemporaryDirectory(prefix='avatar-gles-golden-') as temporary:
tmp=Path(temporary);(tmp/'vertex').write_text(vertex);(tmp/'fragment').write_text(fragment)
subprocess.run(['cc','-O2',str(ROOT/'tests/avatar-pixels/gles-golden.c'),'-lEGL','-lGLESv2','-lm','-o',str(tmp/'golden')],check=True)
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),str(body.shape[1]),str(body.shape[0]),str(args.zoom),str(args.center_y)],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,args.zoom,args.center_y);diff=np.abs(actual.astype(int)-expected.astype(int))
row={'case':label,'maxAbsRGB':int(diff.max()),'meanAbsRGB':float(diff.mean()),'viewport':[w,h],'bodyShape':[body.shape[1],body.shape[0]],'bodyTransformCrop':crop,'zoom':args.zoom,'centerY':args.center_y,'gl':p.stdout.strip()}
results.append(row)
assert diff.max()<=2,row
if opacity==0 and w==body.shape[1] and h==body.shape[0] and not crop and args.zoom==1 and args.center_y==.5: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[: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 [(bw,bh),(360,800),(800,480),(540,540)]:
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,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'))
for vw,vh in ([(bw,bh),(540,540)] if args.framing_preset!='legacy' else [(bw,bh)]):
check(body,patch,row['x'],row['y'],0 if level==0 else 1,vw,vh,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; '+('6 fixed frames x5 levels' if m else 'procedural edge/fractional-coordinate cases')+'; Android device pending')
if __name__=='__main__':main()