利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
Add configurable video encoder fallback
harry07037f612312c66a
diff --git a/app/services/video.py b/app/services/video.pyindex 43b32610..d30bc2c3 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -7,6 +7,7 @@ import gcimport shutilimport subprocessfrom contextlib import redirect_stdout+from functools import lru_cachefrom typing import Listfrom loguru import loggerimport numpy as np@@ -23,6 +24,7 @@ from moviepy import (from moviepy.video.tools.subtitles import SubtitlesClipfrom PIL import Image, ImageDraw, ImageFont+from app.config import configfrom app.models import constfrom app.models.schema import (MaterialInfo,@@ -64,9 +66,18 @@ audio_codec = "aac"# Docker 里的 ffmpeg/AAC 组合在默认配置下更容易出现音频质量波动,# 这里显式抬高音频码率,避免成片阶段因为默认值过低而引入明显失真。audio_bitrate = "192k"-video_codec = "libx264"fps = 30_BGM_EXTENSIONS = (".mp3",)+_DEFAULT_VIDEO_CODEC = "libx264"+_SUPPORTED_VIDEO_CODECS = (+ "libx264",+ "h264_nvenc",+ "h264_amf",+ "h264_qsv",+ "h264_mf",+ "h264_videotoolbox",+)+_runtime_disabled_video_codecs = set()def _prioritize_unique_source_clips(@@ -135,39 +146,179 @@ def get_ffmpeg_binary():return "ffmpeg"+def _get_configured_video_codec() -> str:+ """+ 读取用户配置的视频编码器。++ 该配置面向高级用户,用于尝试启用 NVENC/AMF/QSV/VideoToolbox 等硬件+ 编码。这里刻意只允许固定白名单,避免开放任意 FFmpeg 参数后,用户填错+ 参数导致输出格式不可控,甚至让生成任务在后续阶段才失败。+ """+ configured_codec = str(+ config.app.get("video_codec", _DEFAULT_VIDEO_CODEC) or _DEFAULT_VIDEO_CODEC+ ).strip()+ if configured_codec not in _SUPPORTED_VIDEO_CODECS:+ logger.warning(+ f"unsupported video codec configured: {configured_codec}, "+ f"fallback to {_DEFAULT_VIDEO_CODEC}"+ )+ return _DEFAULT_VIDEO_CODEC+ return configured_codec+++@lru_cache(maxsize=16)+def _ffmpeg_encoder_exists(ffmpeg_binary: str, codec: str) -> bool:+ """+ 检查当前 FFmpeg 是否声明支持指定编码器。++ 这只能证明 FFmpeg 编译时包含该 encoder,不能证明当前机器硬件和驱动+ 一定可用。因此实际编码失败时仍会再回退到 libx264。+ """+ try:+ result = subprocess.run(+ [ffmpeg_binary, "-hide_banner", "-encoders"],+ capture_output=True,+ text=True,+ check=False,+ timeout=10,+ )+ except (OSError, subprocess.TimeoutExpired) as exc:+ logger.warning(+ "failed to inspect ffmpeg encoders, "+ f"fallback to {_DEFAULT_VIDEO_CODEC}: {str(exc)}"+ )+ return False++ if result.returncode != 0:+ logger.warning(+ "failed to inspect ffmpeg encoders, "+ f"fallback to {_DEFAULT_VIDEO_CODEC}: {(result.stderr or result.stdout or '').strip()}"+ )+ return False+ return codec in result.stdout+++def _get_effective_video_codec(preferred_codec: str | None = None) -> str:+ """+ 返回本次实际使用的视频编码器。++ 用户选择硬件编码器时,先做 FFmpeg encoder 列表检测;如果本进程里已经+ 实际编码失败过,也直接回退,避免一个任务里每个片段都重复失败。+ """+ selected_codec = preferred_codec or _get_configured_video_codec()+ if selected_codec == _DEFAULT_VIDEO_CODEC:+ return _DEFAULT_VIDEO_CODEC++ if selected_codec in _runtime_disabled_video_codecs:+ logger.warning(+ f"video codec {selected_codec} was disabled after a runtime failure, "+ f"fallback to {_DEFAULT_VIDEO_CODEC}"+ )+ return _DEFAULT_VIDEO_CODEC++ ffmpeg_binary = get_ffmpeg_binary()+ if not _ffmpeg_encoder_exists(ffmpeg_binary, selected_codec):+ logger.warning(+ f"ffmpeg encoder {selected_codec} is not available, "+ f"fallback to {_DEFAULT_VIDEO_CODEC}"+ )+ return _DEFAULT_VIDEO_CODEC++ return selected_codec+++def _disable_runtime_video_codec(codec: str, reason: str):+ if codec == _DEFAULT_VIDEO_CODEC:+ return+ _runtime_disabled_video_codecs.add(codec)+ logger.warning(+ f"video codec {codec} failed, fallback to {_DEFAULT_VIDEO_CODEC}. "+ f"reason: {reason}"+ )+++def _fallback_write_videofile(clip, output_file: str, failed_codec: str, reason: str, **kwargs):+ """+ 硬件编码失败后用 libx264 重试,只有重试成功才禁用该硬件编码器。++ Windows 上 FFmpeg 失败原因比较复杂:可能是显卡/驱动不支持,也可能是输出+ 文件被占用、目录权限、杀软拦截等通用 IO 问题。只有 libx264 能成功写出时,+ 才能判断原始失败大概率来自硬件编码器本身,避免误伤后续任务。+ """+ clip.write_videofile(output_file, codec=_DEFAULT_VIDEO_CODEC, **kwargs)+ _disable_runtime_video_codec(failed_codec, reason)+ return _DEFAULT_VIDEO_CODEC+++def _write_videofile_with_codec_fallback(clip, output_file: str, codec: str, **kwargs):+ """+ 使用指定编码器写出视频,失败时自动用 libx264 重试一次。++ 硬件编码器是否可用不仅取决于 FFmpeg,还取决于显卡、驱动和当前运行环境。+ 生成任务不能因为高级编码器不可用而整体失败,所以这里把回退集中处理。+ """+ effective_codec = _get_effective_video_codec(codec)+ try:+ clip.write_videofile(output_file, codec=effective_codec, **kwargs)+ return effective_codec+ except Exception as exc:+ if effective_codec == _DEFAULT_VIDEO_CODEC:+ raise+ return _fallback_write_videofile(+ clip,+ output_file,+ failed_codec=effective_codec,+ reason=str(exc),+ **kwargs,+ )++def _escape_ffmpeg_concat_path(file_path: str) -> str:# concat demuxer 使用单引号包裹路径,路径中的单引号需要先转义。return file_path.replace("'", "'\\''")+def _format_ffmpeg_concat_path(file_path: str) -> str:+ """+ 生成 concat demuxer 文件列表中的路径。++ FFmpeg 官方文档要求 concat list 中的特殊字符和空格需要转义;Windows+ 绝对路径里的反斜杠也容易被解析成转义字符。这里统一转成正斜杠形式,+ 让 `C:\\Users\\...` 变成 `C:/Users/...`,再处理单引号,兼容 macOS/Linux。+ """+ absolute_path = os.path.abspath(file_path)+ return _escape_ffmpeg_concat_path(absolute_path.replace("\\", "/"))++def concat_video_clips_with_ffmpeg(clip_files: List[str], output_file: str, threads: int, output_dir: str):concat_list_file = os.path.join(output_dir, "ffmpeg-concat-list.txt")with open(concat_list_file, "w", encoding="utf-8") as fp:for clip_file in clip_files:- absolute_path = os.path.abspath(clip_file)- fp.write(f"file '{_escape_ffmpeg_concat_path(absolute_path)}'\n")-- command = [- get_ffmpeg_binary(),- "-y",- "-f",- "concat",- "-safe",- "0",- "-i",- concat_list_file,- "-c:v",- video_codec,- "-threads",- str(threads or 2),- "-pix_fmt",- "yuv420p",- output_file,- ]-- try:+ fp.write(f"file '{_format_ffmpeg_concat_path(clip_file)}'\n")++ def build_command(codec: str) -> list[str]:+ return [+ get_ffmpeg_binary(),+ "-y",+ "-f",+ "concat",+ "-safe",+ "0",+ "-i",+ concat_list_file,+ "-c:v",+ codec,+ "-threads",+ str(threads or 2),+ "-pix_fmt",+ "yuv420p",+ output_file,+ ]++ def run_concat(codec: str):+ command = build_command(codec)# 使用 ffmpeg 只做一次串联与编码,避免 MoviePy 逐段合并时反复重编码,# 从而降低画质劣化与颜色偏移风险。result = subprocess.run(@@ -179,6 +330,18 @@ def concat_video_clips_with_ffmpeg(if result.returncode != 0:error_message = (result.stderr or result.stdout or "").strip()raise RuntimeError(error_message or "ffmpeg concat failed")+ return codec++ try:+ effective_codec = _get_effective_video_codec()+ try:+ return run_concat(effective_codec)+ except Exception as exc:+ if effective_codec == _DEFAULT_VIDEO_CODEC:+ raise+ result_codec = run_concat(_DEFAULT_VIDEO_CODEC)+ _disable_runtime_video_codec(effective_codec, str(exc))+ return result_codecfinally:delete_files(concat_list_file)@@ -478,7 +641,13 @@ def combine_videos(# wirte clip to temp fileclip_file = f"{output_dir}/temp-clip-{i+1}.mp4"- clip.write_videofile(clip_file, logger=None, fps=fps, codec=video_codec)+ _write_videofile_with_codec_fallback(+ clip,+ clip_file,+ codec=_get_configured_video_codec(),+ logger=None,+ fps=fps,+ )# Store clip duration before closingclip_duration_saved = clip.duration@@ -816,8 +985,10 @@ def generate_video(# 显式沿用输入音频的采样率;如果取不到,再回退到 MoviePy 默认的 44100Hz。# 这样可以减少不同运行环境,尤其是 Docker 环境中再次重采样带来的音质波动。output_audio_fps = int(getattr(audio_clip, "fps", 0) or 44100)- video_clip.write_videofile(- output_file,+ _write_videofile_with_codec_fallback(+ video_clip,+ output_file=output_file,+ codec=_get_configured_video_codec(),audio_codec=audio_codec,audio_fps=output_audio_fps,audio_bitrate=audio_bitrate,diff --git a/config.example.toml b/config.example.tomlindex 767ee272..4883d995 100644--- a/config.example.toml+++ b/config.example.toml@@ -210,6 +210,16 @@ subtitle_provider = "edge"# In such cases, you can manually download ffmpeg and set the ffmpeg_path, download link: https://www.gyan.dev/ffmpeg/builds/# ffmpeg_path = "C:\\Users\\harry\\Downloads\\ffmpeg.exe"++# 视频编码器。默认 libx264 最稳定;高级用户可以尝试硬件编码器提升速度。+# 如果当前 FFmpeg 或硬件驱动不支持所选编码器,程序会自动回退到 libx264。+# 可选值: "libx264", "h264_nvenc", "h264_amf", "h264_qsv", "h264_mf", "h264_videotoolbox"+# video_codec = "libx264"++# Video encoder. libx264 is the safest default; advanced users can try hardware encoders.+# If the selected encoder is not supported by the current FFmpeg or driver, the app falls back to libx264.+# Available values: "libx264", "h264_nvenc", "h264_amf", "h264_qsv", "h264_mf", "h264_videotoolbox"+# video_codec = "libx264"########################################################################################## 当视频生成成功后,API服务提供的视频下载接入点,默认为当前服务的地址和监听端口diff --git a/test/services/test_video.py b/test/services/test_video.pyindex 0bf558f4..31660cdb 100644--- a/test/services/test_video.py+++ b/test/services/test_video.py@@ -81,10 +81,16 @@ class TestSecurityControls(unittest.TestCase):class TestVideoService(unittest.TestCase):def setUp(self):+ self.original_app_config = dict(config.app)self.test_img_path = os.path.join(resources_dir, "1.png")+ vd._runtime_disabled_video_codecs.clear()+ vd._ffmpeg_encoder_exists.cache_clear()def tearDown(self):- pass+ config.app.clear()+ config.app.update(self.original_app_config)+ vd._runtime_disabled_video_codecs.clear()+ vd._ffmpeg_encoder_exists.cache_clear()def test_preprocess_video(self):if not os.path.exists(self.test_img_path):@@ -195,6 +201,163 @@ class TestVideoService(unittest.TestCase):), patch.dict(sys.modules, {"imageio_ffmpeg": fake_imageio_ffmpeg}):self.assertEqual(vd.get_ffmpeg_binary(), "/tmp/bundled-ffmpeg")+ def test_get_effective_video_codec_falls_back_when_encoder_missing(self):+ """+ 用户选择的硬件编码器必须先经过 FFmpeg encoder 列表检测。检测不到+ 时直接回退 libx264,避免生成任务在写文件阶段才失败。+ """+ config.app["video_codec"] = "h264_nvenc"++ with patch.object(vd, "_ffmpeg_encoder_exists", return_value=False):+ self.assertEqual(vd._get_effective_video_codec(), "libx264")++ def test_ffmpeg_encoder_exists_falls_back_when_probe_fails(self):+ """+ Windows 上用户配置的 ffmpeg 可能因为路径损坏、权限或杀软拦截而无法+ 正常执行。encoder 探测失败时必须返回 False,让上层稳定回退 libx264。+ """+ with patch.object(+ vd.subprocess,+ "run",+ side_effect=OSError("permission denied"),+ ):+ self.assertFalse(vd._ffmpeg_encoder_exists("C:/ffmpeg/bin/ffmpeg.exe", "h264_nvenc"))++ def test_write_videofile_falls_back_after_runtime_encoder_failure(self):+ """+ FFmpeg 声明支持某个硬件编码器,不代表当前显卡或驱动一定可用。+ 首次实际编码失败后,应立即用 libx264 重试,并在本进程禁用该编码器。+ """++ class _FakeClip:+ def __init__(self):+ self.codecs = []++ def write_videofile(self, output_file, codec, **kwargs):+ self.codecs.append(codec)+ if codec == "h264_nvenc":+ raise RuntimeError("nvenc device not available")++ fake_clip = _FakeClip()++ with patch.object(vd, "_ffmpeg_encoder_exists", return_value=True):+ used_codec = vd._write_videofile_with_codec_fallback(+ fake_clip,+ "/tmp/fake.mp4",+ codec="h264_nvenc",+ logger=None,+ fps=30,+ )++ self.assertEqual(used_codec, "libx264")+ self.assertEqual(fake_clip.codecs, ["h264_nvenc", "libx264"])+ self.assertIn("h264_nvenc", vd._runtime_disabled_video_codecs)++ def test_write_videofile_does_not_disable_codec_when_fallback_also_fails(self):+ """+ 如果 libx264 兜底也失败,失败原因更可能是输出路径、权限、文件占用等+ 通用问题,不能误判为硬件编码器不可用。+ """++ class _FakeClip:+ def write_videofile(self, output_file, codec, **kwargs):+ raise RuntimeError(f"{codec} cannot write output")++ with patch.object(vd, "_ffmpeg_encoder_exists", return_value=True):+ with self.assertRaises(RuntimeError):+ vd._write_videofile_with_codec_fallback(+ _FakeClip(),+ "/tmp/fake.mp4",+ codec="h264_nvenc",+ logger=None,+ fps=30,+ )++ self.assertNotIn("h264_nvenc", vd._runtime_disabled_video_codecs)++ def test_format_ffmpeg_concat_path_normalizes_windows_path(self):+ """+ concat demuxer 的文件列表对 Windows 反斜杠较敏感,写入 list 前统一+ 转成正斜杠,并继续保留单引号转义。+ """+ with patch.object(vd.os.path, "abspath", return_value=r"C:\Users\Harry's Videos\clip.mp4"):+ self.assertEqual(+ vd._format_ffmpeg_concat_path(r"C:\Users\Harry's Videos\clip.mp4"),+ "C:/Users/Harry'\\''s Videos/clip.mp4",+ )++ def test_concat_video_clips_falls_back_after_runtime_encoder_failure(self):+ """+ 最终 ffmpeg concat 阶段也要具备同样的回退能力。这里用 mock 模拟+ h264_nvenc 编码失败,确认会自动再用 libx264 执行一次。+ """+ config.app["video_codec"] = "h264_nvenc"++ def fake_run(command, capture_output, text, check):+ codec_index = command.index("-c:v") + 1+ codec = command[codec_index]+ if codec == "h264_nvenc":+ return types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="nvenc device not available",+ )+ return types.SimpleNamespace(returncode=0, stdout="", stderr="")++ 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=fake_run) as run:+ vd.concat_video_clips_with_ffmpeg(+ clip_files=[clip_file],+ output_file=output_file,+ threads=1,+ output_dir=temp_dir,+ )++ used_codecs = [+ call.args[0][call.args[0].index("-c:v") + 1]+ for call in run.call_args_list+ ]+ self.assertEqual(used_codecs, ["h264_nvenc", "libx264"])+ self.assertIn("h264_nvenc", vd._runtime_disabled_video_codecs)++ def test_concat_video_clips_does_not_disable_codec_when_fallback_also_fails(self):+ """+ concat 阶段如果 libx264 也失败,说明可能是输入 list、路径或输出权限+ 问题,不能把硬件编码器加入运行时禁用列表。+ """+ config.app["video_codec"] = "h264_nvenc"++ def fake_run(command, capture_output, text, check):+ codec_index = command.index("-c:v") + 1+ codec = command[codec_index]+ return types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr=f"{codec} cannot write output",+ )++ 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=fake_run):+ with self.assertRaises(RuntimeError):+ vd.concat_video_clips_with_ffmpeg(+ clip_files=[clip_file],+ output_file=output_file,+ threads=1,+ output_dir=temp_dir,+ )++ self.assertNotIn("h264_nvenc", vd._runtime_disabled_video_codecs)+def test_open_video_clip_quietly_suppresses_moviepy_stdout(self):"""MoviePy 2.1.x 的 FFMPEG_VideoReader 会直接向 stdout 打印 metadatadiff --git a/webui/Main.py b/webui/Main.pyindex e500d63a..d0924e0b 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -773,6 +773,29 @@ with middle_panel:options=[1, 2, 3, 4, 5],index=0,)++ with st.expander(tr("Advanced Video Settings"), expanded=False):+ video_codec_options = [+ ("libx264 (CPU)", "libx264"),+ ("NVIDIA NVENC (h264_nvenc)", "h264_nvenc"),+ ("AMD AMF (h264_amf)", "h264_amf"),+ ("Intel QSV (h264_qsv)", "h264_qsv"),+ ("Windows MediaFoundation (h264_mf)", "h264_mf"),+ ("macOS VideoToolbox (h264_videotoolbox)", "h264_videotoolbox"),+ ]+ saved_video_codec = config.app.get("video_codec", "libx264")+ saved_video_codec_values = [item[1] for item in video_codec_options]+ if saved_video_codec not in saved_video_codec_values:+ saved_video_codec = "libx264"+ selected_codec_index = saved_video_codec_values.index(saved_video_codec)+ selected_codec_index = st.selectbox(+ tr("Video Encoder"),+ options=range(len(video_codec_options)),+ index=selected_codec_index,+ format_func=lambda x: video_codec_options[x][0],+ help=tr("Video Encoder Help"),+ )+ config.app["video_codec"] = video_codec_options[selected_codec_index][1]with st.container(border=True):st.write(tr("Audio Settings"))diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex 4a201e2a..e289dc6d 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -132,6 +132,9 @@"Pixabay API Key added successfully": "Pixabay API Key added successfully","Select Pixabay API Key to delete": "Select Pixabay API Key to delete","Delete Selected Pixabay API Key": "Delete Selected Pixabay API Key",- "Pixabay API Key deleted successfully": "Pixabay API Key deleted successfully"+ "Pixabay API Key deleted successfully": "Pixabay API Key deleted successfully",+ "Advanced Video Settings": "Advanced Video Settings",+ "Video Encoder": "Video Encoder",+ "Video Encoder Help": "Advanced option. libx264 is the safest default. When a hardware encoder is selected, the app falls back to libx264 if the current FFmpeg, GPU, or driver cannot use it."}}diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex 15676aab..03a846f4 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -132,6 +132,9 @@"Pixabay API Key added successfully": "Pixabay API Key 添加成功","Select Pixabay API Key to delete": "选择要删除的 Pixabay API Key","Delete Selected Pixabay API Key": "删除选定的 Pixabay API Key",- "Pixabay API Key deleted successfully": "Pixabay API Key 删除成功"+ "Pixabay API Key deleted successfully": "Pixabay API Key 删除成功",+ "Advanced Video Settings": "高级视频设置",+ "Video Encoder": "视频编码器",+ "Video Encoder Help": "高级选项。默认 libx264 最稳定;选择硬件编码器时,如果当前 FFmpeg、显卡或驱动不可用,会自动回退到 libx264。"}}