feat: add face dector and bug fix

This commit is contained in:
haixin.yang committed 2026-07-10 15:21:48 +08:00
1 parent 1cc16c8c2f
commit ebcb6e880a
25 files changed
+4882 -193

No files matched your search

+298
View File
@@ -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();
}
+366 -64
View File
@@ -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";
+96
View File
@@ -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),
};
}
+1
View File
@@ -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 : [],
};
}
+782
View File
@@ -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 已释放"));
}
+696
View File
@@ -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;