fix(nvenc): force yuv420p output — RGB pipe input made nvenc emit GBR-colorspace H.264 that web players render with swapped colors

This commit is contained in:
juancarlos.cavero 2026-07-18 02:00:18 +02:00
parent 79e1ef707d
commit 913c461b9b
2 changed files with 15 additions and 6 deletions

View file

@ -27,14 +27,19 @@ _X264_ARGS = {
# NVENC -cq is not 1:1 with x264 CRF: benchmarked on the prod GPU (RTX 4000
# Ada), cq ≈ crf + 7 lands in the same file-size ballpark, with vbr + AQ for
# quality. Presets p1-p7: p5 ≈ "medium", p4 ≈ "fast".
# -pix_fmt yuv420p is REQUIRED: with RGB input (the bgr24 rawvideo pipe from
# OpenCV) nvenc otherwise emits H.264 in gbrp/GBR colorspace, which ffmpeg
# reads fine but web players render as a magenta/green mess.
_NVENC_ARGS = {
QUALITY: ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
"-rc", "vbr", "-cq", "25", "-b:v", "0",
"-spatial-aq", "1", "-temporal-aq", "1"],
"-spatial-aq", "1", "-temporal-aq", "1", "-pix_fmt", "yuv420p"],
QUALITY_FAST: ["-c:v", "h264_nvenc", "-preset", "p4", "-tune", "hq",
"-rc", "vbr", "-cq", "25", "-b:v", "0", "-spatial-aq", "1"],
"-rc", "vbr", "-cq", "25", "-b:v", "0", "-spatial-aq", "1",
"-pix_fmt", "yuv420p"],
DELIVERY: ["-c:v", "h264_nvenc", "-preset", "p4",
"-rc", "vbr", "-cq", "29", "-b:v", "0", "-spatial-aq", "1"],
"-rc", "vbr", "-cq", "29", "-b:v", "0", "-spatial-aq", "1",
"-pix_fmt", "yuv420p"],
}
_probe_lock = threading.Lock()

View file

@ -37,9 +37,13 @@ def test_unknown_tier_raises():
def test_nvenc_mode_uses_nvenc_when_probe_passes(monkeypatch):
monkeypatch.setenv("FFMPEG_ENCODER", "nvenc")
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True)
args = video_encode_args(QUALITY)
for tier in (QUALITY, QUALITY_FAST, DELIVERY):
args = video_encode_args(tier)
assert args[:2] == ["-c:v", "h264_nvenc"]
assert "-cq" in args
# Without an explicit yuv420p, RGB input makes nvenc emit GBR-space
# H.264 that web players render with wrong colors.
assert args[-2:] == ["-pix_fmt", "yuv420p"]
def test_nvenc_mode_falls_back_to_x264_when_probe_fails(monkeypatch):