Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
259 lines
10 KiB
Python
259 lines
10 KiB
Python
"""固定 FFmpeg 参数的素材编排适配。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import html
|
||
import re
|
||
|
||
from app.adapters.media import input_options, inspect_media, run_process
|
||
from app.domain.execution import CpuResult
|
||
from app.domain.errors import MediaError as ProviderError
|
||
from .contracts import _invalid, _keys, _int, _float, _string
|
||
from .contracts import validate_arguments
|
||
|
||
from typing import TYPE_CHECKING
|
||
|
||
if TYPE_CHECKING:
|
||
from .client import Provider
|
||
|
||
|
||
async def _compose(provider: Provider, inputs, p, assets, work):
|
||
if "story_spec" in p:
|
||
from app.domain.stories import compile_story_render
|
||
from app.adapters.media import compose_story
|
||
|
||
validate_arguments("video.compose", inputs, p, provider.settings)
|
||
plan = compile_story_render(p["story_spec"], p["render_inputs"])
|
||
audio_id = inputs.get("audio_asset_id")
|
||
frozen_audio = p["render_inputs"].get("audio")
|
||
if frozen_audio:
|
||
import hashlib
|
||
|
||
def digest_file(path):
|
||
h = hashlib.sha256()
|
||
with path.open("rb") as stream:
|
||
while chunk := stream.read(1024 * 1024):
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
# 音轨与视频都校验已冻结字节,不能在等待合成期间替换源文件。
|
||
if (
|
||
await asyncio.to_thread(digest_file, provider._asset(audio_id, assets))
|
||
!= frozen_audio["sha256"]
|
||
):
|
||
raise _invalid("Frozen story audio SHA differs.")
|
||
return await compose_story(
|
||
plan,
|
||
work,
|
||
settings=provider.settings,
|
||
sources=[provider._asset(c["asset_id"], assets) for c in plan.clips],
|
||
audio=provider._asset(audio_id, assets) if audio_id else None,
|
||
)
|
||
if "workflow_spec" in p:
|
||
from app.domain.timeline import compile_timeline
|
||
from app.adapters.media import compose_workflow
|
||
|
||
validate_arguments("video.compose", inputs, p, provider.settings)
|
||
audio_id = inputs.get("audio_asset_id")
|
||
audio = provider._asset(audio_id, assets) if audio_id else None
|
||
owned = {audio_id: await inspect_media(audio, provider.settings)} if audio else {}
|
||
try:
|
||
plan = compile_timeline(p["workflow_spec"], owned)
|
||
except ValueError:
|
||
raise _invalid("Invalid workflow audio timeline.") from None
|
||
return await compose_workflow(
|
||
plan,
|
||
work,
|
||
settings=provider.settings,
|
||
sources=[provider._asset(c["asset_id"], assets) for c in p["clips"]],
|
||
audio=audio,
|
||
)
|
||
_keys(inputs, {"asset_ids", "audio_asset_id"})
|
||
_keys(p, {"clips", "audio_asset_id", "subtitles", "width", "height", "fps"})
|
||
clips = p.get("clips")
|
||
if not isinstance(clips, list) or not 1 <= len(clips) <= 1000:
|
||
raise _invalid("请选择1至1000个视频片段。")
|
||
width, height, fps = p.get("width", 1280), p.get("height", 720), p.get("fps", 24)
|
||
_int(width, 256, 3840, 2)
|
||
_int(height, 256, 2160, 2)
|
||
if type(fps) is not int or fps not in {24, 25, 30, 60}:
|
||
raise _invalid("不支持此成片帧率。")
|
||
normalized = []
|
||
for clip in clips:
|
||
_keys(clip, {"asset_id", "start_seconds", "end_seconds"})
|
||
start = _float(clip.get("start_seconds", 0), 0, 86400)
|
||
end = clip.get("end_seconds")
|
||
if end is not None and _float(end, 0, 86400) <= start:
|
||
raise _invalid("片段结束时间必须大于开始时间。")
|
||
normalized.append((provider._asset(clip.get("asset_id"), assets), start, end))
|
||
if "asset_ids" in inputs and inputs["asset_ids"] != [clip["asset_id"] for clip in clips]:
|
||
raise _invalid("素材顺序应与编排片段一致。")
|
||
a, b = inputs.get("audio_asset_id"), p.get("audio_asset_id")
|
||
if a and b and a != b:
|
||
raise _invalid("请只选择一个成片音轨。")
|
||
audio = provider._asset(a or b, assets) if a or b else None
|
||
subtitles = p.get("subtitles", [])
|
||
if not isinstance(subtitles, list) or len(subtitles) > 1000:
|
||
raise _invalid("人工字幕数量超出限制。")
|
||
cues = []
|
||
for cue in subtitles:
|
||
_keys(cue, {"start", "end", "text"})
|
||
start, end = (
|
||
_float(cue.get("start"), 0, 86400 * 1000),
|
||
_float(cue.get("end"), 0, 86400 * 1000),
|
||
)
|
||
text = _string(cue.get("text"), 2000)
|
||
if end <= start or "\n\n" in text or re.search(r"[\\{}\x00-\x08\x0b-\x1f]", text):
|
||
raise _invalid("字幕时间或纯文本内容无效;不支持ASS控制语法。")
|
||
cues.append((start, end, html.escape(text, quote=False)))
|
||
parts, total = [], 0.0
|
||
for source, start, end in normalized:
|
||
info = await inspect_media(source, provider.settings)
|
||
if info["kind"] != "video":
|
||
raise _invalid("编排片段必须是视频素材。")
|
||
end = info["duration_seconds"] if end is None else end
|
||
if start >= end or end > info["duration_seconds"] + 0.05 or end - start < 0.05:
|
||
raise _invalid("裁剪范围超出视频实际时长。")
|
||
total += end - start
|
||
parts.append((source, start, end - start, info.get("has_audio", False)))
|
||
if any(end > total + 0.05 for _, end, _ in cues):
|
||
raise _invalid("字幕超出成片时长。")
|
||
if audio and (await inspect_media(audio, provider.settings))["kind"] != "audio":
|
||
raise _invalid("成片音轨必须为音频素材。")
|
||
files = []
|
||
async with asyncio.timeout(900):
|
||
for index, (source, start, duration, has_audio) in enumerate(parts):
|
||
target = work / f"clip-{index:03d}.mp4"
|
||
command = [
|
||
provider.settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-nostdin",
|
||
*input_options(),
|
||
"-i",
|
||
str(source),
|
||
]
|
||
if not has_audio:
|
||
command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"]
|
||
command += [
|
||
"-ss",
|
||
f"{start:.6f}",
|
||
"-t",
|
||
f"{duration:.6f}",
|
||
"-map",
|
||
"0:v:0",
|
||
"-map",
|
||
"0:a:0" if has_audio else "1:a:0",
|
||
"-vf",
|
||
f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}",
|
||
"-c:v",
|
||
"libx264",
|
||
"-preset",
|
||
"veryfast",
|
||
"-crf",
|
||
"20",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
"-c:a",
|
||
"aac",
|
||
"-ar",
|
||
"48000",
|
||
"-ac",
|
||
"2",
|
||
"-threads",
|
||
"2",
|
||
"-fs",
|
||
str(provider.settings.max_output_bytes),
|
||
str(target),
|
||
]
|
||
await run_process(command, timeout=min(600, max(60, duration * 5)))
|
||
files.append(target)
|
||
if sum(path.stat().st_size for path in files) >= provider.settings.max_output_bytes:
|
||
raise ProviderError("output_too_large", "成片中间文件超出大小限制。")
|
||
listing = work / "concat.txt"
|
||
listing.write_text("".join(f"file '{path.name}'\n" for path in files), encoding="utf-8")
|
||
if cues:
|
||
|
||
def stamp(value):
|
||
milliseconds = round(value * 1000)
|
||
hours, milliseconds = divmod(milliseconds, 3600000)
|
||
minutes, milliseconds = divmod(milliseconds, 60000)
|
||
seconds, milliseconds = divmod(milliseconds, 1000)
|
||
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
|
||
|
||
(work / "subtitles.srt").write_text(
|
||
"".join(
|
||
f"{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n"
|
||
for index, (start, end, text) in enumerate(cues, 1)
|
||
),
|
||
encoding="utf-8",
|
||
)
|
||
target = work / "composition.mp4"
|
||
command = [
|
||
provider.settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-nostdin",
|
||
"-f",
|
||
"concat",
|
||
"-safe",
|
||
"1",
|
||
"-i",
|
||
listing.name,
|
||
]
|
||
if audio:
|
||
command += [*input_options(), "-i", str(audio)]
|
||
command += ["-map", "0:v:0", "-map", "1:a:0" if audio else "0:a:0"]
|
||
if cues:
|
||
command += [
|
||
"-vf",
|
||
"subtitles=filename=subtitles.srt",
|
||
"-c:v",
|
||
"libx264",
|
||
"-preset",
|
||
"veryfast",
|
||
"-crf",
|
||
"20",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
]
|
||
else:
|
||
command += ["-c:v", "copy"]
|
||
command += [
|
||
"-af",
|
||
"apad",
|
||
"-t",
|
||
f"{total:.6f}",
|
||
"-c:a",
|
||
"aac",
|
||
"-threads",
|
||
"2",
|
||
"-movflags",
|
||
"+faststart",
|
||
"-fs",
|
||
str(provider.settings.max_output_bytes),
|
||
str(target),
|
||
]
|
||
await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work)
|
||
info = await inspect_media(target, provider.settings)
|
||
if (
|
||
abs(info["duration_seconds"] - total) > max(0.2, 2 / fps)
|
||
or target.stat().st_size >= provider.settings.max_output_bytes
|
||
):
|
||
raise ProviderError("composition_incomplete", "成片未完整输出或超出大小限制。")
|
||
result = {
|
||
"duration_seconds": info["duration_seconds"],
|
||
"width": width,
|
||
"height": height,
|
||
"fps": fps,
|
||
"clip_count": len(parts),
|
||
"subtitle_count": len(cues),
|
||
}
|
||
manifest = provider._json_file(work, "composition.json", result)
|
||
return CpuResult(
|
||
[target, manifest],
|
||
result,
|
||
{"provider": "ffmpeg-cpu", "audio": "uploaded" if audio else "original-or-silence"},
|
||
)
|