"""Verifier-only decoding and native effect helpers.""" import argparse,hashlib,json,math,os,shutil,subprocess,tempfile from pathlib import Path import numpy as np from PIL import Image TICKS=254016000000 def digest(p): h=hashlib.sha256() with p.open('rb') as f: for block in iter(lambda:f.read(1024*1024),b''):h.update(block) return h.hexdigest() def run(args,timeout=120):return subprocess.run(args,capture_output=True,timeout=timeout) def probe(p): r=run(['ffprobe','-v','error','-show_streams','-show_format','-of','json',str(p)]) if r.returncode:raise ValueError(r.stderr.decode(errors='replace')[-1000:]) d=json.loads(r.stdout);s=next(s for s in d['streams'] if s['codec_type']=='video') return d,s def val(effect,name,default=None): p=effect.get('params',{}).get(name,{}) if p.get('keyframes'):return None v=p.get('value',{}) return next(iter(v.values()),default) if isinstance(v,dict) else v def normal(c,media): if c.get('speed',1)!=1 or c.get('reverse') or c.get('frame_hold') is not None:return False interpret=media.get('interpret',{}) if interpret.get('frame_rate'):return None for e in c.get('effects',[]): if e.get('enabled',True) and e.get('effect')=='time_remap': speed=val(e,'speed',100) if speed is None:return None if speed!=100:return False return True def geometry(c,media,w,h): """Resolve basic motion, including scale-to-frame and anchor offsets. Unknown effects/keyframes/PAR overrides defer to native/render review. """ v=media.get('info',{}).get('video') if not v:return None sw,sh=v['width'],v['height'];par=v.get('par',[1,1]);interp=media.get('interpret',{}) if interp.get('par') or par[0]!=par[1]:return None motion=None;opacity=100 for e in c.get('effects',[]): if not e.get('enabled',True):continue kind=e.get('effect') if kind=='motion':motion=e elif kind=='opacity': opacity=val(e,'opacity',100) if val(e,'blend',0)!=0:return None elif kind=='time_remap':continue else:return None if not motion:return None scale=val(motion,'scale',100);width=val(motion,'scale_width',100);uniform=val(motion,'uniform_scale',True) position=val(motion,'position',{'x':w/2,'y':h/2});anchor=val(motion,'anchor',{'x':sw/2,'y':sh/2});rotation=val(motion,'rotation',0) if any(x is None for x in [scale,width,uniform,position,anchor,rotation,opacity]):return None if rotation!=0:return {'upright':False,'opacity':opacity} base=min(w/sw,h/sh) if c.get('scale_to_frame') else 1 sy=base*scale/100;sx=sy if uniform else base*width/100 return {'x':position['x']-anchor['x']*sx,'y':position['y']-anchor['y']*sy,'w':sw*sx,'h':sh*sy,'sx':sx,'sy':sy,'upright':True,'opacity':opacity} def decoded_frames(p,w,h,filter_prefix='',limit=None): vf=filter_prefix+(',' if filter_prefix else '')+f'scale={w}:{h}:flags=area' args=['ffmpeg','-v','error','-threads','2','-i',str(p),'-an','-vf',vf] if limit:args+=['-frames:v',str(limit)] args+=['-pix_fmt','rgb24','-f','rawvideo','pipe:1'] r=run(args,timeout=600) if r.returncode:raise ValueError(r.stderr.decode(errors='replace')[-1000:]) size=w*h*3 if len(r.stdout)%size:raise ValueError('Partial decoded frame') return np.frombuffer(r.stdout,dtype=np.uint8).reshape(-1,h,w,3) def reference_frames(p,W,H): _,s=probe(p);sw,sh=s['width'],s['height'];factor=min(W/sw,H/sh) rw=round(sw*factor);rh=round(sh*factor) vf=f'trim=start=0:end=5,setpts=PTS-STARTPTS,fps=30,scale={rw}:{rh}:flags=bicubic,setsar=1,pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:black' return decoded_frames(p,192 if W>=H else 108,108 if W>=H else 192,vf,150)