diff --git a/ffmpeg_utils.py b/ffmpeg_utils.py index a271810..2e06014 100644 --- a/ffmpeg_utils.py +++ b/ffmpeg_utils.py @@ -12,6 +12,7 @@ audio codecs, filters) stay at each call site. import os import subprocess import threading +import time # Quality tiers pinning the historical libx264 settings. QUALITY = "quality" # was: -preset medium -crf 18 @@ -223,3 +224,75 @@ def escape_filter_value(value): control this: use a neutral name, never one derived from a video title. """ return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'") + + +# An mp4 that ffmpeg abandoned before writing the moov atom is a few dozen +# bytes of ftyp, or nothing at all. Anything a real cut produces is orders of +# magnitude larger, so this only ever catches a failed encode. +MIN_CUT_BYTES = 1024 + +# Retries of a failed cut, on the SAME encoder, and how long to wait before +# each one. Deliberately not a fallback to libx264: the clip has to come out +# of the GPU like every other one, and a CPU re-encode of a 1080p cut on a box +# that is already busy enough to have failed the first attempt is the wrong +# trade. Waiting is the whole mechanism — whatever the GPU could not give this +# encode, another job finishes and gives back. +CUT_RETRY_WAITS = (3, 9) + + +def cut_clip(input_video, clip_temp_path, start, end, clip_number): + """Cut [start, end] out of the source into ``clip_temp_path``. + + Raises RuntimeError with ffmpeg's own stderr when the cut does not produce + a playable file. That report is the point: since dec-2025 the cut ran with + its return code ignored and stderr captured into a pipe nobody read, so a + failed cut handed an empty file to the reframer and the job's only visible + error was "moov atom not found" three layers downstream — from ffmpeg, + TransNetV2 and PySceneDetect in turn, each naming the temp file rather + than the encode that never wrote it (prod, 9-sep-2026: three clips of one + job lost, cause unrecoverable because the stderr had been discarded). + + A failed cut is retried on the same encoder after a wait. The failure this + exists for is transient: the same command, on the same source file, cut + fine by hand minutes later, and the nvenc probe is a 256x256 lavfi frame + cached for the life of the process, so it stays true while a real 1080p + session cannot allocate on a GPU that other jobs are filling. + """ + encode_args = video_encode_args(QUALITY_FAST) + command = [ + 'ffmpeg', '-y', + '-ss', str(start), + '-to', str(end), + '-i', input_video, + *encode_args, + *audio_encode_args(), + clip_temp_path + ] + + def _run(): + result = subprocess.run(command, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, text=True, errors="replace") + # ffmpeg has been seen exiting 0 having written nothing, so the file + # itself is the verdict, not just the return code. + size = os.path.getsize(clip_temp_path) if os.path.exists(clip_temp_path) else 0 + ok = result.returncode == 0 and size >= MIN_CUT_BYTES + return ok, f"exit {result.returncode}, {size} bytes\n{(result.stderr or '').strip()[-800:]}" + + for attempt, wait in enumerate(CUT_RETRY_WAITS + (None,), start=1): + ok, report = _run() + if ok: + if attempt > 1: + print(f" ✅ Clip {clip_number} cut on attempt {attempt}.") + return + if wait is None: + break + print(f" ⚠️ Cut of clip {clip_number} failed ({report}) — " + f"retrying in {wait}s.") + time.sleep(wait) + + raise RuntimeError( + f"ffmpeg could not cut clip {clip_number} ({start}s-{end}s) from " + f"{os.path.basename(input_video)} in {len(CUT_RETRY_WAITS) + 1} " + f"attempts: {report}") + + diff --git a/main.py b/main.py index 09b65fe..de6fa42 100644 --- a/main.py +++ b/main.py @@ -28,7 +28,7 @@ import llm_backend from clip_selection import (build_transcript_windows, clip_count_targets, clip_duration_bounds, snap_clip_to_words, trim_to_best) -from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY, +from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv import json @@ -1997,16 +1997,7 @@ if __name__ == '__main__': try: # ffmpeg cut — re-encoding for precision on strict seconds - cut_command = [ - 'ffmpeg', '-y', - '-ss', str(start), - '-to', str(end), - '-i', input_video, - *video_encode_args(QUALITY_FAST), - *audio_encode_args(), - clip_temp_path - ] - subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + cut_clip(input_video, clip_temp_path, start, end, i + 1) success = render_clip(clip_temp_path, clip_final_path, output_format) # Layer order: watermark burns into the canonical (so any diff --git a/tests/test_ffmpeg_utils.py b/tests/test_ffmpeg_utils.py index 1e66147..bd4e426 100644 --- a/tests/test_ffmpeg_utils.py +++ b/tests/test_ffmpeg_utils.py @@ -143,3 +143,68 @@ def test_ai_disclosure_never_destroys_the_file_it_cannot_tag(): assert mark_ai_generated(p) is False assert open(p, "rb").read() == b"not a video" assert not os.path.exists(p + ".aitag.mp4") + + +# --- cut_clip: a failed cut must say why, not hand an empty file downstream --- + +class _FakeRun: + """Stand-in for subprocess.run that writes what a real ffmpeg would.""" + + def __init__(self, outcomes): + self.outcomes = list(outcomes) # (returncode, bytes_written, stderr) + self.commands = [] + + def __call__(self, command, **kwargs): + self.commands.append(command) + returncode, size, stderr = self.outcomes.pop(0) + with open(command[-1], "wb") as fh: + fh.write(b"\0" * size) + return subprocess.CompletedProcess(command, returncode, None, stderr) + + +@pytest.fixture +def _cut(tmp_path, monkeypatch): + """Run cut_clip against a scripted ffmpeg, on the GPU encoder, no waiting.""" + monkeypatch.setenv("FFMPEG_ENCODER", "auto") + monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True) + slept = [] + monkeypatch.setattr(ffmpeg_utils.time, "sleep", slept.append) + + def run(outcomes): + fake = _FakeRun(outcomes) + monkeypatch.setattr(ffmpeg_utils.subprocess, "run", fake) + ffmpeg_utils.cut_clip("source.mp4", str(tmp_path / "temp_clip.mp4"), 1.5, 12.0, 4) + return fake + + run.slept = slept + return run + + +def test_successful_cut_runs_once(_cut): + fake = _cut([(0, 5_000_000, "")]) + assert len(fake.commands) == 1 + assert "h264_nvenc" in fake.commands[0] + + +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"), + (0, 5_000_000, "")]) + assert len(fake.commands) == 2 + assert all("h264_nvenc" in cmd for cmd in fake.commands) + assert "libx264" not in fake.commands[1] + assert _cut.slept == [ffmpeg_utils.CUT_RETRY_WAITS[0]] + + +def test_exit_zero_with_an_empty_file_is_still_a_failure(_cut): + """The prod symptom: ffmpeg wrote nothing, so the reframer met a file with + no moov atom and blamed the temp clip instead of the encode.""" + fake = _cut([(0, 0, ""), (0, 5_000_000, "")]) + assert len(fake.commands) == 2 + + +def test_every_attempt_failing_raises_with_ffmpeg_stderr(_cut): + attempts = len(ffmpeg_utils.CUT_RETRY_WAITS) + 1 + with pytest.raises(RuntimeError, match="Invalid data found"): + _cut([(1, 0, "Invalid data found when processing input")] * attempts) + assert _cut.slept == list(ffmpeg_utils.CUT_RETRY_WAITS)