Wan-2.2-Studio / end_frame_trim.py
amisima's picture
Support final-frame trimming across FFmpeg versions
d52f7d2 verified
Raw History Blame Contribute Delete
4.37 kB
"""Remove one final presentation frame on the CPU, after GPU generation."""
from __future__ import annotations
import math
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import uuid
def _ffmpeg_executable() -> str:
for name in ("FFMPEG_BINARY", "IMAGEIO_FFMPEG_EXE", "FFMPEG_BIN"):
value = os.environ.get(name)
if value and (Path(value).is_file() or shutil.which(value)):
return value
try:
import imageio_ffmpeg
return imageio_ffmpeg.get_ffmpeg_exe()
except ImportError:
pass
executable = shutil.which("ffmpeg")
if not executable:
raise RuntimeError("FFmpeg is required to remove the final frame.")
return executable
def _run(args: list[str]) -> subprocess.CompletedProcess:
result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True,
text=True, encoding="utf-8", errors="replace", timeout=180)
if result.returncode:
raise RuntimeError("Final-frame removal failed: " + result.stderr[-1800:])
return result
def _frame_timing(ffmpeg: str, source: str) -> tuple[int, float, str, float]:
# Decode presentation order. Counting/cutting encoded packets is unsafe with B-frames.
result = _run([ffmpeg, "-hide_banner", "-nostdin", "-copyts", "-start_at_zero", "-i", source,
"-map", "0:v:0", "-an", "-vf", "showinfo", "-vsync", "0",
"-f", "null", "-"])
timestamps = [float(value) for value in re.findall(
r"\bn:\s*\d+\s+pts:\s*\S+\s+pts_time:\s*([-+\d.eE]+)", result.stderr)]
if len(timestamps) < 2:
raise ValueError("The video needs at least two frames to remove its final frame.")
duration = timestamps[-1] - timestamps[0]
if not math.isfinite(duration) or duration <= 0:
raise ValueError("The video has invalid frame timestamps.")
rate = re.search(r"config in time_base:\s*\S+,\s*frame_rate:\s*(\d+/\d+)", result.stderr)
if rate and all(int(n) > 0 for n in rate.group(1).split('/')):
frame_rate = rate.group(1)
else:
intervals = [b - a for a, b in zip(timestamps, timestamps[1:]) if b > a]
frame_rate = f"{1.0 / min(intervals):.9f}"
return len(timestamps), duration, frame_rate, timestamps[-1]
def trim_last_video_frame(input_path: str, output_path: str | None = None) -> str:
"""Return a playable MP4 with exactly the final decoded frame removed.
The End image and all preceding frame colors are ungraded. Audio is cropped
to the new video endpoint. Encoding runs entirely on the CPU, using standard
H.264/AAC for playback compatibility. An explicit input=output is atomic.
"""
if not input_path:
raise ValueError("Upload a video before removing its final frame.")
source = Path(input_path).expanduser().resolve()
if not source.is_file():
raise FileNotFoundError("The video to trim was not found.")
ffmpeg = _ffmpeg_executable()
frames, duration, frame_rate, cutoff = _frame_timing(ffmpeg, str(source))
destination = (Path(output_path).expanduser().resolve() if output_path else
source.with_name(source.stem + "_trimmed_" + uuid.uuid4().hex[:8] + ".mp4"))
destination.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=".end-frame-", suffix=".mp4",
dir=str(destination.parent))
os.close(descriptor)
try:
_run([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
"-copyts", "-start_at_zero", "-i", str(source), "-map", "0:v:0", "-map", "0:a:0?",
"-map_metadata", "0", "-vf",
f"trim=end_frame={frames - 1},pad=ceil(iw/2)*2:ceil(ih/2)*2",
"-af", f"atrim=end={cutoff:.12f}",
"-c:v", "libx264", "-preset", "fast", "-crf", "18", "-bf", "0", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k", "-vsync", "0",
"-movflags", "+faststart",
temporary])
if not Path(temporary).is_file() or Path(temporary).stat().st_size == 0:
raise RuntimeError("Final-frame removal produced an empty video.")
os.replace(temporary, destination)
finally:
Path(temporary).unlink(missing_ok=True)
return str(destination)