Datasets:

Tasks:
Other
ArXiv:
File size: 4,466 Bytes
53ed7ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""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()