"""本主题专属离线算法，仅读取同目录合成JSON，不联网、不控制设备。"""
import csv, json, math, re, struct
from pathlib import Path
from fractions import Fraction
BASE=Path(__file__).resolve().parent
data=json.loads((BASE/'input.json').read_text(encoding='utf-8'))['data']
import subprocess, shutil
ffmpeg=shutil.which('ffmpeg');ffprobe=shutil.which('ffprobe')
if not ffmpeg or not ffprobe:raise RuntimeError('需要本地FFmpeg与ffprobe；本脚本不下载软件')
media_version=subprocess.run([ffmpeg,'-version'],capture_output=True,text=True,encoding='utf-8',errors='replace',check=True).stdout.splitlines()[0]
def make_png(source,graph,filename):
 target=BASE/filename
 command=[ffmpeg,'-hide_banner','-nostdin','-y','-filter_threads','1','-f','lavfi','-i',source,'-vf',graph,'-frames:v','1','-c:v','png','-threads','1',str(target)]
 run=subprocess.run(command,capture_output=True,text=True,encoding='utf-8',errors='replace')
 if run.returncode:raise RuntimeError(run.stderr)
 probe_command=[ffprobe,'-v','error','-select_streams','v:0','-show_entries','stream=width,height,pix_fmt','-of','json',str(target)]
 probe=subprocess.run(probe_command,capture_output=True,text=True,encoding='utf-8',check=True)
 return {'file':filename,'command':command,'probe_command':probe_command,'stream':json.loads(probe.stdout)['streams'][0],'exit_code':run.returncode}

w,h=data['canvas'];rows=[]
for name,rects in data['cases'].items():
 xs=sorted({0,w,*[max(0,min(w,r[0])) for r in rects],*[max(0,min(w,r[0]+r[2])) for r in rects]});ys=sorted({0,h,*[r[1] for r in rects],*[r[1]+r[3] for r in rects]})
 gap=overlap=0
 for x0,x1 in zip(xs,xs[1:]):
  for y0,y1 in zip(ys,ys[1:]):
   count=sum(r[0]<=x0 and x1<=r[0]+r[2] and r[1]<=y0 and y1<=r[1]+r[3] for r in rects);area=(x1-x0)*(y1-y0)
   if count==0:gap+=area
   if count>1:overlap+=area
 outside=any(r[0]<0 or r[1]<0 or r[0]+r[2]>w or r[1]+r[3]>h for r in rects)
 rows.append({'case':name,'uncovered_pixels':gap,'overlap_pixels':overlap,'out_of_bounds':outside})
assert rows[0]['uncovered_pixels']==0 and rows[1]['uncovered_pixels']==1080 and rows[2]['overlap_pixels']==1080
media=make_png('testsrc2=size=3840x1080:rate=1','crop=1920:1080:1920:0','right-output.png')
assert (media['stream']['width'],media['stream']['height'])==(1920,1080)
result={'coverage':rows,'media_version':media_version,'actual_media_run':media,'real_outputs_measured':False}
(BASE/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False))
