Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(video): bound FFmpeg concat and fail stalled tasks

Rudy Celekli403794eaa09b
diff --git a/app/services/video.py b/app/services/video.py
index fdb34d4e..9a0593ca 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -87,6 +87,7 @@ _DEFAULT_VIDEO_CODEC = "libx264"
# ffmpeg 串联片段期间没有阶段日志,`subprocess.run` 又阻塞到进程退出,耗时拼接在
# 日志上表现为“无输出”。这里按间隔记录存活信息,便于区分编码中与已经卡死。
_FFMPEG_CONCAT_HEARTBEAT_SECONDS = 30.0
+_DEFAULT_FFMPEG_CONCAT_TIMEOUT_SECONDS = 3600
_SUBTITLE_SPRING_DURATION_SECONDS = 0.18
_MIN_SUBTITLE_SPRING_SCALE = 0.05
_MAX_SUBTITLE_SPRING_SCALE = 1.35
@@ -474,7 +475,36 @@ def _run_concat_with_heartbeat(command: list[str], output_file: str):
reporter = threading.Thread(target=log_heartbeat, daemon=True)
reporter.start()
try:
- return subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)
+ configured_timeout = config.app.get(
+ "ffmpeg_concat_timeout_seconds", _DEFAULT_FFMPEG_CONCAT_TIMEOUT_SECONDS
+ )
+ try:
+ timeout_seconds = float(configured_timeout)
+ except (TypeError, ValueError) as exc:
+ raise ValueError("ffmpeg_concat_timeout_seconds must be positive") from exc
+ if (
+ isinstance(configured_timeout, bool)
+ or not math.isfinite(timeout_seconds)
+ or timeout_seconds <= 0
+ ):
+ raise ValueError("ffmpeg_concat_timeout_seconds must be positive")
+
+ try:
+ # subprocess.run kills and waits for FFmpeg on timeout, so a stalled
+ # encoder cannot leave an orphaned child or a permanently active task.
+ return subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ timeout=timeout_seconds,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise TimeoutError(
+ f"ffmpeg concat exceeded {timeout_seconds:g} seconds"
+ ) from exc
finally:
stop_event.set()
@@ -527,6 +557,10 @@ def concat_video_clips_with_ffmpeg(
effective_codec = _get_effective_video_codec()
try:
return run_concat(effective_codec)
+ except TimeoutError:
+ # A hung encoder is not evidence that another codec will work. Do
+ # not spend a second timeout period retrying the same input.
+ raise
except Exception as exc:
if effective_codec == _DEFAULT_VIDEO_CODEC:
raise
diff --git a/config.example.toml b/config.example.toml
index 66a771ee..d7efbfb5 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -440,6 +440,11 @@ subtitle_provider = "edge"
# Windows example: ffmpeg_path = "C:\\path\\to\\ffmpeg.exe"
# ffmpeg_path = ""
+# Fail a stalled FFmpeg concatenation after this many seconds (default: 3600).
+# Increase this for unusually long videos or slow machines. On timeout, FFmpeg
+# is stopped and the task reports a failure instead of staying at 50% forever.
+# ffmpeg_concat_timeout_seconds = 3600
+
# Leave unset to follow the app default (libx264). Hardware encoders are optional;
# unsupported encoders automatically fall back to libx264.
# Available values: "libx264", "h264_nvenc", "h264_amf", "h264_qsv",
diff --git a/test/services/test_video.py b/test/services/test_video.py
index 53a18cef..e6f39b70 100644
--- a/test/services/test_video.py
+++ b/test/services/test_video.py
@@ -1,5 +1,6 @@
import os
import shutil
+import subprocess
import sys
import tempfile
import time
@@ -1061,6 +1062,35 @@ class TestVideoService(unittest.TestCase):
self.assertTrue(heartbeats, "耗时拼接期间必须记录存活日志")
self.assertRegex(heartbeats[0], r"elapsed=\d+s, output size: 0\.00 MB")
+ def test_concat_timeout_fails_without_retrying_another_codec(self):
+ """A stalled FFmpeg must fail the task and release the concat list file."""
+ config.app["ffmpeg_concat_timeout_seconds"] = 12
+ config.app["video_codec"] = "h264_nvenc"
+
+ def timed_out_run(command, **kwargs):
+ self.assertEqual(kwargs["timeout"], 12)
+ raise subprocess.TimeoutExpired(
+ command, kwargs["timeout"], stderr=b"stalled"
+ )
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ clip_file = os.path.join(temp_dir, "clip.mp4")
+ output_file = os.path.join(temp_dir, "combined.mp4")
+ Path(clip_file).write_bytes(b"fake")
+
+ with patch.object(vd, "_ffmpeg_encoder_exists", return_value=True):
+ with patch.object(vd.subprocess, "run", side_effect=timed_out_run) as run:
+ with self.assertRaisesRegex(TimeoutError, "12 seconds"):
+ vd.concat_video_clips_with_ffmpeg(
+ clip_files=[clip_file],
+ output_file=output_file,
+ threads=1,
+ output_dir=temp_dir,
+ )
+
+ self.assertEqual(run.call_count, 1)
+ self.assertFalse(Path(temp_dir, "ffmpeg-concat-list.txt").exists())
+
def test_concat_video_clips_heartbeat_tolerates_missing_output_file(self):
"""
拼接刚开始时输出文件尚未创建,心跳描述必须安全降级;若探测文件大小的异常