File size: 15,118 Bytes
4ae8702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
"""Shared ffmpeg command validator: synthetic media, execution, static checks, metrics.

Used by the audit, the baselines and the fine-tuned eval so every number comes
from the same code path. Requires ffmpeg on PATH.
"""
import os
import re
import shlex
import shutil
import subprocess
import tempfile

VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".m4v", ".mpg", ".mpeg", ".ts", ".wmv", ".3gp"}
AUDIO_EXT = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg", ".opus", ".wma", ".aiff", ".amr"}
IMAGE_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff", ".tif", ".ppm", ".pgm", ".pam"}
SUB_EXT = {".srt", ".ass", ".ssa", ".vtt", ".ttml"}
LAVFI_SOURCES = {"testsrc", "testsrc2", "sine", "color", "anullsrc", "mandelbrot",
                 "smptebars", "smptehdbars", "rgbtestsrc", "life", "cellauto", "haldclutsrc",
                 "nullsrc", "gradients", "qrencodesrc", "zeroes", "srtpacketsrc", "vignette",
                 "aevalsrc", "avectorscope", "showwaves", "showwavespic", "showspectrum", "showcqt"}
STATIC_ONLY_MARKERS = [
    "nvenc", "qsv", "v4l2", "rtsp", "srt:", "udp:", "rtp:", "videotoolbox", "vaapi",
    "d3d11va", "dxva2", "mediacodec", "cuda", "cuvid", "mmal", "omx",
    "dshow", "avfoundation", "x11grab", "gdigrab", ":video=", ":audio=",
]
HEAVY = ("minterpolate", "loop=loop=-1", "framerate=240", "fps=240")

_cap_cache = {}


def _run(cmd, timeout):
    return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)


def capabilities():
    """Cached sets of real ffmpeg filters, encoders and muxers."""
    if "filters" not in _cap_cache:
        filt = _run(["ffmpeg", "-hide_banner", "-filters"], 15).stdout.decode(errors="replace")
        _cap_cache["filters"] = set(re.findall(r"^ [A-Z0-9\.]+\s+(\w+)", filt, re.M))
    if "encoders" not in _cap_cache:
        enc = _run(["ffmpeg", "-hide_banner", "-encoders"], 15).stdout.decode(errors="replace")
        _cap_cache["encoders"] = set(re.findall(r"^ [AVS\.]{6}\s+(\S+)", enc, re.M))
    if "muxers" not in _cap_cache:
        mux = _run(["ffmpeg", "-hide_banner", "-muxers"], 15).stdout.decode(errors="replace")
        _cap_cache["muxers"] = set(re.findall(r"^ [A-Z0-9\.]+\s+(\w+)", mux, re.M))
    return _cap_cache


def ext_of(fn):
    m = re.search(r"\.([A-Za-z0-9]{1,6})$", fn)
    return ("." + m.group(1).lower()) if m else ""


def is_sequence(fn):
    return bool(re.search(r"%0?\d*d", fn))


def is_glob(fn):
    return bool(re.search(r"[\*\?]", fn))


def seq_dir(fn):
    return os.path.dirname(fn) or "."


def is_lavfi_source(tok):
    return tok.split("=")[0].split(":")[0] in LAVFI_SOURCES


def command_inputs(cmd):
    """Positional inputs + filenames embedded in filter args."""
    try:
        toks = shlex.split(cmd)
    except ValueError:
        return []
    ins, i = [], 1
    while i < len(toks):
        t = toks[i]
        if t == "-i" and i + 1 < len(toks):
            ins.append(toks[i + 1])
            i += 2
            continue
        i += 1
    files = []
    for m in re.finditer(r"(?:subtitles|ass)=([^:'\"\s]+\.(?:srt|ass|ssa|vtt))|"
                         r"(?:textfile|fontfile|filename)=([\w./\-]+\.\w+)", cmd):
        files.append(m.group(1) or m.group(2))
    out = []
    for fn in ins + files:
        if not fn or fn.startswith("-") or is_lavfi_source(fn) or ":" in fn:
            continue
        if "." not in fn and "%" not in fn and "*" not in fn and "/" not in fn:
            continue
        if fn not in out:
            out.append(fn)
    return out


def make_input_file(path, is_concat=False):
    """Create a tiny synthetic media file at `path` based on its extension."""
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    ext = ext_of(path)
    try:
        if ext == ".txt" and is_concat:
            with open(path, "w") as f:
                f.write("file 'video.mp4'\n")
            return os.path.exists(path)
        if is_glob(path):
            d = seq_dir(path)
            os.makedirs(d, exist_ok=True)
            e = ext_of(path) or ".jpg"
            for k in range(1, 4):
                _run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi",
                      "-i", "testsrc=size=64x64:rate=1", "-frames:v", "1",
                      os.path.join(d, f"synthimg_{k:03d}{e}")], 15)
            return len(os.listdir(d)) >= 3
        if ext in SUB_EXT or ext == ".txt":
            with open(path, "w") as f:
                f.write("1\n00:00:00,000 --> 00:00:00,500\nhello world\n\nsample text\n")
            return os.path.exists(path)
        if is_sequence(path) or ext in IMAGE_EXT:
            args = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi",
                    "-i", "testsrc=duration=0.5:size=64x64:rate=5"]
            if is_sequence(path):
                args.append(path)
            else:
                args += ["-frames:v", "1", path]
            _run(args, 15)
            if is_sequence(path):
                import glob as _g
                base = re.sub(r"%0?\d*d", "*", os.path.basename(path))
                return len(_g.glob(os.path.join(seq_dir(path), base))) >= 1
            return os.path.exists(path)
        if ext in (".mpg", ".mpeg"):
            _run(["ffmpeg", "-v", "error", "-y",
                  "-f", "lavfi", "-i", "testsrc=duration=12:size=640x480:rate=10",
                  "-f", "lavfi", "-i", "sine=duration=12",
                  "-map", "0:v", "-map", "1:a", "-c:v", "mpeg2video", "-c:a", "mp2",
                  "-pix_fmt", "yuvj420p", path], 60)
            return os.path.exists(path)
        if ext == ".opus":
            _run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=3",
                  "-c:a", "libopus", path], 30)
            return os.path.exists(path)
        if ext in AUDIO_EXT:
            _run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi",
                  "-i", "sine=duration=12:frequency=440", "-ar", "44100", "-ac", "1", path], 30)
            return os.path.exists(path)
        if ext in VIDEO_EXT or ext == "":
            sub_fmt = {".mp4": "mov_text", ".m4v": "mov_text", ".mov": "mov_text",
                       ".mkv": "srt", ".webm": "webvtt"}.get(ext)
            srt = os.path.join(os.path.dirname(path) or ".", "_synth.srt")
            with open(srt, "w") as f:
                f.write("1\n00:00:00,000 --> 00:00:11,500\nhello world\n\n2\n"
                        "00:00:05,000 --> 00:00:11,500\nsecond line\n\n")
            args = ["ffmpeg", "-v", "error", "-y",
                    "-f", "lavfi", "-i", "testsrc=duration=12:size=640x480:rate=10",
                    "-f", "lavfi", "-i", "sine=duration=12:frequency=440"]
            maps = ["-map", "0:v", "-map", "1:a"]
            if sub_fmt:
                args += ["-i", srt]
                maps += ["-map", "2:s", "-c:s", sub_fmt]
            args += maps + ["-pix_fmt", "yuvj420p", "-shortest", path]
            _run(args, 60)
            return os.path.exists(path)
        return False
    except Exception:
        return False


class MediaPool:
    """Creates synthetic inputs on demand, keyed by referenced filename."""

    def __init__(self, base_dir):
        self.base = base_dir
        self.made = {}

    def get(self, fn, is_concat=False):
        if fn in self.made:
            return self.made[fn]
        if is_glob(fn) or is_sequence(fn):
            path = os.path.join(self.base, "_pat", os.path.basename(fn))
        else:
            path = os.path.join(self.base, re.sub(r"[^\w.\-]", "_", fn))
        ok = make_input_file(path, is_concat=is_concat)
        self.made[fn] = path if ok else None
        return self.made[fn]


def is_static_only(cmd):
    text = cmd
    if any(m in text for m in STATIC_ONLY_MARKERS):
        return True
    try:
        toks = shlex.split(cmd)
    except ValueError:
        return False
    return any(not t.startswith("-") and t.split("=")[0].split(":")[0] in LAVFI_SOURCES
               for t in toks) and any(t == "-f" and i + 1 < len(toks) and toks[i + 1] == "lavfi"
                                      for i, t in enumerate(toks)) and False


def static_validate(cmd):
    """Problems that mean the command cannot work on any ffmpeg build (empty = OK)."""
    caps = capabilities()
    problems = []
    for m in re.finditer(r"-v(?:f)?\s+(?:(['\"])(.*?)\1|(\S+))|-af\s+(?:(['\"])(.*?)\4|(\S+))|"
                         r"-filter_complex\s+(?:(['\"])(.*?)\7|(\S+))", cmd):
        chain = next((g for g in m.groups() if g), "")
        for part in re.split(r"[,;]", chain):
            n = part.strip().split("=")[0].split("[")[0].strip()
            if n and re.fullmatch(r"[a-z0-9_]+", n) and n not in caps["filters"]:
                problems.append(f"filter not found: {n}")
    for m in re.finditer(r"(?:-c:v|-c:a|-vcodec|-acodec)\s+(\S+)", cmd):
        enc = m.group(1)
        if enc not in ("copy", "none") and enc not in caps["encoders"]:
            problems.append(f"encoder not found: {enc}")
    return problems


def run_command(cmd, pool, timeout=12):
    """Run the command verbatim in a temp dir with synthetic inputs. Returns dict."""
    static_only = any(m in cmd for m in STATIC_ONLY_MARKERS)
    inputs = command_inputs(cmd)
    if static_only:
        probs = static_validate(cmd)
        return {"mode": "static", "ok": not probs, "reason": "; ".join(probs) or "static checks passed"}
    with tempfile.TemporaryDirectory(dir="/tmp") as td:
        try:
            missing = []
            for fn in inputs:
                is_concat = "-f concat" in cmd and ext_of(fn) == ".txt"
                src = pool.get(fn, is_concat=is_concat)
                if src is None:
                    missing.append(fn)
                    continue
                if is_sequence(fn) or is_glob(fn):
                    d = seq_dir(fn)
                    os.makedirs(os.path.join(td, d), exist_ok=True)
                    for f in os.listdir(os.path.dirname(src)):
                        shutil.copy(os.path.join(os.path.dirname(src), f),
                                    os.path.join(td, d, os.path.basename(f)))
                else:
                    dst = os.path.join(td, os.path.basename(fn))
                    if os.path.abspath(src) != os.path.abspath(dst):
                        shutil.copy(src, dst)
            if missing:
                probs = static_validate(cmd)
                if probs:
                    return {"mode": "static", "ok": False, "reason": "static: " + "; ".join(probs)}
                return {"mode": "static", "ok": True,
                        "reason": "input not creatable: " + ",".join(missing[:3])}
            p = _run(["/bin/sh", "-lc", f"cd {td} && timeout {timeout} {cmd}"], timeout + 4)
            err = p.stderr.decode(errors="replace").strip().splitlines()
            if p.returncode == 0:
                return {"mode": "run", "ok": True, "reason": ""}
            reason = err[-1] if err else f"exit {p.returncode}"
            if p.returncode == 124 or "timeout" in reason.lower():
                if any(h in cmd for h in HEAVY):
                    probs = static_validate(cmd)
                    return {"mode": "static", "ok": not probs,
                            "reason": "heavy filter: " + ("; ".join(probs) or "static checks passed")}
                return {"mode": "run", "ok": False, "reason": "timeout"}
            return {"mode": "run", "ok": False, "reason": reason[:300]}
        except Exception as e:
            return {"mode": "run", "ok": False, "reason": f"harness error: {e}"}


# ---------------------------------------------------------------- metrics

def normalize_cmd(s):
    s = s.strip().lower()
    s = s.replace('"', "'").replace("`", "")
    s = re.sub(r"\s+", " ", s)
    s = re.sub(r"\s*=\s*", "=", s)
    return s.strip()


def token_f1(ref, pred):
    r, p = ref.split(), pred.split()
    common = {}
    for t in r:
        common[t] = max(common.get(t, 0), p.count(t))
    tp = sum(min(r.count(t), p.count(t)) for t in set(r))
    prec = tp / len(p) if p else 0.0
    rec = tp / len(r) if r else 0.0
    return 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0


def extract_filters(cmd):
    out = set()
    for m in re.finditer(r"-v(?:f)?\s+(?:(['\"])(.*?)\1|(\S+))|-af\s+(?:(['\"])(.*?)\4|(\S+))|"
                         r"-filter_complex\s+(?:(['\"])(.*?)\7|(\S+))", cmd):
        chain = next((g for g in m.groups() if g), "")
        for part in re.split(r"[,;]", chain):
            n = part.strip().split("=")[0].split("[")[0].strip()
            if n and re.fullmatch(r"[a-z0-9_]+", n):
                out.add(n)
    return out


def extract_flags(cmd):
    try:
        toks = shlex.split(cmd)
    except ValueError:
        return set()
    return {t.split("=")[0] for t in toks if t.startswith("-") and len(t) > 1
            and not re.fullmatch(r"-[\d.]+", t)}


# core options that ffmpeg 7.x -h full does not list but always accept
CORE_OPTS = {
    "i", "f", "map", "map_chapters", "c", "c:v", "c:a", "c:s", "vf", "af",
    "filter_complex", "ss", "to", "t", "b", "b:v", "b:a", "ar", "ac", "vn", "an",
    "sn", "dn", "y", "n", "pix_fmt", "r", "s", "shortest", "vcodec", "acodec",
    "scodec", "frames", "q", "crf", "preset", "profile", "level", "metadata",
    "aspect", "hwaccel", "itsoffset", "loop", "update", "nostdin", "hide_banner",
    "v", "stats", "filter_threads", "max_muxing_queue_size", "movflags",
    "hls_time", "hls_playlist_type", "hls_segment_filename", "segment_time",
    "map_metadata", "map_channel", "vol", "sample_fmt", "channel_layout", "rc",
}


def hallucinated_items(cmd):
    """Flags/filters in cmd that do not exist in this ffmpeg build."""
    caps = capabilities()
    bad = []
    for f in extract_filters(cmd):
        if f not in caps["filters"]:
            bad.append(f"filter:{f}")
    for fl in extract_flags(cmd):
        base = fl.lstrip("-")
        if base not in _cap_cache.get("options", set()) and base not in CORE_OPTS:
            bad.append(f"flag:{fl}")
    return bad


def load_options():
    opts = set()
    p = _run(["ffmpeg", "-h", "full"], 15)
    for m in re.finditer(r"^\s*(-{1,2}[\w:\-]+)", p.stdout.decode(errors="replace"), re.M):
        opts.add(m.group(1).lstrip("-"))
    _cap_cache["options"] = opts
    return opts


def format_ok(pred):
    if "\n" in pred.strip() or "\r" in pred.strip():
        return False
    s = pred.strip()
    return bool(re.match(r"^ffmpeg(\s|$)", s)) and "```" not in s and len(s) > len("ffmpeg")


def classify_category(cmd):
    text = cmd
    if any(m in text for m in ("rtsp", "udp:", "rtp:", "srt:", "http://", "https://", "m3u8", "-hls")):
        return "streaming"
    if "concat" in text:
        return "concat"
    if "-ss" in text or "-to" in text or re.search(r"\s-t\s", text):
        return "trim"
    try:
        toks = shlex.split(text)
    except ValueError:
        toks = text.split()
    if "-af" in toks:
        return "audio filter"
    if "-vf" in toks or "filter_complex" in text:
        return "video filter"
    return "conversion"