"""本主题专属离线算法，仅读取同目录合成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}

c=data['crop'];default_model={k:v-v%2 for k,v in c.items()}
a=make_png('testsrc2=size=800x450:rate=1','crop=641:359:101:31','crop-default.png')
b=make_png('testsrc2=size=800x450:rate=1','crop=641:359:101:31:exact=1','crop-exact.png')
assert (a['stream']['width'],a['stream']['height'])==(640,358)
assert (b['stream']['width'],b['stream']['height'])==(641,359)
result={'request':c,'default_alignment_model':default_model,'model_origin_verified_by_pixel_comparison':False,'media_version':media_version,'actual_media_runs':[a,b],'scope':'实际验证输出尺寸；原点为规则模型'}
(BASE/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False))
