87 lines
6.5 KiB
Python
87 lines
6.5 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):
|
|
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<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)
|
|
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
|
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])],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],'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==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[: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)]:
|
|
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'))
|
|
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; '+('6 fixed frames x5 levels' if m else 'procedural edge/fractional-coordinate cases')+'; Android device pending')
|
|
|
|
if __name__=='__main__':main()
|