196 lines
8.0 KiB
Python
196 lines
8.0 KiB
Python
"""Video tool operations: each op builds an ffmpeg argv given (in_path, out_path, params)."""
|
||
import os
|
||
import re
|
||
import subprocess
|
||
|
||
FFMPEG = "ffmpeg"
|
||
MAX_INPUT = 2 * 1024 * 1024 * 1024 # 2GB
|
||
ALLOWED_EXT = {
|
||
".mp4", ".webm", ".mkv", ".mov", ".avi", ".flv", ".wmv", ".ts", ".m4v",
|
||
".gif", ".mp3", ".wav", ".aac", ".ogg", ".flac", ".m4a", ".wma", ".weba",
|
||
}
|
||
AUDIO_EXT = {"mp3": ".mp3", "wav": ".wav", "aac": ".m4a", "ogg": ".ogg"}
|
||
|
||
|
||
def _num(v, lo, hi, default):
|
||
try:
|
||
x = float(v)
|
||
except Exception:
|
||
return default
|
||
return max(lo, min(hi, x))
|
||
|
||
|
||
def _int(v, lo, hi, default):
|
||
return int(_num(v, lo, hi, default))
|
||
|
||
|
||
def build_cmd(op: str, fin: str, fout: str, p: dict):
|
||
"""returns (argv, out_name_hint) or raises ValueError"""
|
||
if op == "convert":
|
||
fmt = p.get("fmt", "mp4")
|
||
if fmt == "mp4":
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libx264", "-preset", "fast", "-crf", "21",
|
||
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", fout], "mp4"
|
||
if fmt == "webm":
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "34",
|
||
"-cpu-used", "4", "-c:a", "libopus", "-b:a", "96k", fout], "webm"
|
||
if fmt == "mkv":
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libx264", "-preset", "fast", "-crf", "21",
|
||
"-c:a", "aac", fout], "mkv"
|
||
if fmt == "mov":
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libx264", "-preset", "fast", "-crf", "21",
|
||
"-c:a", "aac", fout], "mov"
|
||
if fmt == "avi":
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libx264", "-preset", "fast", "-crf", "21",
|
||
"-c:a", "libmp3lame", "-b:a", "128k", fout], "avi"
|
||
raise ValueError("不支持的格式")
|
||
|
||
if op == "gif":
|
||
w = _int(p.get("width"), 160, 1920, 480)
|
||
fps = _int(p.get("fps"), 5, 30, 12)
|
||
return [FFMPEG, "-y", "-i", fin, "-vf", f"fps={fps},scale={w}:-2:flags=lanczos",
|
||
"-loop", "0", fout], "gif"
|
||
|
||
if op == "gif2video":
|
||
return [FFMPEG, "-y", "-i", fin, "-movflags", "+faststart", "-pix_fmt", "yuv420p",
|
||
"-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", fout], "mp4"
|
||
|
||
if op == "compress":
|
||
crf = _int(p.get("crf"), 18, 45, 30)
|
||
scale = _int(p.get("scale"), 0, 2160, 0)
|
||
vf = f"scale=-2:{scale}" if scale > 0 else "null"
|
||
return [FFMPEG, "-y", "-i", fin, "-c:v", "libx264", "-preset", "fast", "-crf", str(crf),
|
||
"-vf", vf, "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "trim":
|
||
start = max(0.0, _num(p.get("start"), 0, 86400, 0))
|
||
dur = max(0.1, _num(p.get("duration"), 0.1, 86400, 10))
|
||
return [FFMPEG, "-y", "-ss", f"{start:.3f}", "-i", fin, "-t", f"{dur:.3f}",
|
||
"-c:v", "libx264", "-preset", "fast", "-crf", "21", "-c:a", "aac",
|
||
"-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "rotate":
|
||
deg = p.get("deg", "90")
|
||
tf = {"90": "transpose=1", "180": "transpose=1,transpose=1", "270": "transpose=2"}.get(str(deg))
|
||
if not tf:
|
||
raise ValueError("角度无效")
|
||
return [FFMPEG, "-y", "-i", fin, "-vf", tf, "-c:v", "libx264", "-preset", "fast",
|
||
"-crf", "21", "-c:a", "copy", "-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "flip":
|
||
mode = p.get("mode", "h")
|
||
tf = "hflip" if mode == "h" else "vflip"
|
||
return [FFMPEG, "-y", "-i", fin, "-vf", tf, "-c:v", "libx264", "-preset", "fast",
|
||
"-crf", "21", "-c:a", "copy", "-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "speed":
|
||
factor = _num(p.get("factor"), 0.25, 4, 1)
|
||
# video: setpts, audio: atempo chain (atempo limited to [0.5, 2] per node)
|
||
chain = []
|
||
f = factor
|
||
while f > 2.0:
|
||
chain.append("atempo=2.0")
|
||
f /= 2.0
|
||
while f < 0.5:
|
||
chain.append("atempo=0.5")
|
||
f /= 0.5
|
||
chain.append(f"atempo={f:.4f}")
|
||
af = ",".join(chain)
|
||
return [FFMPEG, "-y", "-i", fin, "-filter:v", f"setpts={1/factor:.6f}*PTS",
|
||
"-filter:a", af, "-c:v", "libx264", "-preset", "fast", "-crf", "21",
|
||
"-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "mute":
|
||
return [FFMPEG, "-y", "-i", fin, "-an", "-c:v", "copy", "-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "audio":
|
||
fmt = p.get("fmt", "mp3")
|
||
ext = AUDIO_EXT.get(fmt)
|
||
if not ext:
|
||
raise ValueError("不支持的音频格式")
|
||
if fmt == "mp3":
|
||
ac = ["-c:a", "libmp3lame", "-b:a", "192k"]
|
||
elif fmt == "wav":
|
||
ac = ["-c:a", "pcm_s16le"]
|
||
elif fmt == "aac":
|
||
ac = ["-c:a", "aac", "-b:a", "192k"]
|
||
else: # ogg
|
||
ac = ["-c:a", "libvorbis", "-q:a", "5"]
|
||
return [FFMPEG, "-y", "-i", fin, "-vn"] + ac + [fout], ext.lstrip(".")
|
||
|
||
if op == "watermark":
|
||
# text watermark via drawtext
|
||
text = str(p.get("text") or "").strip()
|
||
if not text:
|
||
raise ValueError("请输入水印文字")
|
||
text = text.replace("'", "").replace(":", ":").replace("%", "")
|
||
pos = p.get("position", "br")
|
||
fs_size = _int(p.get("fontsize"), 12, 200, 36)
|
||
color = p.get("color", "white")
|
||
if color not in ("white", "black", "red", "yellow", "cyan", "gray"):
|
||
color = "white"
|
||
opacity = max(10, min(100, _int(p.get("opacity"), 10, 100, 70))) / 100.0
|
||
margin = _int(p.get("margin"), 0, 300, 24)
|
||
if pos == "tl":
|
||
xy = f"x={margin}:y={margin}"
|
||
elif pos == "tr":
|
||
xy = f"x=w-tw-{margin}:y={margin}"
|
||
elif pos == "bl":
|
||
xy = f"x={margin}:y=h-th-{margin}"
|
||
elif pos == "br":
|
||
xy = f"x=w-tw-{margin}:y=h-th-{margin}"
|
||
else: # center
|
||
xy = "x=(w-tw)/2:y=(h-th)/2"
|
||
font = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"
|
||
vf = (f"drawtext=fontfile={font}:text={text}:fontsize={fs_size}"
|
||
f":fontcolor={color}@{opacity:.2f}:{xy}")
|
||
return [FFMPEG, "-y", "-i", fin, "-vf", vf, "-c:v", "libx264", "-preset", "fast",
|
||
"-crf", "20", "-c:a", "copy", "-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "unwatermark":
|
||
# remove watermark region: blur overlay (any background) or delogo fill
|
||
x = _int(p.get("x"), 0, 7680, 0)
|
||
y = _int(p.get("y"), 0, 4320, 0)
|
||
w = _int(p.get("w"), 8, 7680, 100)
|
||
h = _int(p.get("h"), 8, 4320, 100)
|
||
sigma = _int(p.get("sigma"), 5, 100, 30)
|
||
fc = (f"[0:v]crop={w}:{h}:{x}:{y},gblur=sigma={sigma}[ck];"
|
||
f"[0:v][ck]overlay={x}:{y}")
|
||
return [FFMPEG, "-y", "-i", fin, "-filter_complex", fc, "-c:v", "libx264",
|
||
"-preset", "fast", "-crf", "20", "-c:a", "copy",
|
||
"-movflags", "+faststart", fout], "mp4"
|
||
|
||
if op == "screenshot":
|
||
t = max(0.0, _num(p.get("time"), 0, 86400, 0))
|
||
return [FFMPEG, "-y", "-ss", f"{t:.3f}", "-i", fin, "-frames:v", "1", fout], "png"
|
||
|
||
if op == "thumbnail":
|
||
# extract 3 evenly spaced frames -> handled by caller running 3 cmds? keep single-frame
|
||
t = max(0.0, _num(p.get("time"), 0, 86400, 0))
|
||
return [FFMPEG, "-y", "-ss", f"{t:.3f}", "-i", fin, "-frames:v", "1",
|
||
"-vf", "scale=640:-2", fout], "png"
|
||
|
||
raise ValueError("未知操作")
|
||
|
||
|
||
def probe_duration(fin: str) -> float:
|
||
try:
|
||
r = subprocess.run(
|
||
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", fin],
|
||
capture_output=True, text=True, timeout=30,
|
||
)
|
||
return float(r.stdout.strip() or 0)
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def run_ffmpeg(argv, timeout=900):
|
||
env = dict(os.environ)
|
||
env.pop("HTTPS_PROXY", None)
|
||
env.pop("HTTP_PROXY", None)
|
||
r = subprocess.run(argv, capture_output=True, timeout=timeout, env=env)
|
||
if r.returncode != 0:
|
||
err = r.stderr.decode("utf-8", "ignore")[-500:]
|
||
raise RuntimeError("ffmpeg 处理失败: " + err)
|
||
return True
|