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

+29
View File
@@ -2,6 +2,35 @@
给下一个会话的交接。**权威运行器:`scripts/library_run.py`**(不要再恢复旧的 `hevc_lib.py`)。
## 2026-10-14:tier `qsv` —— 路径做出来,质量数字留给硬件(Batch 4b-1)
**改了什么**:新增**第四个 tier `qsv`**(自己的锁 `run-qsv.lock` —— 两个不同的 ASIC 不该共用一把硬件规则锁)、
参数 `--qsv-quality` / `--qsv-preset`、以及「后端根本没起来」这类失败的可读分类。
| 位置 | 内容 |
|---|---|
| `encode()` | qsv 分支:`-c:v hevc_qsv -preset <本 build 的整数 7..1> -global_quality <q>`;**`-pix_fmt nv12`**(不是 x265 的 `yuv420p`);**不加 `-maxrate`** |
| `QSV_PRESET_ENUM` | 三个 tier 都收**同一个词**(veryfast…veryslow),**引擎翻译**成整数 7..1(本机 `-h encoder=hevc_qsv` 实测) |
| `qsv_preset_value()` | 纯函数,名字/数字都收,非法值 `ValueError`(带可选值清单) |
| `BACKEND_INIT_PATTERNS` / `backend_failure()` | ffmpeg 非 0 退出时先看**是不是初始化失败**(qsv: `MFX session`;nvenc: `nvcuda`/`No capable devices`;amf: `amfrt64.dll`)→ 状态写成 `FAIL backend qsv unavailable: …`,**不是** `FAIL ffmpeg rc=`、**不是** `FAIL quality` |
| `main()` 守卫 | `--tier/--force-tier qsv` 而缺 `--qsv-quality`/`--qsv-preset` → **在任何运行准备之前**退出非 0:「no default exists: neither has been measured on Intel hardware」 |
| 自报能力 | `CAPABILITIES_VERSION` **1→2**(形状变了:tiers 多一个、knobs/defaults 多两项)、`__version__ 1.0.0→1.1.0`;`quality_knobs` 的取值改为从 `QUALITY_KNOB_OPTIONS` 派生(5a 那轮键名是手写的,正好漏掉了 `qsv_preset`) |
**两条不能忘的规矩**:
1. **没有测过的数字不进命令**。两个旋钮**故意没有默认值**,`--capabilities` 里也如实报 `null` —— 本机没有 Intel iGPU
(自检 `no-device`),任何写死的 global_quality / preset 都是编的。4b-2 有硬件时再填。
2. **QSV 不吃 `-maxrate`**:`-global_quality` 是 ICQ 模式,MaxKbps 到底认不认得取决于驱动的 MFX 版本 —— 这台机器上
答不了这个问题(4b-2 要量的第一件事)。**闸门没松**:编码后的「输出视频码率不得超源」断言对每个 tier 都还在,
只是 QSV 会在编码后拒,而不是编到一半被掐。
**向后兼容**:纯加法。x265 / nvenc / copy 的命令行**逐字未变**(`scripts/test_qsv_tier.py` 里把它们整条 argv 断言了一遍,
就是这个用途)。回滚 = 控制面把 `implemented` 改回 `False`(引擎这条分支留着也无害)。
**验收(本机真跑)**:`python scripts/test_qsv_tier.py` **25/25 PASS**(preset 翻译、qsv 命令构造、无 `-crf`、`nv12`、
x265/nvenc 命令逐字回归、初始化失败分类、无旋钮时的拒绝且**不创建任何东西**);`scripts/test_capabilities.py`
**42/42 PASS**(新增「qsv 不得有编出来的默认值」「两个旋钮都要出现在自报里」)。控制面侧的验收在其对等文档。
## 2026-10-14:`--capabilities` —— 引擎自报能力(Batch 5a)
**改了什么**:`library_run.py` 新增 `--capabilities`(人读)与 `--capabilities --json`(机器读,**一行 ASCII
+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()
+15 -2
View File
@@ -73,11 +73,24 @@ check("contract_is_an_int", isinstance(cap.get("contract"), int) and cap["contra
check("flags_key_set", set(cap.get("flags") or {}) == {"work_dir", "stage_dir", "dest", "keep_source",
"lock_tag"}, sorted(cap.get("flags") or {}))
check("quality_knobs_key_set", set(cap.get("quality_knobs") or {}) == {"crf", "cq", "qsv_quality",
"x265_preset", "nvenc_preset"},
"qsv_preset", "x265_preset",
"nvenc_preset"},
sorted(cap.get("quality_knobs") or {}))
check("defaults_key_set", set(cap.get("defaults") or {}) == {"work", "root", "crf", "cq", "x265_preset",
"nvenc_preset"},
"nvenc_preset", "qsv_quality",
"qsv_preset"},
sorted(cap.get("defaults") or {}))
# Batch 4b-1: the QSV knobs must have NO default. `null` is the report SAYING "the caller has to supply
# a measured number" - a value here would be an invented gear, which this repo does not encode with.
check("qsv_reports_no_invented_default",
(cap.get("defaults") or {}).get("qsv_quality") is None
and (cap.get("defaults") or {}).get("qsv_preset") is None,
"%s / %s" % ((cap.get("defaults") or {}).get("qsv_quality"),
(cap.get("defaults") or {}).get("qsv_preset")))
check("qsv_knobs_are_advertised",
(cap.get("quality_knobs") or {}).get("qsv_quality") == "--qsv-quality"
and (cap.get("quality_knobs") or {}).get("qsv_preset") == "--qsv-preset",
(cap.get("quality_knobs") or {}))
check("locks_key_set", set(cap.get("locks") or {}) == {"template", "tags"},
sorted(cap.get("locks") or {}))
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Batch 4b-1: the `qsv` TIER - command construction, preset translation, and the honest refusal.
The Intel QSV ENCODE PATH exists as of this batch, but its quality has not been measured (there is no
Intel iGPU on this machine - the self-test reports `no-device`), and this repo does not encode at an
invented number. So the tier is written to be:
* selectable - `--tier qsv` is a real tier with its own lock (`run-qsv.lock`), so the control
plane can point a lane at an Intel box without touching the other tiers;
* buildable - the command takes QSV's own arguments, not x265's (this is where the pixel-format
and quality-scale traps live): `-global_quality`, `-pix_fmt nv12`, an INTEGER `-preset`;
* REFUSABLE - with no measured `--qsv-quality/--qsv-preset` it exits non-zero, says why, and has
touched nothing (no mkdir, no stage, no ledger, no byte of the source).
And - the regression half that matters more than the new code - the x265 and NVENC command lines are
UNCHANGED, byte for byte, from before this batch.
Usage: python scripts/test_qsv_tier.py exit 0 = every assertion held
"""
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import library_run as LR # noqa: E402
ENTRY = os.path.join(HERE, "library_run.py")
PY = sys.executable
checks = {}
def check(name, ok, detail=""):
checks[name] = bool(ok)
print("%-52s %s%s" % (name, "PASS" if ok else "FAIL", (" " + str(detail)) if detail else ""))
# ---------------------------------------------------------------- preset translation (pure)
def preset_cases():
got = {k: LR.qsv_preset_value(k) for k in ("veryfast", "faster", "fast", "medium", "slow",
"slower", "veryslow")}
return got
got = preset_cases()
check("preset_names_map_to_this_builds_ints",
got == {"veryfast": 7, "faster": 6, "fast": 5, "medium": 4, "slow": 3, "slower": 2,
"veryslow": 1}, got)
check("preset_accepts_a_digit", LR.qsv_preset_value("4") == 4 and LR.qsv_preset_value(3) == 3)
check("preset_normalises_case_and_space", LR.qsv_preset_value(" Medium ") == 4)
for bad in ("placebo", "", None, "9"):
try:
LR.qsv_preset_value(bad)
except ValueError as e:
check("preset_rejects_%s" % (bad or "empty"), "unknown qsv preset" in str(e) or "0-7" in str(e),
str(e)[:60])
else:
check("preset_rejects_%s" % (bad or "empty"), False, "no ValueError raised")
# ---------------------------------------------------------------- command construction
CAPTURED = {}
def fake_run(cmd, watch, stall_s=None, timeout=None):
CAPTURED["cmd"] = list(cmd)
return subprocess.CompletedProcess(cmd, 1, "", "boom: fake ffmpeg")
LR.run_watched = fake_run
parser = LR.build_parser()
INFO = {"acodec": "aac"}
def cmd_for(argv, vbps=1_500_000):
a = parser.parse_args(argv)
LR.encode("C:/tmp/in.mp4", "C:/tmp/out.mp4", INFO, a, a.force_tier or a.tier or "x265", vbps)
return CAPTURED["cmd"]
qsv = cmd_for(["--tier", "qsv", "--force-tier", "qsv", "--qsv-quality", "30", "--qsv-preset",
"medium"])
def argval(cmd, flag):
return cmd[cmd.index(flag) + 1] if flag in cmd else None
check("qsv_uses_hevc_qsv", argval(qsv, "-c:v") == "hevc_qsv", argval(qsv, "-c:v"))
check("qsv_preset_is_the_translated_int", argval(qsv, "-preset") == "4", argval(qsv, "-preset"))
check("qsv_quality_is_global_quality", argval(qsv, "-global_quality") == "30")
check("qsv_has_no_crf", "-crf" not in qsv, "QSV has no -crf at all; the scales are different")
check("qsv_pix_fmt_is_nv12", argval(qsv, "-pix_fmt") == "nv12", argval(qsv, "-pix_fmt"))
check("qsv_keeps_the_playability_flags",
argval(qsv, "-tag:v") == "hvc1" and argval(qsv, "-fps_mode") == "cfr"
and argval(qsv, "-profile:v") == "main")
check("qsv_has_no_maxrate", "-maxrate" not in qsv,
"whether MaxKbps binds in ICQ mode is a hardware question - the post-encode size gate still runs")
check("qsv_audio_is_copied_when_it_is_aac", argval(qsv, "-c:a") == "copy")
# the quality ladder must still work on this tier: one step better = one lower global_quality
a = parser.parse_args(["--tier", "qsv", "--qsv-quality", "30", "--qsv-preset", "medium"])
LR.encode("C:/tmp/in.mp4", "C:/tmp/out.mp4", INFO, a, "qsv", 1_500_000, q_off=2)
check("qsv_quality_ladder_step", argval(CAPTURED["cmd"], "-global_quality") == "28",
argval(CAPTURED["cmd"], "-global_quality"))
# ---- the regression: the OTHER two tiers' command lines are untouched -----------------------
x265 = cmd_for(["--tier", "x265", "--force-tier", "x265", "--crf", "26", "--x265-preset", "medium",
"--pools", "10"])
check("x265_command_is_unchanged",
x265 == [LR.FFMPEG, "-y", "-hide_banner", "-loglevel", "warning", "-stats",
"-i", "C:/tmp/in.mp4", "-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "0",
"-c:v", "libx265", "-preset", "medium", "-crf", "26", "-x265-params", "pools=10",
"-maxrate", "1500000", "-bufsize", "3750000",
"-profile:v", "main", "-pix_fmt", "yuv420p", "-tag:v", "hvc1", "-fps_mode", "cfr",
"-c:a", "copy", "-movflags", "+faststart", "C:/tmp/out.mp4"], x265)
nvenc = cmd_for(["--tier", "nvenc", "--force-tier", "nvenc", "--cq", "31", "--nvenc-preset", "p7"])
check("nvenc_command_is_unchanged",
nvenc == [LR.FFMPEG, "-y", "-hide_banner", "-loglevel", "warning", "-stats",
"-i", "C:/tmp/in.mp4", "-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "0",
"-c:v", "hevc_nvenc", "-preset", "p7", "-tune", "hq", "-rc", "vbr",
"-cq", "31", "-b:v", "0", "-spatial-aq", "1", "-temporal-aq", "1",
"-rc-lookahead", "32", "-b_ref_mode", "middle", "-bf", "4", "-g", "240",
"-maxrate", "1500000", "-bufsize", "3750000",
"-profile:v", "main", "-pix_fmt", "yuv420p", "-tag:v", "hvc1", "-fps_mode", "cfr",
"-c:a", "copy", "-movflags", "+faststart", "C:/tmp/out.mp4"], nvenc)
# ---------------------------------------------------------------- the failure classifier
which, line = LR.backend_failure("qsv", "Some noise\n[mfx] Error creating a MFX session: -9\nmore")
check("mfx_session_is_a_backend_failure", which == "qsv" and "MFX session" in line, (which, line))
which2, _ = LR.backend_failure("qsv", "Conversion failed!\nInvalid argument")
check("a_real_encode_failure_stays_a_real_failure", which2 is None)
which3, _ = LR.backend_failure("nvenc", "Cannot load nvcuda.dll")
check("nvenc_init_failure_is_recognised", which3 == "nvenc")
check("an_empty_stderr_is_not_a_backend_claim", LR.backend_failure("qsv", "")[0] is None)
# ---------------------------------------------------------------- the refusal (real process)
with tempfile.TemporaryDirectory(prefix="qsvtier_") as tmp:
work = os.path.join(tmp, "work")
os.makedirs(work)
src = os.path.join(tmp, "clip.mp4")
with open(src, "wb") as fh:
fh.write(b"\x00" * 4096)
before = os.path.getsize(src)
p = subprocess.run([PY, "-u", ENTRY, "--work-dir", work, "--path", src, "--tier", "qsv",
"--force-tier", "qsv"],
capture_output=True, text=True, encoding="utf-8", errors="replace")
check("qsv_without_measured_knobs_refuses", p.returncode != 0, "rc=%d" % p.returncode)
check("the_refusal_names_the_missing_numbers",
"backend qsv unmeasured" in (p.stdout or "") and "--qsv-quality" in (p.stdout or ""),
(p.stdout or "").strip()[:120])
check("the_refusal_touches_nothing",
os.listdir(work) == [] and os.path.getsize(src) == before,
"work=%s src=%d" % (os.listdir(work), os.path.getsize(src)))
p2 = subprocess.run([PY, "-u", ENTRY, "--work-dir", work, "--path", src, "--tier", "qsv",
"--qsv-quality", "30", "--qsv-preset", "ultrafast"],
capture_output=True, text=True, encoding="utf-8", errors="replace")
check("a_typo_in_the_preset_is_readable", p2.returncode != 0 and "unknown qsv preset" in
(p2.stdout or ""), (p2.stdout or "").strip()[:120])
print("\n%d/%d checks passed" % (sum(checks.values()), len(checks)))
sys.exit(0 if all(checks.values()) else 1)