feat: 视频工具 — 11个ffmpeg视频处理工具(转码/压缩/裁剪/旋转/翻转/变速/消音/提取音频/截图/GIF互转), 受控授权

This commit is contained in:
personal82555 committed 2026-10-12 10:55:57 +08:00
1 parent 827547e622
commit 0ec5624add
12 files changed
+902 -3

No files matched your search

+1
View File
@@ -235,6 +235,7 @@ declare module '@vue/runtime-core' {
UserAgentResultCards: typeof import('./src/tools/user-agent-parser/user-agent-result-cards.vue')['default']
UserMenu: typeof import('./src/components/UserMenu.vue')['default']
UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default']
VideoTools: typeof import('./src/tools/video-tools/video-tools.vue')['default']
WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default']
XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default']
XmlToJson: typeof import('./src/tools/xml-to-json/xml-to-json.vue')['default']
+73 -1
View File
@@ -44,7 +44,7 @@ AUTH_PASS = os.environ.get("AUTH_PASS", "")
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools"}
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools"}
MACHINE_RE = re.compile(r"^\d{10,16}$")
# verify() messages that unconditionally block activation
@@ -882,11 +882,83 @@ class Handler(BaseHTTPRequestHandler):
except Exception: # noqa: BLE001
return {}
def _handle_video(self):
import uuid as _uuid
import video_ops
machine = self.headers.get("X-Machine-Id", "")
status = check(machine, "video-tools")
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
ctype = self.headers.get("Content-Type", "")
length = int(self.headers.get("Content-Length") or 0)
if length > video_ops.MAX_INPUT + 1024 * 1024:
self._reply(413, json.dumps({"code": 413, "message": "文件超过 2GB 限制"}, ensure_ascii=False).encode(), "application/json")
return
raw = self.rfile.read(length) if length else b""
env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)}
fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True)
fobj = fs["file"] if ("file" in fs.keys()) else None
if not fobj or not getattr(fobj, "filename", None):
self._reply(400, json.dumps({"code": 400, "message": "缺少视频文件"}, ensure_ascii=False).encode(), "application/json")
return
fname = os.path.basename(fobj.filename or "video")
ext = os.path.splitext(fname)[1].lower()
if ext not in video_ops.ALLOWED_EXT:
self._reply(400, json.dumps({"code": 400, "message": "不支持的文件类型 " + ext}, ensure_ascii=False).encode(), "application/json")
return
op = (fs["op"].value if "op" in fs.keys() else "") or ""
params = {}
for k in fs.keys():
if k not in ("file", "op"):
params[k] = fs[k].value
fdata = fobj.file.read()
if not fdata:
self._reply(400, json.dumps({"code": 400, "message": "文件为空"}, ensure_ascii=False).encode(), "application/json")
return
workdir = "/tmp/video-" + _uuid.uuid4().hex[:12]
os.makedirs(workdir, exist_ok=True)
fin = os.path.join(workdir, "in" + ext)
with open(fin, "wb") as f:
f.write(fdata)
duration = video_ops.probe_duration(fin)
argv, out_ext = video_ops.build_cmd(op, fin, None, params)
fout = os.path.join(workdir, "out." + out_ext)
argv[argv.index(fout) if fout in argv else len(argv) - 1] = fout
video_ops.run_ffmpeg(argv)
with open(fout, "rb") as f:
out = f.read()
base = os.path.splitext(fname)[0][:80]
out_name = base + "-out." + out_ext
body = (b"--vidboundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" +
out_name.encode("utf-8") + b"\"\r\nContent-Type: application/octet-stream\r\n\r\n" +
out + b"\r\n--vidboundary--\r\n")
self.send_response(200)
self.send_header("Content-Type", "multipart/form-data; boundary=vidboundary")
self.send_header("Content-Length", str(len(body)))
self.send_header("X-Duration-Seconds", str(round(duration, 2)))
self.end_headers()
self.wfile.write(body)
except ValueError as e:
self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json")
except Exception as e: # noqa: BLE001
self._reply(500, json.dumps({"code": 500, "message": "处理失败: " + str(e)[:300]}, ensure_ascii=False).encode("utf-8"), "application/json")
finally:
try:
if "workdir" in dir() and workdir and os.path.isdir(workdir):
shutil.rmtree(workdir, ignore_errors=True)
except Exception:
pass
def do_POST(self):
parsed = parse.urlparse(self.path)
if parsed.path.startswith("/user"):
self._handle_user("POST")
return
if parsed.path == "/video":
self._handle_video()
return
if parsed.path == "/convert":
self._handle_convert()
return
+153
View File
@@ -0,0 +1,153 @@
"""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 == "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
+3
View File
@@ -275,6 +275,9 @@ tools:
title: Image OCR
description: Extract text from images with OCR - click, drag & drop or paste a screenshot, get recognized lines with confidence scores, copy or download as TXT.
video-tools:
title: 'Video tools'
description: 'Video convert, compress, trim, speed, audio extract, GIF convert and more'
label-designer:
title: Label designer
description: Design shipping & product labels from ready-made templates, import an existing PDF label to edit it (cover & replace text), then export the result as a printable PDF.
+3
View File
@@ -272,6 +272,9 @@ tools:
title: 图片OCR文字识别
description: 上传、拖拽或粘贴截图识别图片中的文字,逐行输出识别结果和置信度,支持复制全部和下载TXT。
video-tools:
title: '视频工具'
description: '视频格式转换、压缩、裁剪、变速、提取音频、GIF 互转等 11 个常用视频处理工具,服务端高速处理'
label-designer:
title: 面单设计
description: 内置快递面单、物流标签、价格标签等常用模板,导入即可修改;支持上传PDF面单作底图二次编辑(遮盖改字),完成后一键导出PDF打印。
+1 -1
View File
@@ -19,7 +19,7 @@ server {
# license relay (card activation etc; auth gate itself must stay open)
location /relay/ {
client_max_body_size 110m;
client_max_body_size 2g;
proxy_pass http://it-tools-relay:8091/;
proxy_connect_timeout 5s;
proxy_read_timeout 300s;
+1
View File
@@ -22,6 +22,7 @@ const groups: { title: string; items: Item[] }[] = [
{ name: 'AI修图', icon: 'AI', desc: '去水印/修复(涂抹智能填充)、抠图去背景、4x 超分辨率、人脸修复,本地 AI 模型 10 秒级出图', tag: '全新' },
{ name: 'IT网站收藏', icon: '藏', desc: '内置 91 个精选开发站点(社区/文档/工具/AI/设计/视频/媒体平台),数据存用户本地,可自选目录', tag: '全新' },
{ name: '文档格式转换', icon: '转', desc: 'Word/PDF/TXT/RTF/ODT/EPUB/MOBI/AZW3/HTML 九格式互转,自建 calibre 引擎,批量打包下载', tag: '全新' },
{ name: '视频工具', icon: '视', desc: '格式转换、压缩、裁剪、旋转、变速、消音、提取音频、截图、GIF 互转等 11 个工具,服务端 ffmpeg 高速处理,最大 2GB', tag: '全新' },
],
},
{
+6
View File
@@ -48,6 +48,12 @@ const FEATURES: Feature[] = [
icon: '🖼️',
points: ['压缩/转换/尺寸/裁剪/旋转/滤镜等 12 种常用处理', '打码、加水印、拼接、EXIF 查看编辑', '全程浏览器本地处理,图片不上传服务器'],
},
{
path: '/video-tools',
name: '视频工具',
icon: '🎥',
points: ['格式转换/压缩/裁剪/旋转/变速/消音/提取音频/截图/GIF互转等 11 个工具', '服务端 ffmpeg 高速转码,最大支持 2GB 视频', '处理完在线预览,一键下载结果'],
},
{
path: '/label-designer',
name: '面单设计',
+2 -1
View File
@@ -81,6 +81,7 @@ import { tool as codeReader } from './code-reader';
import { tool as pdfOcr } from './pdf-ocr';
import { tool as pdfTools } from './pdf-tools';
import { tool as imageTools } from './image-tools';
import { tool as videoTools } from './video-tools';
import { tool as docConvert } from './doc-convert';
import { tool as aiRetouch } from './ai-retouch';
import { tool as wifiQrCodeGenerator } from './wifi-qr-code-generator';
@@ -152,7 +153,7 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Images and videos',
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, videoTools, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
},
{
name: 'Development',
+1
View File
@@ -14,6 +14,7 @@ export const PROTECTED_TOOLS: Record<string, string> = {
'/doc-convert': '文档格式转换',
'/image-tools': '图片工具',
'/pdf-tools': 'PDF工具',
'/video-tools': '视频工具',
};
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能免费 30 分钟
+12
View File
@@ -0,0 +1,12 @@
import { Movie } from '@vicons/tabler';
import { defineTool } from '../tool';
import { translate } from '@/plugins/i18n.plugin';
export const tool = defineTool({
name: translate('tools.video-tools.title'),
path: '/video-tools',
description: translate('tools.video-tools.description'),
keywords: ['video', 'convert', 'compress', 'trim', 'gif', 'mp4', 'webm', 'mkv', 'audio', 'mp3', '视频', '转码', '压缩', '裁剪', '变速', 'GIF', '提取音频', '截图'],
component: () => import('./video-tools.vue'),
icon: Movie,
});
+646
View File
@@ -0,0 +1,646 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '../license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
useHead({ title: '视频工具 - IT-TOOLS-PRO' });
interface ParamDef {
key: string;
label: string;
type: 'select' | 'slider' | 'text';
options?: { label: string; value: string }[];
min?: number;
max?: number;
step?: number;
def: string | number;
unit?: string;
}
interface VTool {
op: string;
name: string;
icon: string;
color: string;
desc: string;
tags: string[];
params?: ParamDef[];
}
const GROUPS: { title: string; subtitle: string; tools: VTool[] }[] = [
{
title: '格式转换',
subtitle: '在不同视频 / GIF / 音频格式之间互转',
tools: [
{
op: 'convert', name: '视频格式转换', icon: '🎬', color: '#3b82f6',
desc: '支持 MP4、WebM、MKV、MOV、AVI 等主流格式互转',
tags: ['H.264', 'VP9', '保持音轨'],
params: [{ key: 'fmt', label: '输出格式', type: 'select', def: 'mp4', options: [
{ label: 'MP4(推荐)', value: 'mp4' }, { label: 'WebM', value: 'webm' },
{ label: 'MKV', value: 'mkv' }, { label: 'MOV', value: 'mov' }, { label: 'AVI', value: 'avi' },
] }],
},
{
op: 'gif', name: '视频转GIF', icon: '🎞️', color: '#ef4444',
desc: '把视频片段转成 GIF,可调宽度与帧率',
tags: ['自定义宽度', '帧率可调'],
params: [
{ key: 'width', label: 'GIF 宽度', type: 'slider', min: 160, max: 1280, step: 20, def: 480, unit: 'px' },
{ key: 'fps', label: '帧率', type: 'slider', min: 5, max: 30, step: 1, def: 12, unit: 'fps' },
],
},
{
op: 'gif2video', name: 'GIF转视频', icon: '▶️', color: '#8b5cf6',
desc: '把 GIF 转为 MP4,体积更小更易分享',
tags: ['MP4 输出', '兼容社交平台'],
},
{
op: 'compress', name: '视频压缩', icon: '📦', color: '#8b5cf6',
desc: '智能压缩视频体积,可调压缩强度与分辨率',
tags: ['节省空间', '保持清晰'],
params: [
{ key: 'crf', label: '压缩强度', type: 'slider', min: 18, max: 45, step: 1, def: 30, unit: 'CRF 越大越小' },
{ key: 'scale', label: '限制高度', type: 'select', def: '0', options: [
{ label: '保持原分辨率', value: '0' }, { label: '1080p', value: '1080' },
{ label: '720p', value: '720' }, { label: '480p', value: '480' },
] },
],
},
],
},
{
title: '编辑处理',
subtitle: '裁剪、方向、速度与音轨等常见编辑',
tools: [
{
op: 'trim', name: '视频裁剪', icon: '✂️', color: '#f59e0b',
desc: '按起始时间和时长精确截取片段',
tags: ['秒级精度', '快速截取'],
params: [
{ key: 'start', label: '开始时间(秒)', type: 'text', def: '0' },
{ key: 'duration', label: '截取时长(秒)', type: 'text', def: '10' },
],
},
{
op: 'rotate', name: '视频旋转', icon: '🔄', color: '#22c55e',
desc: '90°、180°、270° 旋转画面',
tags: ['无损音轨', '手机竖屏适配'],
params: [{ key: 'deg', label: '旋转角度', type: 'select', def: '90', options: [
{ label: '顺时针 90°', value: '90' }, { label: '180°', value: '180' }, { label: '逆时针 90°', value: '270' },
] }],
},
{
op: 'flip', name: '视频翻转', icon: '🪞', color: '#8b5cf6',
desc: '水平或垂直镜像翻转画面',
tags: ['水平/垂直', '镜像处理'],
params: [{ key: 'mode', label: '翻转方向', type: 'select', def: 'h', options: [
{ label: '水平翻转', value: 'h' }, { label: '垂直翻转', value: 'v' },
] }],
},
{
op: 'speed', name: '视频调速', icon: '⏩', color: '#f59e0b',
desc: '0.25x 到 4x 变速,画面声音同步调整',
tags: ['慢放', '快进', '音画同步'],
params: [{ key: 'factor', label: '播放速度', type: 'select', def: '1', options: [
{ label: '0.25x 慢放', value: '0.25' }, { label: '0.5x', value: '0.5' }, { label: '1x 原速', value: '1' },
{ label: '1.5x', value: '1.5' }, { label: '2x', value: '2' }, { label: '4x 快进', value: '4' },
] }],
},
{
op: 'mute', name: '视频消音', icon: '🔇', color: '#8b5cf6',
desc: '移除视频中的全部音轨',
tags: ['无损画面', '秒级完成'],
},
],
},
{
title: '提取导出',
subtitle: '从视频中抽取音频与画面',
tools: [
{
op: 'audio', name: '视频提取音频', icon: '🎵', color: '#f97316',
desc: '提取视频音轨为 MP3、WAV、AAC、OGG',
tags: ['MP3', 'WAV', 'AAC', 'OGG'],
params: [{ key: 'fmt', label: '音频格式', type: 'select', def: 'mp3', options: [
{ label: 'MP3(192k)', value: 'mp3' }, { label: 'WAV 无损', value: 'wav' },
{ label: 'AAC', value: 'aac' }, { label: 'OGG', value: 'ogg' },
] }],
},
{
op: 'screenshot', name: '视频截图', icon: '🖼️', color: '#06b6d4',
desc: '截取任意时间点的高清画面为 PNG',
tags: ['PNG 高清', '任意时间点'],
params: [{ key: 'time', label: '截图时间点(秒)', type: 'text', def: '1' }],
},
],
},
];
const allTools = GROUPS.flatMap(g => g.tools);
const currentOp = ref(allTools[0].op);
const current = computed(() => allTools.find(t => t.op === currentOp.value)!);
// param values
const paramVals = ref<Record<string, string | number>>({});
function initParams(t: VTool) {
const v: Record<string, string | number> = {};
for (const p of t.params ?? []) {
v[p.key] = p.def;
}
paramVals.value = v;
}
initParams(current.value);
function selectTool(t: VTool) {
currentOp.value = t.op;
initParams(t);
document.getElementById('video-panel')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// file & processing
const file = ref<File | null>(null);
const fileInput = ref<HTMLInputElement>();
const busy = ref(false);
const error = ref('');
const resultBlob = ref<Blob | null>(null);
const resultName = ref('');
const resultUrl = ref('');
const spent = ref(0);
const genHist = useGenHistory('video-tools');
function pickFile() {
fileInput.value?.click();
}
function onFileInput(e: Event) {
const input = e.target as HTMLInputElement;
setFile(input.files?.[0] ?? null);
input.value = '';
}
function onDrop(e: DragEvent) {
setFile(e.dataTransfer?.files?.[0] ?? null);
}
function setFile(f: File | null) {
file.value = f;
error.value = '';
resultBlob.value = null;
if (resultUrl.value) {
URL.revokeObjectURL(resultUrl.value);
resultUrl.value = '';
}
}
async function process() {
if (!file.value) {
error.value = '请先选择文件';
return;
}
busy.value = true;
error.value = '';
const t0 = Date.now();
try {
const fd = new FormData();
fd.append('file', file.value);
fd.append('op', current.value.op);
for (const [k, v] of Object.entries(paramVals.value)) {
fd.append(k, String(v));
}
const res = await fetch('/relay/video', { method: 'POST', body: fd, headers: licenseHeaders() });
if (!res.ok) {
const b = await res.json().catch(() => ({}));
throw new Error(b.message || `处理失败(${res.status})`);
}
const blob = await res.blob();
const disp = res.headers.get('Content-Disposition') || '';
const m = disp.match(/filename="([^"]+)"/);
resultBlob.value = blob;
resultName.value = m ? m[1] : 'result';
resultUrl.value = URL.createObjectURL(blob);
spent.value = Math.round((Date.now() - t0) / 1000);
genHist.add({ title: `${current.value.name}: ${file.value.name}`, detail: `→ ${resultName.value}(${(blob.size / 1024 / 1024).toFixed(1)}MB, ${spent.value}s)` });
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
function download() {
const a = document.createElement('a');
a.href = resultUrl.value;
a.download = resultName.value;
a.click();
}
const isImageResult = computed(() => /\.(png|jpg|jpeg)$/i.test(resultName.value));
</script>
<template>
<div class="vt-root">
<div class="vt-hero">
<div class="vt-hero-title">VideoKit · 视频工具箱</div>
<div class="vt-hero-sub">
视频格式转换、压缩、裁剪、变速、提取音频等 {{ allTools.length }} 个常用视频处理工具,服务端 ffmpeg 高速处理
</div>
</div>
<div v-for="g in GROUPS" :key="g.title" class="vt-group">
<div class="vt-group-head">
<h3 class="vt-group-title">{{ g.title }} <span class="vt-count">{{ g.tools.length }}</span></h3>
<span class="vt-group-sub">{{ g.subtitle }}</span>
</div>
<div class="vt-grid">
<div
v-for="t in g.tools"
:key="t.op"
class="vt-card"
:class="{ active: t.op === currentOp }"
@click="selectTool(t)"
>
<div class="vt-card-icon" :style="{ background: t.color + '22', color: t.color }">
{{ t.icon }}
</div>
<div class="vt-card-name">
{{ t.name }}
</div>
<div class="vt-card-desc">
{{ t.desc }}
</div>
<div class="vt-card-tags">
<span v-for="tag in t.tags" :key="tag" class="vt-tag">{{ tag }}</span>
</div>
</div>
</div>
</div>
<!-- processing panel -->
<div id="video-panel" class="vt-panel">
<div class="vt-panel-title">
{{ current.icon }} {{ current.name }}
</div>
<div class="vt-drop" @click="pickFile" @dragover.prevent @drop.prevent="onDrop">
<input ref="fileInput" type="file" hidden accept="video/*,.mkv,.avi,.flv,.wmv,.ts,.gif,audio/*" @change="onFileInput">
<template v-if="!file">
<div class="vt-drop-hint">
📁 点击选择或拖拽文件到这里
</div>
<div class="vt-drop-sub">
支持 MP4/WebM/MKV/MOV/AVI/GIF 及常见音视频格式,最大 2GB
</div>
</template>
<div v-else class="vt-file">
🎞️ {{ file.name }} <span class="vt-file-size">({{ (file.size / 1024 / 1024).toFixed(1) }} MB)</span>
<a href="javascript:;" class="vt-clear" @click.stop="setFile(null)">✕ 换一个</a>
</div>
</div>
<div v-if="current.params?.length" class="vt-params">
<div v-for="p in current.params" :key="p.key" class="vt-param">
<label class="vt-param-label">{{ p.label }}</label>
<select
v-if="p.type === 'select'"
v-model="paramVals[p.key]"
class="vt-select"
>
<option v-for="o in p.options" :key="o.value" :value="o.value">{{ o.label }}</option>
</select>
<div v-else-if="p.type === 'slider'" class="vt-slider-row">
<input v-model.number="paramVals[p.key]" type="range" :min="p.min" :max="p.max" :step="p.step" class="vt-slider">
<span class="vt-slider-val">{{ paramVals[p.key] }}{{ p.unit ? ' ' + p.unit : '' }}</span>
</div>
<input v-else v-model="paramVals[p.key]" class="vt-input" type="number" min="0" step="0.1">
</div>
</div>
<div class="vt-actions">
<button class="vt-btn" :disabled="busy || !file" @click="process">
{{ busy ? '⏳ 处理中,请稍候…' : '🚀 开始处理' }}
</button>
</div>
<div v-if="error" class="vt-error">
{{ error }}
</div>
<div v-if="resultUrl" class="vt-result">
<video v-if="!isImageResult" :src="resultUrl" controls class="vt-preview" />
<img v-else :src="resultUrl" class="vt-preview-img" alt="result">
<div class="vt-result-bar">
<span class="vt-result-name">{{ resultName }}({{ (resultBlob?.size ?? 0) / 1024 / 1024 > 1 ? ((resultBlob!.size) / 1024 / 1024).toFixed(1) + ' MB' : ((resultBlob!.size) / 1024).toFixed(0) + ' KB' }} · 用时 {{ spent }}s)</span>
<button class="vt-btn vt-btn-sm" @click="download">
⬇ 下载结果
</button>
</div>
</div>
</div>
<GenHistory tool="video-tools" label="视频处理记录" class="mt-20px" />
</div>
</template>
<style lang="less" scoped>
.vt-root {
max-width: 1000px;
margin: 0 auto;
padding-bottom: 60px;
}
.vt-hero {
text-align: center;
margin: 10px 0 26px;
.vt-hero-title {
font-size: 24px;
font-weight: 800;
background: linear-gradient(48deg, #25636c 0%, #3b956f 55%, #14a058 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.vt-hero-sub {
margin-top: 8px;
font-size: 13px;
opacity: 0.6;
}
}
.vt-group {
margin-bottom: 22px;
.vt-group-head {
display: flex;
align-items: baseline;
gap: 10px;
margin-bottom: 10px;
.vt-group-title {
font-size: 16px;
font-weight: 700;
margin: 0;
.vt-count {
font-size: 11px;
font-weight: 500;
opacity: 0.45;
margin-left: 4px;
}
}
.vt-group-sub {
font-size: 12px;
opacity: 0.5;
}
}
}
.vt-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
}
.vt-card {
border: 1px solid rgba(128, 128, 128, 0.22);
border-radius: 12px;
padding: 13px 14px;
cursor: pointer;
transition: border-color 0.15s, box-shadow 0.15s, transform 0.1s;
&:hover {
border-color: rgba(24, 160, 88, 0.55);
transform: translateY(-1px);
}
&.active {
border-color: #18a058;
box-shadow: 0 0 0 1px #18a058;
}
.vt-card-icon {
width: 36px;
height: 36px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 19px;
margin-bottom: 8px;
}
.vt-card-name {
font-size: 14px;
font-weight: 700;
margin-bottom: 4px;
}
.vt-card-desc {
font-size: 12px;
opacity: 0.62;
line-height: 1.6;
margin-bottom: 8px;
}
.vt-card-tags {
display: flex;
flex-wrap: wrap;
gap: 4px;
.vt-tag {
font-size: 10.5px;
background: rgba(128, 128, 128, 0.1);
border-radius: 5px;
padding: 2px 7px;
opacity: 0.75;
}
}
}
// panel
.vt-panel {
border: 1.5px solid rgba(24, 160, 88, 0.4);
border-radius: 14px;
padding: 18px 20px;
background: rgba(24, 160, 88, 0.03);
margin-top: 8px;
.vt-panel-title {
font-size: 16px;
font-weight: 800;
margin-bottom: 12px;
}
}
.vt-drop {
border: 1.5px dashed rgba(128, 128, 128, 0.4);
border-radius: 10px;
text-align: center;
padding: 18px;
cursor: pointer;
transition: border-color 0.15s;
margin-bottom: 12px;
&:hover {
border-color: #18a058;
}
.vt-drop-hint {
font-size: 14px;
font-weight: 600;
}
.vt-drop-sub {
font-size: 11.5px;
opacity: 0.5;
margin-top: 4px;
}
.vt-file {
font-size: 13.5px;
font-weight: 600;
.vt-file-size {
font-weight: 400;
opacity: 0.55;
}
.vt-clear {
color: #d03050;
margin-left: 12px;
text-decoration: none;
font-weight: 400;
&:hover {
text-decoration: underline;
}
}
}
}
.vt-params {
display: flex;
flex-wrap: wrap;
gap: 14px 24px;
margin-bottom: 12px;
.vt-param {
min-width: 200px;
.vt-param-label {
display: block;
font-size: 12px;
opacity: 0.65;
margin-bottom: 4px;
}
.vt-select,
.vt-input {
width: 100%;
box-sizing: border-box;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 7px;
padding: 6px 10px;
font-size: 13px;
background: #fff;
outline: none;
&:focus {
border-color: #18a058;
}
}
.vt-slider-row {
display: flex;
align-items: center;
gap: 8px;
.vt-slider {
flex: 1;
}
.vt-slider-val {
font-size: 12px;
opacity: 0.7;
min-width: 90px;
}
}
}
}
.vt-actions {
margin-bottom: 6px;
}
.vt-btn {
background: #18a058;
color: #fff;
border: none;
border-radius: 9px;
padding: 9px 26px;
font-size: 14.5px;
font-weight: 700;
cursor: pointer;
transition: opacity 0.15s;
&:hover:not(:disabled) {
opacity: 0.85;
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
&.vt-btn-sm {
padding: 6px 18px;
font-size: 13px;
}
}
.vt-error {
color: #d03050;
font-size: 12.5px;
margin-top: 8px;
word-break: break-all;
}
.vt-result {
margin-top: 14px;
.vt-preview {
width: 100%;
max-height: 380px;
border-radius: 10px;
background: #000;
}
.vt-preview-img {
max-width: 100%;
max-height: 380px;
border-radius: 10px;
}
.vt-result-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
flex-wrap: wrap;
.vt-result-name {
font-size: 12.5px;
opacity: 0.7;
}
}
}
</style>