"""本主题专属离线算法，仅读取同目录合成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}

sw,sh=data['source'];tw,th=data['target'];fit=min(Fraction(tw,sw),Fraction(th,sh));fill=max(Fraction(tw,sw),Fraction(th,sh))
fit_size=[sw*fit,sh*fit];fill_size=[sw*fill,sh*fill];crop_y=(fill_size[1]-th)/2
assert fit_size[0]==Fraction(8192,9) and fill_size==[2560,1440] and crop_y==464
a=make_png('testsrc2=size=1920x1080:rate=1','scale=910:512,setsar=1,pad=2560:512:825:0:black','fit.png')
b=make_png('testsrc2=size=1920x1080:rate=1','scale=2560:1440,setsar=1,crop=2560:512:0:464','fill.png')
assert all((x['stream']['width'],x['stream']['height'])==(2560,512) for x in [a,b])
result={'fit_scale_exact':str(fit),'fit_size_exact':[str(v) for v in fit_size],'fit_padding_each_exact':str((tw-fit_size[0])/2),'integer_fit_candidate':[910,512,825,0],'fill_scale_exact':str(fill),'fill_size':[int(v) for v in fill_size],'fill_crop_y':int(crop_y),'media_version':media_version,'actual_media_runs':[a,b]}
(BASE/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False))
