@@ -27,12 +27,13 @@ export function Popover({ children, onClose }) {
}
export function WaveformStrip({ peaks, active = false, hidden = false }) {
+ const safePeaks = Array.isArray(peaks) ? peaks : [];
return (
- {peaks.map((peak, index) => (
+ {safePeaks.map((peak, index) => (
))}
diff --git a/src/config/editor.js b/src/config/editor.js
index 3bf4541..2d25ac7 100644
--- a/src/config/editor.js
+++ b/src/config/editor.js
@@ -4,6 +4,7 @@ import {
ImageSquare,
MagicWand,
MusicNote,
+ Scan,
Sparkle,
Sticker,
TextT,
@@ -110,6 +111,7 @@ export const TOOL_RAIL = [
{ id: "media", label: "媒体", icon: ImageSquare },
{ id: "text", label: "文本", icon: TextT },
{ id: "caption", label: "字幕", icon: ClosedCaptioning },
+ { id: "smart", label: "智能", icon: Scan },
{ id: "audio", label: "音频", icon: MusicNote },
{ id: "transition", label: "转场", icon: CirclesThree },
{ id: "effects", label: "效果", icon: Sparkle },
diff --git a/src/config/models.js b/src/config/models.js
index d677822..929d76f 100644
--- a/src/config/models.js
+++ b/src/config/models.js
@@ -1,3 +1,9 @@
export const MODEL_ID = "onnx-community/Kokoro-82M-v1.0-ONNX";
export const AUTOMATIC_CAPTION_MODEL_ID = "onnx-community/whisper-small";
export const AUTOMATIC_CAPTION_MODEL_LABEL = "Whisper small";
+export const YOLOS_TINY_MODEL_ID = "Xenova/yolos-tiny";
+export const YOLOS_TINY_MODEL_LABEL = "YOLOS tiny";
+export const YOLOS_TINY_MODEL_REVISION = "e2f9c7673f0fa61849efe2b56a0d7774779ebb9d";
+export const MODNET_MODEL_ID = "Xenova/modnet";
+export const MODNET_MODEL_LABEL = "MODNet";
+export const MODNET_MODEL_REVISION = "fa2fa546052fba4c08921230a26cc69a333fca12";
diff --git a/src/i18n.js b/src/i18n.js
index 92875f2..4f19cf7 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -41,6 +41,7 @@ export const UI_COPY = {
media: "媒体",
text: "文本",
caption: "字幕",
+ smart: "智能",
audio: "音频",
transition: "转场",
effects: "效果",
@@ -73,7 +74,7 @@ export const UI_COPY = {
zoomOut: "缩小时间线",
fitTimeline: "缩放适配",
zoomIn: "放大时间线",
- imageTrack: "图片",
+ imageTrack: "画面",
stickerTrack: "贴纸",
sourceTrack: "视频原声",
voiceTrack: "配音音频",
@@ -108,10 +109,83 @@ export const UI_COPY = {
favorite: "收藏",
saved: "已收藏",
showCaptions: "显示字幕",
+ smartVisionTitle: "AI 智能画面",
+ smartVisionKicker: "本地 ONNX 视觉",
+ smartVisionReady: "分析完成",
+ smartVisionIdle: "等待分析",
+ smartVisionRunning: "模型运行中",
+ smartVisionNoMedia: "先把图片或视频放到图片轨,再分析视觉素材。",
+ smartVisionAnalyze: "识别并优化当前图片",
+ smartVisionAnalyzeAgain: "重新分析当前图片",
+ smartVisionAnalyzeVideo: "分析整段视频",
+ smartVisionAnalyzeAgainVideo: "重新分析整段视频",
+ smartVisionCancel: "取消视觉分析",
+ smartVisionDetection: "主体识别框",
+ smartVisionDetectionDesc: "显示 YOLOS tiny 检出的主体与常见物体",
+ smartVisionMatting: "MODNet 智能抠图",
+ smartVisionMattingDesc: "生成透明人像前景并用于预览与导出",
+ smartVisionCaptionAvoidance: "字幕智能避让",
+ smartVisionCaptionAvoidanceDesc: "自动选择与主体重叠最少的字幕位置",
+ smartVisionCrop: "主体智能裁切",
+ smartVisionCropDesc: "切换画幅时持续把主体保留在安全区",
+ smartVisionSubject: "主主体",
+ smartVisionObjects: "识别物体",
+ smartVisionConfidence: "置信度",
+ smartVisionImageOnly: "视频会先完成全片时序分析,再把 YOLOS 主体轨迹和 MODNet 遮罩用于每个播放与导出时刻。",
+ smartVisionModels: "YOLOS tiny 定位 · MODNet 人像抠图",
+ smartVisionVideoCoverage: "全视频已覆盖",
+ smartVisionTemporalFrames: "个时序帧",
+ smartVisionVideoCutoutExport: "遮罩随视频导出",
+ smartVisionClear: "清除当前分析",
+ smartVisionCutoutDownload: "下载透明 PNG",
+ smartVisionNoSubject: "没有找到高置信度主体,可换一帧后重试。",
+ avatarKicker: "Avatar lab · WebGPU",
+ avatarTitle: "数字人(实验室)",
+ avatarExperimental: "实验功能",
+ avatarSupported: "浏览器已就绪",
+ avatarDescription: "使用正脸照片与当前 AI 配音生成会说话的人像。首版采用浏览器端 ONNX 路径,模型将在首次生成时按需下载。",
+ avatarPortrait: "正脸照片",
+ avatarWebgpu: "WebGPU",
+ avatarAudio: "当前配音",
+ avatarCheck: "检查浏览器支持",
+ avatarRecheck: "重新检查 WebGPU",
+ avatarOfficial: "官方服务路线",
+ avatarService: "官方推理服务",
+ avatarServiceNeeded: "待配置官方 LivePortrait 服务",
+ avatarServiceHint: "官方 LivePortrait 通过服务端完整模型运行:头像 + 音频驱动视频 → 正式人像动画。浏览器不会再生成伪口型结果。",
+ avatarOpen: "打开数字人控制台",
+ avatarLipSyncTitle: "字幕口型同步",
+ avatarLipSyncDescription: "将字幕时间轴和当前 AI 配音映射为人物嘴型与表情节奏。",
+ avatarCurrentPortrait: "当前图片将作为数字人头像",
+ avatarNeedsPortrait: "请先在画面轨放入一张正脸图片",
+ avatarNeedsAudio: "请先生成或添加配音",
+ avatarLipSyncSource: "口型驱动",
+ avatarCaptionSync: "按字幕时间轴同步",
+ avatarNeedsCaptions: "请先生成或添加字幕",
+ avatarSyncMode: "同步方式",
+ avatarSyncModeCaption: "字幕 + 配音精确对齐",
+ avatarGenerationNote: "生成时会按需下载浏览器 ONNX 模型;首次运行需要 WebGPU,并可能耗时较长。",
+ avatarGenerate: "生成口型视频",
+ avatarGenerating: "正在生成数字人视频",
+ avatarGenerationHint: "首次运行会下载模型;请保持此页面打开。",
top: "顶部",
middle: "居中",
bottom: "底部",
fontSize: "字号",
+ captionStyle: "字幕样式",
+ captionStyleHint: "预览和导出会保持一致",
+ captionPresetClassic: "经典",
+ captionPresetNeon: "霓虹",
+ captionPresetBubble: "气泡",
+ captionTextColor: "文字",
+ captionBackground: "底色",
+ captionBorderColor: "外框",
+ captionOpacity: "底色透明度",
+ captionBorderWidth: "外框大小",
+ captionRadius: "圆角",
+ captionPaddingX: "左右间距",
+ captionPaddingY: "上下间距",
+ captionShadow: "文字阴影",
currentCaption: "当前字幕",
captionScriptLabel: "字幕文案",
captionList: "字幕列表",
@@ -199,6 +273,7 @@ export const UI_COPY = {
media: "Media",
text: "Text",
caption: "Captions",
+ smart: "Smart",
audio: "Audio",
transition: "Transitions",
effects: "Effects",
@@ -231,7 +306,7 @@ export const UI_COPY = {
zoomOut: "Zoom out",
fitTimeline: "Fit timeline",
zoomIn: "Zoom in",
- imageTrack: "Image",
+ imageTrack: "Visuals",
stickerTrack: "Stickers",
sourceTrack: "Source audio",
voiceTrack: "Voiceover",
@@ -266,10 +341,83 @@ export const UI_COPY = {
favorite: "Favorite",
saved: "Saved",
showCaptions: "Show captions",
+ smartVisionTitle: "AI Smart Frame",
+ smartVisionKicker: "Local ONNX vision",
+ smartVisionReady: "Analysis ready",
+ smartVisionIdle: "Waiting to analyze",
+ smartVisionRunning: "Running models",
+ smartVisionNoMedia: "Place an image or video on the visual track, then analyze the visual asset.",
+ smartVisionAnalyze: "Detect and optimize image",
+ smartVisionAnalyzeAgain: "Analyze image again",
+ smartVisionAnalyzeVideo: "Analyze full video",
+ smartVisionAnalyzeAgainVideo: "Analyze full video again",
+ smartVisionCancel: "Cancel vision analysis",
+ smartVisionDetection: "Subject detection boxes",
+ smartVisionDetectionDesc: "Show subjects and common objects found by YOLOS tiny",
+ smartVisionMatting: "MODNet background removal",
+ smartVisionMattingDesc: "Create a transparent portrait foreground for preview and export",
+ smartVisionCaptionAvoidance: "Smart caption avoidance",
+ smartVisionCaptionAvoidanceDesc: "Choose the caption position with the least subject overlap",
+ smartVisionCrop: "Subject-aware crop",
+ smartVisionCropDesc: "Keep the subject inside the safe area across aspect ratios",
+ smartVisionSubject: "Primary subject",
+ smartVisionObjects: "Objects",
+ smartVisionConfidence: "Confidence",
+ smartVisionImageOnly: "Video is analyzed across its full duration, then YOLOS tracks and MODNet masks are resolved for every preview and export time.",
+ smartVisionModels: "YOLOS tiny detection · MODNet portrait matting",
+ smartVisionVideoCoverage: "Full video coverage",
+ smartVisionTemporalFrames: "temporal frames",
+ smartVisionVideoCutoutExport: "Mask exports with video",
+ smartVisionClear: "Clear current analysis",
+ smartVisionCutoutDownload: "Download transparent PNG",
+ smartVisionNoSubject: "No high-confidence subject found. Seek to another frame and retry.",
+ avatarKicker: "Avatar lab · WebGPU",
+ avatarTitle: "Talking avatar (Lab)",
+ avatarExperimental: "Experimental",
+ avatarSupported: "Browser ready",
+ avatarDescription: "Generate a talking portrait from a front-facing photo and the current AI voiceover. The browser ONNX model will download on first use.",
+ avatarPortrait: "Front-facing photo",
+ avatarWebgpu: "WebGPU",
+ avatarAudio: "Current voiceover",
+ avatarCheck: "Check browser support",
+ avatarRecheck: "Recheck WebGPU",
+ avatarOfficial: "Official service path",
+ avatarService: "Official inference service",
+ avatarServiceNeeded: "Official LivePortrait service required",
+ avatarServiceHint: "Official LivePortrait runs as a full server-side pipeline: portrait + audio-driven video → portrait animation. The browser will no longer produce simulated lip-sync output.",
+ avatarOpen: "Open avatar controls",
+ avatarLipSyncTitle: "Caption lip sync",
+ avatarLipSyncDescription: "Map caption timing and the current voiceover into mouth and expression timing.",
+ avatarCurrentPortrait: "Use the current image as the avatar portrait",
+ avatarNeedsPortrait: "Put a front-facing photo on the visual track first",
+ avatarNeedsAudio: "Generate or add voiceover first",
+ avatarLipSyncSource: "Lip-sync driver",
+ avatarCaptionSync: "caption timing sync",
+ avatarNeedsCaptions: "Generate or add captions first",
+ avatarSyncMode: "Sync method",
+ avatarSyncModeCaption: "Captions + voiceover alignment",
+ avatarGenerationNote: "The browser ONNX model downloads on demand. First use requires WebGPU and can take a while.",
+ avatarGenerate: "Generate lip-sync video",
+ avatarGenerating: "Generating avatar video",
+ avatarGenerationHint: "First use downloads models. Keep this page open.",
top: "Top",
middle: "Middle",
bottom: "Bottom",
fontSize: "Font size",
+ captionStyle: "Caption style",
+ captionStyleHint: "Matches preview and export",
+ captionPresetClassic: "Classic",
+ captionPresetNeon: "Neon",
+ captionPresetBubble: "Bubble",
+ captionTextColor: "Text",
+ captionBackground: "Background",
+ captionBorderColor: "Border",
+ captionOpacity: "Background opacity",
+ captionBorderWidth: "Border width",
+ captionRadius: "Corner radius",
+ captionPaddingX: "Horizontal padding",
+ captionPaddingY: "Vertical padding",
+ captionShadow: "Text shadow",
currentCaption: "Current caption",
captionScriptLabel: "Caption text",
captionList: "Caption list",
@@ -380,11 +528,11 @@ export const UI_COPY = {
recordingUnsupported: "このブラウザは録音に対応していません",
recordingPermissionDenied: "マイクにアクセスできません。ブラウザ権限を確認してください。",
regenerateVoice: "音声を再生成",
- imageTrack: "画像",
+ imageTrack: "映像",
sourceTrack: "動画原音",
voiceTrack: "ナレーション",
musicTrack: "BGM",
- dropVisualHere: "画像トラックにドロップ",
+ dropVisualHere: "映像トラックにドロップ",
dropVoiceHere: "ナレーショントラックにドロップ",
dropSourceHere: "原音を分離",
dropMusicHere: "BGMトラックにドロップ",
@@ -428,7 +576,7 @@ Object.assign(UI_COPY, {
chooseVoice: "음성 선택",
generateVoice: "음성 생성",
regenerateVoice: "음성 다시 생성",
- imageTrack: "이미지",
+ imageTrack: "화면",
sourceTrack: "원본 오디오",
voiceTrack: "더빙 오디오",
musicTrack: "배경 음악",
@@ -469,7 +617,7 @@ Object.assign(UI_COPY, {
chooseVoice: "Elegir voz",
generateVoice: "Generar voz",
regenerateVoice: "Regenerar voz",
- imageTrack: "Imagen",
+ imageTrack: "Visual",
sourceTrack: "Audio original",
voiceTrack: "Narración",
musicTrack: "Música",
@@ -510,7 +658,7 @@ Object.assign(UI_COPY, {
chooseVoice: "Choisir une voix",
generateVoice: "Générer la voix",
regenerateVoice: "Regénérer la voix",
- imageTrack: "Image",
+ imageTrack: "Visuel",
sourceTrack: "Audio source",
voiceTrack: "Voix off",
musicTrack: "Musique",
@@ -551,7 +699,7 @@ Object.assign(UI_COPY, {
chooseVoice: "Stimme wählen",
generateVoice: "Stimme erzeugen",
regenerateVoice: "Stimme neu erzeugen",
- imageTrack: "Bild",
+ imageTrack: "Bildmaterial",
sourceTrack: "Originalton",
voiceTrack: "Voiceover",
musicTrack: "Musik",
@@ -592,7 +740,7 @@ Object.assign(UI_COPY, {
chooseVoice: "Escolher voz",
generateVoice: "Gerar voz",
regenerateVoice: "Gerar voz novamente",
- imageTrack: "Imagem",
+ imageTrack: "Visual",
sourceTrack: "Áudio original",
voiceTrack: "Narração",
musicTrack: "Música",
@@ -633,7 +781,7 @@ Object.assign(UI_COPY, {
chooseVoice: "เลือกเสียง",
generateVoice: "สร้างเสียง",
regenerateVoice: "สร้างเสียงใหม่",
- imageTrack: "รูปภาพ",
+ imageTrack: "ภาพ",
sourceTrack: "เสียงต้นฉบับ",
voiceTrack: "เสียงพากย์",
musicTrack: "เพลง",
diff --git a/src/lib/captionLayout.js b/src/lib/captionLayout.js
new file mode 100644
index 0000000..f82da8b
--- /dev/null
+++ b/src/lib/captionLayout.js
@@ -0,0 +1,298 @@
+const CAPTION_FONT_WEIGHT = 700;
+const CAPTION_LINE_HEIGHT = 1.35;
+const CAPTION_PADDING_X = 22;
+const CAPTION_PADDING_Y = 12;
+const CAPTION_MIN_HEIGHT = 44;
+const CAPTION_MIN_WIDTH_RATIO = 0.32;
+const CAPTION_MAX_WIDTH_RATIO = 0.68;
+const CAPTION_MAX_WIDTH = 680;
+const CAPTION_RADIUS = 7;
+const CAPTION_SHADOW_BLUR = 6;
+const CAPTION_SHADOW_OFFSET_Y = 1;
+
+export const CAPTION_FONT_FAMILY =
+ 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif';
+
+function toPositiveNumber(value, fallback = 0) {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? number : fallback;
+}
+
+function normalizeFrameSize(size) {
+ return {
+ width: toPositiveNumber(size?.width),
+ height: toPositiveNumber(size?.height),
+ };
+}
+
+function clamp(value, minimum, maximum) {
+ return Math.max(minimum, Math.min(maximum, value));
+}
+
+export function getCaptionScale(referenceFrame, renderFrame) {
+ const reference = normalizeFrameSize(referenceFrame);
+ const render = normalizeFrameSize(renderFrame);
+ if (!reference.height || !render.height) {
+ return 1;
+ }
+ return render.height / reference.height;
+}
+
+export function resolveCaptionMetrics({
+ captionSize = 12,
+ captionStyle = {},
+ referenceFrame,
+ renderFrame,
+} = {}) {
+ const frame = normalizeFrameSize(renderFrame);
+ const scale = getCaptionScale(referenceFrame, frame);
+ const fontSize = Math.max(1, toPositiveNumber(captionSize, 12) * scale);
+ const paddingX = toPositiveNumber(captionStyle.paddingX, CAPTION_PADDING_X) * scale;
+ const paddingY = toPositiveNumber(captionStyle.paddingY, CAPTION_PADDING_Y) * scale;
+ const minWidth = frame.width * CAPTION_MIN_WIDTH_RATIO;
+ const maxWidth = Math.max(
+ minWidth,
+ Math.min(frame.width * CAPTION_MAX_WIDTH_RATIO, CAPTION_MAX_WIDTH * scale),
+ );
+
+ return {
+ scale,
+ fontSize,
+ fontWeight: CAPTION_FONT_WEIGHT,
+ fontFamily: CAPTION_FONT_FAMILY,
+ font: `${CAPTION_FONT_WEIGHT} ${fontSize}px ${CAPTION_FONT_FAMILY}`,
+ lineHeight: fontSize * CAPTION_LINE_HEIGHT,
+ paddingX,
+ paddingY,
+ minHeight: CAPTION_MIN_HEIGHT * scale,
+ minWidth,
+ maxWidth,
+ radius: toPositiveNumber(captionStyle.radius, CAPTION_RADIUS) * scale,
+ shadowBlur: CAPTION_SHADOW_BLUR * scale,
+ shadowOffsetY: CAPTION_SHADOW_OFFSET_Y * scale,
+ };
+}
+
+let measurementContext = null;
+
+export function getCaptionMeasurementContext() {
+ if (measurementContext || typeof document === "undefined") {
+ return measurementContext;
+ }
+ const canvas = document.createElement("canvas");
+ measurementContext = canvas.getContext("2d");
+ return measurementContext;
+}
+
+function getGraphemes(text) {
+ if (typeof Intl !== "undefined" && Intl.Segmenter) {
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
+ return Array.from(segmenter.segment(text), (item) => item.segment);
+ }
+ return Array.from(text);
+}
+
+function getWrapTokens(text) {
+ if (typeof Intl !== "undefined" && Intl.Segmenter) {
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "word" });
+ return Array.from(segmenter.segment(text), (item) => item.segment);
+ }
+ return text.match(/\s+|[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]|[^\s\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]+/gu) ?? [];
+}
+
+function splitOversizedToken(context, token, maxWidth) {
+ const chunks = [];
+ let current = "";
+ getGraphemes(token).forEach((grapheme) => {
+ const candidate = current + grapheme;
+ if (current && context.measureText(candidate).width > maxWidth) {
+ chunks.push(current);
+ current = grapheme;
+ } else {
+ current = candidate;
+ }
+ });
+ if (current) {
+ chunks.push(current);
+ }
+ return chunks;
+}
+
+export function wrapCaptionText(context, text, maxWidth) {
+ const safeText = String(text ?? "");
+ const paragraphs = safeText.split(/\r?\n/);
+ const lines = [];
+
+ paragraphs.forEach((paragraph) => {
+ if (!paragraph) {
+ lines.push("");
+ return;
+ }
+
+ let current = "";
+ getWrapTokens(paragraph).forEach((token) => {
+ const candidate = current + token;
+ if (context.measureText(candidate).width <= maxWidth) {
+ current = candidate;
+ return;
+ }
+
+ if (current) {
+ lines.push(current.trimEnd());
+ }
+ const nextToken = token.trimStart();
+ if (!nextToken) {
+ current = "";
+ return;
+ }
+
+ if (context.measureText(nextToken).width <= maxWidth) {
+ current = nextToken;
+ return;
+ }
+
+ const chunks = splitOversizedToken(context, nextToken, maxWidth);
+ lines.push(...chunks.slice(0, -1));
+ current = chunks.at(-1) ?? "";
+ });
+
+ lines.push(current.trimEnd());
+ });
+
+ return lines.length ? lines : [""];
+}
+
+function getFallbackTextWidth(text, fontSize) {
+ return getGraphemes(String(text ?? "")).reduce(
+ (width, grapheme) => width + (/^[\u0000-\u00ff]$/.test(grapheme) ? fontSize * 0.58 : fontSize),
+ 0,
+ );
+}
+
+export function getCaptionTextLayout({
+ context = getCaptionMeasurementContext(),
+ text = "",
+ captionSize = 12,
+ captionStyle = {},
+ referenceFrame,
+ renderFrame,
+} = {}) {
+ const frame = normalizeFrameSize(renderFrame);
+ const metrics = resolveCaptionMetrics({ captionSize, captionStyle, referenceFrame, renderFrame: frame });
+ if (context) {
+ context.font = metrics.font;
+ }
+
+ const paragraphWidths = String(text ?? "")
+ .split(/\r?\n/)
+ .map((paragraph) =>
+ context ? context.measureText(paragraph).width : getFallbackTextWidth(paragraph, metrics.fontSize),
+ );
+ const preferredTextWidth = Math.max(0, ...paragraphWidths);
+ const width = clamp(
+ preferredTextWidth + metrics.paddingX * 2,
+ metrics.minWidth,
+ metrics.maxWidth,
+ );
+ const contentWidth = Math.max(1, width - metrics.paddingX * 2);
+ const lines = context
+ ? wrapCaptionText(context, text, contentWidth)
+ : String(text ?? "").split(/\r?\n/);
+ const height = Math.max(
+ metrics.minHeight,
+ lines.length * metrics.lineHeight + metrics.paddingY * 2,
+ );
+
+ return {
+ text: String(text ?? ""),
+ frame,
+ metrics,
+ width,
+ height,
+ contentWidth,
+ lines,
+ style: captionStyle,
+ };
+}
+
+function normalizePlacement(placement) {
+ if (typeof placement === "string") {
+ const placements = {
+ top: { x: 50, y: 18 },
+ middle: { x: 50, y: 50 },
+ bottom: { x: 50, y: 78 },
+ };
+ return placements[placement] ?? placements.bottom;
+ }
+ return {
+ x: Number.isFinite(Number(placement?.x)) ? Number(placement.x) : 50,
+ y: Number.isFinite(Number(placement?.y)) ? Number(placement.y) : 78,
+ };
+}
+
+export function positionCaptionLayout(layout, placement) {
+ const point = normalizePlacement(placement);
+ return {
+ x: (layout.frame.width * point.x) / 100 - layout.width / 2,
+ y: (layout.frame.height * point.y) / 100 - layout.height / 2,
+ centerX: (layout.frame.width * point.x) / 100,
+ centerY: (layout.frame.height * point.y) / 100,
+ };
+}
+
+function roundedRectPath(context, x, y, width, height, radius) {
+ const safeRadius = Math.max(0, Math.min(radius, width / 2, height / 2));
+ context.beginPath();
+ if (typeof context.roundRect === "function") {
+ context.roundRect(x, y, width, height, safeRadius);
+ return;
+ }
+ context.moveTo(x + safeRadius, y);
+ context.lineTo(x + width - safeRadius, y);
+ context.quadraticCurveTo(x + width, y, x + width, y + safeRadius);
+ context.lineTo(x + width, y + height - safeRadius);
+ context.quadraticCurveTo(x + width, y + height, x + width - safeRadius, y + height);
+ context.lineTo(x + safeRadius, y + height);
+ context.quadraticCurveTo(x, y + height, x, y + height - safeRadius);
+ context.lineTo(x, y + safeRadius);
+ context.quadraticCurveTo(x, y, x + safeRadius, y);
+ context.closePath();
+}
+
+export function drawCaptionLayout(context, layout, position = { x: 0, y: 0 }) {
+ const { metrics } = layout;
+ const style = layout.style ?? {};
+ const opacity = Math.max(0, Math.min(1, Number(style.backgroundOpacity ?? 0.62)));
+ const borderWidth = Math.max(0, Number(style.borderWidth ?? 0)) * metrics.scale;
+ context.save();
+ roundedRectPath(context, position.x, position.y, layout.width, layout.height, metrics.radius);
+ context.fillStyle = style.backgroundColor || "#05080d";
+ context.globalAlpha = opacity;
+ context.fill();
+ context.globalAlpha = 1;
+ if (borderWidth) {
+ context.lineWidth = borderWidth;
+ context.strokeStyle = style.borderColor || "#ffffff";
+ context.stroke();
+ }
+
+ context.font = metrics.font;
+ context.textAlign = "center";
+ context.textBaseline = "middle";
+ context.fillStyle = style.textColor || "#f5fbff";
+ context.shadowColor = style.effect === "neon" ? (style.borderColor || "#35f0dd") : `rgba(0, 0, 0, ${Math.max(0, Math.min(1, Number(style.shadowOpacity ?? 0.45)))})`;
+ context.shadowBlur = style.effect === "neon" ? metrics.shadowBlur * 2.6 : metrics.shadowBlur;
+ context.shadowOffsetX = 0;
+ context.shadowOffsetY = metrics.shadowOffsetY;
+ const blockHeight = layout.lines.length * metrics.lineHeight;
+ const firstLineY = position.y + (layout.height - blockHeight) / 2 + metrics.lineHeight / 2;
+ layout.lines.forEach((line, index) => {
+ context.fillText(
+ line,
+ position.x + layout.width / 2,
+ firstLineY + index * metrics.lineHeight,
+ layout.contentWidth,
+ );
+ });
+ context.restore();
+}
diff --git a/src/lib/media.js b/src/lib/media.js
index c93728a..3e983aa 100644
--- a/src/lib/media.js
+++ b/src/lib/media.js
@@ -11,6 +11,13 @@ import {
getVisualSegmentTimeline,
makeId,
} from "./timeline.js";
+import {
+ drawCaptionLayout,
+ getCaptionTextLayout,
+ positionCaptionLayout,
+} from "./captionLayout.js";
+import { resolveVisionAnalysisAtTime } from "./vision.js";
+import { getCaptionAvoidancePlacement, getSmartCropRect } from "./visualGeometry.js";
export function getAudioRecordingFormat() {
if (typeof MediaRecorder === "undefined") {
@@ -178,6 +185,96 @@ function loadImage(src) {
});
}
+function createTemporalMaskCache(urls, maxEntries = 8) {
+ const orderedUrls = Array.from(new Set(urls.filter(Boolean)));
+ const urlIndexes = new Map(orderedUrls.map((url, index) => [url, index]));
+ const entries = new Map();
+ let lastReadyImage = null;
+
+ const evictIfNeeded = () => {
+ while (entries.size > maxEntries) {
+ const candidate = Array.from(entries.entries()).find(([, entry]) => entry.image);
+ if (!candidate) {
+ return;
+ }
+ const [url, entry] = candidate;
+ entries.delete(url);
+ if (lastReadyImage === entry.image) {
+ lastReadyImage = null;
+ }
+ entry.image.removeAttribute("src");
+ }
+ };
+
+ const load = (url) => {
+ if (!url) {
+ return Promise.resolve(null);
+ }
+ const existing = entries.get(url);
+ if (existing?.image) {
+ entries.delete(url);
+ entries.set(url, existing);
+ return Promise.resolve(existing.image);
+ }
+ if (existing?.promise) {
+ return existing.promise;
+ }
+
+ const entry = { image: null, promise: null };
+ entry.promise = loadImage(url)
+ .then((image) => {
+ entry.image = image;
+ entry.promise = null;
+ lastReadyImage = image;
+ entries.delete(url);
+ entries.set(url, entry);
+ evictIfNeeded();
+ return image;
+ })
+ .catch(() => {
+ entries.delete(url);
+ return null;
+ });
+ entries.set(url, entry);
+ return entry.promise;
+ };
+
+ const prefetchAround = (url) => {
+ const index = urlIndexes.get(url);
+ if (!Number.isInteger(index)) {
+ return load(url);
+ }
+ return Promise.all(
+ [orderedUrls[index], orderedUrls[index + 1], orderedUrls[index - 1]]
+ .filter(Boolean)
+ .map(load),
+ );
+ };
+
+ return {
+ async prepare(url) {
+ await prefetchAround(url);
+ },
+ get(url) {
+ const entry = entries.get(url);
+ if (entry?.image) {
+ entries.delete(url);
+ entries.set(url, entry);
+ prefetchAround(url).catch(() => {});
+ lastReadyImage = entry.image;
+ return entry.image;
+ }
+ prefetchAround(url).catch(() => {});
+ return lastReadyImage;
+ },
+ dispose() {
+ entries.forEach((entry) => entry.image?.removeAttribute("src"));
+ entries.clear();
+ lastReadyImage = null;
+ },
+ };
+}
+
function loadVideo(src) {
return new Promise((resolve, reject) => {
const video = document.createElement("video");
@@ -198,28 +295,113 @@ function getVisualDimensions(visual) {
};
}
-function drawFittedVisual(context, visual, canvas, fitMode, filter) {
- const { width, height } = canvas;
- const visualSize = getVisualDimensions(visual);
- const imageRatio = visualSize.width / visualSize.height;
- const canvasRatio = width / height;
- const cover = fitMode === "cover";
- let drawWidth;
- let drawHeight;
+const maskedVisualLayerCache = new WeakMap();
- if (cover ? imageRatio > canvasRatio : imageRatio < canvasRatio) {
- drawHeight = height;
- drawWidth = height * imageRatio;
- } else {
- drawWidth = width;
- drawHeight = width / imageRatio;
+function getMaskedVisualLayer(canvas) {
+ let layer = maskedVisualLayerCache.get(canvas);
+ if (!layer) {
+ layer = document.createElement("canvas");
+ maskedVisualLayerCache.set(canvas, layer);
+ }
+ if (layer.width !== canvas.width || layer.height !== canvas.height) {
+ layer.width = canvas.width;
+ layer.height = canvas.height;
+ }
+ return layer;
+}
+
+function drawVisualUsingLayout(context, visual, layout, isMask = false) {
+ if (layout.smartCropRect) {
+ const visualSize = getVisualDimensions(visual);
+ const scaleX = isMask ? visualSize.width / Math.max(1, layout.sourceSize.width) : 1;
+ const scaleY = isMask ? visualSize.height / Math.max(1, layout.sourceSize.height) : 1;
+ context.drawImage(
+ visual,
+ layout.smartCropRect.x * scaleX,
+ layout.smartCropRect.y * scaleY,
+ layout.smartCropRect.width * scaleX,
+ layout.smartCropRect.height * scaleY,
+ 0,
+ 0,
+ layout.outputSize.width,
+ layout.outputSize.height,
+ );
+ return;
}
- const x = (width - drawWidth) / 2;
- const y = (height - drawHeight) / 2;
- context.filter = filter;
- context.drawImage(visual, x, y, drawWidth, drawHeight);
- context.filter = "none";
+ context.drawImage(
+ visual,
+ layout.drawRect.x,
+ layout.drawRect.y,
+ layout.drawRect.width,
+ layout.drawRect.height,
+ );
+}
+
+function drawFittedVisual(context, visual, canvas, fitMode, filter, vision = null) {
+ const { width, height } = canvas;
+ const visualSize = getVisualDimensions(visual);
+ const smartCropEnabled = Boolean(vision?.options?.smartCrop && vision?.subject?.box);
+ const smartCropRect = smartCropEnabled
+ ? getSmartCropRect(visualSize, canvas, vision.subject.box, { padding: 0.14 })
+ : null;
+
+ let layout;
+ if (smartCropRect) {
+ layout = {
+ sourceSize: visualSize,
+ smartCropRect,
+ drawRect: { x: 0, y: 0, width, height },
+ fitMode: "cover",
+ outputSize: { width, height },
+ };
+ } else {
+ const imageRatio = visualSize.width / visualSize.height;
+ const canvasRatio = width / height;
+ const cover = fitMode === "cover";
+ let drawWidth;
+ let drawHeight;
+
+ if (cover ? imageRatio > canvasRatio : imageRatio < canvasRatio) {
+ drawHeight = height;
+ drawWidth = height * imageRatio;
+ } else {
+ drawWidth = width;
+ drawHeight = width / imageRatio;
+ }
+
+ const x = (width - drawWidth) / 2;
+ const y = (height - drawHeight) / 2;
+ layout = {
+ sourceSize: visualSize,
+ smartCropRect: null,
+ drawRect: { x, y, width: drawWidth, height: drawHeight },
+ fitMode,
+ outputSize: { width, height },
+ };
+ }
+
+ const maskVisual =
+ vision?.options?.removeBackground && vision?.maskVisual ? vision.maskVisual : null;
+ if (maskVisual) {
+ const layer = getMaskedVisualLayer(canvas);
+ const layerContext = layer.getContext("2d");
+ layerContext.clearRect(0, 0, layer.width, layer.height);
+ layerContext.save();
+ layerContext.filter = filter;
+ drawVisualUsingLayout(layerContext, visual, layout);
+ layerContext.filter = "none";
+ layerContext.globalCompositeOperation = "destination-in";
+ drawVisualUsingLayout(layerContext, maskVisual, layout, true);
+ layerContext.restore();
+ context.drawImage(layer, 0, 0);
+ } else {
+ context.filter = filter;
+ drawVisualUsingLayout(context, visual, layout);
+ context.filter = "none";
+ }
+
+ return layout;
}
function drawPreviewFrame(context, visual, canvas, options) {
@@ -232,37 +414,52 @@ function drawPreviewFrame(context, visual, canvas, options) {
captionPosition = "bottom",
captionPlacement = null,
captionSize = 12,
+ captionStyle = {},
+ captionReferenceSize = null,
sticker = null,
stickerImage = null,
transitionId = "none",
+ vision = null,
} = options;
const { width, height } = canvas;
context.clearRect(0, 0, width, height);
context.fillStyle = "#090b0f";
context.fillRect(0, 0, width, height);
- drawFittedVisual(context, visual, canvas, fitMode, filter);
+ const visualLayout = drawFittedVisual(context, visual, canvas, fitMode, filter, vision);
if (captionsEnabled && subtitle) {
- const overlayHeight = Math.max(72, captionSize * 2.25);
- const yMap = {
- top: 48,
- middle: height / 2 - overlayHeight / 2,
- bottom: height - overlayHeight - 42,
- };
- const overlayWidth = width - 192;
- const overlayX = captionPlacement
- ? Math.max(24, Math.min(width - overlayWidth - 24, (width * captionPlacement.x) / 100 - overlayWidth / 2))
- : 96;
- const overlayY = captionPlacement
- ? Math.max(24, Math.min(height - overlayHeight - 24, (height * captionPlacement.y) / 100 - overlayHeight / 2))
- : yMap[captionPosition] ?? yMap.bottom;
- context.fillStyle = "rgba(5, 8, 13, 0.62)";
- context.fillRect(overlayX, overlayY, overlayWidth, overlayHeight);
- context.font = `600 ${captionSize}px Inter, system-ui, sans-serif`;
- context.textAlign = "center";
- context.fillStyle = "#f5fbff";
- context.fillText(subtitle.slice(0, 34), overlayX + overlayWidth / 2, overlayY + overlayHeight * 0.62);
+ const captionLayout = getCaptionTextLayout({
+ context,
+ text: subtitle,
+ captionSize,
+ captionStyle,
+ referenceFrame: captionReferenceSize ?? canvas,
+ renderFrame: canvas,
+ });
+ const baseCaptionPlacement = captionPlacement ?? captionPosition;
+ const avoidingPlacement =
+ vision?.options?.avoidCaptions && vision?.subject?.box
+ ? getCaptionAvoidancePlacement(vision.subject.box, {
+ sourceSize: visualLayout.sourceSize,
+ frameSize: canvas,
+ fitMode: visualLayout.fitMode,
+ smartCrop: visualLayout.smartCropRect || false,
+ basePlacement: baseCaptionPlacement,
+ previousPlacement: baseCaptionPlacement,
+ captionSize: {
+ width: captionLayout.width / Math.max(1, width),
+ height: captionLayout.height,
+ },
+ safeMargin: 0.045,
+ })
+ : null;
+ const effectiveCaptionPlacement = avoidingPlacement || baseCaptionPlacement;
+ drawCaptionLayout(
+ context,
+ captionLayout,
+ positionCaptionLayout(captionLayout, effectiveCaptionPlacement),
+ );
}
if (sticker?.src && stickerImage) {
@@ -367,6 +564,8 @@ export async function exportBrowserVideo({
captionPosition,
captionPlacement,
captionSize,
+ captionStyle,
+ captionReferenceSize,
sticker,
stickerSegments = [],
transitionId,
@@ -376,16 +575,59 @@ export async function exportBrowserVideo({
throw new Error("当前浏览器不支持 MediaRecorder,无法导出视频。");
}
+ if (document.fonts?.ready) {
+ await document.fonts.ready.catch(() => {});
+ }
+
onProgress?.({ progress: 4, phase: "准备导出画面" });
const exportVisualSegments = visualSegments.some((segment) => segment.src)
? visualSegments.filter((segment) => segment.src)
: [{ id: "export-visual", src: imageSrc, type: visualType, duration }];
const exportVisualTimeline = getVisualSegmentTimeline(exportVisualSegments);
const visualItems = await Promise.all(
- exportVisualSegments.map(async (segment) => ({
- segment,
- visual: segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src),
- })),
+ exportVisualSegments.map(async (segment) => {
+ const visual = segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src);
+ if (segment.type === "video") {
+ await seekVideoFrame(
+ visual,
+ Math.max(0, Number(segment.sourceStart) || 0),
+ );
+ }
+ const shouldUseCutout = Boolean(
+ segment.type === "image" &&
+ segment.vision?.options?.removeBackground &&
+ segment.vision?.cutoutUrl,
+ );
+ const cutoutVisual = shouldUseCutout
+ ? await loadImage(segment.vision.cutoutUrl).catch(() => null)
+ : null;
+ const temporalMaskUrls =
+ segment.type === "video" && segment.vision?.options?.removeBackground
+ ? Array.from(
+ new Set(
+ (segment.vision.samples ?? [])
+ .map((sample) => sample.cutoutUrl)
+ .filter(Boolean),
+ ),
+ )
+ : [];
+ const temporalMaskCache = temporalMaskUrls.length
+ ? createTemporalMaskCache(temporalMaskUrls)
+ : null;
+ if (temporalMaskCache) {
+ const initialVision = resolveVisionAnalysisAtTime(
+ segment.vision,
+ Math.max(0, Number(segment.sourceStart) || 0),
+ );
+ await temporalMaskCache.prepare(initialVision?.cutoutUrl);
+ }
+ return {
+ segment,
+ visual,
+ cutoutVisual,
+ temporalMaskCache,
+ };
+ }),
);
const stickerSources = Array.from(
new Set([
@@ -477,25 +719,47 @@ export async function exportBrowserVideo({
onProgress?.({ progress: 16, phase: "开始录制视频流" });
recorder.start(250);
- const singleVideo =
- visualItems.length === 1 && visualItems[0]?.segment.type === "video"
- ? visualItems[0].visual
- : null;
- if (singleVideo) {
- singleVideo.currentTime = 0;
- singleVideo.loop = totalDuration > (singleVideo.duration || totalDuration);
- await singleVideo.play().catch(() => {});
- }
const startTime = performance.now();
let animationFrame = 0;
let lastProgressUpdate = 0;
+ let activeVideoItem = null;
const getVisualItemAtTime = (elapsed) => {
const visualIndex = getVisualSegmentIndexAtTime(exportVisualSegments, elapsed);
+ const resolvedIndex =
+ visualIndex >= 0
+ ? visualIndex
+ : Math.max(0, visualItems.length - 1);
return {
- item: visualItems[Math.max(0, visualIndex)] ?? visualItems[0],
- range: exportVisualTimeline[Math.max(0, visualIndex)] ?? exportVisualTimeline[0],
+ item: visualItems[resolvedIndex] ?? visualItems[0],
+ range: exportVisualTimeline[resolvedIndex] ?? exportVisualTimeline[0],
};
};
+ const syncVideoItem = (visualItem, localTime) => {
+ if (visualItem?.segment.type !== "video") {
+ activeVideoItem?.visual.pause();
+ activeVideoItem = null;
+ return Math.max(0, Number(visualItem?.segment.sourceStart) || 0) + localTime;
+ }
+
+ const video = visualItem.visual;
+ const maximumTime = Math.max(0, (Number(video.duration) || 0) - 0.001);
+ const expectedTime = Math.min(
+ maximumTime,
+ Math.max(0, Number(visualItem.segment.sourceStart) || 0) + localTime,
+ );
+ if (activeVideoItem !== visualItem) {
+ activeVideoItem?.visual.pause();
+ activeVideoItem = visualItem;
+ video.loop = false;
+ if (Math.abs(video.currentTime - expectedTime) > 0.03) {
+ video.currentTime = expectedTime;
+ }
+ video.play().catch(() => {});
+ } else if (!video.seeking && Math.abs(video.currentTime - expectedTime) > 0.35) {
+ video.currentTime = expectedTime;
+ }
+ return Math.min(maximumTime, Math.max(0, Number(video.currentTime) || expectedTime));
+ };
const getStickerAtTime = (elapsed) => {
if (!stickerSegments.length) {
return sticker;
@@ -518,15 +782,24 @@ export async function exportBrowserVideo({
const exportCaption =
segmentIndex >= 0 && !exportSegments[segmentIndex]?.hidden ? segments[segmentIndex] : "";
const { item: visualItem, range: visualRange } = getVisualItemAtTime(elapsed);
- if (visualItem?.segment.type === "video" && !singleVideo) {
- const localTime = Math.max(0, elapsed - (visualRange?.start ?? 0));
- const nextVideoTime = Math.min(localTime, visualItem.visual.duration || localTime);
- if (Math.abs(visualItem.visual.currentTime - nextVideoTime) > 0.18) {
- visualItem.visual.currentTime = nextVideoTime;
- }
- }
+ const localTime = Math.max(0, elapsed - (visualRange?.start ?? 0));
+ const visualSourceTime = syncVideoItem(visualItem, localTime);
const exportSticker = getStickerAtTime(elapsed);
- drawPreviewFrame(context, visualItem.visual, canvas, {
+ const exportVisual = visualItem.cutoutVisual || visualItem.visual;
+ const resolvedVision = resolveVisionAnalysisAtTime(
+ visualItem.segment.vision ?? null,
+ visualSourceTime,
+ );
+ const frameVision = resolvedVision
+ ? {
+ ...resolvedVision,
+ options: visualItem.segment.vision?.options ?? resolvedVision.options,
+ maskVisual: resolvedVision.cutoutUrl
+ ? visualItem.temporalMaskCache?.get(resolvedVision.cutoutUrl) ?? null
+ : null,
+ }
+ : null;
+ drawPreviewFrame(context, exportVisual, canvas, {
subtitle: exportCaption,
progress: elapsed / totalDuration,
fitMode,
@@ -535,9 +808,12 @@ export async function exportBrowserVideo({
captionPosition,
captionPlacement,
captionSize,
+ captionStyle,
+ captionReferenceSize,
sticker: exportSticker,
stickerImage: exportSticker?.src ? stickerImageMap.get(exportSticker.src) : null,
transitionId,
+ vision: frameVision,
});
if (elapsed === totalDuration || performance.now() - lastProgressUpdate > 180) {
@@ -565,9 +841,24 @@ export async function exportBrowserVideo({
}
});
const finalSegmentIndex = getSegmentIndexAtTime(exportSegments, totalDuration, captionTargetDuration);
- const { item: finalVisualItem } = getVisualItemAtTime(totalDuration);
+ const { item: finalVisualItem, range: finalVisualRange } = getVisualItemAtTime(totalDuration);
const finalSticker = getStickerAtTime(totalDuration);
- drawPreviewFrame(context, finalVisualItem.visual, canvas, {
+ const finalLocalTime = Math.max(0, totalDuration - (finalVisualRange?.start ?? 0));
+ const finalVisualSourceTime = syncVideoItem(finalVisualItem, finalLocalTime);
+ const finalResolvedVision = resolveVisionAnalysisAtTime(
+ finalVisualItem.segment.vision ?? null,
+ finalVisualSourceTime,
+ );
+ const finalFrameVision = finalResolvedVision
+ ? {
+ ...finalResolvedVision,
+ options: finalVisualItem.segment.vision?.options ?? finalResolvedVision.options,
+ maskVisual: finalResolvedVision.cutoutUrl
+ ? finalVisualItem.temporalMaskCache?.get(finalResolvedVision.cutoutUrl) ?? null
+ : null,
+ }
+ : null;
+ drawPreviewFrame(context, finalVisualItem.cutoutVisual || finalVisualItem.visual, canvas, {
subtitle:
finalSegmentIndex >= 0 && !exportSegments[finalSegmentIndex]?.hidden
? segments[finalSegmentIndex]
@@ -579,9 +870,12 @@ export async function exportBrowserVideo({
captionPosition,
captionPlacement,
captionSize,
+ captionStyle,
+ captionReferenceSize,
sticker: finalSticker,
stickerImage: finalSticker?.src ? stickerImageMap.get(finalSticker.src) : null,
transitionId,
+ vision: finalFrameVision,
});
recorder.stop();
onProgress?.({ progress: 94, phase: "封装导出文件" });
@@ -589,6 +883,14 @@ export async function exportBrowserVideo({
canvasStream.getTracks().forEach((track) => track.stop());
destination?.stream.getTracks().forEach((track) => track.stop());
await audioContext?.close().catch(() => {});
+ visualItems.forEach((item) => {
+ item.temporalMaskCache?.dispose();
+ if (item.segment.type === "video") {
+ item.visual.pause();
+ item.visual.removeAttribute("src");
+ item.visual.load();
+ }
+ });
const blobType = recorder.mimeType || recordingFormat.mimeType || "video/webm";
diff --git a/src/lib/projectArchive.js b/src/lib/projectArchive.js
new file mode 100644
index 0000000..df0c9d6
--- /dev/null
+++ b/src/lib/projectArchive.js
@@ -0,0 +1,96 @@
+import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
+
+export const PROJECT_ARCHIVE_FORMAT = "timeline-studio-archive";
+export const PROJECT_ARCHIVE_VERSION = 2;
+const PROJECT_FILE = "project.json";
+
+function readWithFileReader(file, mode) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(reader.error || new Error("无法读取工程文件"));
+ reader.onload = () => resolve(reader.result);
+ if (mode === "text") reader.readAsText(file);
+ else reader.readAsArrayBuffer(file);
+ });
+}
+
+export async function readProjectFileAsText(file) {
+ return typeof file?.text === "function" ? file.text() : readWithFileReader(file, "text");
+}
+
+async function readProjectFileAsArrayBuffer(file) {
+ return typeof file?.arrayBuffer === "function" ? file.arrayBuffer() : readWithFileReader(file, "arrayBuffer");
+}
+
+function extensionFor(blob, fallback = "bin") {
+ const type = blob?.type || "";
+ const known = {
+ "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/gif": "gif",
+ "video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov",
+ "audio/mpeg": "mp3", "audio/wav": "wav", "audio/x-wav": "wav", "audio/ogg": "ogg", "audio/webm": "webm",
+ };
+ return known[type] || fallback;
+}
+
+function safeName(name, fallback) {
+ return String(name || fallback).replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 96) || fallback;
+}
+
+async function blobForSource(source, blob) {
+ if (blob instanceof Blob) return blob;
+ if (!source) return null;
+ const response = await fetch(source);
+ if (!response.ok) throw new Error("无法读取媒体素材");
+ return response.blob();
+}
+
+/** Create a portable .timeline archive with media binaries and project metadata. */
+export async function createProjectArchive({ project, visualSegments = [], audio, sourceAudio, music }) {
+ const files = {};
+ const media = { visuals: [], audio: null, sourceAudio: null, music: null };
+
+ for (let index = 0; index < visualSegments.length; index += 1) {
+ const segment = visualSegments[index];
+ if (!segment?.src && !segment?.blob) continue;
+ const blob = await blobForSource(segment.src, segment.blob);
+ if (!blob) continue;
+ const path = `media/visuals/${String(index + 1).padStart(3, "0")}-${safeName(segment.name, "visual")}.${extensionFor(blob, segment.type === "video" ? "mp4" : "png")}`;
+ files[path] = new Uint8Array(await blob.arrayBuffer());
+ media.visuals.push({ id: segment.id, path, name: segment.name || "素材", type: blob.type, size: blob.size });
+ }
+
+ for (const [key, track] of Object.entries({ audio, sourceAudio, music })) {
+ if (!(track?.blob instanceof Blob)) continue;
+ const path = `media/audio/${key}-${safeName(track.name, key)}.${extensionFor(track.blob, "webm")}`;
+ files[path] = new Uint8Array(await track.blob.arrayBuffer());
+ media[key] = { path, name: track.name || key, type: track.blob.type, size: track.blob.size };
+ }
+
+ const payload = {
+ format: PROJECT_ARCHIVE_FORMAT,
+ version: PROJECT_ARCHIVE_VERSION,
+ exportedAt: new Date().toISOString(),
+ project,
+ media,
+ };
+ files[PROJECT_FILE] = strToU8(JSON.stringify(payload));
+ return new Blob([zipSync(files, { level: 6 })], { type: "application/zip" });
+}
+
+/** Read and validate a portable project archive. Returns metadata plus media Blobs. */
+export async function readProjectArchive(file) {
+ const files = unzipSync(new Uint8Array(await readProjectFileAsArrayBuffer(file)));
+ if (!files[PROJECT_FILE]) throw new Error("缺少 project.json");
+ const payload = JSON.parse(strFromU8(files[PROJECT_FILE]));
+ if (payload?.format !== PROJECT_ARCHIVE_FORMAT || !payload.project) throw new Error("无效工程包");
+ const getBlob = (entry) => entry?.path && files[entry.path]
+ ? new Blob([files[entry.path]], { type: entry.type || "application/octet-stream" })
+ : null;
+ return {
+ payload,
+ visualMedia: new Map((payload.media?.visuals || []).map((entry) => [entry.id, { ...entry, blob: getBlob(entry) }])),
+ audio: getBlob(payload.media?.audio),
+ sourceAudio: getBlob(payload.media?.sourceAudio),
+ music: getBlob(payload.media?.music),
+ };
+}
diff --git a/src/lib/timeline.js b/src/lib/timeline.js
index 4a3be91..a160d14 100644
--- a/src/lib/timeline.js
+++ b/src/lib/timeline.js
@@ -35,6 +35,7 @@ export function getVisualAssetPayload(asset) {
blob: asset.blob ?? null,
width: asset.width ?? asset.naturalWidth ?? 0,
height: asset.height ?? asset.naturalHeight ?? 0,
+ sourceStart: Math.max(0, Number(asset.sourceStart) || 0),
trackFrames: Array.isArray(asset.trackFrames) ? asset.trackFrames : [],
};
}
diff --git a/src/lib/vision.js b/src/lib/vision.js
new file mode 100644
index 0000000..70b76ec
--- /dev/null
+++ b/src/lib/vision.js
@@ -0,0 +1,782 @@
+const pendingVisionRequests = new Map();
+
+let visionWorker = null;
+
+function createRequestId() {
+ if (globalThis.crypto?.randomUUID) {
+ return `vision-${globalThis.crypto.randomUUID()}`;
+ }
+ return `vision-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+function createAbortError() {
+ if (typeof DOMException !== "undefined") {
+ return new DOMException("视觉分析已取消。", "AbortError");
+ }
+ const error = new Error("视觉分析已取消。");
+ error.name = "AbortError";
+ return error;
+}
+
+function throwIfAborted(signal) {
+ if (signal?.aborted) {
+ throw createAbortError();
+ }
+}
+
+function settleVisionRequest(requestId, settle) {
+ const request = pendingVisionRequests.get(requestId);
+ if (!request) {
+ return;
+ }
+
+ pendingVisionRequests.delete(requestId);
+ request.signal?.removeEventListener("abort", request.handleAbort);
+ settle(request);
+}
+
+function rejectPendingVisionRequests(error) {
+ pendingVisionRequests.forEach((request) => {
+ request.signal?.removeEventListener("abort", request.handleAbort);
+ request.reject(error);
+ });
+ pendingVisionRequests.clear();
+}
+
+function resetVisionWorker(error = null) {
+ visionWorker?.terminate();
+ visionWorker = null;
+ if (error) {
+ rejectPendingVisionRequests(error);
+ }
+}
+
+function getVisionWorker() {
+ if (typeof Worker === "undefined") {
+ return null;
+ }
+
+ if (visionWorker) {
+ return visionWorker;
+ }
+
+ visionWorker = new Worker(new URL("../workers/vision.worker.js", import.meta.url), {
+ type: "module",
+ });
+
+ visionWorker.addEventListener("message", (event) => {
+ const message = event.data;
+ const request = pendingVisionRequests.get(message?.requestId);
+ if (!request) {
+ return;
+ }
+
+ if (message.type === "progress") {
+ try {
+ request.onProgress?.({
+ progress: Math.max(0, Math.min(100, Number(message.progress) || 0)),
+ phase: String(message.phase ?? ""),
+ });
+ } catch (error) {
+ console.warn("Vision progress callback failed.", error);
+ }
+ return;
+ }
+
+ if (message.type === "result") {
+ settleVisionRequest(message.requestId, ({ resolve }) => {
+ resolve({
+ requestId: message.requestId,
+ ...message.result,
+ });
+ });
+ return;
+ }
+
+ if (message.type === "error") {
+ settleVisionRequest(message.requestId, ({ reject }) => {
+ reject(new Error(message.error || "视觉主体分析失败"));
+ });
+ }
+ });
+
+ visionWorker.addEventListener("error", (event) => {
+ resetVisionWorker(new Error(event.message || "视觉分析 Worker 运行失败"));
+ });
+
+ visionWorker.addEventListener("messageerror", () => {
+ resetVisionWorker(new Error("视觉分析 Worker 返回了无法读取的数据"));
+ });
+
+ return visionWorker;
+}
+
+/**
+ * Return a stable cache key for an imported asset or visual timeline segment.
+ * Source URL is included so replacing media invalidates stale AI data. Dimensions
+ * are intentionally excluded because they are populated asynchronously after import.
+ */
+export function getVisionKey(segment) {
+ if (!segment) {
+ return "";
+ }
+
+ const identity = segment.assetId ?? segment.id ?? segment.src ?? segment.name ?? "visual";
+ const source = segment.src ?? "";
+ return `${identity}::${source}`;
+}
+
+/**
+ * Analyze an image Blob in a lazily-created WASM worker.
+ *
+ * Stable call form:
+ * analyzeVisualSubject({ blob, includeMatting, threshold, preferredLabels, onProgress, signal })
+ */
+export function analyzeVisualSubject(input, legacyOptions = {}) {
+ const options = input instanceof Blob ? { ...legacyOptions, blob: input } : input ?? {};
+ const {
+ blob,
+ includeMatting = options.removeBackground ?? false,
+ threshold = 0.35,
+ preferredLabels = ["person"],
+ onProgress,
+ signal,
+ } = options;
+
+ if (!(blob instanceof Blob) || blob.size <= 0) {
+ return Promise.reject(new TypeError("analyzeVisualSubject 需要非空图片 Blob。"));
+ }
+ if (blob.type && !blob.type.startsWith("image/")) {
+ return Promise.reject(new TypeError("请先用 captureVisualFrame 把视频转换成图片 Blob。"));
+ }
+
+ try {
+ throwIfAborted(signal);
+ } catch (error) {
+ return Promise.reject(error);
+ }
+
+ const worker = getVisionWorker();
+ if (!worker) {
+ return Promise.reject(new Error("当前浏览器不支持 Worker 视觉分析。"));
+ }
+
+ const requestId = createRequestId();
+ return new Promise((resolve, reject) => {
+ const handleAbort = () => {
+ if (!pendingVisionRequests.has(requestId)) {
+ return;
+ }
+ worker.postMessage({ type: "cancel", requestId });
+ settleVisionRequest(requestId, (request) => request.reject(createAbortError()));
+ };
+
+ pendingVisionRequests.set(requestId, {
+ resolve,
+ reject,
+ onProgress,
+ signal,
+ handleAbort,
+ });
+ signal?.addEventListener("abort", handleAbort, { once: true });
+
+ try {
+ onProgress?.({ progress: 0, phase: "准备视觉分析 Worker" });
+ worker.postMessage({
+ type: "analyze",
+ requestId,
+ imageBlob: blob,
+ removeBackground: Boolean(includeMatting),
+ threshold: Math.max(0.01, Math.min(0.99, Number(threshold) || 0.35)),
+ preferredLabels: Array.isArray(preferredLabels) ? preferredLabels : ["person"],
+ });
+ } catch (error) {
+ settleVisionRequest(requestId, (request) => request.reject(error));
+ }
+ });
+}
+
+function isVideoElement(value) {
+ return Boolean(value && String(value.tagName ?? "").toUpperCase() === "VIDEO");
+}
+
+function isImageElement(value) {
+ return Boolean(value && String(value.tagName ?? "").toUpperCase() === "IMG");
+}
+
+function isCanvas(value) {
+ const tagName = String(value?.tagName ?? "").toUpperCase();
+ return tagName === "CANVAS" || (typeof OffscreenCanvas !== "undefined" && value instanceof OffscreenCanvas);
+}
+
+function waitForEvent(target, eventName, errorName = "error", signal = null) {
+ throwIfAborted(signal);
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ target.removeEventListener(eventName, handleSuccess);
+ target.removeEventListener(errorName, handleError);
+ signal?.removeEventListener("abort", handleAbort);
+ };
+ const handleSuccess = () => {
+ cleanup();
+ resolve();
+ };
+ const handleError = () => {
+ cleanup();
+ reject(new Error("无法读取视觉素材。"));
+ };
+ const handleAbort = () => {
+ cleanup();
+ reject(createAbortError());
+ };
+
+ target.addEventListener(eventName, handleSuccess, { once: true });
+ target.addEventListener(errorName, handleError, { once: true });
+ signal?.addEventListener("abort", handleAbort, { once: true });
+ });
+}
+
+async function ensureVideoReady(video, signal) {
+ if (video.readyState < 1) {
+ await waitForEvent(video, "loadedmetadata", "error", signal);
+ }
+ if (video.readyState < 2) {
+ await waitForEvent(video, "loadeddata", "error", signal);
+ }
+}
+
+async function seekVideo(video, requestedTime, signal) {
+ await ensureVideoReady(video, signal);
+ if (!Number.isFinite(requestedTime)) {
+ return;
+ }
+
+ const duration = Number.isFinite(video.duration) ? video.duration : requestedTime;
+ const time = Math.max(0, Math.min(requestedTime, Math.max(0, duration - 0.001)));
+ if (Math.abs(video.currentTime - time) <= 0.01) {
+ return;
+ }
+
+ const seeked = waitForEvent(video, "seeked", "error", signal);
+ video.currentTime = time;
+ await seeked;
+}
+
+function getVisualDimensions(source) {
+ const width = Number(
+ source?.videoWidth ??
+ source?.naturalWidth ??
+ source?.displayWidth ??
+ source?.width,
+ );
+ const height = Number(
+ source?.videoHeight ??
+ source?.naturalHeight ??
+ source?.displayHeight ??
+ source?.height,
+ );
+ return {
+ width: Number.isFinite(width) ? Math.max(0, width) : 0,
+ height: Number.isFinite(height) ? Math.max(0, height) : 0,
+ };
+}
+
+function getCaptureDimensions(sourceSize, options) {
+ const maximumDimension = Math.max(1, Number(options.maxDimension) || 768);
+ const maximumWidth = Math.max(1, Number(options.maxWidth ?? options.width) || maximumDimension);
+ const maximumHeight = Math.max(1, Number(options.maxHeight ?? options.height) || maximumDimension);
+ const scale = Math.min(
+ maximumDimension / Math.max(sourceSize.width, sourceSize.height),
+ maximumWidth / sourceSize.width,
+ maximumHeight / sourceSize.height,
+ );
+ const boundedScale = options.allowUpscale ? scale : Math.min(1, scale);
+ return {
+ width: Math.max(1, Math.round(sourceSize.width * boundedScale)),
+ height: Math.max(1, Math.round(sourceSize.height * boundedScale)),
+ };
+}
+
+function makeCaptureCanvas(width, height) {
+ if (typeof document !== "undefined") {
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+ }
+ if (typeof OffscreenCanvas !== "undefined") {
+ return new OffscreenCanvas(width, height);
+ }
+ throw new Error("当前环境不支持 Canvas,无法截取视觉帧。");
+}
+
+function canvasToBlob(canvas, type, quality) {
+ if (typeof canvas.convertToBlob === "function") {
+ return canvas.convertToBlob({ type, quality });
+ }
+
+ return new Promise((resolve, reject) => {
+ canvas.toBlob(
+ (blob) => {
+ if (blob) {
+ resolve(blob);
+ } else {
+ reject(new Error("视觉帧编码失败。"));
+ }
+ },
+ type,
+ quality,
+ );
+ });
+}
+
+async function loadImageSource(source, signal) {
+ if (isImageElement(source)) {
+ if (!source.complete || !source.naturalWidth) {
+ await waitForEvent(source, "load", "error", signal);
+ }
+ return { visual: source, cleanup: () => {} };
+ }
+
+ if (isCanvas(source) || (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap)) {
+ return { visual: source, cleanup: () => {} };
+ }
+
+ if (source instanceof Blob && typeof createImageBitmap === "function") {
+ const bitmap = await createImageBitmap(source);
+ return { visual: bitmap, cleanup: () => bitmap.close?.() };
+ }
+
+ if (typeof Image === "undefined") {
+ throw new Error("当前环境无法解码图片。");
+ }
+
+ const objectUrl = source instanceof Blob ? URL.createObjectURL(source) : "";
+ const image = new Image();
+ image.crossOrigin = "anonymous";
+ const loaded = waitForEvent(image, "load", "error", signal);
+ image.src = objectUrl || String(source ?? "");
+ try {
+ await loaded;
+ return {
+ visual: image,
+ cleanup: () => {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ },
+ };
+ } catch (error) {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ throw error;
+ }
+}
+
+async function loadVideoSource(source, time, signal) {
+ if (isVideoElement(source)) {
+ const originalTime = source.currentTime;
+ const wasPlaying = !source.paused;
+ if (Number.isFinite(time)) {
+ source.pause();
+ }
+ try {
+ await seekVideo(source, time, signal);
+ } catch (error) {
+ if (wasPlaying) {
+ source.play().catch(() => {});
+ }
+ throw error;
+ }
+ return {
+ visual: source,
+ cleanup: () => {
+ if (Number.isFinite(time) && Math.abs(source.currentTime - originalTime) > 0.01) {
+ if (wasPlaying) {
+ source.addEventListener("seeked", () => source.play().catch(() => {}), { once: true });
+ }
+ source.currentTime = originalTime;
+ } else if (wasPlaying && source.paused) {
+ source.play().catch(() => {});
+ }
+ },
+ };
+ }
+
+ if (typeof document === "undefined") {
+ throw new Error("当前环境无法解码视频。");
+ }
+
+ const objectUrl = source instanceof Blob ? URL.createObjectURL(source) : "";
+ const video = document.createElement("video");
+ video.crossOrigin = "anonymous";
+ video.muted = true;
+ video.playsInline = true;
+ video.preload = "auto";
+ video.src = objectUrl || String(source ?? "");
+ try {
+ await seekVideo(video, Number.isFinite(time) ? time : 0, signal);
+ return {
+ visual: video,
+ cleanup: () => {
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ },
+ };
+ } catch (error) {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ throw error;
+ }
+}
+
+/**
+ * Capture an image/video source as a bounded image Blob suitable for analyzeVisualSubject.
+ * Stable call form: captureVisualFrame({ src, type, videoElement, maxDimension, time }).
+ */
+export async function captureVisualFrame(input, legacyOptions = {}) {
+ const options =
+ input && typeof input === "object" && !(input instanceof Blob) &&
+ ("src" in input || "videoElement" in input || "maxDimension" in input)
+ ? input
+ : { ...legacyOptions, src: input };
+ const {
+ src,
+ videoElement,
+ type = "",
+ time,
+ signal,
+ outputType = options.mimeType ?? "image/png",
+ quality = 0.92,
+ } = options;
+ const source = videoElement ?? src;
+ if (!source) {
+ throw new TypeError("captureVisualFrame 需要 src 或 videoElement。");
+ }
+ throwIfAborted(signal);
+
+ const isVideo =
+ Boolean(videoElement) ||
+ isVideoElement(source) ||
+ String(type).toLowerCase() === "video" ||
+ String(type).toLowerCase().startsWith("video/") ||
+ (source instanceof Blob && source.type.startsWith("video/"));
+ const loaded = isVideo
+ ? await loadVideoSource(source, Number(time), signal)
+ : await loadImageSource(source, signal);
+
+ try {
+ throwIfAborted(signal);
+ const sourceSize = getVisualDimensions(loaded.visual);
+ if (!sourceSize.width || !sourceSize.height) {
+ throw new Error("视觉素材尺寸无效。");
+ }
+
+ const targetSize = getCaptureDimensions(sourceSize, options);
+ const canvas = makeCaptureCanvas(targetSize.width, targetSize.height);
+ const context = canvas.getContext("2d", { alpha: true });
+ if (!context) {
+ throw new Error("无法创建视觉帧画布。");
+ }
+ context.imageSmoothingEnabled = true;
+ context.imageSmoothingQuality = "high";
+ if (String(outputType).toLowerCase() === "image/jpeg") {
+ context.fillStyle = options.backgroundColor ?? "#000000";
+ context.fillRect(0, 0, targetSize.width, targetSize.height);
+ }
+ context.drawImage(loaded.visual, 0, 0, targetSize.width, targetSize.height);
+ throwIfAborted(signal);
+ return await canvasToBlob(canvas, outputType, Math.max(0, Math.min(1, Number(quality) || 0.92)));
+ } finally {
+ loaded.cleanup();
+ }
+}
+
+const DEFAULT_VIDEO_VISION_FPS = 2;
+const DEFAULT_VIDEO_VISION_MAX_SAMPLES = 180;
+
+function clampNumber(value, minimum, maximum, fallback) {
+ const number = Number(value);
+ return Number.isFinite(number)
+ ? Math.max(minimum, Math.min(maximum, number))
+ : fallback;
+}
+
+/**
+ * Build a bounded set of timestamps that spans the complete video, including
+ * both its first and final decodable frames.
+ */
+export function getVideoVisionSampleTimes(duration, options = {}) {
+ const durationNumber = Number(duration);
+ const safeDuration = Number.isFinite(durationNumber) ? Math.max(0, durationNumber) : 0;
+ if (!safeDuration) {
+ return [0];
+ }
+
+ const fps = clampNumber(options.fps, 0.1, 8, DEFAULT_VIDEO_VISION_FPS);
+ const maxSamples = Math.max(
+ 2,
+ Math.round(
+ clampNumber(
+ options.maxSamples,
+ 2,
+ 600,
+ DEFAULT_VIDEO_VISION_MAX_SAMPLES,
+ ),
+ ),
+ );
+ const targetCount = Math.ceil(safeDuration * fps) + 1;
+ const sampleCount = Math.max(2, Math.min(maxSamples, targetCount));
+ const finalTime = Math.max(0, safeDuration - Math.min(0.04, safeDuration / 2));
+
+ return Array.from({ length: sampleCount }, (_, index) =>
+ index === sampleCount - 1
+ ? finalTime
+ : (index / Math.max(1, sampleCount - 1)) * finalTime,
+ );
+}
+
+function readBoxValue(box, lowerKey, camelKey) {
+ const value = Number(box?.[lowerKey] ?? box?.[camelKey]);
+ return Number.isFinite(value) ? value : 0;
+}
+
+function getSubjectCenter(subject) {
+ if (!subject?.box) {
+ return null;
+ }
+ const xmin = readBoxValue(subject.box, "xmin", "xMin");
+ const ymin = readBoxValue(subject.box, "ymin", "yMin");
+ const xmax = readBoxValue(subject.box, "xmax", "xMax");
+ const ymax = readBoxValue(subject.box, "ymax", "yMax");
+ return {
+ xmin,
+ ymin,
+ xmax,
+ ymax,
+ centerX: (xmin + xmax) / 2,
+ centerY: (ymin + ymax) / 2,
+ };
+}
+
+function interpolateSubject(previous, next, mix) {
+ if (!previous?.box) {
+ return next ?? null;
+ }
+ if (!next?.box) {
+ return previous;
+ }
+ if (String(previous.label ?? "") !== String(next.label ?? "")) {
+ return mix < 0.5 ? previous : next;
+ }
+
+ const previousBox = getSubjectCenter(previous);
+ const nextBox = getSubjectCenter(next);
+ const centerDistance = Math.hypot(
+ previousBox.centerX - nextBox.centerX,
+ previousBox.centerY - nextBox.centerY,
+ );
+ if (centerDistance > 0.48) {
+ return mix < 0.5 ? previous : next;
+ }
+
+ const lerp = (start, end) => start + (end - start) * mix;
+ return {
+ ...(mix < 0.5 ? previous : next),
+ score: lerp(Number(previous.score) || 0, Number(next.score) || 0),
+ box: {
+ xmin: lerp(previousBox.xmin, nextBox.xmin),
+ ymin: lerp(previousBox.ymin, nextBox.ymin),
+ xmax: lerp(previousBox.xmax, nextBox.xmax),
+ ymax: lerp(previousBox.ymax, nextBox.ymax),
+ },
+ };
+}
+
+function getTemporalSampleRange(samples, time) {
+ if (samples.length <= 1) {
+ return { previous: samples[0] ?? null, next: samples[0] ?? null, mix: 0 };
+ }
+
+ let low = 0;
+ let high = samples.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ if ((Number(samples[middle]?.time) || 0) <= time) {
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+
+ const previous = samples[Math.max(0, high)] ?? samples[0];
+ const next = samples[Math.min(samples.length - 1, low)] ?? samples.at(-1);
+ const span = Math.max(0, (Number(next?.time) || 0) - (Number(previous?.time) || 0));
+ const mix = span > 0 ? Math.max(0, Math.min(1, (time - previous.time) / span)) : 0;
+ return { previous, next, mix };
+}
+
+/** Resolve an image analysis or a full-video temporal analysis at source time. */
+export function resolveVisionAnalysisAtTime(analysis, requestedTime = 0) {
+ const samples = Array.isArray(analysis?.samples) ? analysis.samples : [];
+ if (analysis?.kind !== "video-timeline" || !samples.length) {
+ return analysis ?? null;
+ }
+
+ const duration = Math.max(0, Number(analysis.duration) || 0);
+ let time = Math.max(0, Number(requestedTime) || 0);
+ if (duration > 0) {
+ time = Math.min(time, duration);
+ }
+
+ const { previous, next, mix } = getTemporalSampleRange(samples, time);
+ const nearest = mix < 0.5 ? previous : next;
+ if (!nearest) {
+ return analysis;
+ }
+
+ return {
+ ...analysis,
+ ...nearest,
+ sourceSize: nearest.sourceSize ?? analysis.sourceSize,
+ subject: interpolateSubject(previous?.subject, next?.subject, mix),
+ temporal: {
+ time,
+ previousTime: Number(previous?.time) || 0,
+ nextTime: Number(next?.time) || 0,
+ mix,
+ sampleCount: samples.length,
+ },
+ };
+}
+
+/**
+ * Analyze a complete video into a time-indexed YOLOS + MODNet track. The
+ * models stay resident in the worker for the batch; frames are captured and
+ * submitted sequentially so long clips do not queue all source images in RAM.
+ */
+export async function analyzeVideoVisualTrack(options = {}) {
+ const {
+ src: requestedSource,
+ blob,
+ duration: requestedDuration,
+ includeMatting = true,
+ fps = DEFAULT_VIDEO_VISION_FPS,
+ maxSamples = DEFAULT_VIDEO_VISION_MAX_SAMPLES,
+ maxDimension = 512,
+ threshold = 0.32,
+ preferredLabels = ["person", "cat", "dog", "car", "bottle", "chair"],
+ signal,
+ onProgress,
+ } = options;
+ const source = blob ?? requestedSource;
+ if (!source) {
+ throw new TypeError("analyzeVideoVisualTrack 需要视频 src 或 Blob。");
+ }
+
+ throwIfAborted(signal);
+ onProgress?.({ progress: 1, phase: "读取全视频元数据" });
+ const loaded = await loadVideoSource(source, 0, signal);
+
+ try {
+ const video = loaded.visual;
+ const sourceSize = getVisualDimensions(video);
+ if (!sourceSize.width || !sourceSize.height) {
+ throw new Error("视频尺寸无效,无法进行全片视觉分析。");
+ }
+
+ const rawSourceDuration = Number(video.duration);
+ const rawRequestedDuration = Number(requestedDuration);
+ const sourceDuration = Number.isFinite(rawSourceDuration)
+ ? Math.max(0, rawSourceDuration)
+ : 0;
+ const requestedDurationValue = Number.isFinite(rawRequestedDuration)
+ ? Math.max(0, rawRequestedDuration)
+ : 0;
+ const duration = Math.max(
+ 0.05,
+ Math.min(
+ sourceDuration || requestedDurationValue || 0.05,
+ requestedDurationValue > 0 ? requestedDurationValue : sourceDuration || 0.05,
+ ),
+ );
+ const sampleTimes = getVideoVisionSampleTimes(duration, { fps, maxSamples });
+ const targetSize = getCaptureDimensions(sourceSize, { maxDimension });
+ const canvas = makeCaptureCanvas(targetSize.width, targetSize.height);
+ const context = canvas.getContext("2d", { alpha: false });
+ if (!context) {
+ throw new Error("无法创建全视频视觉分析画布。");
+ }
+ context.imageSmoothingEnabled = true;
+ context.imageSmoothingQuality = "high";
+
+ const samples = [];
+ for (let index = 0; index < sampleTimes.length; index += 1) {
+ throwIfAborted(signal);
+ const time = sampleTimes[index];
+ onProgress?.({
+ progress: Math.max(1, (index / sampleTimes.length) * 100),
+ phase: `截取全视频帧 ${index + 1}/${sampleTimes.length}`,
+ });
+ await seekVideo(video, time, signal);
+ context.fillStyle = "#000000";
+ context.fillRect(0, 0, targetSize.width, targetSize.height);
+ context.drawImage(video, 0, 0, targetSize.width, targetSize.height);
+ const frameBlob = await canvasToBlob(canvas, "image/jpeg", 0.9);
+ throwIfAborted(signal);
+
+ const result = await analyzeVisualSubject({
+ blob: frameBlob,
+ includeMatting,
+ threshold,
+ preferredLabels,
+ signal,
+ onProgress: ({ progress, phase }) => {
+ const overall = ((index + progress / 100) / sampleTimes.length) * 100;
+ onProgress?.({
+ progress: overall,
+ phase: `全视频 ${index + 1}/${sampleTimes.length} · ${phase}`,
+ });
+ },
+ });
+ samples.push({ time, ...result });
+ }
+
+ const firstSubjectSample = samples.find((sample) => sample.subject) ?? samples[0] ?? null;
+ const finalTime = Number(samples.at(-1)?.time) || 0;
+ onProgress?.({ progress: 100, phase: "全视频视觉轨道已生成" });
+ return {
+ kind: "video-timeline",
+ duration,
+ sourceSize: samples[0]?.sourceSize ?? targetSize,
+ samples,
+ subject: firstSubjectSample?.subject ?? null,
+ detections: firstSubjectSample?.detections ?? [],
+ complete: true,
+ coverage: {
+ start: Number(samples[0]?.time) || 0,
+ end: finalTime,
+ duration,
+ sampleCount: samples.length,
+ maxGap: samples.reduce(
+ (maximum, sample, index) =>
+ index > 0
+ ? Math.max(maximum, sample.time - samples[index - 1].time)
+ : maximum,
+ 0,
+ ),
+ },
+ modelIds: samples[0]?.modelIds ?? null,
+ modelRevisions: samples[0]?.modelRevisions ?? null,
+ };
+ } catch (error) {
+ if (error?.name === "AbortError") {
+ resetVisionWorker();
+ }
+ throw error;
+ } finally {
+ loaded.cleanup();
+ }
+}
+
+export function disposeVisionWorker() {
+ resetVisionWorker(new Error("视觉分析 Worker 已释放"));
+}
diff --git a/src/lib/visualGeometry.js b/src/lib/visualGeometry.js
new file mode 100644
index 0000000..d42f878
--- /dev/null
+++ b/src/lib/visualGeometry.js
@@ -0,0 +1,696 @@
+const EPSILON = 1e-8;
+
+function toFiniteNumber(value, fallback = 0) {
+ const number = Number(value);
+ return Number.isFinite(number) ? number : fallback;
+}
+
+function clamp(value, minimum = 0, maximum = 1) {
+ return Math.min(maximum, Math.max(minimum, toFiniteNumber(value, minimum)));
+}
+
+function getSize(size) {
+ const width = Math.max(0, toFiniteNumber(size?.width));
+ const height = Math.max(0, toFiniteNumber(size?.height));
+ return { width, height, valid: width > 0 && height > 0 };
+}
+
+function getAspectRatio(target) {
+ if (Number.isFinite(target) && target > 0) {
+ return target;
+ }
+
+ const ratio = toFiniteNumber(target?.aspectRatio);
+ if (ratio > 0) {
+ return ratio;
+ }
+
+ const size = getSize(target);
+ return size.valid ? size.width / size.height : 1;
+}
+
+function getRawBoxCoordinates(box) {
+ if (!box) {
+ return null;
+ }
+
+ if (box.normalized && typeof box.normalized === "object") {
+ return getRawBoxCoordinates(box.normalized);
+ }
+
+ const xMin = box.xMin ?? box.xmin ?? box.left ?? box.x;
+ const yMin = box.yMin ?? box.ymin ?? box.top ?? box.y;
+ const xMax =
+ box.xMax ??
+ box.xmax ??
+ box.right ??
+ (xMin !== undefined && box.width !== undefined
+ ? toFiniteNumber(xMin) + toFiniteNumber(box.width)
+ : undefined);
+ const yMax =
+ box.yMax ??
+ box.ymax ??
+ box.bottom ??
+ (yMin !== undefined && box.height !== undefined
+ ? toFiniteNumber(yMin) + toFiniteNumber(box.height)
+ : undefined);
+
+ if ([xMin, yMin, xMax, yMax].some((value) => !Number.isFinite(Number(value)))) {
+ return null;
+ }
+
+ return {
+ xMin: Math.min(Number(xMin), Number(xMax)),
+ yMin: Math.min(Number(yMin), Number(yMax)),
+ xMax: Math.max(Number(xMin), Number(xMax)),
+ yMax: Math.max(Number(yMin), Number(yMax)),
+ };
+}
+
+/**
+ * Convert a pixel or normalized bounding box into source-relative 0..1 coordinates.
+ */
+export function normalizeBoundingBox(box, sourceSize = null) {
+ const raw = getRawBoxCoordinates(box);
+ if (!raw) {
+ return null;
+ }
+
+ const source = getSize(sourceSize);
+ const values = [raw.xMin, raw.yMin, raw.xMax, raw.yMax];
+ const looksNormalized = values.every((value) => value >= -EPSILON && value <= 1 + EPSILON);
+ const explicitlyNormalized =
+ box?.isNormalized === true ||
+ box?.coordinateSpace === "normalized" ||
+ box?.normalized === true;
+
+ if (!source.valid && !looksNormalized && !explicitlyNormalized) {
+ return null;
+ }
+
+ const xDivisor = source.valid && !looksNormalized && !explicitlyNormalized ? source.width : 1;
+ const yDivisor = source.valid && !looksNormalized && !explicitlyNormalized ? source.height : 1;
+ const xMin = clamp(raw.xMin / xDivisor);
+ const yMin = clamp(raw.yMin / yDivisor);
+ const xMax = clamp(raw.xMax / xDivisor);
+ const yMax = clamp(raw.yMax / yDivisor);
+ const width = Math.max(0, xMax - xMin);
+ const height = Math.max(0, yMax - yMin);
+
+ return {
+ x: xMin,
+ y: yMin,
+ xMin,
+ yMin,
+ xMax,
+ yMax,
+ width,
+ height,
+ centerX: xMin + width / 2,
+ centerY: yMin + height / 2,
+ isNormalized: true,
+ };
+}
+
+export function normalizeDetections(detections, sourceSize) {
+ return (Array.isArray(detections) ? detections : [])
+ .map((detection) => {
+ const box = normalizeBoundingBox(detection?.box, sourceSize);
+ if (!box || box.width <= EPSILON || box.height <= EPSILON) {
+ return null;
+ }
+
+ return {
+ ...detection,
+ label: String(detection?.label ?? "object"),
+ score: clamp(detection?.score),
+ box,
+ };
+ })
+ .filter(Boolean);
+}
+
+function getBoxArea(box) {
+ return Math.max(0, box?.width ?? 0) * Math.max(0, box?.height ?? 0);
+}
+
+function getCenterAffinity(box) {
+ const distance = Math.hypot((box?.centerX ?? 0.5) - 0.5, (box?.centerY ?? 0.5) - 0.5);
+ return clamp(1 - distance / Math.SQRT1_2);
+}
+
+/**
+ * Rank detections as editing subjects. Preferred labels (person by default) win,
+ * followed by confidence, visible area, and proximity to the frame center.
+ */
+export function selectPrimarySubject(detections, options = {}) {
+ const preferredLabels = (options.preferredLabels ?? ["person"])
+ .map((label) => String(label).trim().toLowerCase())
+ .filter(Boolean);
+ const preferredRanks = new Map(preferredLabels.map((label, index) => [label, index]));
+ const minScore = clamp(options.minScore ?? 0);
+ const minArea = Math.max(0, toFiniteNumber(options.minArea, 0));
+
+ const ranked = (Array.isArray(detections) ? detections : [])
+ .map((detection) => {
+ const box = normalizeBoundingBox(detection?.box);
+ const score = clamp(detection?.score);
+ const area = getBoxArea(box);
+ if (!box || score < minScore || area <= minArea) {
+ return null;
+ }
+
+ const label = String(detection?.label ?? "object");
+ const preferredRank = preferredRanks.get(label.toLowerCase());
+ const preferredBonus =
+ preferredRank === undefined ? 0 : Math.max(0.35, 0.72 - preferredRank * 0.08);
+ const rankScore =
+ preferredBonus + score * 0.48 + Math.sqrt(area) * 0.34 + getCenterAffinity(box) * 0.18;
+
+ return {
+ detection: {
+ ...detection,
+ label,
+ score,
+ box,
+ },
+ rankScore,
+ };
+ })
+ .filter(Boolean)
+ .sort((left, right) => right.rankScore - left.rankScore);
+
+ return ranked.length
+ ? {
+ ...ranked[0].detection,
+ rankScore: ranked[0].rankScore,
+ }
+ : null;
+}
+
+function positionCropAxis({ sourceLength, cropLength, focus, paddedMinimum, paddedMaximum }) {
+ const maximumStart = Math.max(0, sourceLength - cropLength);
+ const idealStart = focus * sourceLength - cropLength / 2;
+ const containmentMinimum = Math.max(0, paddedMaximum * sourceLength - cropLength);
+ const containmentMaximum = Math.min(maximumStart, paddedMinimum * sourceLength);
+
+ if (containmentMinimum <= containmentMaximum) {
+ return clamp(idealStart, containmentMinimum, containmentMaximum);
+ }
+
+ return clamp(idealStart, 0, maximumStart);
+}
+
+function getIntersectionArea(left, right) {
+ if (!left || !right) {
+ return 0;
+ }
+
+ const width = Math.max(0, Math.min(left.xMax, right.xMax) - Math.max(left.xMin, right.xMin));
+ const height = Math.max(0, Math.min(left.yMax, right.yMax) - Math.max(left.yMin, right.yMin));
+ return width * height;
+}
+
+/**
+ * Return the largest source crop with the target aspect ratio, anchored so the
+ * detected subject and requested padding remain visible whenever possible.
+ * Pixel coordinates are returned for CanvasRenderingContext2D.drawImage, with
+ * an additional normalized rectangle for DOM/object-position calculations.
+ */
+export function getSmartCropRect(sourceSize, target, subjectBox = null, options = {}) {
+ const settings =
+ typeof options === "number"
+ ? { padding: options }
+ : options && typeof options === "object"
+ ? options
+ : {};
+ const source = getSize(sourceSize);
+ if (!source.valid) {
+ return null;
+ }
+
+ const targetAspectRatio = Math.max(EPSILON, getAspectRatio(target));
+ const sourceAspectRatio = source.width / source.height;
+ let width;
+ let height;
+
+ if (sourceAspectRatio > targetAspectRatio) {
+ height = source.height;
+ width = height * targetAspectRatio;
+ } else {
+ width = source.width;
+ height = width / targetAspectRatio;
+ }
+
+ width = Math.min(source.width, width);
+ height = Math.min(source.height, height);
+
+ const subject = normalizeBoundingBox(subjectBox) ?? normalizeBoundingBox({ xMin: 0.5, yMin: 0.5, xMax: 0.5, yMax: 0.5 });
+ const padding = Math.max(0, toFiniteNumber(settings.padding, 0.12));
+ const paddedX = subject.width * padding;
+ const paddedY = subject.height * padding;
+ const padded = {
+ xMin: clamp(subject.xMin - paddedX),
+ yMin: clamp(subject.yMin - paddedY),
+ xMax: clamp(subject.xMax + paddedX),
+ yMax: clamp(subject.yMax + paddedY),
+ };
+ const focusX = clamp(settings.focusX ?? subject.centerX ?? 0.5);
+ const focusY = clamp(settings.focusY ?? subject.centerY ?? 0.5);
+ const x = positionCropAxis({
+ sourceLength: source.width,
+ cropLength: width,
+ focus: focusX,
+ paddedMinimum: padded.xMin,
+ paddedMaximum: padded.xMax,
+ });
+ const y = positionCropAxis({
+ sourceLength: source.height,
+ cropLength: height,
+ focus: focusY,
+ paddedMinimum: padded.yMin,
+ paddedMaximum: padded.yMax,
+ });
+ const normalized = {
+ x: x / source.width,
+ y: y / source.height,
+ xMin: x / source.width,
+ yMin: y / source.height,
+ xMax: (x + width) / source.width,
+ yMax: (y + height) / source.height,
+ width: width / source.width,
+ height: height / source.height,
+ centerX: (x + width / 2) / source.width,
+ centerY: (y + height / 2) / source.height,
+ isNormalized: true,
+ };
+ const subjectArea = getBoxArea(subject);
+ const subjectCoverage = subjectArea > 0 ? getIntersectionArea(subject, normalized) / subjectArea : 1;
+
+ return {
+ x,
+ y,
+ xMin: x,
+ yMin: y,
+ xMax: x + width,
+ yMax: y + height,
+ width,
+ height,
+ sourceWidth: source.width,
+ sourceHeight: source.height,
+ targetAspectRatio,
+ normalized,
+ subjectCoverage: clamp(subjectCoverage),
+ };
+}
+
+function getNormalizedCrop(cropRect, sourceSize) {
+ if (cropRect?.normalized) {
+ return normalizeBoundingBox(cropRect.normalized);
+ }
+
+ const inferredSource =
+ sourceSize ??
+ (cropRect?.sourceWidth && cropRect?.sourceHeight
+ ? { width: cropRect.sourceWidth, height: cropRect.sourceHeight }
+ : null);
+ return normalizeBoundingBox(cropRect, inferredSource) ?? normalizeBoundingBox({ xMin: 0, yMin: 0, xMax: 1, yMax: 1 });
+}
+
+/** Map a source-relative subject box through a crop rectangle into frame pixels. */
+export function mapSourceBoxToFrame(subjectBox, cropRect, frameSize, sourceSize = null) {
+ const frame = getSize(frameSize);
+ const source = getSize(
+ sourceSize ??
+ (cropRect?.sourceWidth && cropRect?.sourceHeight
+ ? { width: cropRect.sourceWidth, height: cropRect.sourceHeight }
+ : null),
+ );
+ const subject = normalizeBoundingBox(subjectBox, source.valid ? source : null);
+ const crop = getNormalizedCrop(cropRect, source.valid ? source : null);
+ if (!frame.valid || !subject || !crop || crop.width <= EPSILON || crop.height <= EPSILON) {
+ return null;
+ }
+
+ const unclipped = {
+ xMin: (subject.xMin - crop.xMin) / crop.width,
+ yMin: (subject.yMin - crop.yMin) / crop.height,
+ xMax: (subject.xMax - crop.xMin) / crop.width,
+ yMax: (subject.yMax - crop.yMin) / crop.height,
+ };
+ const normalized = normalizeBoundingBox({
+ ...unclipped,
+ coordinateSpace: "normalized",
+ });
+ if (!normalized) {
+ return null;
+ }
+
+ const subjectArea = getBoxArea(subject);
+ const visibleRatio = subjectArea > 0 ? getIntersectionArea(subject, crop) / subjectArea : 0;
+ const x = normalized.xMin * frame.width;
+ const y = normalized.yMin * frame.height;
+ const width = normalized.width * frame.width;
+ const height = normalized.height * frame.height;
+
+ return {
+ x,
+ y,
+ xMin: x,
+ yMin: y,
+ xMax: x + width,
+ yMax: y + height,
+ width,
+ height,
+ frameWidth: frame.width,
+ frameHeight: frame.height,
+ normalized,
+ unclippedNormalized: {
+ ...unclipped,
+ width: unclipped.xMax - unclipped.xMin,
+ height: unclipped.yMax - unclipped.yMin,
+ },
+ visibleRatio: clamp(visibleRatio),
+ };
+}
+
+function getLayoutPosition(layout) {
+ const position = layout?.objectPosition ?? layout?.position ?? {};
+ const rawX = toFiniteNumber(position.x ?? layout?.positionX, 0.5);
+ const rawY = toFiniteNumber(position.y ?? layout?.positionY, 0.5);
+ return {
+ x: clamp(Math.abs(rawX) > 1 ? rawX / 100 : rawX),
+ y: clamp(Math.abs(rawY) > 1 ? rawY / 100 : rawY),
+ };
+}
+
+/**
+ * Map a normalized source box into a rendered frame using the same contain,
+ * cover, or smart-crop geometry used by DOM media and export canvases.
+ */
+export function mapNormalizedBoxToFrame(box, sourceSize, frameSize, layout = {}) {
+ const source = getSize(sourceSize);
+ const frame = getSize(frameSize);
+ const normalizedBox = normalizeBoundingBox(box, source.valid ? source : null);
+ if (!source.valid || !frame.valid || !normalizedBox) {
+ return null;
+ }
+
+ const smartCrop = layout?.smartCrop;
+ if (smartCrop) {
+ const cropRect =
+ smartCrop && typeof smartCrop === "object" && (smartCrop.normalized || smartCrop.width)
+ ? smartCrop
+ : getSmartCropRect(
+ source,
+ layout?.outputSize ?? frame,
+ normalizedBox,
+ layout?.padding ?? layout?.cropPadding ?? 0.12,
+ );
+ const mapped = mapSourceBoxToFrame(normalizedBox, cropRect, frame);
+ return mapped
+ ? {
+ ...mapped,
+ fitMode: "smart-crop",
+ cropRect,
+ drawRect: { x: 0, y: 0, width: frame.width, height: frame.height },
+ }
+ : null;
+ }
+
+ const fitMode = layout?.fitMode === "cover" ? "cover" : "contain";
+ const sourceAspectRatio = source.width / source.height;
+ const frameAspectRatio = frame.width / frame.height;
+ const useWidth =
+ fitMode === "cover"
+ ? sourceAspectRatio < frameAspectRatio
+ : sourceAspectRatio > frameAspectRatio;
+ const drawWidth = useWidth ? frame.width : frame.height * sourceAspectRatio;
+ const drawHeight = useWidth ? frame.width / sourceAspectRatio : frame.height;
+ const position = getLayoutPosition(layout);
+ const drawX = (frame.width - drawWidth) * position.x;
+ const drawY = (frame.height - drawHeight) * position.y;
+ const raw = {
+ xMin: drawX + normalizedBox.xMin * drawWidth,
+ yMin: drawY + normalizedBox.yMin * drawHeight,
+ xMax: drawX + normalizedBox.xMax * drawWidth,
+ yMax: drawY + normalizedBox.yMax * drawHeight,
+ };
+ const unclippedNormalized = {
+ xMin: raw.xMin / frame.width,
+ yMin: raw.yMin / frame.height,
+ xMax: raw.xMax / frame.width,
+ yMax: raw.yMax / frame.height,
+ };
+ const clippedNormalized = normalizeBoundingBox({
+ ...unclippedNormalized,
+ coordinateSpace: "normalized",
+ });
+ if (!clippedNormalized) {
+ return null;
+ }
+
+ const unclippedArea = Math.max(0, unclippedNormalized.xMax - unclippedNormalized.xMin) *
+ Math.max(0, unclippedNormalized.yMax - unclippedNormalized.yMin);
+ const visibleArea = getBoxArea(clippedNormalized);
+ const x = clippedNormalized.xMin * frame.width;
+ const y = clippedNormalized.yMin * frame.height;
+ const width = clippedNormalized.width * frame.width;
+ const height = clippedNormalized.height * frame.height;
+
+ return {
+ x,
+ y,
+ xMin: x,
+ yMin: y,
+ xMax: x + width,
+ yMax: y + height,
+ width,
+ height,
+ frameWidth: frame.width,
+ frameHeight: frame.height,
+ normalized: clippedNormalized,
+ unclippedNormalized: {
+ ...unclippedNormalized,
+ width: unclippedNormalized.xMax - unclippedNormalized.xMin,
+ height: unclippedNormalized.yMax - unclippedNormalized.yMin,
+ },
+ visibleRatio: unclippedArea > 0 ? clamp(visibleArea / unclippedArea) : 0,
+ fitMode,
+ cropRect: null,
+ drawRect: { x: drawX, y: drawY, width: drawWidth, height: drawHeight },
+ };
+}
+
+function normalizeFrameRect(rect, frameSize) {
+ if (rect?.normalized) {
+ return normalizeBoundingBox(rect.normalized);
+ }
+ return normalizeBoundingBox(rect, frameSize);
+}
+
+function normalizePlacementPoint(placement, fallback) {
+ if (typeof placement === "string") {
+ const placements = {
+ top: { x: 0.5, y: 0.18 },
+ middle: { x: 0.5, y: 0.5 },
+ bottom: { x: 0.5, y: 0.82 },
+ };
+ return placements[placement] ?? fallback;
+ }
+
+ if (!placement) {
+ return fallback;
+ }
+
+ const rawX = toFiniteNumber(placement.x, fallback.x);
+ const rawY = toFiniteNumber(placement.y, fallback.y);
+ return {
+ x: clamp(Math.abs(rawX) > 1 ? rawX / 100 : rawX),
+ y: clamp(Math.abs(rawY) > 1 ? rawY / 100 : rawY),
+ };
+}
+
+function getCaptionDimension(value, frameDimension, fallback) {
+ const dimension = toFiniteNumber(value, fallback);
+ if (dimension <= 0) {
+ return fallback;
+ }
+ return clamp(dimension > 1 ? dimension / frameDimension : dimension, 0.01, 1);
+}
+
+function createCaptionRect(point, width, height, safeMargin) {
+ const usableWidth = Math.max(0.01, 1 - safeMargin * 2);
+ const usableHeight = Math.max(0.01, 1 - safeMargin * 2);
+ const safeWidth = Math.min(width, usableWidth);
+ const safeHeight = Math.min(height, usableHeight);
+ const centerX = clamp(point.x, safeMargin + safeWidth / 2, 1 - safeMargin - safeWidth / 2);
+ const centerY = clamp(point.y, safeMargin + safeHeight / 2, 1 - safeMargin - safeHeight / 2);
+
+ return {
+ xMin: centerX - safeWidth / 2,
+ yMin: centerY - safeHeight / 2,
+ xMax: centerX + safeWidth / 2,
+ yMax: centerY + safeHeight / 2,
+ width: safeWidth,
+ height: safeHeight,
+ centerX,
+ centerY,
+ isNormalized: true,
+ };
+}
+
+const DEFAULT_CAPTION_CANDIDATES = [
+ { id: "bottom", x: 0.5, y: 0.82 },
+ { id: "top", x: 0.5, y: 0.18 },
+ { id: "bottom-left", x: 0.22, y: 0.82 },
+ { id: "bottom-right", x: 0.78, y: 0.82 },
+ { id: "top-left", x: 0.22, y: 0.18 },
+ { id: "top-right", x: 0.78, y: 0.18 },
+ { id: "middle-left", x: 0.22, y: 0.5 },
+ { id: "middle-right", x: 0.78, y: 0.5 },
+ { id: "middle", x: 0.5, y: 0.5 },
+];
+
+/**
+ * Choose a normalized caption center with the least subject overlap. Pixel or
+ * normalized subject rectangles are accepted. The previous placement receives
+ * a movement penalty to reduce visible jumping between sampled video frames.
+ */
+function chooseCaptionAvoidancePlacement(
+ subjectRects,
+ frameSize,
+ captionSize = {},
+ options = {},
+) {
+ const frame = getSize(frameSize);
+ if (!frame.valid) {
+ return { x: 50, y: 78, placement: "bottom", overlapRatio: 0 };
+ }
+
+ const subjects = (Array.isArray(subjectRects) ? subjectRects : [subjectRects])
+ .map((rect) => normalizeFrameRect(rect, frame))
+ .filter((rect) => rect && rect.width > EPSILON && rect.height > EPSILON);
+ const defaultHeight = Math.max(0.08, Math.min(0.2, 72 / frame.height));
+ const captionWidth = getCaptionDimension(captionSize.width, frame.width, 0.68);
+ const captionHeight = getCaptionDimension(captionSize.height, frame.height, defaultHeight);
+ const safeMargin = clamp(options.safeMargin ?? 0.04, 0, 0.2);
+ const preferred = normalizePlacementPoint(options.preferredPlacement, { x: 0.5, y: 0.82 });
+ const previous = options.previousPlacement
+ ? normalizePlacementPoint(options.previousPlacement, preferred)
+ : null;
+ const configuredCandidates = Array.isArray(options.candidates) && options.candidates.length
+ ? options.candidates
+ : DEFAULT_CAPTION_CANDIDATES;
+ const candidates = previous
+ ? [{ id: "previous", ...previous }, ...configuredCandidates]
+ : configuredCandidates;
+ const captionArea = captionWidth * captionHeight;
+
+ const ranked = candidates.map((candidate, index) => {
+ const point = normalizePlacementPoint(candidate, preferred);
+ const rect = createCaptionRect(point, captionWidth, captionHeight, safeMargin);
+ const intersections = subjects.map((subject) => getIntersectionArea(rect, subject));
+ const totalIntersection = intersections.reduce((sum, area) => sum + area, 0);
+ const overlapRatio = captionArea > 0 ? Math.min(1, totalIntersection / captionArea) : 0;
+ const maximumSubjectCoverage = subjects.reduce((coverage, subject, subjectIndex) => {
+ const subjectArea = getBoxArea(subject);
+ return Math.max(
+ coverage,
+ subjectArea > 0 ? intersections[subjectIndex] / subjectArea : 0,
+ );
+ }, 0);
+ const preferredDistance = Math.hypot(rect.centerX - preferred.x, rect.centerY - preferred.y);
+ const movementDistance = previous
+ ? Math.hypot(rect.centerX - previous.x, rect.centerY - previous.y)
+ : 0;
+ const score =
+ overlapRatio * 20 +
+ maximumSubjectCoverage * 4 +
+ preferredDistance * 0.32 +
+ movementDistance * 0.72 +
+ index * 1e-5;
+
+ return {
+ id: candidate.id ?? `candidate-${index}`,
+ rect,
+ overlapRatio,
+ score,
+ };
+ });
+
+ ranked.sort((left, right) => left.score - right.score);
+ const best = ranked[0];
+ const rect = best?.rect ?? createCaptionRect(preferred, captionWidth, captionHeight, safeMargin);
+ const x = rect.centerX * 100;
+ const y = rect.centerY * 100;
+
+ return {
+ x,
+ y,
+ placement: best?.id ?? "bottom",
+ overlapRatio: best?.overlapRatio ?? 0,
+ score: best?.score ?? 0,
+ normalizedPosition: { x: rect.centerX, y: rect.centerY },
+ rect: {
+ x: rect.xMin * frame.width,
+ y: rect.yMin * frame.height,
+ xMin: rect.xMin * frame.width,
+ yMin: rect.yMin * frame.height,
+ xMax: rect.xMax * frame.width,
+ yMax: rect.yMax * frame.height,
+ width: rect.width * frame.width,
+ height: rect.height * frame.height,
+ normalized: rect,
+ },
+ };
+}
+
+export function getCaptionAvoidancePlacement(
+ subjectBox,
+ optionsOrFrameSize = {},
+ legacyCaptionSize = {},
+ legacyOptions = {},
+) {
+ const isStructuredCall = Boolean(
+ optionsOrFrameSize?.frameSize ||
+ optionsOrFrameSize?.sourceSize ||
+ optionsOrFrameSize?.fitMode ||
+ optionsOrFrameSize?.smartCrop,
+ );
+
+ if (!isStructuredCall) {
+ return chooseCaptionAvoidancePlacement(
+ subjectBox,
+ optionsOrFrameSize,
+ legacyCaptionSize,
+ legacyOptions,
+ );
+ }
+
+ const options = optionsOrFrameSize;
+ const frameSize = options.frameSize;
+ const mappedSubject = options.sourceSize
+ ? mapNormalizedBoxToFrame(subjectBox, options.sourceSize, frameSize, {
+ fitMode: options.fitMode,
+ smartCrop: options.smartCrop,
+ outputSize: options.outputSize ?? frameSize,
+ padding: options.padding ?? options.cropPadding,
+ objectPosition: options.objectPosition,
+ })
+ : subjectBox;
+
+ return chooseCaptionAvoidancePlacement(
+ mappedSubject,
+ frameSize,
+ options.captionSize ?? {},
+ {
+ preferredPlacement: options.basePlacement ?? options.preferredPlacement,
+ previousPlacement: options.previousPlacement,
+ candidates: options.candidates,
+ safeMargin: options.safeMargin,
+ },
+ );
+}
+
+export const getAvoidingCaptionPlacement = getCaptionAvoidancePlacement;
diff --git a/src/styles.css b/src/styles.css
index acd1b7c..e44f8dc 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -102,6 +102,103 @@ button:disabled {
line-height: 1.2;
}
+.project-title-row {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+}
+
+.project-file-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ border: 0;
+ padding: 2px 5px;
+ border-radius: 5px;
+ color: #8e9aa5;
+ font: inherit;
+ font-size: 12px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.project-file-button:hover { color: #e8fffc; background: rgba(255,255,255,.075); }
+.project-file-input { display: none; }
+.file-menu-card {
+ display: grid;
+ width: 294px;
+ gap: 5px;
+ padding: 8px;
+}
+
+.file-menu-heading {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ padding: 5px 6px 8px;
+ color: #f1f8fa;
+ font-size: 13px;
+ font-weight: 700;
+}
+
+.file-menu-heading small {
+ color: #72808b;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: .04em;
+ text-transform: uppercase;
+}
+
+.file-menu-action {
+ display: grid;
+ grid-template-columns: 30px minmax(0, 1fr) auto;
+ align-items: center;
+ min-height: 56px;
+ gap: 9px;
+ width: 100%;
+ padding: 7px 8px;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: #e2edf1;
+ text-align: left;
+ background: transparent;
+ cursor: pointer;
+ transition: background .16s ease, border-color .16s ease, transform .16s ease;
+}
+
+.file-menu-action:hover {
+ border-color: rgba(49, 239, 217, .23);
+ background: rgba(53, 240, 221, .08);
+}
+
+.file-menu-action:active { transform: scale(.985); }
+.file-menu-icon {
+ display: grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border-radius: 7px;
+ color: #aebbc3;
+ background: rgba(255,255,255,.07);
+}
+.file-menu-copy { display: grid; gap: 3px; min-width: 0; }
+.file-menu-copy strong { color: #eaf4f7; font-size: 13px; font-weight: 650; }
+.file-menu-copy small { color: #84929d; font-size: 11px; white-space: nowrap; }
+.file-menu-format {
+ align-self: start;
+ margin-top: 3px;
+ color: #72818b;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 10px;
+}
+.file-menu-divider { height: 1px; margin: 3px 5px; background: rgba(255,255,255,.08); }
+.file-menu-new { min-height: 46px; }
+.file-menu-new .file-menu-copy small { display: none; }
+.file-menu-action.is-primary { background: rgba(38, 221, 202, .09); }
+.file-menu-action.is-primary .file-menu-icon { color: #0f2021; background: #35e9d6; }
+.file-menu-action.is-primary .file-menu-copy strong { color: #dffff9; }
+.file-menu-action.is-primary:hover { border-color: rgba(53, 240, 221, .48); background: rgba(38, 221, 202, .15); }
+
.autosave {
display: flex;
align-items: center;
@@ -230,6 +327,13 @@ button:disabled {
box-shadow: 0 22px 48px rgba(0, 0, 0, 0.42);
}
+/* The project trigger sits in the left side of the top bar. Open into the
+ workspace, not back over the app's left edge. */
+.project-file-popover {
+ right: auto;
+ left: 0;
+}
+
.popover-close {
position: absolute;
top: 8px;
@@ -995,6 +1099,412 @@ button:disabled {
letter-spacing: 0;
}
+.smart-vision-panel {
+ gap: 14px;
+ padding-right: 2px;
+ scrollbar-color: rgba(143, 158, 172, 0.38) transparent;
+ scrollbar-width: thin;
+}
+
+.smart-vision-heading {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.smart-vision-heading > div > span {
+ display: block;
+ margin-bottom: 4px;
+ color: #6f7e89;
+ font-size: 10px;
+ font-weight: 780;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+}
+
+.smart-vision-heading h2 {
+ margin: 0;
+}
+
+.smart-vision-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ flex: 0 0 auto;
+ min-height: 25px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ padding: 0 9px;
+ color: #87939e;
+ font-size: 10px;
+ font-weight: 720;
+ background: rgba(255, 255, 255, 0.035);
+}
+
+.smart-vision-status i {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #68747e;
+}
+
+.smart-vision-status.is-ready {
+ border-color: rgba(53, 234, 217, 0.2);
+ color: #9cefe7;
+ background: rgba(53, 234, 217, 0.07);
+}
+
+.smart-vision-status.is-ready i {
+ background: #35ead9;
+ box-shadow: 0 0 9px rgba(53, 234, 217, 0.55);
+}
+
+.smart-vision-status.is-running {
+ border-color: rgba(118, 161, 255, 0.28);
+ color: #b9ccff;
+ background: rgba(91, 132, 239, 0.08);
+}
+
+.smart-vision-status.is-running i {
+ background: #7aa2ff;
+ animation: vision-status-pulse 1s ease-in-out infinite;
+}
+
+@keyframes vision-status-pulse {
+ 50% {
+ opacity: 0.32;
+ transform: scale(0.74);
+ }
+}
+
+.vision-model-stack {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.vision-model-stack > div {
+ display: grid;
+ grid-template-columns: 26px minmax(0, 1fr);
+ align-items: center;
+ gap: 7px;
+ min-width: 0;
+ min-height: 58px;
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 8px;
+ padding: 9px;
+ color: #8baeff;
+ background:
+ linear-gradient(135deg, rgba(103, 144, 255, 0.08), rgba(53, 234, 217, 0.035)),
+ rgba(255, 255, 255, 0.025);
+}
+
+.vision-model-stack > div:last-child {
+ color: #40dfcf;
+}
+
+.vision-model-stack span {
+ display: grid;
+ min-width: 0;
+}
+
+.vision-model-stack strong {
+ overflow: hidden;
+ color: #e7f0f5;
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.vision-model-stack em {
+ overflow: hidden;
+ margin-top: 2px;
+ color: #76838e;
+ font-size: 9px;
+ font-style: normal;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.vision-empty-state {
+ border: 1px dashed rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ padding: 14px;
+ color: #7f8c97;
+ font-size: 12px;
+ line-height: 1.55;
+ text-align: center;
+ background: rgba(255, 255, 255, 0.022);
+}
+
+.vision-analyze-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ flex: 0 0 auto;
+ width: 100%;
+ min-height: 44px;
+}
+
+.vision-progress {
+ display: grid;
+ gap: 8px;
+ border: 1px solid rgba(122, 162, 255, 0.16);
+ border-radius: 8px;
+ padding: 11px;
+ background: rgba(81, 119, 218, 0.055);
+}
+
+.vision-progress > div {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ color: #9aa8b5;
+ font-size: 10px;
+}
+
+.vision-progress > div span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.vision-progress > div strong {
+ color: #dce7ff;
+ font-size: 10px;
+}
+
+.vision-progress-track {
+ display: block;
+ height: 4px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+}
+
+.vision-progress-track > span {
+ display: block;
+ height: 100%;
+ border-radius: inherit;
+ background: linear-gradient(90deg, #6e91ff, #35ead9);
+ transition: width 180ms ease;
+}
+
+.vision-result-card {
+ display: grid;
+ grid-template-columns: 34px minmax(0, 1fr) auto auto;
+ align-items: center;
+ gap: 9px;
+ min-height: 64px;
+ border: 1px solid rgba(53, 234, 217, 0.16);
+ border-radius: 8px;
+ padding: 10px;
+ background:
+ radial-gradient(circle at 8% 16%, rgba(53, 234, 217, 0.09), transparent 42%),
+ rgba(255, 255, 255, 0.025);
+}
+
+.vision-result-card > div:not(.vision-subject-icon) {
+ display: grid;
+ gap: 3px;
+ min-width: 0;
+}
+
+.vision-result-card span {
+ color: #71808b;
+ font-size: 9px;
+}
+
+.vision-result-card strong {
+ overflow: hidden;
+ color: #eef9f8;
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.vision-result-card p {
+ grid-column: 1 / -1;
+ margin: 0;
+ color: #a6b2bd;
+ font-size: 11px;
+ line-height: 1.5;
+}
+
+.vision-subject-icon {
+ display: grid;
+ place-items: center;
+ width: 34px;
+ height: 34px;
+ border-radius: 8px;
+ color: #35ead9;
+ background: rgba(53, 234, 217, 0.1);
+}
+
+.vision-confidence,
+.vision-object-count {
+ min-width: 38px;
+ border-left: 1px solid rgba(255, 255, 255, 0.065);
+ padding-left: 9px;
+}
+
+.vision-timeline-summary {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ min-height: 34px;
+ border: 1px solid rgba(110, 145, 255, 0.14);
+ border-radius: 7px;
+ padding: 8px 10px;
+ color: #82909b;
+ background: rgba(110, 145, 255, 0.055);
+ font-size: 10px;
+}
+
+.vision-timeline-summary strong {
+ color: #79eadf;
+ font-size: 13px;
+}
+
+.vision-timeline-summary em {
+ color: #82909b;
+ font-style: normal;
+}
+
+.vision-feature-list {
+ display: grid;
+ gap: 8px;
+}
+
+.vision-feature-list label {
+ display: grid;
+ grid-template-columns: 28px minmax(0, 1fr) 30px;
+ align-items: center;
+ gap: 9px;
+ min-height: 62px;
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 8px;
+ padding: 9px 10px;
+ color: #8091a0;
+ background: rgba(255, 255, 255, 0.028);
+ transition: border-color 140ms ease, background 140ms ease, opacity 140ms ease;
+}
+
+.vision-feature-list label.is-active {
+ border-color: rgba(53, 234, 217, 0.26);
+ color: #37e5d4;
+ background: rgba(53, 234, 217, 0.055);
+}
+
+.vision-feature-list label.is-disabled {
+ opacity: 0.42;
+}
+
+.vision-feature-list label > span {
+ display: grid;
+ gap: 3px;
+ min-width: 0;
+}
+
+.vision-feature-list strong {
+ color: #dce7ec;
+ font-size: 11px;
+}
+
+.vision-feature-list em {
+ color: #75828d;
+ font-size: 9px;
+ font-style: normal;
+ line-height: 1.35;
+}
+
+.vision-feature-list input {
+ position: relative;
+ width: 28px;
+ height: 16px;
+ margin: 0;
+ appearance: none;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+ cursor: pointer;
+ transition: background 140ms ease, border-color 140ms ease;
+}
+
+.vision-feature-list input::after {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: #87939d;
+ content: "";
+ transition: transform 140ms ease, background 140ms ease;
+}
+
+.vision-feature-list input:checked {
+ border-color: rgba(53, 234, 217, 0.62);
+ background: rgba(53, 234, 217, 0.22);
+}
+
+.vision-feature-list input:checked::after {
+ background: #35ead9;
+ transform: translateX(12px);
+}
+
+.vision-feature-list input:disabled {
+ cursor: not-allowed;
+}
+
+.vision-model-note {
+ margin: -2px 2px 0;
+ color: #697681;
+ font-size: 10px;
+ line-height: 1.55;
+}
+
+.avatar-lab-card { display: grid; gap: 10px; border: 1px solid rgba(123, 142, 255, .2); border-radius: 10px; padding: 12px; background: linear-gradient(135deg, rgba(88, 113, 234, .11), rgba(53, 234, 217, .04)); }
+.avatar-lab-heading { display: grid; grid-template-columns: 30px minmax(0, 1fr) auto; align-items: center; gap: 8px; }
+.avatar-lab-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; color: #b7c8ff; background: rgba(112, 139, 255, .16); }
+.avatar-lab-heading > div { display: grid; gap: 2px; }
+.avatar-lab-heading > div > span { color: #8290b8; font-size: 9px; font-weight: 750; letter-spacing: .09em; text-transform: uppercase; }
+.avatar-lab-heading strong { color: #eff4ff; font-size: 12px; }
+.avatar-lab-heading em { border: 1px solid rgba(255, 255, 255, .1); border-radius: 999px; padding: 3px 6px; color: #98a5ba; font-size: 9px; font-style: normal; }
+.avatar-lab-heading em.is-ready { border-color: rgba(53, 234, 217, .28); color: #89eadf; background: rgba(53, 234, 217, .08); }
+.avatar-lab-card p { margin: 0; color: #92a0ae; font-size: 10px; line-height: 1.55; }
+.avatar-lab-requirements { display: flex; flex-wrap: wrap; gap: 5px; }
+.avatar-lab-requirements span { border: 1px solid rgba(255, 255, 255, .08); border-radius: 5px; padding: 4px 6px; color: #788794; font-size: 9px; }
+.avatar-lab-requirements span.is-ready { border-color: rgba(53, 234, 217, .25); color: #8eece2; background: rgba(53, 234, 217, .06); }
+.avatar-open-button { display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 36px; width: 100%; font-size: 11px; }
+
+.avatar-context-panel { display: grid; gap: 14px; }
+.avatar-context-hero { display: grid; grid-template-columns: 42px minmax(0, 1fr); gap: 10px; align-items: start; padding: 13px; border: 1px solid rgba(109, 137, 255, .22); border-radius: 10px; background: linear-gradient(135deg, rgba(85, 112, 235, .15), rgba(53, 234, 217, .05)); }
+.avatar-context-hero > span { display: grid; place-items: center; width: 42px; height: 42px; border-radius: 10px; color: #b4c7ff; background: rgba(108, 137, 255, .18); }
+.avatar-context-hero > div { display: grid; gap: 4px; }
+.avatar-context-hero small { color: #91a5d9; font-size: 9px; font-weight: 780; letter-spacing: .1em; text-transform: uppercase; }
+.avatar-context-hero strong { color: #eff5ff; font-size: 15px; }
+.avatar-context-hero em { color: #9aa8b8; font-size: 10px; font-style: normal; line-height: 1.45; }
+.avatar-input-list { display: grid; gap: 8px; }
+.avatar-input-list > div { display: grid; grid-template-columns: 25px minmax(0, 1fr); align-items: center; gap: 8px; min-height: 53px; border: 1px solid rgba(255,255,255,.07); border-radius: 8px; padding: 8px 10px; color: #758494; background: rgba(255,255,255,.025); }
+.avatar-input-list > div.is-ready { border-color: rgba(53,234,217,.2); color: #61dace; background: rgba(53,234,217,.045); }
+.avatar-input-list span { display: grid; gap: 3px; }.avatar-input-list strong { color: #dfe9ef; font-size: 11px; }.avatar-input-list em { color: #778592; font-size: 9px; font-style: normal; }
+.avatar-sync-mode { display: flex; justify-content: space-between; align-items: center; border-radius: 8px; padding: 10px; color: #93a2b0; background: rgba(255,255,255,.035); font-size: 10px; }.avatar-sync-mode strong { color: #77e5da; font-size: 10px; }.avatar-context-note { margin: 0; color: #778592; font-size: 10px; line-height: 1.55; }.avatar-generate-button { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 42px; width: 100%; }
+.avatar-official-notice { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 8px; align-items: start; border: 1px solid rgba(108, 137, 255, .24); border-radius: 8px; padding: 10px; color: #9bb6ff; background: rgba(93, 122, 240, .08); }.avatar-official-notice > span { display: grid; gap: 3px; }.avatar-official-notice strong { color: #dce7ff; font-size: 11px; }.avatar-official-notice em { color: #94a2b4; font-size: 9px; font-style: normal; line-height: 1.45; }
+
+.vision-result-actions {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 8px;
+}
+
+.vision-result-actions button {
+ width: 100%;
+}
+
.side-textarea {
width: 100%;
min-height: 210px;
@@ -1269,9 +1779,19 @@ button:disabled {
}
.caption-tool-panel {
- overflow: hidden;
+ overflow-x: hidden;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+ padding-right: 8px;
+ padding-bottom: 18px;
+ scrollbar-color: rgba(143, 158, 172, 0.42) transparent;
+ scrollbar-width: thin;
}
+.caption-tool-panel::-webkit-scrollbar { width: 7px; }
+.caption-tool-panel::-webkit-scrollbar-thumb { border-radius: 999px; background: rgba(143, 158, 172, 0.42); }
+
.caption-tool-panel > h2,
.caption-tool-panel > .switch-row,
.caption-tool-panel > .segmented,
@@ -1307,6 +1827,16 @@ button:disabled {
margin: 14px 0;
}
+.caption-style-panel { display: grid; gap: 10px; padding: 11px; border: 1px solid rgba(255,255,255,.07); border-radius: 9px; background: rgba(255,255,255,.025); }
+.caption-style-heading { display: grid; gap: 2px; }
+.caption-style-heading strong { font-size: 13px; color: #eaf7f7; }
+.caption-style-heading span { font-size: 11px; color: #82909c; }
+.caption-style-presets, .caption-color-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
+.caption-style-presets button { min-height: 30px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; color: #b8c5cd; background: rgba(255,255,255,.04); cursor:pointer; }
+.caption-style-presets button.is-active { color: #061515; border-color: #37e8d8; background: #37e8d8; }
+.caption-color-row label { display:grid; gap:4px; color:#93a0aa; font-size:11px; }
+.caption-color-row input { width:100%; height:28px; padding:2px; border:1px solid rgba(255,255,255,.1); border-radius:5px; background:#0c1015; }
+
.caption-editor > label:first-child {
color: #d8e4ea;
font-size: 12px;
@@ -1701,6 +2231,21 @@ button:disabled {
box-shadow: 0 14px 42px rgba(0, 0, 0, 0.32);
}
+.preview-frame.has-background-removed {
+ background-color: #11171c;
+ background-image:
+ linear-gradient(45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%),
+ linear-gradient(-45deg, rgba(255, 255, 255, 0.055) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%),
+ linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, 0.055) 75%);
+ background-position: 0 0, 0 7px, 7px -7px, -7px 0;
+ background-size: 14px 14px;
+}
+
+.preview-frame.has-background-removed > img {
+ background: transparent;
+}
+
.preview-frame img,
.preview-frame video {
display: block;
@@ -1716,6 +2261,105 @@ button:disabled {
object-fit: cover;
}
+.vision-detection-box {
+ position: absolute;
+ z-index: 4;
+ min-width: 8px;
+ min-height: 8px;
+ border: 1px solid rgba(123, 163, 255, 0.9);
+ border-radius: 2px;
+ pointer-events: none;
+ box-shadow:
+ 0 0 0 1px rgba(3, 7, 12, 0.5),
+ inset 0 0 18px rgba(109, 147, 255, 0.05);
+}
+
+.vision-detection-box::before,
+.vision-detection-box::after {
+ position: absolute;
+ width: 9px;
+ height: 9px;
+ border-color: #8caaff;
+ content: "";
+}
+
+.vision-detection-box::before {
+ top: -2px;
+ left: -2px;
+ border-top: 2px solid;
+ border-left: 2px solid;
+}
+
+.vision-detection-box::after {
+ right: -2px;
+ bottom: -2px;
+ border-right: 2px solid;
+ border-bottom: 2px solid;
+}
+
+.vision-detection-box.is-subject {
+ border-color: rgba(53, 234, 217, 0.92);
+ box-shadow:
+ 0 0 0 1px rgba(3, 7, 12, 0.55),
+ 0 0 18px rgba(53, 234, 217, 0.11),
+ inset 0 0 22px rgba(53, 234, 217, 0.045);
+}
+
+.vision-detection-box.is-subject::before,
+.vision-detection-box.is-subject::after {
+ border-color: #35ead9;
+}
+
+.vision-detection-box > span {
+ position: absolute;
+ top: -20px;
+ left: -1px;
+ max-width: 150px;
+ overflow: hidden;
+ border-radius: 3px 3px 3px 0;
+ padding: 3px 5px;
+ color: #eef3ff;
+ font-size: 8px;
+ font-weight: 760;
+ line-height: 1;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ background: rgba(65, 94, 172, 0.94);
+ box-shadow: 0 3px 8px rgba(0, 0, 0, 0.24);
+}
+
+.vision-detection-box.is-subject > span {
+ color: #071716;
+ background: rgba(53, 234, 217, 0.96);
+}
+
+.preview-ai-badges {
+ position: absolute;
+ top: 10px;
+ left: 10px;
+ z-index: 5;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ max-width: calc(100% - 20px);
+ pointer-events: none;
+}
+
+.preview-ai-badges span {
+ overflow: hidden;
+ border: 1px solid rgba(53, 234, 217, 0.22);
+ border-radius: 999px;
+ padding: 4px 7px;
+ color: #b5f5ef;
+ font-size: 8px;
+ font-weight: 740;
+ line-height: 1;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ background: rgba(7, 15, 20, 0.74);
+ backdrop-filter: blur(8px);
+}
+
.preview-frame.is-image-hidden::before {
display: grid;
place-items: center;
@@ -1732,19 +2376,22 @@ button:disabled {
.caption-overlay {
position: absolute;
z-index: 2;
- width: min(68%, 680px);
+ box-sizing: border-box;
border: 0;
- border-radius: 7px;
- padding: 12px 22px;
- color: #f5fbff;
- font-weight: 700;
- line-height: 1.35;
- text-align: center;
- background: rgba(5, 8, 13, 0.62);
+ padding: 0;
+ overflow: visible;
+ background: transparent;
cursor: move;
transform: translate(-50%, -50%);
touch-action: none;
- text-shadow: 0 1px 6px rgba(0, 0, 0, 0.45);
+ appearance: none;
+}
+
+.caption-overlay canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
}
.caption-overlay:hover,
diff --git a/src/workers/vision.worker.js b/src/workers/vision.worker.js
new file mode 100644
index 0000000..089d0f0
--- /dev/null
+++ b/src/workers/vision.worker.js
@@ -0,0 +1,351 @@
+import {
+ MODNET_MODEL_ID,
+ MODNET_MODEL_LABEL,
+ MODNET_MODEL_REVISION,
+ YOLOS_TINY_MODEL_ID,
+ YOLOS_TINY_MODEL_LABEL,
+ YOLOS_TINY_MODEL_REVISION,
+} from "../config/models.js";
+import { normalizeDetections, selectPrimarySubject } from "../lib/visualGeometry.js";
+
+let transformersPromise = null;
+let detectorPromise = null;
+let backgroundRemoverPromise = null;
+let analysisQueue = Promise.resolve();
+
+const canceledRequests = new Set();
+
+function clampProgress(value) {
+ const number = Number(value);
+ return Number.isFinite(number) ? Math.max(0, Math.min(100, number)) : 0;
+}
+
+function isCanceled(requestId) {
+ return canceledRequests.has(requestId);
+}
+
+function postProgress(requestId, progress, phase) {
+ if (isCanceled(requestId)) {
+ return;
+ }
+
+ self.postMessage({
+ type: "progress",
+ requestId,
+ progress: clampProgress(progress),
+ phase,
+ });
+}
+
+function createModelLoadProgressCallback(requestId, { start, end, label }) {
+ const progressByFile = new Map();
+ let lastReported = start;
+
+ return (event) => {
+ if (isCanceled(requestId)) {
+ return;
+ }
+
+ const rawProgress = Number(event?.progress);
+ if (!Number.isFinite(rawProgress)) {
+ return;
+ }
+
+ const fileKey = event.file ?? event.name ?? event.url ?? "__model__";
+ progressByFile.set(fileKey, clampProgress(rawProgress));
+ const values = Array.from(progressByFile.values());
+ const average = values.reduce((sum, value) => sum + value, 0) / Math.max(1, values.length);
+ const nextProgress = Math.round(start + (average / 100) * (end - start));
+ if (nextProgress <= lastReported) {
+ return;
+ }
+
+ lastReported = nextProgress;
+ postProgress(requestId, nextProgress, `下载或读取 ${label} ONNX`);
+ };
+}
+
+function getTransformers() {
+ transformersPromise ??= import("@huggingface/transformers").then((transformers) => {
+ if (transformers.env?.backends?.onnx?.wasm) {
+ transformers.env.backends.onnx.wasm.numThreads = 1;
+ }
+ return transformers;
+ });
+ return transformersPromise;
+}
+
+async function getDetector(requestId) {
+ if (!detectorPromise) {
+ detectorPromise = (async () => {
+ const { pipeline } = await getTransformers();
+ return pipeline("object-detection", YOLOS_TINY_MODEL_ID, {
+ device: "wasm",
+ dtype: "q8",
+ revision: YOLOS_TINY_MODEL_REVISION,
+ progress_callback: createModelLoadProgressCallback(requestId, {
+ start: 8,
+ end: 48,
+ label: YOLOS_TINY_MODEL_LABEL,
+ }),
+ });
+ })().catch((error) => {
+ detectorPromise = null;
+ throw error;
+ });
+ } else {
+ postProgress(requestId, 48, `${YOLOS_TINY_MODEL_LABEL} 已就绪`);
+ }
+
+ return detectorPromise;
+}
+
+async function getBackgroundRemover(requestId) {
+ if (!backgroundRemoverPromise) {
+ backgroundRemoverPromise = (async () => {
+ const { pipeline } = await getTransformers();
+ return pipeline("background-removal", MODNET_MODEL_ID, {
+ device: "wasm",
+ dtype: "q8",
+ revision: MODNET_MODEL_REVISION,
+ progress_callback: createModelLoadProgressCallback(requestId, {
+ start: 62,
+ end: 88,
+ label: MODNET_MODEL_LABEL,
+ }),
+ });
+ })().catch((error) => {
+ backgroundRemoverPromise = null;
+ throw error;
+ });
+ } else {
+ postProgress(requestId, 88, `${MODNET_MODEL_LABEL} 已就绪`);
+ }
+
+ return backgroundRemoverPromise;
+}
+
+function getErrorMessage(error) {
+ if (error instanceof Error && error.message) {
+ return error.message;
+ }
+ return "视觉主体分析失败";
+}
+
+function getMatteSubject(cutoutImage, sourceSize) {
+ const channels = Number(cutoutImage?.channels) || 0;
+ const data = cutoutImage?.data;
+ const width = Number(cutoutImage?.width) || 0;
+ const height = Number(cutoutImage?.height) || 0;
+ if (!data || !width || !height || (channels !== 2 && channels !== 4)) {
+ return null;
+ }
+
+ const alphaOffset = channels - 1;
+ const alphaThreshold = 24;
+ let xmin = width;
+ let ymin = height;
+ let xmax = -1;
+ let ymax = -1;
+ let foregroundPixels = 0;
+
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const alpha = data[(y * width + x) * channels + alphaOffset];
+ if (alpha < alphaThreshold) {
+ continue;
+ }
+ foregroundPixels += 1;
+ xmin = Math.min(xmin, x);
+ ymin = Math.min(ymin, y);
+ xmax = Math.max(xmax, x);
+ ymax = Math.max(ymax, y);
+ }
+ }
+
+ const matteCoverage = foregroundPixels / Math.max(1, width * height);
+ if (xmax < xmin || ymax < ymin || matteCoverage < 0.004 || matteCoverage > 0.96) {
+ return null;
+ }
+
+ return {
+ label: "foreground",
+ score: Math.max(0.58, Math.min(0.96, 0.72 + Math.sqrt(matteCoverage) * 0.24)),
+ box: {
+ xmin: xmin / sourceSize.width,
+ ymin: ymin / sourceSize.height,
+ xmax: (xmax + 1) / sourceSize.width,
+ ymax: (ymax + 1) / sourceSize.height,
+ },
+ source: "modnet",
+ matteCoverage,
+ };
+}
+
+function mergePortraitSubject(detectedSubject, matteSubject) {
+ if (!detectedSubject) {
+ return matteSubject;
+ }
+ if (!matteSubject || String(detectedSubject.label).toLowerCase() !== "person") {
+ return detectedSubject;
+ }
+
+ return {
+ ...detectedSubject,
+ box: {
+ xmin: Math.min(detectedSubject.box.xmin, matteSubject.box.xmin),
+ ymin: Math.min(detectedSubject.box.ymin, matteSubject.box.ymin),
+ xmax: Math.max(detectedSubject.box.xmax, matteSubject.box.xmax),
+ ymax: Math.max(detectedSubject.box.ymax, matteSubject.box.ymax),
+ },
+ matteCoverage: matteSubject.matteCoverage,
+ };
+}
+
+async function analyzeVisual(message) {
+ const {
+ requestId,
+ imageBlob,
+ removeBackground = false,
+ threshold = 0.35,
+ preferredLabels = ["person"],
+ } = message;
+
+ if (!(imageBlob instanceof Blob) || imageBlob.size <= 0) {
+ throw new Error("没有可分析的图片数据。");
+ }
+
+ postProgress(requestId, 3, "解码视觉素材");
+ const { RawImage } = await getTransformers();
+ const image = await RawImage.read(imageBlob);
+ const sourceSize = {
+ width: Math.max(1, Number(image.width) || 1),
+ height: Math.max(1, Number(image.height) || 1),
+ };
+
+ if (isCanceled(requestId)) {
+ return;
+ }
+
+ const detector = await getDetector(requestId);
+ postProgress(requestId, 52, `使用 ${YOLOS_TINY_MODEL_LABEL} 识别主体`);
+ const rawDetections = await detector(image, {
+ threshold: Math.max(0.01, Math.min(0.99, Number(threshold) || 0.35)),
+ percentage: false,
+ });
+ const detections = normalizeDetections(rawDetections, sourceSize)
+ .map((detection) => ({
+ label: detection.label,
+ score: detection.score,
+ box: {
+ xmin: detection.box.xMin,
+ ymin: detection.box.yMin,
+ xmax: detection.box.xMax,
+ ymax: detection.box.yMax,
+ },
+ }))
+ .sort((left, right) => right.score - left.score);
+ const rankedSubject = selectPrimarySubject(detections, { preferredLabels });
+ let subject = rankedSubject
+ ? {
+ label: rankedSubject.label,
+ score: rankedSubject.score,
+ box: {
+ xmin: rankedSubject.box.xMin,
+ ymin: rankedSubject.box.yMin,
+ xmax: rankedSubject.box.xMax,
+ ymax: rankedSubject.box.yMax,
+ },
+ }
+ : null;
+ postProgress(
+ requestId,
+ removeBackground ? 60 : 96,
+ subject ? `已识别主体:${subject.label}` : "未识别到高置信度主体",
+ );
+
+ if (isCanceled(requestId)) {
+ return;
+ }
+
+ let cutoutBlob = null;
+ let matteSubject = null;
+ if (removeBackground) {
+ const backgroundRemover = await getBackgroundRemover(requestId);
+ postProgress(requestId, 90, `使用 ${MODNET_MODEL_LABEL} 生成透明抠图`);
+ const cutoutImages = await backgroundRemover(image);
+ const cutoutImage = Array.isArray(cutoutImages) ? cutoutImages[0] : cutoutImages;
+ if (!cutoutImage) {
+ throw new Error(`${MODNET_MODEL_LABEL} 没有返回有效抠图。`);
+ }
+ matteSubject = getMatteSubject(cutoutImage, sourceSize);
+ subject = mergePortraitSubject(subject, matteSubject);
+ if (!detections.length && matteSubject) {
+ detections.push(matteSubject);
+ }
+ cutoutBlob = await cutoutImage.toBlob("image/png");
+ if (!(cutoutBlob instanceof Blob) || cutoutBlob.size <= 0) {
+ throw new Error(`${MODNET_MODEL_LABEL} 透明 PNG 生成失败。`);
+ }
+ postProgress(requestId, 97, "透明抠图已生成");
+ }
+
+ if (isCanceled(requestId)) {
+ return;
+ }
+
+ postProgress(requestId, 100, "视觉主体分析完成");
+ self.postMessage({
+ type: "result",
+ requestId,
+ result: {
+ sourceSize,
+ detections,
+ subject,
+ matteSubject,
+ cutoutBlob,
+ modelIds: {
+ detector: YOLOS_TINY_MODEL_ID,
+ matting: removeBackground ? MODNET_MODEL_ID : null,
+ },
+ modelRevisions: {
+ detector: YOLOS_TINY_MODEL_REVISION,
+ matting: removeBackground ? MODNET_MODEL_REVISION : null,
+ },
+ },
+ });
+}
+
+function enqueueAnalysis(message) {
+ analysisQueue = analysisQueue.then(async () => {
+ try {
+ if (!isCanceled(message.requestId)) {
+ await analyzeVisual(message);
+ }
+ } catch (error) {
+ if (!isCanceled(message.requestId)) {
+ self.postMessage({
+ type: "error",
+ requestId: message.requestId,
+ error: getErrorMessage(error),
+ });
+ }
+ } finally {
+ canceledRequests.delete(message.requestId);
+ }
+ });
+}
+
+self.addEventListener("message", (event) => {
+ const message = event.data;
+ if (message?.type === "cancel") {
+ if (message.requestId) {
+ canceledRequests.add(message.requestId);
+ }
+ return;
+ }
+
+ if (message?.type === "analyze" && message.requestId) {
+ enqueueAnalysis(message);
+ }
+});