perf(render): decode on the GPU and blur the backdrop at quarter size

At peak (8 jobs x 3 clip workers) balrog sat at load ~100 on 20 threads
while the RTX 4000's decoder stayed at 0%: NVENC only took the encode, and
decoding plus the filter graphs ran on the CPU, starving the Coolify builds
and every other service on the box.

- ffmpeg_utils.video_decode_args(): -hwaccel cuda before the video input
  whenever the encode is on nvenc (FFMPEG_HWDECODE=0 turns it off). Used in
  the cut, the reframe v2 segments, watermark, hook and caption passes.
- ffmpeg_utils.blurred_backdrop(): the GENERAL and INSET blurred fill blurs
  at a quarter of the output size and scales up, instead of a full-size
  gblur on 1080x1920.

Measured in the prod container on a real 1080p source, 10 s GENERAL
segment: ~16-18 s of CPU before, ~5-7 s after, SSIM 0.994 against the old
output. All four hwaccel passes checked end to end on the prod GPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victormanuel.caverogracia 2026-09-25 13:33:30 +02:00
parent 0e5b733385
commit 1d3d20c77c
9 changed files with 113 additions and 14 deletions

View file

@ -506,7 +506,20 @@ process itself was the biggest tenant (7.7 GB idle on 17-sep-2026): the
thumbnail studio and `/api/subtitle` on a dubbed clip transcribe thumbnail studio and `/api/subtitle` on a dubbed clip transcribe
in-process and the ASR singletons then lived in uvicorn for good, so both in-process and the ASR singletons then lived in uvicorn for good, so both
now call `transcribe_backends.release_models()` when they are done. Size now call `transcribe_backends.release_models()` when they are done. Size
`MAX_CONCURRENT_JOBS` against the free VRAM, not the core count. `MAX_CONCURRENT_JOBS` against the free VRAM first, then check the CPU.
The CPU is the other ceiling. NVENC only takes the encode: decoding and
every filter (scale, blur, overlay, captions) run on the host's 20 threads,
and at peak (8 jobs x `CLIP_WORKERS`=3) balrog sat at load ~100 with the
card's decoder at 0% (22 and 25-sep-2026), starving the Coolify builds and
everything else on the box. Two fixes in `ffmpeg_utils`, and new render code
should use both:
- `video_decode_args()` before a video's `-i`: NVDEC decode (`-hwaccel cuda`)
whenever the encode is on nvenc; `FFMPEG_HWDECODE=0` switches it off.
- `blurred_backdrop()` for any blurred fill: gblur at quarter size, then
scaled up. The full-size gblur on 1080x1920 was most of a GENERAL segment's
cost. Together, a GENERAL segment dropped from ~16 s to ~6 s of CPU per 10 s
of clip (measured in prod, SSIM 0.994 against the old output).
Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing
per hour at peak with `MAX_CONCURRENT_JOBS=8`): per hour at peak with `MAX_CONCURRENT_JOBS=8`):

View file

@ -259,6 +259,7 @@ WHISPER_MODEL=large-v3-turbo
WHISPER_DEVICE=cuda WHISPER_DEVICE=cuda
WHISPER_COMPUTE=float16 WHISPER_COMPUTE=float16
FFMPEG_ENCODER=auto # probes h264_nvenc at startup, falls back to x264 FFMPEG_ENCODER=auto # probes h264_nvenc at startup, falls back to x264
FFMPEG_HWDECODE=1 # default: decode on the GPU (NVDEC) whenever the encode is on nvenc
TRANSCRIBE_BACKEND=parakeet # optional: ~2x faster than whisper, 25 European languages, auto-falls back to whisper TRANSCRIBE_BACKEND=parakeet # optional: ~2x faster than whisper, 25 European languages, auto-falls back to whisper
ASR_GPU_CONCURRENCY=1 ASR_GPU_CONCURRENCY=1
``` ```

View file

@ -20,6 +20,8 @@ them with margin.
""" """
import os import os
from ffmpeg_utils import blurred_backdrop
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
# frame) still counts as anchored to it # frame) still counts as anchored to it
@ -281,8 +283,7 @@ def inset_filtergraph(orig_w, orig_h, out_w, out_h, box, camera_ratio=None):
# Blurred backdrop so the leftover strip is not a black bar. Scaled by # Blurred backdrop so the leftover strip is not a black bar. Scaled by
# HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there # HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there
# is no 1920-tall crop to take out of that. # is no 1920-tall crop to take out of that.
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h}," f"[bga]{blurred_backdrop(out_w, out_h, 14)}[bg];"
f"scale={out_w}:{out_h},gblur=sigma=14[bg];"
f"[sa]scale={out_w}:{screen_h}[screen];" f"[sa]scale={out_w}:{screen_h}[screen];"
f"[ca]crop=w={w}:h={h}:x={x}:y={y},scale={out_w}:{cam_h}[cam];" f"[ca]crop=w={w}:h={h}:x={x}:y={y},scale={out_w}:{cam_h}[cam];"
f"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];" f"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];"

View file

@ -206,6 +206,42 @@ def video_encode_args(tier=QUALITY):
return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier]) return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier])
def video_decode_args():
"""Input args that decode the video on the GPU (NVDEC), or [] for software.
Spliced in right before the video's ``-i``. Only on when the encode runs
on nvenc too: a card that encodes can decode. The frames come back to
system memory, so every CPU filter downstream sees the same pixels, and a
codec NVDEC cannot take falls back to software decode on its own.
Until 25-sep-2026 only the encode was on the GPU: the card's decoder sat at
0% while 8 jobs x 3 clips decoded 1080p on the 20-thread CPU and saturated
the host. FFMPEG_HWDECODE=0 turns it off.
"""
if os.environ.get("FFMPEG_HWDECODE", "1").strip() == "0":
return []
mode = os.environ.get("FFMPEG_ENCODER", "x264").strip().lower()
if mode in ("nvenc", "auto") and nvenc_available():
return ["-hwaccel", "cuda"]
return []
def blurred_backdrop(out_w, out_h, sigma):
"""Filter chain (no labels) filling out_w x out_h with a blurred copy.
The blur runs at a quarter of the output size and is scaled up afterwards:
a blurred picture carries no detail to lose, and the result is visually
the same (SSIM 0.994 against the full-size gblur on a prod clip) for ~45%
less CPU on the whole segment encode. ``sigma`` is the full-size one.
"""
small_w = max(2, out_w // 4 - (out_w // 4) % 2)
small_h = max(2, out_h // 4 - (out_h // 4) % 2)
return (
f"scale=-2:{small_h},crop=w=min(iw\\,{small_w}):h={small_h},"
f"gblur=sigma={sigma / 4:g},scale={out_w}:{out_h}"
)
def escape_filter_value(value): def escape_filter_value(value):
r"""Escape a path/value for use inside a quoted FFmpeg filter argument. r"""Escape a path/value for use inside a quoted FFmpeg filter argument.
@ -263,6 +299,7 @@ def cut_clip(input_video, clip_temp_path, start, end, clip_number):
'ffmpeg', '-y', 'ffmpeg', '-y',
'-ss', str(start), '-ss', str(start),
'-to', str(end), '-to', str(end),
*video_decode_args(),
'-i', input_video, '-i', input_video,
*encode_args, *encode_args,
*audio_encode_args(), *audio_encode_args(),

View file

@ -6,7 +6,7 @@ import urllib.request
import uuid import uuid
from PIL import Image, ImageDraw, ImageFont, ImageFilter from PIL import Image, ImageDraw, ImageFont, ImageFilter
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB from ffmpeg_utils import video_encode_args, video_decode_args, QUALITY, METADATA_SCRUB
def _truncate_bytes(text, max_bytes): def _truncate_bytes(text, max_bytes):
@ -426,6 +426,7 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
ffmpeg_cmd = [ ffmpeg_cmd = [
'ffmpeg', '-y', 'ffmpeg', '-y',
*video_decode_args(),
'-i', video_path, '-i', video_path,
'-i', img_path, '-i', img_path,
'-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}" '-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}"

View file

@ -30,8 +30,8 @@ from clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, dedupe_overlapping, clip_duration_bounds, dedupe_overlapping,
score_batches, shortlist_target, score_batches, shortlist_target,
snap_clip_to_words, trim_to_best) snap_clip_to_words, trim_to_best)
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, from ffmpeg_utils import (video_encode_args, video_decode_args, audio_encode_args,
QUALITY_FAST, METADATA_SCRUB) cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv from dotenv import load_dotenv
import json import json
@ -1253,7 +1253,7 @@ def apply_watermark(video_path):
f"[0:v][wm]overlay=x={x}:y={y}" f"[0:v][wm]overlay=x={x}:y={y}"
) )
tmp_path = video_path + ".wm.mp4" tmp_path = video_path + ".wm.mp4"
cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path, cmd = ["ffmpeg", "-y", *video_decode_args(), "-i", video_path, "-i", logo_path,
"-filter_complex", filt, "-filter_complex", filt,
*video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB, *video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB,
"-movflags", "+faststart", tmp_path] "-movflags", "+faststart", tmp_path]

View file

@ -27,8 +27,8 @@ import punch_in
import screencast_layout import screencast_layout
import layout_ranges import layout_ranges
import split_layout import split_layout
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST, from ffmpeg_utils import (video_encode_args, video_decode_args, blurred_backdrop,
METADATA_SCRUB) escape_filter_value, QUALITY_FAST, METADATA_SCRUB)
ANALYSIS_MAX_WIDTH = 640 ANALYSIS_MAX_WIDTH = 640
@ -157,8 +157,7 @@ def general_filtergraph(out_w, out_h, content_h=None, orig_w=None, orig_h=None):
fg_h += fg_h % 2 fg_h += fg_h % 2
return ( return (
f"[0:v]split=2[bga][fga];" f"[0:v]split=2[bga][fga];"
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h}," f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];"
f"scale={out_w}:{out_h},gblur=sigma=12[bg];"
# Scale by HEIGHT, then trim any overflow to the output width. crop # Scale by HEIGHT, then trim any overflow to the output width. crop
# centres by default, and min() makes it a no-op when the scaled source # centres by default, and min() makes it a no-op when the scaled source
# is already narrower than the frame (portrait/square sources). # is already narrower than the frame (portrait/square sources).
@ -577,7 +576,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
_run([ _run([
"ffmpeg", "-y", "-loglevel", "error", "ffmpeg", "-y", "-loglevel", "error",
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", "-i", input_video, "-ss", f"{ss:.4f}", "-t", f"{dur:.4f}",
*video_decode_args(), "-i", input_video,
"-filter_complex", graph, "-map", "[v]", "-filter_complex", graph, "-map", "[v]",
*video_encode_args(QUALITY_FAST), "-an", seg_path, *video_encode_args(QUALITY_FAST), "-an", seg_path,
]) ])

View file

@ -3,8 +3,8 @@ import re
import subprocess import subprocess
import sys import sys
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, from ffmpeg_utils import (video_encode_args, video_decode_args, escape_filter_value,
METADATA_SCRUB) QUALITY, METADATA_SCRUB)
_STDIO_CONFIGURED = False _STDIO_CONFIGURED = False
@ -563,6 +563,7 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
cmd = [ cmd = [
'ffmpeg', '-y', 'ffmpeg', '-y',
*video_decode_args(),
'-i', video_path, '-i', video_path,
'-vf', vf, '-vf', vf,
'-c:a', 'copy', '-c:a', 'copy',

View file

@ -9,8 +9,10 @@ from ffmpeg_utils import (
METADATA_SCRUB, METADATA_SCRUB,
QUALITY, QUALITY,
QUALITY_FAST, QUALITY_FAST,
blurred_backdrop,
mark_ai_generated, mark_ai_generated,
reset_encoder_cache, reset_encoder_cache,
video_decode_args,
video_encode_args, video_encode_args,
) )
@ -18,6 +20,7 @@ from ffmpeg_utils import (
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _clean_encoder_state(monkeypatch): def _clean_encoder_state(monkeypatch):
monkeypatch.delenv("FFMPEG_ENCODER", raising=False) monkeypatch.delenv("FFMPEG_ENCODER", raising=False)
monkeypatch.delenv("FFMPEG_HWDECODE", raising=False)
reset_encoder_cache() reset_encoder_cache()
yield yield
reset_encoder_cache() reset_encoder_cache()
@ -84,6 +87,42 @@ def test_returns_a_fresh_list_each_call():
assert "-mutated" not in video_encode_args(QUALITY) assert "-mutated" not in video_encode_args(QUALITY)
def test_decode_stays_on_the_cpu_under_x264():
assert video_decode_args() == []
def test_decode_moves_to_the_gpu_with_the_encode(monkeypatch):
monkeypatch.setenv("FFMPEG_ENCODER", "auto")
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True)
assert video_decode_args() == ["-hwaccel", "cuda"]
def test_decode_stays_on_the_cpu_when_nvenc_is_unusable(monkeypatch):
monkeypatch.setenv("FFMPEG_ENCODER", "auto")
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: False)
assert video_decode_args() == []
def test_hwdecode_can_be_switched_off_on_a_gpu(monkeypatch):
monkeypatch.setenv("FFMPEG_ENCODER", "nvenc")
monkeypatch.setenv("FFMPEG_HWDECODE", "0")
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True)
assert video_decode_args() == []
def test_backdrop_blurs_at_quarter_size_and_fills_the_frame():
chain = blurred_backdrop(1080, 1920, 12)
assert "scale=-2:480,crop=w=min(iw\\,270):h=480" in chain
assert "gblur=sigma=3," in chain
assert chain.endswith("scale=1080:1920")
def test_backdrop_keeps_the_small_size_even():
chain = blurred_backdrop(1080, 1350, 14)
assert "scale=-2:336" in chain and "min(iw\\,270)" in chain
assert "gblur=sigma=3.5," in chain
def test_metadata_scrub_covers_global_and_per_stream(): def test_metadata_scrub_covers_global_and_per_stream():
# Global -map_metadata -1 alone leaves the audio handler_name intact on a # Global -map_metadata -1 alone leaves the audio handler_name intact on a
# stream copy — the per-stream specifiers are what strip YouTube's # stream copy — the per-stream specifiers are what strip YouTube's
@ -186,6 +225,12 @@ def test_successful_cut_runs_once(_cut):
assert "h264_nvenc" in fake.commands[0] assert "h264_nvenc" in fake.commands[0]
def test_cut_decodes_the_source_on_the_gpu(_cut):
cmd = _cut([(0, 5_000_000, "")]).commands[0]
assert cmd.index("-hwaccel") < cmd.index("-i")
assert cmd[cmd.index("-hwaccel") + 1] == "cuda"
def test_retry_stays_on_the_gpu_after_a_wait(_cut): def test_retry_stays_on_the_gpu_after_a_wait(_cut):
"""No libx264 fallback: the GPU failure is transient, so wait and ask again.""" """No libx264 fallback: the GPU failure is transient, so wait and ask again."""
fake = _cut([(1, 0, "OpenEncodeSessionEx failed: out of memory"), fake = _cut([(1, 0, "OpenEncodeSessionEx failed: out of memory"),