diff --git a/CLAUDE.md b/CLAUDE.md index 9870fa8..73f3dc2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 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 -`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 per hour at peak with `MAX_CONCURRENT_JOBS=8`): diff --git a/README.md b/README.md index af89264..9b32559 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,7 @@ WHISPER_MODEL=large-v3-turbo WHISPER_DEVICE=cuda WHISPER_COMPUTE=float16 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 ASR_GPU_CONCURRENCY=1 ``` diff --git a/camera_inset.py b/camera_inset.py index 19e8348..c95b1c0 100644 --- a/camera_inset.py +++ b/camera_inset.py @@ -20,6 +20,8 @@ them with margin. """ import os +from ffmpeg_utils import blurred_backdrop + CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the # 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 # HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there # 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"scale={out_w}:{out_h},gblur=sigma=14[bg];" + f"[bga]{blurred_backdrop(out_w, out_h, 14)}[bg];" 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"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];" diff --git a/ffmpeg_utils.py b/ffmpeg_utils.py index 2e06014..8cb2183 100644 --- a/ffmpeg_utils.py +++ b/ffmpeg_utils.py @@ -206,6 +206,42 @@ def video_encode_args(tier=QUALITY): 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): 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', '-ss', str(start), '-to', str(end), + *video_decode_args(), '-i', input_video, *encode_args, *audio_encode_args(), diff --git a/hooks.py b/hooks.py index 73c1a59..39367b5 100644 --- a/hooks.py +++ b/hooks.py @@ -6,7 +6,7 @@ import urllib.request import uuid 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): @@ -426,6 +426,7 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale= ffmpeg_cmd = [ 'ffmpeg', '-y', + *video_decode_args(), '-i', video_path, '-i', img_path, '-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}" diff --git a/main.py b/main.py index 71f1b41..b6d1d92 100644 --- a/main.py +++ b/main.py @@ -30,8 +30,8 @@ from clip_selection import (build_transcript_windows, clip_count_targets, clip_duration_bounds, dedupe_overlapping, score_batches, shortlist_target, snap_clip_to_words, trim_to_best) -from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, - QUALITY_FAST, METADATA_SCRUB) +from ffmpeg_utils import (video_encode_args, video_decode_args, audio_encode_args, + cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv import json @@ -1253,7 +1253,7 @@ def apply_watermark(video_path): f"[0:v][wm]overlay=x={x}:y={y}" ) 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, *video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB, "-movflags", "+faststart", tmp_path] diff --git a/reframe_v2.py b/reframe_v2.py index 396b840..2abbe7c 100644 --- a/reframe_v2.py +++ b/reframe_v2.py @@ -27,8 +27,8 @@ import punch_in import screencast_layout import layout_ranges import split_layout -from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST, - METADATA_SCRUB) +from ffmpeg_utils import (video_encode_args, video_decode_args, blurred_backdrop, + escape_filter_value, QUALITY_FAST, METADATA_SCRUB) 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 return ( f"[0:v]split=2[bga][fga];" - f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h}," - f"scale={out_w}:{out_h},gblur=sigma=12[bg];" + f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];" # 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 # 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([ "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]", *video_encode_args(QUALITY_FAST), "-an", seg_path, ]) diff --git a/subtitles.py b/subtitles.py index efaf431..7e3a0a1 100644 --- a/subtitles.py +++ b/subtitles.py @@ -3,8 +3,8 @@ import re import subprocess import sys -from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, - METADATA_SCRUB) +from ffmpeg_utils import (video_encode_args, video_decode_args, escape_filter_value, + QUALITY, METADATA_SCRUB) _STDIO_CONFIGURED = False @@ -563,6 +563,7 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16, cmd = [ 'ffmpeg', '-y', + *video_decode_args(), '-i', video_path, '-vf', vf, '-c:a', 'copy', diff --git a/tests/test_ffmpeg_utils.py b/tests/test_ffmpeg_utils.py index bd4e426..881f51c 100644 --- a/tests/test_ffmpeg_utils.py +++ b/tests/test_ffmpeg_utils.py @@ -9,8 +9,10 @@ from ffmpeg_utils import ( METADATA_SCRUB, QUALITY, QUALITY_FAST, + blurred_backdrop, mark_ai_generated, reset_encoder_cache, + video_decode_args, video_encode_args, ) @@ -18,6 +20,7 @@ from ffmpeg_utils import ( @pytest.fixture(autouse=True) def _clean_encoder_state(monkeypatch): monkeypatch.delenv("FFMPEG_ENCODER", raising=False) + monkeypatch.delenv("FFMPEG_HWDECODE", raising=False) reset_encoder_cache() yield reset_encoder_cache() @@ -84,6 +87,42 @@ def test_returns_a_fresh_list_each_call(): 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(): # Global -map_metadata -1 alone leaves the audio handler_name intact on a # 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] +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): """No libx264 fallback: the GPU failure is transient, so wait and ask again.""" fake = _cut([(1, 0, "OpenEncodeSessionEx failed: out of memory"),