Skip to content

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

Fix video duration safety margin

harry0703a4c3396d6b8c
diff --git a/README.md b/README.md
index efc6b2c8..c56a069e 100644
--- a/README.md
+++ b/README.md
@@ -42,10 +42,10 @@
<tr>
<td align="center" width="160">
<a href="https://www.volcengine.com/activity/codingplan?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=MoneyPrinterTurbo"><img src="docs/sponsors/volcengine-logo.svg" alt="火山引擎" height="32"></a><br>
- <a href="https://ai.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=MoneyPrinterTurbo"><strong>方舟 Agent Plan</strong></a>
+ <a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=MoneyPrinterTurbo"><strong>方舟 Agent Plan</strong></a>
</td>
<td align="left">
- <sub>感谢 <a href="https://ai.volcengine.com/activity/agentplan?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=MoneyPrinterTurbo">方舟 Agent Plan</a> 对本项目的赞助。模型自由,工具不限,最新支持 MiniMax-M3 与 GLM-5.1,受邀下单叠加 9.5 折!集合主流优秀国产编程模型,多生态兼容,无缝融入您的工具链,依托字节资源保障和工程能力,更大容量,更快、更稳、更丝滑!</sub>
+ <sub>感谢 <a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=MoneyPrinterTurbo">方舟 Agent Plan</a> 对本项目的赞助。模型自由,工具不限,最新支持 MiniMax-M3 与 GLM-5.1,受邀下单叠加 9.5 折!集合主流优秀国产编程模型,多生态兼容,无缝融入您的工具链,依托字节资源保障和工程能力,更大容量,更快、更稳、更丝滑!</sub>
</td>
</tr>
<tr>
diff --git a/app/services/video.py b/app/services/video.py
index e38e2f2c..9102e32f 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -69,6 +69,10 @@ audio_codec = "aac"
# 这里显式抬高音频码率,避免成片阶段因为默认值过低而引入明显失真。
audio_bitrate = "192k"
fps = 30
+# FFmpeg 按帧率拼接/转码时,最终时长可能比 MoviePy 读到的理论时长短几十毫秒。
+# 这里给视频素材多留一个很小的安全余量,避免音频末尾因为帧舍入出现黑屏、
+# 卡顿或最后一小段旁白没有画面的情况。
+_VIDEO_DURATION_SAFETY_MARGIN = 0.1
_BGM_EXTENSIONS = (".mp3",)
_DEFAULT_VIDEO_CODEC = "libx264"
_SUPPORTED_VIDEO_CODECS = (
@@ -82,6 +86,17 @@ _SUPPORTED_VIDEO_CODECS = (
_runtime_disabled_video_codecs = set()
+def _get_required_video_duration(audio_duration: float) -> float:
+ """
+ 返回视频素材拼接的目标时长。
+
+ 使用场景:合成视频时需要素材时长覆盖旁白音频。只做到“刚好等于”
+ 音频时长时,FFmpeg 可能因为帧率舍入让最终视频略短,因此统一加一个
+ 轻量余量。函数独立出来,便于测试和后续按实际反馈调整余量大小。
+ """
+ return max(0.0, float(audio_duration) + _VIDEO_DURATION_SAFETY_MARGIN)
+
+
def _prioritize_unique_source_clips(
subclipped_items: List[SubClippedVideoClip],
concat_mode: VideoConcatMode,
@@ -536,6 +551,11 @@ def combine_videos(
close_clip(audio_clip)
logger.info(f"audio duration: {audio_duration} seconds")
logger.info(f"maximum clip duration: {max_clip_duration} seconds")
+ required_video_duration = _get_required_video_duration(audio_duration)
+ logger.info(
+ f"required video duration: {required_video_duration:.2f} seconds "
+ f"(audio duration + {_VIDEO_DURATION_SAFETY_MARGIN:.2f}s safety margin)"
+ )
# 兼容 API 直接调用时未传转场模式的情况,避免后续访问 .value 时崩溃。
transition_value = getattr(video_transition_mode, "value", video_transition_mode)
@@ -586,14 +606,14 @@ def combine_videos(
# Add downloaded clips over and over until the duration of the audio (max_duration) has been reached
for i, subclipped_item in enumerate(subclipped_items):
- if video_duration >= audio_duration:
+ if video_duration >= required_video_duration:
break
logger.debug(
f"processing clip {i+1}: {subclipped_item.width}x{subclipped_item.height}, "
f"source: {os.path.basename(subclipped_item.source_file_path)}, "
f"current duration: {video_duration:.2f}s, "
- f"remaining: {audio_duration - video_duration:.2f}s"
+ f"remaining: {required_video_duration - video_duration:.2f}s"
)
try:
@@ -675,16 +695,23 @@ def combine_videos(
except Exception as e:
logger.error(f"failed to process clip: {str(e)}")
- # loop processed clips until the video duration matches or exceeds the audio duration.
- if video_duration < audio_duration:
- logger.warning(f"video duration ({video_duration:.2f}s) is shorter than audio duration ({audio_duration:.2f}s), looping clips to match audio length.")
+ # loop processed clips until the video duration covers the audio duration and the small safety margin.
+ if video_duration < required_video_duration:
+ logger.warning(
+ f"video duration ({video_duration:.2f}s) is shorter than required duration "
+ f"({required_video_duration:.2f}s), looping clips to match audio length."
+ )
base_clips = processed_clips.copy()
for clip in itertools.cycle(base_clips):
- if video_duration >= audio_duration:
+ if video_duration >= required_video_duration:
break
processed_clips.append(clip)
video_duration += clip.duration
- logger.info(f"video duration: {video_duration:.2f}s, audio duration: {audio_duration:.2f}s, looped {len(processed_clips)-len(base_clips)} clips")
+ logger.info(
+ f"video duration: {video_duration:.2f}s, audio duration: {audio_duration:.2f}s, "
+ f"required duration: {required_video_duration:.2f}s, "
+ f"looped {len(processed_clips)-len(base_clips)} clips"
+ )
# merge video clips progressively, avoid loading all videos at once to avoid memory overflow
logger.info("starting clip merging process")
diff --git a/test/services/test_video.py b/test/services/test_video.py
index aacda263..c47ffbaf 100644
--- a/test/services/test_video.py
+++ b/test/services/test_video.py
@@ -440,6 +440,66 @@ class TestVideoService(unittest.TestCase):
)
self.assertEqual(result, combined_video_path)
+ def test_combine_videos_keeps_small_duration_safety_margin(self):
+ """
+ 音频和素材累计时长刚好相等时,仍应继续追加一个短片段作为安全余量。
+
+ FFmpeg 按帧率拼接后可能让最终视频比理论时长短几十毫秒。如果这里
+ 在 10.0s == 10.0s 时立即停止,成片末尾就可能出现音频还在播放但
+ 视频素材已经结束的边界问题。
+ """
+
+ class _FakeAudioClip:
+ duration = 10.0
+
+ def close(self):
+ pass
+
+ class _FakeVideoClip:
+ def __init__(self, duration):
+ self.duration = duration
+ self.size = (1080, 1920)
+ self.w = 1080
+ self.h = 1920
+
+ def subclipped(self, start_time, end_time):
+ return _FakeVideoClip(end_time - start_time)
+
+ video_durations = {
+ "clip-1.mp4": 3.0,
+ "clip-2.mp4": 4.0,
+ "clip-3.mp4": 3.0,
+ "clip-4.mp4": 2.0,
+ }
+
+ def _open_fake_video_clip(video_path):
+ return _FakeVideoClip(video_durations[video_path])
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ combined_video_path = os.path.join(temp_dir, "combined.mp4")
+
+ with patch.object(vd, "AudioFileClip", return_value=_FakeAudioClip()):
+ with patch.object(
+ vd, "_open_video_clip_quietly", side_effect=_open_fake_video_clip
+ ):
+ with patch.object(
+ vd, "_write_videofile_with_codec_fallback"
+ ) as write_mock:
+ with patch.object(vd, "concat_video_clips_with_ffmpeg"):
+ with patch.object(vd, "delete_files"):
+ result = vd.combine_videos(
+ combined_video_path=combined_video_path,
+ video_paths=list(video_durations.keys()),
+ audio_file=os.path.join(temp_dir, "audio.mp3"),
+ video_aspect=vd.VideoAspect.portrait,
+ video_concat_mode=vd.VideoConcatMode.sequential,
+ video_transition_mode=None,
+ max_clip_duration=10,
+ )
+
+ self.assertEqual(result, combined_video_path)
+ self.assertEqual(write_mock.call_count, 4)
+
def test_prioritize_unique_source_clips_uses_each_source_before_reuse(self):
"""
随机模式下,一个长素材会被拆成多个片段。调度层应先让每个源素材