File size: 9,889 Bytes
f517c0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
"""Check a suite's media folder against MEDIA_STANDARD.md (v2, 2026-10-16: above 1080p, ray or path tracing only).

Usage: python3 check_media.py <suite_dir> [--teaser-only]

Layout: <suite_dir>/<task_id>/{video.mp4, poster.png, meta.json} or {still.png, meta.json},
plus an optional <suite_dir>/teaser.mp4. Needs ffprobe and ffmpeg on PATH. Exit code 1 if anything fails.
"""
import json
import re
import subprocess
import sys
from pathlib import Path

META_KEYS = ("suite", "task", "source", "renderer", "rendering", "width", "height", "fps", "speed", "success_check")
RENDERINGS = ("path-tracing", "ray-tracing")
# renderers that rasterize (addendum 2): never accepted, whatever the resolution
RASTER = re.compile(r"\b(raster\w*|opengl|egl|osmesa|eevee|workbench|pyrender|mujoco[ _-]?(?:native|viewer|renderer)|default[ _-]?shader)\b", re.I)


def size_problem(name, w, h):
    """Addendum 2: masters, posters and stills must be larger than 1920x1080; 2560x1440 is the target."""
    if w <= 1920 or h <= 1080:
        return f"{name}: {w}x{h} is not above 1920x1080 (render at 2560x1440)"
    return None
SOURCES = ("oracle", "agent-success:", "official-demo:", "scene-orbit")


def probe(path):
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
         "stream=codec_name,pix_fmt,width,height,r_frame_rate,avg_frame_rate,bit_rate:format=duration,bit_rate",
         "-of", "json", str(path)], capture_output=True, text=True)
    if out.returncode:
        return None
    d = json.loads(out.stdout)
    s = (d.get("streams") or [{}])[0]
    f = d.get("format") or {}
    s["duration"] = float(f.get("duration") or 0)
    s["bit_rate"] = int(s.get("bit_rate") or f.get("bit_rate") or 0)
    return s


def rate(text):
    num, _, den = (text or "0/1").partition("/")
    return float(num) / float(den or 1) if float(den or 1) else 0.0


def encoder_crf(path):
    """CRF recorded by x264/x265 in the stream's SEI text, or None for other encoders."""
    with open(path, "rb") as fh:
        head = fh.read(4 << 20)
    i = head.find(b"crf=")
    if i < 0 or (b"x264" not in head and b"x265" not in head):
        return None
    try:
        return float(head[i + 4:i + 12].split(b" ")[0])
    except ValueError:
        return None


def black_bars(path, duration, width, height):
    """Detect letterboxing or pillarboxing in the middle of the clip (a warning: dark scenes can trip it)."""
    out = subprocess.run(
        ["ffmpeg", "-hide_banner", "-ss", str(max(0.0, duration / 2 - 0.5)), "-i", str(path), "-frames:v", "12",
         "-vf", "cropdetect=24:2:0", "-f", "null", "-"], capture_output=True, text=True)
    crops = [ln.rsplit("crop=", 1)[1].strip() for ln in out.stderr.splitlines() if "crop=" in ln]
    if not crops:
        return False
    w, h = (int(v) for v in crops[-1].split(":")[:2])
    return w < 0.96 * width or h < 0.96 * height


def check_video(path, teaser, problems, warnings):
    s = probe(path)
    if not s:
        problems.append(f"{path.name}: unreadable")
        return None
    w, h, fps = int(s.get("width") or 0), int(s.get("height") or 0), rate(s.get("r_frame_rate"))
    if (p := size_problem(path.name, w, h)):
        problems.append(p)
    elif w < 2560 or h < 1440:
        warnings.append(f"{path.name}: {w}x{h} is below the 2560x1440 target")
    if h and abs(w / h - 16 / 9) > 0.02:
        problems.append(f"{path.name}: aspect {w}x{h} is not 16:9")
    if fps < 29.9:
        problems.append(f"{path.name}: {fps:.2f} fps is below 30")
    if abs(rate(s.get("avg_frame_rate")) - fps) > 0.5:
        warnings.append(f"{path.name}: frame rate looks variable")
    if s.get("codec_name") not in ("h264", "hevc"):
        problems.append(f"{path.name}: codec {s.get('codec_name')} (use H.264 or H.265)")
    if s.get("pix_fmt") not in ("yuv420p", "yuvj420p"):
        warnings.append(f"{path.name}: pixel format {s.get('pix_fmt')} (yuv420p plays everywhere)")
    crf = encoder_crf(path)
    if crf is not None:
        if crf > 18.05:
            problems.append(f"{path.name}: encoded at CRF {crf:g}; masters need CRF 18 or lower")
    else:
        # No encoder record: fall back to a bitrate floor scaled to 1080p30. Clean renders of simple scenes
        # compress well, so this is only a warning.
        floor = 2e6 * (w * h * max(fps, 1)) / (1920 * 1080 * 30)
        if s["bit_rate"] and s["bit_rate"] < floor:
            warnings.append(f"{path.name}: {s['bit_rate'] / 1e6:.1f} Mbps; if this is a re-encode, deliver the original")
    lo, hi = (10, 40) if teaser else (5, 60)
    if not lo <= s["duration"] <= hi:
        warnings.append(f"{path.name}: {s['duration']:.1f} s (expected {lo}-{hi} s)")
    if w and h and black_bars(path, s["duration"], w, h):
        warnings.append(f"{path.name}: black bars detected; check by eye")
    return w, h, fps


def check_image(path, problems):
    s = probe(path)
    if not s:
        problems.append(f"{path.name}: unreadable")
        return
    w, h = int(s.get("width") or 0), int(s.get("height") or 0)
    if (p := size_problem(path.name, w, h)):
        problems.append(p)
    if path.suffix.lower() != ".png":
        problems.append(f"{path.name}: use PNG for stills and posters")


def check_task(d):
    problems, warnings = [], []
    video, still, poster, meta = d / "video.mp4", d / "still.png", d / "poster.png", d / "meta.json"
    dims = None
    if video.exists():
        dims = check_video(video, False, problems, warnings)
        if poster.exists():
            check_image(poster, problems)
        else:
            problems.append("poster.png missing")
    elif still.exists():
        check_image(still, problems)
        warnings.append("still only: a video is preferred")
    else:
        problems.append("neither video.mp4 nor still.png")
    if not meta.exists():
        problems.append("meta.json missing")
    else:
        try:
            m = json.loads(meta.read_text())
        except ValueError:
            problems.append("meta.json is not valid JSON")
            m = {}
        missing = [k for k in META_KEYS if k not in m]
        if missing:
            problems.append(f"meta.json lacks {', '.join(missing)}")
        if m.get("source") and not str(m["source"]).startswith(SOURCES):
            problems.append(f"meta.json source '{m['source']}' is not oracle / agent-success:* / official-demo:* / scene-orbit")
        if "rendering" in m and m.get("rendering") not in RENDERINGS:
            problems.append(f"meta.json rendering '{m.get('rendering')}' is not path-tracing or ray-tracing (addendum 2)")
        if RASTER.search(str(m.get("renderer", ""))):
            problems.append(f"meta.json renderer '{m.get('renderer')}' is a rasterizer; render with ray or path tracing (addendum 2)")
        if m.get("success_check") is False and m.get("source") != "scene-orbit":
            problems.append("meta.json says the replay did not succeed; never publish it as a solved run")
        kind = str(m.get("source", "")).split(":")[0]
        if (still.exists() and not video.exists() or kind in ("scene-orbit", "still")) and not str(m.get("why_no_video", "")).strip():
            problems.append("a still or an orbit needs \"why_no_video\" in meta.json (addendum 1)")
        if dims and m.get("width") and (m.get("width"), m.get("height")) != dims[:2]:
            warnings.append(f"meta.json size {m.get('width')}x{m.get('height')} differs from the file {dims[0]}x{dims[1]}")
    return problems, warnings


def check_highlights(root):
    """<suite>/highlights.json: at least 5 hard tasks, each with a video where the robot moves; the teaser among them."""
    problems = []
    path = root / "highlights.json"
    if not path.exists():
        return ["no highlights.json: list at least 5 hard tasks with the robot moving (addendum 1)"]
    try:
        h = json.loads(path.read_text())
    except ValueError:
        return ["highlights.json is not valid JSON"]
    ids = [str(x) for x in h.get("highlights") or []]
    for t in ids:
        d = root / t
        m = json.loads((d / "meta.json").read_text()) if (d / "meta.json").exists() else {}
        kind = str(m.get("source", "")).split(":")[0]
        if not d.is_dir():
            problems.append(f"highlight {t}: no such task")
        elif not (d / "video.mp4").exists() or kind in ("scene-orbit", "still"):
            problems.append(f"highlight {t}: needs a video where the robot moves")
    if h.get("teaser") and h["teaser"] not in ids:
        problems.append("the teaser must be one of the highlights")
    if len(set(ids)) < 5 and not str(h.get("why_fewer", "")).strip():
        problems.append(f"{len(set(ids))} highlights: list at least 5, or say why in why_fewer")
    return problems


def main():
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    root = Path(sys.argv[1])
    failed = 0
    teaser = root / "teaser.mp4"
    if teaser.exists():
        problems, warnings = [], []
        check_video(teaser, True, problems, warnings)
        failed += bool(problems)
        print(("FAIL" if problems else "WARN" if warnings else "PASS"), "teaser", *(problems + warnings), sep="  ")
    else:
        print("WARN  teaser  teaser.mp4 missing")
    hp = check_highlights(root)
    failed += bool(hp)
    print("FAIL" if hp else "PASS", "highlights", *hp, sep="  ")
    if "--teaser-only" not in sys.argv:
        tasks = sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith((".", "_")))
        for d in tasks:
            problems, warnings = check_task(d)
            failed += bool(problems)
            print(("FAIL" if problems else "WARN" if warnings else "PASS"), d.name, *(problems + warnings), sep="  ")
        print(f"\n{len(tasks)} tasks, {failed} failing")
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()