clipwright/ffmpeg_utils.py
juancarlos.cavero 719d444139 feat: GPU pipeline — Parakeet ASR backend with whisper fallback + NVENC encoder helper
- transcribe_backends.py: parakeet-tdt-0.6b-v3 (onnx-asr, VAD+timestamps) as
  selectable backend (TRANSCRIBE_BACKEND), token->word reconstruction keeping
  the leading-space convention, absolute timestamps, native floats, language
  detection via py3langid, and automatic whisper fallback (errors, empty
  output, or language outside parakeet's 25).
- whisper singleton + ASR GPU semaphore (model stays resident; GPU decodes
  serialized; CPU path behavior unchanged).
- ffmpeg_utils.py: central encoder args (FFMPEG_ENCODER=x264|nvenc|auto with
  cached probe + fallback); migrated the 9 hardcoded libx264 call sites.
- saasshorts now honors WHISPER_* config instead of hardcoded base/cpu/int8.
- Dockerfile: ARG GPU=1 installs CUDA user-space libs (cuBLAS/cuDNN9) +
  onnx-asr/onnxruntime-gpu; LD_LIBRARY_PATH + NVIDIA_DRIVER_CAPABILITIES.
- Validated on prod GPU (RTX 4000 Ada, driver 580): 94s clip transcribed in
  6.5s, word timestamps within ~0.1s of whisper, fallback path exercised.
2026-07-18 01:38:11 +02:00

102 lines
3.6 KiB
Python

"""Central video-encoder selection for every ffmpeg encode call site.
FFMPEG_ENCODER env values:
x264 (default) — CPU libx264, exact pre-GPU behavior
nvenc — force h264_nvenc; probed once and falls back to x264
(with a warning) if the GPU/driver is unavailable
auto — h264_nvenc when the probe succeeds, else x264
Only the codec/quality args live here; surrounding args (-movflags, -pix_fmt,
audio codecs, filters) stay at each call site.
"""
import os
import subprocess
import threading
# Quality tiers pinning the historical libx264 settings.
QUALITY = "quality" # was: -preset medium -crf 18
QUALITY_FAST = "quality_fast" # was: -preset fast -crf 18
DELIVERY = "delivery" # was: -preset fast -crf 22
_X264_ARGS = {
QUALITY: ["-c:v", "libx264", "-preset", "medium", "-crf", "18"],
QUALITY_FAST: ["-c:v", "libx264", "-preset", "fast", "-crf", "18"],
DELIVERY: ["-c:v", "libx264", "-preset", "fast", "-crf", "22"],
}
# 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".
_NVENC_ARGS = {
QUALITY: ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
"-rc", "vbr", "-cq", "25", "-b:v", "0",
"-spatial-aq", "1", "-temporal-aq", "1"],
QUALITY_FAST: ["-c:v", "h264_nvenc", "-preset", "p4", "-tune", "hq",
"-rc", "vbr", "-cq", "25", "-b:v", "0", "-spatial-aq", "1"],
DELIVERY: ["-c:v", "h264_nvenc", "-preset", "p4",
"-rc", "vbr", "-cq", "29", "-b:v", "0", "-spatial-aq", "1"],
}
_probe_lock = threading.Lock()
_nvenc_ok = None # None = not probed yet
_announced = False
def _probe_nvenc():
"""One tiny lavfi encode to prove h264_nvenc works end-to-end.
NVENC rejects frames smaller than ~145px, so the probe uses 256x256.
Any failure (no ffmpeg binary, no GPU, no driver libs) means False.
"""
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-f", "lavfi", "-i", "color=black:s=256x256:d=0.1",
"-c:v", "h264_nvenc", "-f", "null", "-",
]
try:
result = subprocess.run(
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30
)
return result.returncode == 0
except Exception:
return False
def nvenc_available():
"""Probe h264_nvenc once and cache the verdict (thread-safe)."""
global _nvenc_ok
if _nvenc_ok is None:
with _probe_lock:
if _nvenc_ok is None:
_nvenc_ok = _probe_nvenc()
return _nvenc_ok
def reset_encoder_cache():
"""Test hook: forget the cached probe result."""
global _nvenc_ok, _announced
with _probe_lock:
_nvenc_ok = None
_announced = False
def video_encode_args(tier=QUALITY):
"""Return the codec/quality args for one encode, honoring FFMPEG_ENCODER."""
global _announced
if tier not in _X264_ARGS:
raise ValueError(f"Unknown encode tier: {tier!r}")
mode = os.environ.get("FFMPEG_ENCODER", "x264").strip().lower()
use_nvenc = False
if mode in ("nvenc", "auto"):
use_nvenc = nvenc_available()
if mode == "nvenc" and not use_nvenc:
print("⚠️ [Encoder] FFMPEG_ENCODER=nvenc but h264_nvenc is not "
"usable here — falling back to libx264")
if not _announced:
_announced = True
print(f"🎞️ [Encoder] video encoder: {'h264_nvenc' if use_nvenc else 'libx264'} "
f"(FFMPEG_ENCODER={mode})")
return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier])