File size: 4,329 Bytes
1daa78e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import hashlib,json,subprocess
from pathlib import Path
from functools import lru_cache
import numpy as np
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'];scale=min(W/sw,H/sh) if W>H else max(W/sw,H/sh)
 rw=round(sw*scale);rh=round(sh*scale)
 vf=f'trim=start=0:end=5,setpts=PTS-STARTPTS,fps=30,scale={rw}:{rh}:flags=bicubic,setsar=1'
 vf+=f',pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:black' if W>H else f',crop={W}:{H}:(iw-ow)/2:(ih-oh)/2'
 return decoded_frames(p,192 if W>H else 108,108 if W>H else 192,vf,150)


@lru_cache(maxsize=16)
def video_end(path):
 """True video-track presentation end, excluding longer audio/container tails."""
 r=run(['ffprobe','-v','error','-select_streams','v:0','-show_frames','-show_entries','frame=best_effort_timestamp_time,pkt_duration_time,duration_time','-of','json',str(path)],600)
 if r.returncode:raise ValueError('Cannot decode source presentation timing')
 frames=json.loads(r.stdout).get('frames',[])
 _,stream=probe(path)
 num,den=map(float,stream.get('avg_frame_rate','30/1').split('/'))
 fallback=den/num
 ends=[float(f['best_effort_timestamp_time'])+float(f.get('duration_time',f.get('pkt_duration_time',fallback))) for f in frames if 'best_effort_timestamp_time' in f]
 if not ends:raise ValueError('Source has no decoded video timing')
 return max(ends)