Batch 4b-1:引擎新增 tier qsv(自己的锁 + -global_quality + 整数 preset + nv12)

- 新 tier `qsv`:--tier/--force-tier 的 choices 加 qsv,锁是 run-qsv.lock(两个不同 ASIC 不共用一把
  硬件规则锁),命令 -c:v hevc_qsv -preset <本 build 整数 7..1> -global_quality <q> -pix_fmt nv12;
  不加 -maxrate(ICQ 模式下 MaxKbps 是否生效取决于 MFX 版本,本机无法验证;编码后的「不得超源码率」
  断言仍在)。
- QSV_PRESET_ENUM + qsv_preset_value():三个 tier 收同一批 preset 词,引擎翻译成本 build 的整数。
- BACKEND_INIT_PATTERNS + backend_failure():ffmpeg 非 0 退出时把「后端没起来」认出来,状态写成
  FAIL backend qsv unavailable: …(不是 FAIL ffmpeg rc=、不是 FAIL quality)。
- main() 守卫:--tier qsv 缺 --qsv-quality/--qsv-preset 就在任何运行准备之前退出非 0(两个旋钮故意
  无默认值:本机没有 Intel 硬件,写死的数字就是编的)。
- capabilities:CAPABILITIES_VERSION 1→2、__version__ 1.1.0;quality_knobs 取值改从 QUALITY_KNOB_OPTIONS
  派生(5a 手写的键名正好漏了 qsv_preset)。
- scripts/test_qsv_tier.py 25 例(含 x265/nvenc 整条 argv 的逐字回归);test_capabilities.py 42/42。
This commit is contained in:
hoelee committed 2026-10-14 11:40:29 +08:00
1 parent b69c52135e
commit 83f9cbc48f
4 files changed
+353 -14

No files matched your search

+146 -12
View File
@@ -143,6 +143,25 @@ X265_PRESET = "medium" # ... and the CPU is the contended resource here (thr
# by side), so the x265 default stays `medium`; --x265-preset / the dashboard can move it.
X265_POOLS = 10 # E-cores only (affinity 0x3FF0000)
E_CORE_MASK = 0x3FF0000
# ---- Intel QSV (Batch 4b-1): the PATH exists, the QUALITY NUMBER does not -----------------------
# `hevc_qsv` is a THIRD, independent encoder: its speed dial is `-preset`, an INTEGER 0-7 (read out of
# this build's own `-h encoder=hevc_qsv`), and it has no `-crf` at all - quality goes through
# `-global_quality`, whose scale is NOT x265's crf and NOT nvenc's cq. So this backend gets its own two
# knobs and its own tier (hence its own `run-qsv.lock`: "one <vendor> job at a time" is a HARDWARE rule
# and two different ASICs must not share one lock).
#
# ⚠ Both knobs ship with NO DEFAULT, on purpose. Every gear in this repo was chosen from measurements
# on real hardware, and there is no Intel iGPU on this machine (the self-test reports `no-device`), so
# any number written here would be invented. A run that asks for the tier without both values REFUSES
# with a readable reason instead of encoding at a made-up quality; Batch 4b-2 fills them in on a
# machine that has the hardware.
QSV_PRESET_ENUM = {"veryfast": 7, "faster": 6, "fast": 5, "medium": 4, "slow": 3, "slower": 2,
"veryslow": 1} # name -> this build's integer, so all three tiers accept the SAME
# word in jobs.yaml and the ENGINE does the translation
QSV_PIX_FMT = "nv12" # `hevc_qsv`'s supported pixel formats start at nv12 - `yuv420p` is not in the
# list, and copying x265's `-pix_fmt yuv420p` fails or silently goes software
SSIM_TARGET = 0.985 # per-frame floor vs the source window (480x270 comparison)
SSIM_WINDOW = 60 # seconds sampled for the SSIM gate
BAD_FRAME_SSIM = 0.85 # a frame this far below the source is 'bad' for the share test
@@ -1033,6 +1052,61 @@ def affinity_mask() -> int:
return 0
# ---- backend-init failures: a REFUSAL to start, not a quality verdict ----------------------------
# Measured on this machine (2026-10-14): no Intel iGPU -> `Error creating a MFX session: -9`; no AMD
# runtime -> `DLL amfrt64.dll failed to open`. Both reach the engine as a plain non-zero ffmpeg exit,
# and `FAIL ffmpeg rc=1 ...` reads like a QUALITY problem to everything downstream (the queue's panel
# offers gear remedies for those, and each attempt burns an attempt count). Recognising the SHAPE lets
# the status say what it is: the backend never started. Only messages seen in the field are listed -
# a guess would mislabel a genuine encode failure.
BACKEND_INIT_PATTERNS = {
"qsv": ("error creating a mfx session", "cannot load libmfx", "mfx session", "mfx plugin"),
"nvenc": ("cannot load nvcuda", "no capable devices found", "openencodesessionex failed",
"initializeencoder failed"),
"amf": ("amfrt64.dll", "amf failed", "cannot load amf"),
}
def backend_failure(tier, stderr):
"""(backend, line) when ffmpeg's failure is an INIT failure of `tier`'s own encoder.
("qsv", "Error creating a MFX session: -9") on a machine with no Intel iGPU; (None, "") for
anything else - a genuine encode failure must keep its own, honest diagnosis.
"""
low = (stderr or "").lower()
if not low:
return None, ""
for pat in BACKEND_INIT_PATTERNS.get(tier or "", ()):
if pat in low:
line = next((l.strip() for l in (stderr or "").splitlines() if pat in l.lower()), "")
return tier, (line or stderr.strip().splitlines()[0])[:200]
return None, ""
def qsv_preset_value(name):
"""The QSV `-preset` INTEGER for a preset NAME (`veryfast`..`veryslow` -> 7..1, this build).
All three tiers take the SAME word in `jobs.yaml` and the ENGINE translates, so a gear is portable
across backends instead of depending on which vendor's numbering the file was written against. A
digit is accepted as-is (0-7) for a hand-run engine.
"""
if isinstance(name, int) and not isinstance(name, bool):
v = name
else:
key = str(name if name is not None else "").strip().lower()
if key.isdigit():
v = int(key)
elif key in QSV_PRESET_ENUM:
v = QSV_PRESET_ENUM[key]
else:
raise ValueError("unknown qsv preset %r - use one of %s"
% (name, ", ".join(sorted(QSV_PRESET_ENUM,
key=lambda k: QSV_PRESET_ENUM[k]))))
if not 0 <= v <= 7:
raise ValueError("qsv preset must be within this build's -preset range 0-7, got %r" % (name,))
return v
def encode(src_local, dst_local, info, args, tier, vbps, q_off=0):
cmd = [FFMPEG, "-y", "-hide_banner", "-loglevel", "warning", "-stats",
"-i", src_local, "-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "0"]
@@ -1047,14 +1121,27 @@ def encode(src_local, dst_local, info, args, tier, vbps, q_off=0):
# weighted_pred are REJECTED here)
"-spatial-aq", "1", "-temporal-aq", "1", "-rc-lookahead", "32",
"-b_ref_mode", "middle", "-bf", "4", "-g", "240"]
elif tier == "qsv":
# Intel Quick Sync (Batch 4b-1). Two things are deliberately NOT copied from the x265 line:
# there is no `-crf` (quality is `-global_quality`, a different scale - see QSV_PRESET_ENUM's
# note), and `-pix_fmt` has to be nv12 further down. `-preset` is an INTEGER here, translated
# from the same words the other tiers accept.
cmd += ["-c:v", "hevc_qsv", "-preset", str(qsv_preset_value(args.qsv_preset)),
"-global_quality", str(max(1, int(args.qsv_quality) - q_off))]
else:
cmd += ["-c:v", "libx265", "-preset", args.x265_preset, "-crf", str(max(1, args.crf - q_off)),
"-x265-params", "pools=%d" % args.pools]
if tier != "copy" and vbps > 0:
if tier not in ("copy", "qsv") and vbps > 0:
# Hard ceiling at the source's own video bitrate: the output physically cannot grow.
# QSV is excluded because whether MaxKbps binds in its ICQ mode (`-global_quality`) depends on
# the driver's MFX version - a hardware question this machine cannot answer (Batch 4b-2
# measures it). The POST-ENCODE assertion below still refuses any output that grew, so
# "never bigger" keeps its gate on every tier; QSV just gets refused after the encode instead
# of being capped during it.
cmd += ["-maxrate", str(int(vbps * SIZE_CEIL)), "-bufsize", str(int(vbps * SIZE_CEIL * 2.5))]
if tier != "copy":
cmd += ["-profile:v", "main", "-pix_fmt", "yuv420p", "-tag:v", "hvc1", "-fps_mode", "cfr"]
cmd += ["-profile:v", "main", "-pix_fmt", QSV_PIX_FMT if tier == "qsv" else "yuv420p",
"-tag:v", "hvc1", "-fps_mode", "cfr"]
if info["acodec"] in ("aac", "mp4a", ""):
cmd += ["-c:a", "copy"]
else:
@@ -1170,6 +1257,12 @@ def process(src, args, dest=None, origin=None):
attempt += 1
r, el = encode(loc_src, loc_out, info, args, tier, vbps, q_off)
if r.returncode != 0 or not os.path.exists(loc_out):
# A backend that never STARTED is not a bad encode (Batch 4b-1): say so, so the queue
# records "backend unavailable" instead of offering quality remedies for an item whose
# pictures were never the problem.
which, line = backend_failure(tier, r.stderr)
if which:
return "FAIL backend %s unavailable: %s" % (which, line), None
return "FAIL ffmpeg rc=%s %s" % (r.returncode, (r.stderr or "").strip()[-300:]), None
# 3. verify the LOCAL output (structural + full decode)
ok, msg = T.verify(info, loc_out, expect_vc, "aac", check_decode=False)
@@ -1384,9 +1477,11 @@ def build_parser():
help="work root for this run: ledger.jsonl, gate_policy.json and run-*.lock "
"(default %s, this file's compiled-in constant, so a hand-run engine is "
"unchanged). An explicit value moves ALL of them." % WORK)
ap.add_argument("--tier", choices=["copy", "nvenc", "x265"],
help="only touch files classified into this tier (run tiers separately)")
ap.add_argument("--force-tier", choices=["copy", "nvenc", "x265"], default=None,
ap.add_argument("--tier", choices=["copy", "nvenc", "x265", "qsv"],
help="only touch files classified into this tier (run tiers separately). `qsv` is "
"never chosen by the bpp rule - it is a BACKEND the control plane selects, "
"and it needs --qsv-quality/--qsv-preset (no measured default yet)")
ap.add_argument("--force-tier", choices=["copy", "nvenc", "x265", "qsv"], default=None,
help="override the bpp classification for this run instead of skipping the "
"file (the control plane needs it: an owner decision can say a LEAN "
"source is still worth re-encoding, and `--tier x265` would otherwise "
@@ -1400,6 +1495,15 @@ def build_parser():
ap.add_argument("--audio", default=None,
help="audio bitrate; default = the SOURCE's own bitrate (never a fixed 256k)")
ap.add_argument("--nvenc-preset", default=NVENC_PRESET)
ap.add_argument("--qsv-quality", type=int, default=None,
help="Intel QSV quality (`-global_quality`). NO DEFAULT ON PURPOSE: the scale is "
"neither x265's crf nor nvenc's cq, and it has not been measured on real "
"Intel hardware yet (Batch 4b-2) - a run without it REFUSES instead of "
"inventing a number")
ap.add_argument("--qsv-preset", default=None,
help="Intel QSV speed dial, one of %s (this build maps them to -preset 7..1). No "
"default for the same reason as --qsv-quality"
% "/".join(sorted(QSV_PRESET_ENUM, key=lambda k: QSV_PRESET_ENUM[k])))
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--only", default=None, help="substring filter")
ap.add_argument("--path", default=None,
@@ -1436,8 +1540,18 @@ def build_parser():
# copy that can disagree with the code it describes;
# * it prints one line and exits BEFORE any run setup (no stage sweep, no mkdir, no lock), so asking
# costs nothing and changes nothing.
CAPABILITIES_VERSION = 1 # bump when the SHAPE or the MEANING of the report changes
__version__ = "1.0.0" # human/ledger build id; the control plane only prints it
CAPABILITIES_VERSION = 2 # bump when the SHAPE or the MEANING of the report changes
# (1 = Batch 5a introduced it; 2 = 4b-1 added the `qsv` tier and its two
# knobs, so `tiers`/`quality_knobs`/`defaults` all gained entries)
__version__ = "1.1.0" # human/ledger build id; the control plane only prints it
# Which options are quality dials, and their names in the report. The NAME->option mapping has to be
# written down (only a human knows which flags are quality knobs), but every VALUE is read back out of
# the real parser, so a renamed or deleted option shows up as `null` instead of a stale string. Adding a
# backend's knobs means adding a line HERE - that is the one place to look.
QUALITY_KNOB_OPTIONS = {"crf": "--crf", "cq": "--cq", "qsv_quality": "--qsv-quality",
"qsv_preset": "--qsv-preset", "x265_preset": "--x265-preset",
"nvenc_preset": "--nvenc-preset"}
def capabilities(ap=None):
@@ -1461,15 +1575,16 @@ def capabilities(ap=None):
("dest", "--dest"),
("keep_source", "--keep-source"),
("lock_tag", "--lock-tag"))},
"quality_knobs": {"crf": knob("--crf"), "cq": knob("--cq"),
"qsv_quality": knob("--qsv-quality"),
"x265_preset": knob("--x265-preset"),
"nvenc_preset": knob("--nvenc-preset")},
"quality_knobs": {k: knob(v) for k, v in sorted(QUALITY_KNOB_OPTIONS.items())},
"defaults": {"work": WORK, "root": ROOT,
"crf": getattr(act("--crf"), "default", None),
"cq": getattr(act("--cq"), "default", None),
"x265_preset": getattr(act("--x265-preset"), "default", None),
"nvenc_preset": getattr(act("--nvenc-preset"), "default", None)},
"nvenc_preset": getattr(act("--nvenc-preset"), "default", None),
# None here is INFORMATION, not an omission: it says "this build has no measured
# number for this backend, the caller must supply one" (Batch 4b-1/4b-2).
"qsv_quality": getattr(act("--qsv-quality"), "default", None),
"qsv_preset": getattr(act("--qsv-preset"), "default", None)},
"locks": {"template": LOCK_TEMPLATE, "tags": "--lock-tag" in opts},
}
@@ -1484,6 +1599,12 @@ def print_capabilities(cap):
print(" defaults : work=%s root=%s crf=%s cq=%s x265_preset=%s nvenc_preset=%s" % (
cap["defaults"]["work"], cap["defaults"]["root"], cap["defaults"]["crf"],
cap["defaults"]["cq"], cap["defaults"]["x265_preset"], cap["defaults"]["nvenc_preset"]))
d = cap["defaults"]
if "qsv_quality" in d or "qsv_preset" in d:
print(" qsv : quality=%s preset=%s%s" % (
d.get("qsv_quality"), d.get("qsv_preset"),
" (no measured default - the caller must supply both)" if not d.get("qsv_quality")
else ""))
print(" locks : %s%s" % (cap["locks"]["template"],
" (own lock per --lock-tag)" if cap["locks"]["tags"] else ""))
@@ -1510,6 +1631,19 @@ def main():
if args.stage_dir:
STAGE = os.path.abspath(args.stage_dir)
log("=== stage dir: %s (ledger + locks stay in %s)" % (STAGE, WORK))
if "qsv" in (args.tier, args.force_tier):
# The QSV PATH exists since Batch 4b-1, but its QUALITY has not been measured on real Intel
# hardware, and this repo does not encode at an invented number. Refuse HERE - before the stage
# sweep, before any mkdir, before a byte of the source is touched - with something actionable.
if not args.qsv_quality or not args.qsv_preset:
log("FAIL backend qsv unmeasured: pass both --qsv-quality and --qsv-preset (no default "
"exists: neither has been measured on Intel hardware - Batch 4b-2)")
sys.exit(1)
try:
qsv_preset_value(args.qsv_preset)
except ValueError as e:
log("FAIL backend qsv: %s" % e)
sys.exit(1)
os.makedirs(STAGE, exist_ok=True)
swept = sweep_stage()