840 lines
31 KiB
Python
840 lines
31 KiB
Python
"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
import math
|
||
import os
|
||
import re
|
||
import unicodedata
|
||
from pathlib import Path
|
||
import uuid
|
||
import wave
|
||
|
||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||
|
||
|
||
from app.domain.errors import MediaError
|
||
from app.domain.execution import CpuResult
|
||
from app.adapters.storage import file_thread
|
||
|
||
|
||
def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path:
|
||
try:
|
||
candidate = Path(path)
|
||
boundary = Path(root or settings.workspace_root).resolve()
|
||
if not candidate.is_absolute():
|
||
raise ValueError
|
||
resolved = candidate.resolve()
|
||
if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()):
|
||
raise ValueError
|
||
return resolved
|
||
except (OSError, ValueError, TypeError):
|
||
raise MediaError("invalid_asset", "素材文件不存在或不可访问。") from None
|
||
|
||
|
||
async def _stop(process):
|
||
if process.returncode is None:
|
||
try:
|
||
process.terminate()
|
||
except ProcessLookupError:
|
||
pass
|
||
try:
|
||
await asyncio.wait_for(process.wait(), 2)
|
||
except asyncio.TimeoutError:
|
||
try:
|
||
process.kill()
|
||
except ProcessLookupError:
|
||
pass
|
||
await asyncio.wait_for(process.wait(), 5)
|
||
|
||
|
||
async def _cleanup(process, readers):
|
||
for task in readers:
|
||
if not task.done():
|
||
task.cancel()
|
||
await asyncio.gather(*readers, return_exceptions=True)
|
||
|
||
async def discard(stream):
|
||
while await stream.read(65536):
|
||
pass
|
||
|
||
# 超限或取消后也要排空管道,否则子进程退出后 transport 仍可能被满管道占住。
|
||
drains = [
|
||
asyncio.create_task(discard(process.stdout)),
|
||
asyncio.create_task(discard(process.stderr)),
|
||
]
|
||
try:
|
||
await _stop(process)
|
||
await asyncio.wait_for(asyncio.gather(*drains), 5)
|
||
finally:
|
||
for task in drains:
|
||
if not task.done():
|
||
task.cancel()
|
||
await asyncio.gather(*drains, return_exceptions=True)
|
||
|
||
|
||
async def run_process(
|
||
argv: list[str],
|
||
*,
|
||
timeout: float = 120,
|
||
max_output: int = 1024 * 1024,
|
||
cwd: Path | None = None,
|
||
return_stderr: bool = False,
|
||
) -> bytes | tuple[bytes, bytes]:
|
||
"""只管理本次 FFmpeg/ffprobe 子进程,取消时执行 TERM/KILL/wait。
|
||
|
||
读取期间就限制管道大小,避免任意诊断输出耗尽内存;不会停止共享模型服务。
|
||
"""
|
||
process = None
|
||
readers = []
|
||
|
||
async def read_bounded(stream):
|
||
chunks, count = [], 0
|
||
while chunk := await stream.read(65536):
|
||
count += len(chunk)
|
||
if count > max_output:
|
||
raise MediaError("media_output_limit", "媒体处理诊断超出限制。")
|
||
chunks.append(chunk)
|
||
return b"".join(chunks)
|
||
|
||
try:
|
||
process = await asyncio.create_subprocess_exec(
|
||
*[str(value) for value in argv],
|
||
stdin=asyncio.subprocess.DEVNULL,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
cwd=str(cwd) if cwd else None,
|
||
start_new_session=(os.name == "posix"),
|
||
)
|
||
readers = [
|
||
asyncio.create_task(read_bounded(process.stdout)),
|
||
asyncio.create_task(read_bounded(process.stderr)),
|
||
]
|
||
async with asyncio.timeout(timeout):
|
||
stdout, stderr = await asyncio.gather(*readers)
|
||
await process.wait()
|
||
if process.returncode != 0:
|
||
raise MediaError("media_processing_failed", "媒体解码或处理失败,请检查素材格式。")
|
||
return (stdout, stderr) if return_stderr else stdout
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except asyncio.TimeoutError:
|
||
raise MediaError("media_timeout", "媒体处理超时,请缩短素材后重试。", True) from None
|
||
except (OSError, ValueError):
|
||
raise MediaError("media_unavailable", "媒体处理程序不可用。", True) from None
|
||
finally:
|
||
if process is not None:
|
||
cleanup = asyncio.create_task(_cleanup(process, readers))
|
||
recancelled = False
|
||
while not cleanup.done():
|
||
try:
|
||
await asyncio.shield(cleanup)
|
||
except asyncio.CancelledError:
|
||
recancelled = True
|
||
await cleanup
|
||
if recancelled:
|
||
raise asyncio.CancelledError
|
||
|
||
|
||
def input_options() -> list[str]:
|
||
# 限制输入协议与容器,排除播放列表、网络协议和嵌套文件列表。
|
||
return [
|
||
"-protocol_whitelist",
|
||
"file,pipe",
|
||
"-format_whitelist",
|
||
"mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts",
|
||
]
|
||
|
||
|
||
def _image_info(path):
|
||
try:
|
||
with Image.open(path) as image:
|
||
mime = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp"}.get(
|
||
image.format
|
||
)
|
||
if mime is None or image.width * image.height > 40_000_000:
|
||
raise MediaError("invalid_image", "仅支持像素数受限的 PNG、JPEG、WebP 图片。")
|
||
image.load()
|
||
return {
|
||
"kind": "image",
|
||
"mime_type": mime,
|
||
"width": image.width,
|
||
"height": image.height,
|
||
"duration_seconds": None,
|
||
}
|
||
except UnidentifiedImageError:
|
||
return None
|
||
except (OSError, ValueError, Image.DecompressionBombError):
|
||
raise MediaError("invalid_image", "图片文件无法解码。") from None
|
||
|
||
|
||
def _text_info(path):
|
||
if path.suffix.lower() not in {".json", ".txt", ".md", ".srt", ".vtt"}:
|
||
return None
|
||
try:
|
||
if path.stat().st_size > 4 * 1024 * 1024:
|
||
raise ValueError
|
||
text = path.read_text(encoding="utf-8-sig")
|
||
if "\x00" in text or not text.strip():
|
||
raise ValueError
|
||
is_json = path.suffix.lower() == ".json"
|
||
if is_json:
|
||
json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
|
||
return {
|
||
"kind": "json" if is_json else "text",
|
||
"mime_type": "application/json" if is_json else "text/plain",
|
||
"width": None,
|
||
"height": None,
|
||
"duration_seconds": None,
|
||
}
|
||
except (OSError, UnicodeError, ValueError, RecursionError):
|
||
raise MediaError("invalid_text", "文本或 JSON 文件格式无效。") from None
|
||
|
||
|
||
async def inspect_media(path: Path, settings) -> dict:
|
||
source = confined(path, settings)
|
||
if source.stat().st_size <= 0:
|
||
raise MediaError("invalid_asset", "素材文件为空。")
|
||
text = await asyncio.to_thread(_text_info, source)
|
||
if text is not None:
|
||
return text
|
||
image = await asyncio.to_thread(_image_info, source)
|
||
if image is not None:
|
||
return image
|
||
if source.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}:
|
||
raise MediaError("invalid_image", "图片文件无法解码。")
|
||
raw = await run_process(
|
||
[
|
||
settings.ffprobe_bin,
|
||
"-v",
|
||
"error",
|
||
*input_options(),
|
||
"-show_entries",
|
||
"format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic",
|
||
"-of",
|
||
"json",
|
||
str(source),
|
||
],
|
||
timeout=30,
|
||
max_output=256 * 1024,
|
||
)
|
||
try:
|
||
data = json.loads(raw)
|
||
streams = data["streams"]
|
||
videos = [
|
||
item
|
||
for item in streams
|
||
if item.get("codec_type") == "video"
|
||
and not item.get("disposition", {}).get("attached_pic")
|
||
]
|
||
audios = [item for item in streams if item.get("codec_type") == "audio"]
|
||
if not videos and not audios:
|
||
raise ValueError
|
||
stream = videos[0] if videos else audios[0]
|
||
duration = float(data.get("format", {}).get("duration", stream.get("duration", 0)))
|
||
start_time = float(data.get("format", {}).get("start_time", 0))
|
||
if not math.isfinite(start_time):
|
||
raise ValueError
|
||
if not math.isfinite(duration) or not 0 < duration <= 86400:
|
||
raise ValueError
|
||
width, height = stream.get("width"), stream.get("height")
|
||
if videos and (
|
||
type(width) is not int
|
||
or type(height) is not int
|
||
or width <= 0
|
||
or height <= 0
|
||
or width * height > 40_000_000
|
||
):
|
||
raise ValueError
|
||
formats = str(data.get("format", {}).get("format_name", "")).split(",")
|
||
if videos:
|
||
mime = (
|
||
"video/webm"
|
||
if "webm" in formats and source.suffix.lower() == ".webm"
|
||
else "video/mp4"
|
||
if "mov" in formats
|
||
else "video/x-matroska"
|
||
if "matroska" in formats
|
||
else "video/mp2t"
|
||
if "mpegts" in formats
|
||
else "video/mpeg"
|
||
if "mpeg" in formats
|
||
else "video/x-msvideo"
|
||
)
|
||
else:
|
||
mime = (
|
||
"audio/wav"
|
||
if "wav" in formats
|
||
else "audio/mpeg"
|
||
if "mp3" in formats
|
||
else "audio/flac"
|
||
if "flac" in formats
|
||
else "audio/ogg"
|
||
if "ogg" in formats
|
||
else "audio/aac"
|
||
if "aac" in formats
|
||
else "audio/mp4"
|
||
)
|
||
return {
|
||
"kind": "video" if videos else "audio",
|
||
"mime_type": mime,
|
||
"has_audio": bool(audios),
|
||
"width": width if videos else None,
|
||
"height": height if videos else None,
|
||
"duration_seconds": duration,
|
||
"start_seconds": start_time,
|
||
}
|
||
except (ValueError, TypeError, KeyError, AttributeError):
|
||
raise MediaError("invalid_media", "媒体文件信息无效。") from None
|
||
|
||
|
||
async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None:
|
||
source, target = confined(path, settings), confined(destination, settings, exists=False)
|
||
info = await inspect_media(source, settings)
|
||
if info["kind"] not in {"image", "video"}:
|
||
return None
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
temporary = target.with_name(target.name + ".part-" + uuid.uuid4().hex + ".jpg")
|
||
try:
|
||
if info["kind"] == "image":
|
||
|
||
def convert():
|
||
with Image.open(source) as image:
|
||
image = ImageOps.exif_transpose(image).convert("RGB")
|
||
image.thumbnail((512, 512))
|
||
image.save(temporary, format="JPEG", quality=85)
|
||
|
||
await file_thread(convert)
|
||
else:
|
||
await run_process(
|
||
[
|
||
settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-nostdin",
|
||
*input_options(),
|
||
"-i",
|
||
str(source),
|
||
"-frames:v",
|
||
"1",
|
||
"-vf",
|
||
"scale=512:512:force_original_aspect_ratio=decrease",
|
||
"-threads",
|
||
"2",
|
||
"-f",
|
||
"image2",
|
||
"-update",
|
||
"1",
|
||
str(temporary),
|
||
],
|
||
timeout=60,
|
||
)
|
||
if not temporary.is_file() or temporary.stat().st_size == 0:
|
||
raise MediaError("thumbnail_failed", "预览图生成失败。")
|
||
os.replace(temporary, target)
|
||
return target
|
||
finally:
|
||
temporary.unlink(missing_ok=True)
|
||
|
||
|
||
async def inspect_video_track(path: Path, settings) -> dict:
|
||
"""Count decoded video frames; container or audio duration cannot mask a short source."""
|
||
from fractions import Fraction
|
||
|
||
source = confined(path, settings)
|
||
raw = await run_process(
|
||
[
|
||
settings.ffprobe_bin,
|
||
"-v",
|
||
"error",
|
||
*input_options(),
|
||
"-select_streams",
|
||
"v:0",
|
||
"-count_frames",
|
||
"-show_entries",
|
||
"stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration",
|
||
"-of",
|
||
"json",
|
||
str(source),
|
||
],
|
||
timeout=120,
|
||
max_output=256 * 1024,
|
||
)
|
||
try:
|
||
data = json.loads(raw)
|
||
stream = data["streams"][0]
|
||
frames = int(stream["nb_read_frames"])
|
||
fps = Fraction(stream["avg_frame_rate"])
|
||
width, height = int(stream["width"]), int(stream["height"])
|
||
if frames <= 0 or fps <= 0 or width <= 0 or height <= 0 or width * height > 40000000:
|
||
raise ValueError
|
||
return {
|
||
"frames": frames,
|
||
"fps": float(fps),
|
||
"width": width,
|
||
"height": height,
|
||
"duration": float(data["format"]["duration"]),
|
||
"time_base": stream.get("time_base"),
|
||
}
|
||
except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError):
|
||
raise MediaError("invalid_media", "Video frame decoding failed.") from None
|
||
|
||
|
||
async def cacheable_segment(path, settings, canvas, frames):
|
||
raw = await run_process(
|
||
[
|
||
settings.ffprobe_bin,
|
||
"-v",
|
||
"error",
|
||
*input_options(),
|
||
"-count_frames",
|
||
"-show_streams",
|
||
"-of",
|
||
"json",
|
||
str(path),
|
||
],
|
||
timeout=120,
|
||
max_output=256 * 1024,
|
||
)
|
||
streams = json.loads(raw).get("streams", [])
|
||
if len(streams) != 1:
|
||
return False
|
||
stream = streams[0]
|
||
required = {
|
||
"codec_type": "video",
|
||
"codec_name": "h264",
|
||
"profile": "High",
|
||
"pix_fmt": "yuv420p",
|
||
"sample_aspect_ratio": "1:1",
|
||
"time_base": "1/12288",
|
||
"avg_frame_rate": "24/1",
|
||
"width": canvas[0],
|
||
"height": canvas[1],
|
||
"nb_read_frames": str(frames),
|
||
}
|
||
return all(stream.get(k) == v for k, v in required.items()) and all(
|
||
stream.get(k) in (None, "unknown", expected)
|
||
for k, expected in (
|
||
("color_space", "bt709"),
|
||
("color_transfer", "bt709"),
|
||
("color_primaries", "bt709"),
|
||
("color_range", "tv"),
|
||
)
|
||
)
|
||
|
||
|
||
async def subtitle_filter_args(cues, work, canvas, ffmpeg_bin):
|
||
if not cues:
|
||
return []
|
||
font = "Microsoft YaHei" if os.name == "nt" else "Noto Sans CJK SC"
|
||
# 只在排版层换行;SRT、台词、手工锁以及识别的原文保持同一份数据。
|
||
width_units = max(5, int(canvas[0] * 0.88 / 26))
|
||
|
||
def wrap(text):
|
||
lines, line, used = [], [], 0
|
||
for char in text:
|
||
width = (
|
||
0
|
||
if unicodedata.combining(char)
|
||
else (2 if unicodedata.east_asian_width(char) in "WF" else 1)
|
||
)
|
||
if used + width > width_units and line:
|
||
lines.append("".join(line))
|
||
line, used = [], 0
|
||
line.append(char)
|
||
used += width
|
||
return "\n".join([*lines, "".join(line)])
|
||
|
||
displayed = [wrap(c["text"]) for c in cues]
|
||
if len(cues) > 32 or any("\n" in s for s in displayed):
|
||
filters = await run_process([ffmpeg_bin, "-hide_banner", "-filters"], timeout=10)
|
||
if re.search(rb"^\s*\S+\s+ass\s+V->V", filters, re.MULTILINE):
|
||
# 24fps 每个边界向下取整至 ASS 厘秒,该时刻位于上一帧之后、本帧之内。
|
||
def stamp(frame):
|
||
seconds, centis = divmod(frame * 100 // 24, 100)
|
||
hours, seconds = divmod(seconds, 3600)
|
||
minutes, seconds = divmod(seconds, 60)
|
||
return f"{hours}:{minutes:02}:{seconds:02}.{centis:02}"
|
||
|
||
header = (
|
||
f"[Script Info]\nScriptType: v4.00+\nPlayResX: {canvas[0]}\nPlayResY: {canvas[1]}\n"
|
||
"WrapStyle: 2\nScaledBorderAndShadow: yes\n[V4+ Styles]\n"
|
||
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour,"
|
||
" Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline,"
|
||
" Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
|
||
f"Style: Default,{font},48,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,"
|
||
"0,0,0,0,100,100,0,0,1,3,0,2,0,0,60,1\n[Events]\n"
|
||
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
|
||
)
|
||
# 入口 Subtitle 已拒绝反斜线、花括号和控制字符;逗号可用于最后一列。
|
||
rows = (
|
||
f"Dialogue: 0,{stamp(c['start_frame'])},{stamp(c['end_frame'])},Default,,0,0,0,,"
|
||
+ text.replace("\n", r"\N")
|
||
+ "\n"
|
||
for c, text in zip(cues, displayed, strict=True)
|
||
)
|
||
(work / "subtitles.ass").write_text(header + "".join(rows), encoding="utf-8")
|
||
return ["-vf", "ass=filename=subtitles.ass"]
|
||
filters = []
|
||
for index, cue in enumerate(cues):
|
||
name = f"cue-{index:04d}.txt"
|
||
(work / name).write_text(displayed[index], encoding="utf-8")
|
||
filters.append(
|
||
f"drawtext=font='{font}':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:"
|
||
f"x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'"
|
||
)
|
||
graph = ",".join(filters)
|
||
if len(graph) < 7000:
|
||
return ["-vf", graph]
|
||
script = work / "subtitle-filter.txt"
|
||
script.write_text(graph, encoding="utf-8")
|
||
version = (await run_process([ffmpeg_bin, "-version"], timeout=10)).decode(errors="replace")
|
||
major = re.search(r"ffmpeg version (?:n)?(\d+)", version)
|
||
option = "-/filter:v" if major and int(major[1]) >= 7 else "-filter_script:v"
|
||
return [option, script.name]
|
||
|
||
|
||
async def compose_workflow(plan, work_dir, control=None, *, settings, sources, audio=None):
|
||
"""Render a frozen multi-shot timeline from internal resolved asset paths."""
|
||
if len(sources) != len(plan.spec["shots"]):
|
||
raise MediaError("invalid_timeline", "Source videos differ from the frozen shot count.")
|
||
story_clips = getattr(plan, "clips", None)
|
||
shot_frames = (
|
||
tuple(c["duration_frames"] for c in story_clips)
|
||
if story_clips
|
||
else plan.shot_frames or (plan.clip_frames,) * len(sources)
|
||
)
|
||
starts = tuple(c["start_frame"] for c in story_clips) if story_clips else (0,) * len(sources)
|
||
duration = plan.frames / plan.fps
|
||
duration_text = f"{duration:.9f}".rstrip("0").rstrip(".")
|
||
sources = [confined(p, settings) for p in sources]
|
||
work = Path(work_dir).resolve()
|
||
if not work.is_relative_to(Path(settings.workspace_root).resolve()):
|
||
raise MediaError("invalid_asset", "Invalid work directory.")
|
||
width, height = plan.canvas
|
||
expected = (
|
||
None
|
||
if story_clips
|
||
else (
|
||
plan.generation_parameters["upscale_width"],
|
||
plan.generation_parameters["upscale_height"],
|
||
)
|
||
)
|
||
for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)):
|
||
info = await inspect_video_track(source, settings)
|
||
if info["frames"] < frames + start:
|
||
raise MediaError(
|
||
"short_source",
|
||
f"Each source needs at least {frames} decoded video frames for its selected duration.",
|
||
)
|
||
dimensions = (
|
||
(story_clips[index]["width"], story_clips[index]["height"]) if story_clips else expected
|
||
)
|
||
if story_clips and (
|
||
("fps" in story_clips[index] and story_clips[index]["fps"] != info["fps"])
|
||
or (
|
||
"source_frames" in story_clips[index]
|
||
and story_clips[index]["source_frames"] != info["frames"]
|
||
)
|
||
):
|
||
raise MediaError(
|
||
"invalid_video_profile", "Source facts differ from frozen decoded video."
|
||
)
|
||
if info["fps"] != 24 or (info["width"], info["height"]) != dimensions:
|
||
raise MediaError(
|
||
"invalid_video_profile", "Source video differs from frozen enhanced profile."
|
||
)
|
||
audio_spec = plan.spec["render"]["audio"]
|
||
if bool(audio_spec) != bool(audio):
|
||
raise MediaError("invalid_timeline", "Audio source does not match timeline.")
|
||
if audio:
|
||
audio = confined(audio, settings)
|
||
info = await inspect_media(audio, settings)
|
||
if "source_end_sample" in audio_spec:
|
||
try:
|
||
with wave.open(str(audio), "rb") as stream:
|
||
valid = (
|
||
stream.getframerate(),
|
||
stream.getnchannels(),
|
||
stream.getsampwidth(),
|
||
) == (48000, 2, 2)
|
||
valid = valid and audio_spec["source_end_sample"] <= stream.getnframes()
|
||
valid = (
|
||
valid
|
||
and audio_spec.get("offset_sample", 0)
|
||
+ audio_spec["source_end_sample"]
|
||
- audio_spec["source_start_sample"]
|
||
<= plan.frames * 2000
|
||
)
|
||
except (wave.Error, EOFError):
|
||
valid = False
|
||
if info["kind"] != "audio" or not valid:
|
||
raise MediaError(
|
||
"invalid_timeline", "Audio sample selection requires measured 48k PCM source."
|
||
)
|
||
elif info["kind"] != "audio" or audio_spec["source_end_ms"] > round(
|
||
info["duration_seconds"] * 1000
|
||
):
|
||
raise MediaError("invalid_timeline", "Audio cut exceeds decoded source.")
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
|
||
async def checkpoint():
|
||
if control is not None:
|
||
result = control() if callable(control) else control.checkpoint()
|
||
if hasattr(result, "__await__"):
|
||
await result
|
||
|
||
parts = []
|
||
for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)):
|
||
await checkpoint()
|
||
target = work / f"shot-{index}.mp4"
|
||
fit = plan.spec["render"]["fit"]
|
||
canvas = f"scale={width}:{height}:force_original_aspect_ratio=" + (
|
||
"decrease" if fit == "contain" else "increase"
|
||
)
|
||
canvas += (
|
||
f",pad={width}:{height}:(ow-iw)/2:(oh-ih)/2"
|
||
if fit == "contain"
|
||
else f",crop={width}:{height}"
|
||
)
|
||
vf = (
|
||
f"trim=start_frame={start}:end_frame={start + frames},setpts=PTS-STARTPTS,"
|
||
+ canvas
|
||
+ ",setsar=1"
|
||
)
|
||
from app.services.normalized_cache import active_cache, clip_key
|
||
|
||
cache = active_cache.get() if story_clips and plan.spec.get("schema_version") == 4 else None
|
||
if cache:
|
||
clip = story_clips[index]
|
||
q = plan.spec["shots"][index]["edit"].get("dedup_frames", 0)
|
||
key = clip_key(
|
||
cache.owner,
|
||
clip["sha256"],
|
||
start - q,
|
||
start + frames,
|
||
q,
|
||
plan.canvas,
|
||
fit,
|
||
plan.fps,
|
||
)
|
||
if not cache or not await cache.restore(clip, key, target):
|
||
await run_process(
|
||
[
|
||
settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-nostdin",
|
||
*input_options(),
|
||
"-i",
|
||
str(source),
|
||
"-map",
|
||
"0:v:0",
|
||
"-an",
|
||
"-vf",
|
||
vf,
|
||
"-r",
|
||
"24",
|
||
"-frames:v",
|
||
str(frames),
|
||
"-c:v",
|
||
"libx264",
|
||
"-preset",
|
||
"veryfast",
|
||
"-crf",
|
||
"20",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
"-threads",
|
||
"2",
|
||
"-fs",
|
||
str(settings.max_output_bytes),
|
||
str(target),
|
||
],
|
||
timeout=600,
|
||
)
|
||
if cache:
|
||
try:
|
||
eligible = await cacheable_segment(target, settings, plan.canvas, frames)
|
||
except (MediaError, TimeoutError, ValueError):
|
||
eligible = False
|
||
if eligible:
|
||
await cache.publish(clip, key, target, plan.canvas, frames)
|
||
parts.append(target)
|
||
if sum(p.stat().st_size for p in parts) >= settings.max_output_bytes:
|
||
raise MediaError("output_too_large", "Intermediate media exceeds size budget.")
|
||
listing = work / "concat.txt"
|
||
listing.write_text("".join(f"file '{p.name}'\n" for p in parts), encoding="utf-8")
|
||
target = work / "workflow.mp4"
|
||
command = [
|
||
settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-nostdin",
|
||
"-f",
|
||
"concat",
|
||
"-safe",
|
||
"1",
|
||
"-i",
|
||
listing.name,
|
||
]
|
||
if audio:
|
||
command += [*input_options(), "-i", str(audio)]
|
||
else:
|
||
command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"]
|
||
if audio:
|
||
if "source_end_sample" in audio_spec:
|
||
start, end = audio_spec["source_start_sample"], audio_spec["source_end_sample"]
|
||
delay = audio_spec.get("offset_sample", 0)
|
||
af = f"atrim=start_sample={start}:end_sample={end},asetpts=PTS-STARTPTS,adelay=delays={delay}S:all=1,apad=whole_len={plan.frames * 2000},atrim=end_sample={plan.frames * 2000}"
|
||
else:
|
||
start, end = audio_spec["source_start_ms"] / 1000, audio_spec["source_end_ms"] / 1000
|
||
delay = audio_spec["offset_frame"] * 1000 / 24
|
||
af = f"atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}"
|
||
else:
|
||
af = f"atrim=duration={duration_text}"
|
||
command += ["-map", "0:v:0", "-map", "1:a:0"]
|
||
command += await subtitle_filter_args(plan.spec["render"]["subtitles"], work, plan.canvas, settings.ffmpeg_bin)
|
||
command += [
|
||
"-af",
|
||
af,
|
||
"-frames:v",
|
||
str(plan.frames),
|
||
"-r",
|
||
"24",
|
||
"-c:v",
|
||
"libx264",
|
||
"-preset",
|
||
"veryfast",
|
||
"-crf",
|
||
"20",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
"-c:a",
|
||
"aac",
|
||
"-ar",
|
||
"48000",
|
||
"-ac",
|
||
"2",
|
||
"-threads",
|
||
"2",
|
||
"-movflags",
|
||
"+faststart",
|
||
"-fs",
|
||
str(settings.max_output_bytes),
|
||
str(target),
|
||
]
|
||
await checkpoint()
|
||
await run_process(command, timeout=min(3600, max(600, duration * 5)), cwd=work)
|
||
info = await inspect_video_track(target, settings)
|
||
if (
|
||
info["frames"] != plan.frames
|
||
or info["fps"] != 24
|
||
or (info["width"], info["height"]) != plan.canvas
|
||
or abs(info["duration"] - duration) > 0.10
|
||
or target.stat().st_size >= settings.max_output_bytes
|
||
):
|
||
raise MediaError(
|
||
"composition_incomplete",
|
||
"Final video differs from the frozen frame count, profile or duration.",
|
||
)
|
||
result = {
|
||
"frames": plan.frames,
|
||
"fps": 24,
|
||
"duration_seconds": duration,
|
||
"width": width,
|
||
"height": height,
|
||
"clip_count": len(sources),
|
||
"subtitle_count": len(plan.spec["render"]["subtitles"]),
|
||
}
|
||
return CpuResult(
|
||
[target],
|
||
result,
|
||
{"provider": "ffmpeg-cpu", "profile": plan.spec["profile"], "template_version": "plain-v1"},
|
||
)
|
||
|
||
|
||
async def compose_story(plan, work_dir, control=None, *, settings, sources, audio=None):
|
||
"""v3 专用计划,保持独立验证,不经过旧 compile_timeline。"""
|
||
from app.domain.stories import StoryRenderPlan
|
||
from dataclasses import replace
|
||
import hashlib
|
||
|
||
recovered_clips = []
|
||
|
||
if not isinstance(plan, StoryRenderPlan):
|
||
raise MediaError("invalid_timeline", "需要冻结的故事合成计划")
|
||
for source, clip in zip(sources, plan.clips):
|
||
source = confined(source, settings)
|
||
|
||
def checksum():
|
||
h = hashlib.sha256()
|
||
with source.open("rb") as stream:
|
||
while chunk := stream.read(1024 * 1024):
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
if await asyncio.to_thread(checksum) != clip["sha256"]:
|
||
raise MediaError("dependency_changed", "冻结视频 SHA 不匹配")
|
||
# 旧自动快照缺少解码尺寸;只在原字节SHA确认后补齐执行副本,不重写历史冻结输入。
|
||
recovered = dict(clip)
|
||
if "width" not in clip or "height" not in clip:
|
||
info = await inspect_video_track(source, settings)
|
||
for key in ("width", "height"):
|
||
if key not in recovered:
|
||
recovered[key] = info[key]
|
||
recovered_clips.append(recovered)
|
||
plan = replace(plan, clips=tuple(recovered_clips))
|
||
return await compose_workflow(
|
||
plan, work_dir, control, settings=settings, sources=sources, audio=audio
|
||
)
|
||
|
||
|
||
async def inspect_video_timeline(path: Path, settings) -> float:
|
||
"""用真实视频帧的时间戳计时;容器时长可能被更长的音轨撑大。"""
|
||
from fractions import Fraction
|
||
from statistics import median
|
||
|
||
source = confined(path, settings)
|
||
raw = await run_process(
|
||
[
|
||
settings.ffprobe_bin,
|
||
"-v",
|
||
"error",
|
||
*input_options(),
|
||
"-select_streams",
|
||
"v:0",
|
||
"-show_frames",
|
||
"-show_entries",
|
||
"frame=best_effort_timestamp_time,duration_time,pkt_duration_time:stream=avg_frame_rate",
|
||
"-of",
|
||
"json",
|
||
str(source),
|
||
],
|
||
timeout=120,
|
||
max_output=16 * 1024 * 1024,
|
||
)
|
||
try:
|
||
data = json.loads(raw)
|
||
frames = data["frames"]
|
||
timestamps = [float(frame["best_effort_timestamp_time"]) for frame in frames]
|
||
if not timestamps or any(not math.isfinite(t) for t in timestamps):
|
||
raise ValueError
|
||
gaps = [b - a for a, b in zip(timestamps, timestamps[1:])]
|
||
if any(gap <= 0 for gap in gaps):
|
||
raise ValueError
|
||
last = frames[-1]
|
||
duration = float(last.get("duration_time", last.get("pkt_duration_time", 0)))
|
||
if not math.isfinite(duration) or duration <= 0:
|
||
duration = (
|
||
median(gaps) if gaps else 1 / float(Fraction(data["streams"][0]["avg_frame_rate"]))
|
||
)
|
||
total = timestamps[-1] + duration - timestamps[0]
|
||
if not math.isfinite(total) or total <= 0:
|
||
raise ValueError
|
||
return total
|
||
except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError):
|
||
raise MediaError("invalid_media", "视频时间轴无法解码。") from None
|