Contents
Offline Video Converter is a desktop video toolkit in Python. It converts, cuts, compresses and merges files by building FFmpeg command lines, and the same core/ package sits behind a PySide6 window and an argparse CLI.
The "Hardware acceleration" checkbox in the Convert tab looks like one flag. Behind it are three separate problems: does the GPU encoder actually work, which quality flags does it take, and what happens if it fails anyway. The test suite has a name for the first one, "a listed-but-unusable" encoder, and this post is about how the code deals with it.
Listed does not mean usable
listed_encoders() in ffmpeg_wrapper.py runs ffmpeg -hide_banner -encoders, parses the names out of the table and caches the set. A name in that list is not proof. The docstring on detect_hw_encoder says it returns the first encoder that is "listed AND actually works", so a second check follows: encode a tiny clip with it.
def is_encoder_usable(name: str) -> bool:
"""Return True if ffmpeg can actually initialize this video encoder."""
if name in _usable_encoders_cache:
return _usable_encoders_cache[name]
try:
result = subprocess.run(
["ffmpeg", "-hide_banner", "-nostdin", "-y",
"-f", "lavfi", "-i", "color=c=black:s=320x240:d=0.1",
"-c:v", name, "-f", "null", "-"],
capture_output=True, text=True, timeout=20,
stdin=subprocess.DEVNULL,
)
ok = result.returncode == 0
except (subprocess.TimeoutExpired, OSError):
ok = False
_usable_encoders_cache[name] = ok
return okThe input is a generated 0.1 second black clip from the lavfi source and the output goes to the null muxer, so nothing is written to disk and no sample file is needed. A 20 second timeout bounds the probe, and a timeout counts as "not usable". The result is cached per encoder name for the life of the process.
The candidates are plain tuples per codec, for example ("h264_nvenc", "h264_amf", "h264_qsv", "h264_vaapi", "h264_videotoolbox"). detect_hw_encoder walks that tuple in order and returns the first name that is both listed and usable, so the order is the priority.
Translating one quality setting
The UI and CLI expose one number, CRF. Hardware encoders do not share a flag for it, so _quality_args in converter.py translates it.
| Encoder | Flags added in CRF mode |
|---|---|
libx264, libx265, libvpx-vp9 | -crf N |
*_nvenc | -rc vbr -cq N |
*_qsv | -global_quality N |
*_amf | -rc cqp -qp_i N -qp_p N |
*_videotoolbox | -q:v Q, with CRF rescaled to 1 to 100 |
In bitrate mode every encoder gets -b:v instead. Hardware encoders also get -pix_fmt yuv420p appended.
The tests pin this down. One passes hw_encoder="hevc_qsv" and asserts that -global_quality is present and -crf is not. Another does the same for h264_nvenc and -cq. Because an explicit hw_encoder skips detection, the assertions do not depend on which GPU the machine running them has.
Choosing an encoder
The decision is one small function.
def _video_encoder(opts: ConvertOptions) -> str:
if opts.video_codec == VideoCodec.COPY:
return "copy"
software = CODEC_MAP[opts.video_codec]
if not opts.use_hw_accel:
return software
if opts.hw_encoder:
return opts.hw_encoder
return detect_hw_encoder(opts.video_codec.value) or softwareI made detection return None instead of raising, so "no usable GPU encoder" is a normal outcome that quietly becomes the software encoder. Hardware acceleration is off by default (use_hw_accel: bool = False), and both front ends only set that one field. The CLI has --hw-accel and the GUI has the checkbox, and neither knows anything about NVENC or QSV.
Retrying in software
A probe can pass and the real encode can still fail. convert() catches that case.
try:
run_ffmpeg(args, duration=info.duration,
progress_callback=progress_callback,
cancel_check=cancel_check)
except FFmpegError:
if not _is_hardware_encoder(encoder):
raise
logger.warning("Hardware encoder %s failed; retrying with software", encoder)
fallback = replace(opts, use_hw_accel=False, hw_encoder=None)
run_ffmpeg(build_convert_args(input_path, output_path, fallback),
duration=info.duration,
progress_callback=progress_callback,
cancel_check=cancel_check)This only works cleanly because build_convert_args(input, output, opts) is a pure function that returns a list of strings. A retry is dataclasses.replace on the options plus another call. The list goes to subprocess.Popen without a shell, so there is no quoting to get wrong, and build_ffmpeg_cmd prepends -hide_banner -nostdin -y to every command.
Software failures are re-raised unchanged. FFmpegError.__str__ appends a filtered tail of FFmpeg's stderr, so the error text carries FFmpeg's own explanation, not only the exit code. signed_exit_code also turns Windows exit codes such as 4294967295 into -1.
Where this stops working
- The
except FFmpegErroris wider than I would like. Cancellation is also raised as anFFmpegError, so cancelling a hardware encode starts the software retry.cancel_checkstill returns true there, so the retry stops again on its first line of FFmpeg output. A narrower exception, or a cancel check before the retry, would be cleaner. - VAAPI is in the candidate tuples, but there are no VAAPI-specific arguments in the repo and
_quality_argshas no branch for it, so it falls through to-crf. I would treat it as unproven. - The probe cache lasts for the whole process. If a driver disappears mid-session, the cache still says the encoder is usable, and only the retry catches it.
- The detection tests return early when no hardware encoder is found, and no test forces a hardware failure, so the fallback path is not checked directly. The converter tests also request the
sample_videofixture, which needs FFmpeg, even for pure argument-building checks.
The approach fits any wrapper around a tool with optional accelerators: probe cheaply, translate settings in one place, and keep a slower path that always works. It is only as reliable as the exceptions you let trigger the slow path.
Found this useful? Share it with your team.