#!/usr/bin/env python3
"""Run the Sublimearts.io encoder test on your own PC.

Article (method, results, limits): https://www.sublimearts.io/en/blog/nvenc-vs-x264-file-size-test

What it does
  1. Downloads the first 10 seconds of four public-domain 1080p60 gameplay captures from
     https://media.xiph.org/video/derf/ (about 7.5 GB in total).
  2. Makes an "OBS-style recording" of each: NVENC H.264 at CQP 16 (x264 CRF 16 if you have no NVENC).
  3. Re-encodes every recording with each encoder your PC has, at several quality settings,
     and scores each result with VMAF against the recording.
  4. Times each encoder on the four recordings joined together (3 runs, median).

Needs: Python 3.9+, and ffmpeg + ffprobe on PATH built with libvmaf (the gyan.dev "full" build on
Windows has it). Nothing is uploaded; the only network use is the clip download.

Tested on an Intel + NVIDIA laptop. The AMD (AMF) and hardware AV1 settings could not be
tested there: if one of them misbehaves on your card, please say so.

Usage:  python encoder_test.py <empty folder with ~25 GB free>
Output: <folder>/results.csv  (every encode)  and  <folder>/speed.csv
"""
import csv
import json
import os
import platform
import statistics
import subprocess
import sys
import time
import urllib.request

if len(sys.argv) != 2:
    sys.exit(__doc__)
ROOT = os.path.abspath(sys.argv[1])
CLIPS = ["CSGO", "GTAV", "MINECRAFT", "Hearthstone"]
FRAMES = 600
Y4M_BYTES = FRAMES * 3110406 + 200
DIRS = {k: os.path.join(ROOT, k) for k in ("clips", "rec", "tmp")}
for d in DIRS.values():
    os.makedirs(d, exist_ok=True)

# Without -maxrate, hevc_nvenc can cap 1080p60 near 16-20 Mbit/s (level 4.1), so low -cq values do nothing.
NV = ["-preset", "p5", "-tune", "hq", "-rc", "vbr", "-b:v", "0", "-multipass", "qres",
      "-maxrate", "200M", "-bufsize", "400M"]
QSV = ["-preset", "medium"]


def one(flag):
    return lambda q: [flag, str(q)]


def amf(q):
    return ["-rc", "cqp", "-qp_i", str(q), "-qp_p", str(q)]


# id -> (codec args, quality-arguments builder, quality values)
ENCODERS = {
    "x264_veryfast": (["-c:v", "libx264", "-preset", "veryfast"], one("-crf"), [15, 18, 21, 23, 24, 27, 30, 33]),
    "x264_medium": (["-c:v", "libx264", "-preset", "medium"], one("-crf"), [18, 21, 23, 24, 27, 30, 33]),
    "x265_medium": (["-c:v", "libx265", "-preset", "medium", "-x265-params", "log-level=error"], one("-crf"), [18, 21, 23, 24, 27, 30, 33]),
    "svtav1_8": (["-c:v", "libsvtav1", "-preset", "8"], one("-crf"), [20, 26, 32, 38, 44, 50]),
    "h264_nvenc": (["-c:v", "h264_nvenc"] + NV, one("-cq"), [19, 23, 27, 31, 35, 39]),
    "hevc_nvenc": (["-c:v", "hevc_nvenc"] + NV, one("-cq"), [20, 23, 24, 28, 32, 36, 40]),
    "av1_nvenc": (["-c:v", "av1_nvenc"] + NV, one("-cq"), [23, 28, 33, 38, 43, 48]),
    "h264_qsv": (["-c:v", "h264_qsv"] + QSV, one("-global_quality"), [18, 22, 23, 26, 30, 34, 38]),
    "hevc_qsv": (["-c:v", "hevc_qsv"] + QSV, one("-global_quality"), [18, 22, 23, 26, 30, 34, 38]),
    "av1_qsv": (["-c:v", "av1_qsv"] + QSV, one("-global_quality"), [18, 23, 28, 33, 38, 43]),
    "h264_amf": (["-c:v", "h264_amf", "-quality", "balanced"], amf, [18, 22, 23, 26, 30, 34, 38]),
    "hevc_amf": (["-c:v", "hevc_amf", "-quality", "balanced"], amf, [18, 22, 23, 26, 30, 34, 38]),
    "av1_amf": (["-c:v", "av1_amf", "-quality", "balanced"], amf, [60, 80, 100, 120, 140, 160]),
}


def run(cmd, cwd=None):
    p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, errors="replace")
    if p.returncode != 0:
        raise RuntimeError(" ".join(cmd) + "\n" + p.stderr[-1500:])
    return p


def pixfmt(eid):
    return "nv12" if eid.endswith(("_qsv", "_amf")) else "yuv420p"


def works(eid):
    args, qargs, qs = ENCODERS[eid]
    try:
        run(["ffmpeg", "-v", "error", "-nostdin", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=30", "-frames:v", "10",
             *args, *qargs(qs[2]), "-pix_fmt", pixfmt(eid), "-f", "null", "-"])
        return True
    except RuntimeError:
        return False


def warm(path):
    with open(path, "rb") as f:
        while f.read(1 << 24):
            pass


def download(clip):
    dst = os.path.join(DIRS["clips"], clip + ".y4m")
    if os.path.exists(dst):
        return dst
    url = f"https://media.xiph.org/video/derf/twitch/y4m/{clip}.y4m"
    part = dst + ".part"
    print("downloading", clip, "(about 1.9 GB)", flush=True)
    req = urllib.request.Request(url, headers={"Range": f"bytes=0-{Y4M_BYTES}", "User-Agent": "encoder-test"})
    with urllib.request.urlopen(req, timeout=60) as r, open(part, "wb") as f:
        while True:
            chunk = r.read(1 << 22)
            if not chunk:
                break
            f.write(chunk)
    run(["ffmpeg", "-v", "error", "-nostdin", "-y", "-i", part, "-frames:v", str(FRAMES), "-f", "yuv4mpegpipe", dst])
    os.remove(part)
    return dst


def vmaf(dist, ref):
    graph = ("[0:v]setpts=PTS-STARTPTS,format=yuv420p[d];[1:v]setpts=PTS-STARTPTS,format=yuv420p[r];"
             f"[d][r]libvmaf=n_threads={os.cpu_count() or 4}:log_fmt=json:log_path=vmaf.json")
    run(["ffmpeg", "-v", "error", "-nostdin", "-i", dist, "-i", ref, "-lavfi", graph, "-f", "null", "-"], cwd=DIRS["tmp"])
    with open(os.path.join(DIRS["tmp"], "vmaf.json"), encoding="utf-8") as f:
        d = json.load(f)
    frames = sorted(fr["metrics"]["vmaf"] for fr in d["frames"])
    return d["pooled_metrics"]["vmaf"]["mean"], frames[max(0, int(len(frames) * 0.01) - 1)]


def main():
    available = [e for e in ENCODERS if works(e)]
    print("encoders found:", ", ".join(available), flush=True)
    recorder = (["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq", "-rc", "constqp", "-qp", "16"]
                if "h264_nvenc" in available else ["-c:v", "libx264", "-preset", "veryfast", "-crf", "16"])
    recs = {}
    for clip in CLIPS:
        src = download(clip)
        recs[clip] = os.path.join(DIRS["rec"], clip + ".mp4")
        if not os.path.exists(recs[clip]):
            run(["ffmpeg", "-v", "error", "-nostdin", "-y", "-i", src, "-an", *recorder, "-pix_fmt", "yuv420p", recs[clip]])

    rows = []
    fields = ["clip", "encoder", "quality", "bytes", "recording_bytes", "vmaf_mean", "vmaf_1pct_low"]
    with open(os.path.join(ROOT, "results.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        for clip, rec in recs.items():
            warm(rec)
            for eid in available:
                args, qargs, qs = ENCODERS[eid]
                for q in qs:
                    out = os.path.join(DIRS["tmp"], "out.mp4")
                    run(["ffmpeg", "-v", "error", "-nostdin", "-y", "-i", rec, "-an", *args, *qargs(q), "-pix_fmt", pixfmt(eid), out])
                    mean, low = vmaf(out, rec)
                    row = dict(zip(fields, [clip, eid, q, os.path.getsize(out), os.path.getsize(rec), round(mean, 3), round(low, 2)]))
                    rows.append(row)
                    w.writerow(row)
                    f.flush()
                    print(f"{clip:12s} {eid:14s} q={q:<4d} {row['bytes']/1e6:8.2f} MB  VMAF {mean:6.2f}", flush=True)

    joined = os.path.join(DIRS["rec"], "joined.mp4")
    with open(os.path.join(DIRS["rec"], "list.txt"), "w") as f:
        f.writelines(f"file '{c}.mp4'\n" for c in CLIPS)
    run(["ffmpeg", "-v", "error", "-nostdin", "-y", "-f", "concat", "-safe", "0", "-i", "list.txt", "-c", "copy", "joined.mp4"], cwd=DIRS["rec"])
    warm(joined)
    total = FRAMES * len(CLIPS)
    with open(os.path.join(ROOT, "speed.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["encoder", "quality", "frames", "median_seconds", "fps", "pc"])
        for eid in available:
            args, qargs, qs = ENCODERS[eid]
            q = min(qs, key=lambda v: abs(statistics.mean(r["vmaf_mean"] for r in rows if r["encoder"] == eid and r["quality"] == v) - 95))
            out = os.path.join(DIRS["tmp"], "speed.mp4")
            cmd = ["ffmpeg", "-v", "error", "-nostdin", "-y", "-i", joined, "-an", *args, *qargs(q), "-pix_fmt", pixfmt(eid), out]
            run(cmd)  # warm-up, not counted
            times = []
            for _ in range(3):
                time.sleep(8)
                t = time.perf_counter()
                run(cmd)
                times.append(time.perf_counter() - t)
            secs = statistics.median(times)
            w.writerow([eid, q, total, round(secs, 3), round(total / secs, 1), f"{platform.processor()} / {platform.system()}"])
            f.flush()
            print(f"speed {eid:14s} q={q} {total/secs:7.1f} fps", flush=True)
    print("\nDone. results.csv and speed.csv are in", ROOT)
    print("Want your GPU added to the article's table? Send both files, plus your CPU and GPU names, to hello@sublimearts.io")


if __name__ == "__main__":
    main()
