"""Rebuild the link-only clips of 4DCodeBench-RealWorld from their public sources. Each clip in `link_only_clips.json` is its source and the chain of steps that turned the source into the benchmark video. A step is one of encode one ffmpeg pass to H.264: input options placed before -i (-ss, -t) vf the filter graph output options placed after the filter (-t, -r, -vsync) crf, preset x264 settings (defaults 18, medium) retime rewrite the timestamps to `fps` without touching a frame (29.97 -> 30, 23.976 -> 24) stabilize virtual-tripod lock with tripod_lock.py; `args` are its CLI flags Usage: python scripts/prepare_videos.py [--downloads downloads] [--out videos] [case ...] Sources are fetched into --downloads. Requires ffmpeg/ffprobe on PATH, numpy and opencv-python. """ import argparse import json import subprocess import tempfile import urllib.request from fractions import Fraction from pathlib import Path import tripod_lock HERE = Path(__file__).resolve().parent ROOT = HERE.parent def fetch(clip, downloads): path = downloads / clip["file"] if path.exists(): return path print(f" downloading {clip['download']}") req = urllib.request.Request(clip["download"], headers={"User-Agent": "Mozilla/5.0"}) part = path.with_suffix(".part") with urllib.request.urlopen(req) as r, open(part, "wb") as f: while chunk := r.read(1 << 20): f.write(chunk) part.rename(path) return path def ffmpeg(*args): subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", *map(str, args)], check=True) def encode(src, dst, input=(), vf=None, output=(), crf=18, preset="medium"): ffmpeg(*input, "-i", src, "-map", "0:v:0", *(["-vf", vf] if vf else []), *output, "-an", "-c:v", "libx264", "-preset", preset, "-crf", crf, "-pix_fmt", "yuv420p", "-movflags", "+faststart", dst) def retime(src, dst, fps): rate = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=r_frame_rate", "-of", "csv=p=0", str(src)], capture_output=True, text=True, check=True).stdout.strip() ffmpeg("-itsscale", float(Fraction(rate) / Fraction(fps)), "-i", src, "-map", "0:v:0", "-c", "copy", "-movflags", "+faststart", dst) def stabilize(src, dst, args): ap = argparse.ArgumentParser() for flag in ("--crop-left", "--crop-right", "--crop-top", "--crop-bottom"): ap.add_argument(flag, type=int, default=0) ap.add_argument("--ref-frame", default="0") a = ap.parse_args(args) extra = (a.crop_left, a.crop_right, a.crop_top, a.crop_bottom) raw, _, _ = tripod_lock.process(src, dst.parent, "similarity", extra, ref_frame=a.ref_frame) ffmpeg("-i", raw, "-c:v", "libx264", "-crf", 18, "-pix_fmt", "yuv420p", dst) raw.unlink() def build(clip, downloads, out_dir): current = fetch(clip, downloads) with tempfile.TemporaryDirectory() as tmp: for i, step in enumerate(clip["steps"]): (kind, params), = step.items() last = i == len(clip["steps"]) - 1 dst = out_dir / f"{clip['case']}.mp4" if last else Path(tmp) / f"{i}.mp4" if kind == "encode": encode(current, dst, **params) elif kind == "retime": retime(current, dst, params["fps"]) else: stabilize(current, dst, params["args"]) current = dst print(f" {current}") def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("cases", nargs="*", help="cases to build (default: all)") ap.add_argument("--downloads", type=Path, default=ROOT / "downloads") ap.add_argument("--out", type=Path, default=ROOT / "videos") args = ap.parse_args() clips = json.loads((HERE / "link_only_clips.json").read_text()) unknown = set(args.cases) - {c["case"] for c in clips} if unknown: raise SystemExit(f"not link-only cases: {sorted(unknown)}") args.downloads.mkdir(parents=True, exist_ok=True) args.out.mkdir(parents=True, exist_ok=True) for clip in clips: if not args.cases or clip["case"] in args.cases: print(clip["case"]) build(clip, args.downloads, args.out) if __name__ == "__main__": main()