"""Hardware video encoders that actually encode a frame on this host.""" from __future__ import annotations import functools import os import re import subprocess from .media_io import FFMPEG CANDIDATE = re.compile(r"^\s*V\S*\s+((?:h264|hevc|av1)_(?:nvenc|vaapi|qsv|amf|videotoolbox|v4l2m2m))\s") RENDER_NODE = "/dev/dri/renderD128" def _works(name: str) -> bool: argv = [FFMPEG, "-v", "error", "-nostdin"] if name.endswith("_vaapi"): if not os.path.exists(RENDER_NODE): return False argv += ["-vaapi_device", RENDER_NODE] argv += ["-f", "lavfi", "-i", "color=c=black:s=256x256:d=0.1", "-frames:v", "1"] if name.endswith("_vaapi"): argv += ["-vf", "format=nv12,hwupload"] argv += ["-c:v", name, "-f", "null", "-"] try: return subprocess.run(argv, capture_output=True, timeout=15, shell=False).returncode == 0 except (OSError, subprocess.TimeoutExpired): return False @functools.cache def hardware_encoders() -> tuple[str, ...]: try: listing = subprocess.run( [FFMPEG, "-hide_banner", "-encoders"], capture_output=True, timeout=15, shell=False, text=True ).stdout except (OSError, subprocess.TimeoutExpired): return () names = [m.group(1) for line in listing.splitlines() if (m := CANDIDATE.match(line))] return tuple(name for name in names if _works(name))