release: modular editor reliability v0.2.0
This commit is contained in:
1 parent
6a17255cf6
commit
e74852abec
70 files changed
+6412
-4963
No files matched your search
@@ -0,0 +1,18 @@
|
||||
export const healthyPortraitFrame = Float32Array.from(
|
||||
{ length: 768 },
|
||||
(_, index) => 0.18 + ((index * 37) % 101) / 160,
|
||||
);
|
||||
|
||||
export const flatCorruptFrame = new Float32Array(768).fill(0.5);
|
||||
|
||||
export const nonFiniteCorruptFrame = (() => {
|
||||
const frame = new Float32Array(768).fill(0.4);
|
||||
frame[256] = Number.NaN;
|
||||
return frame;
|
||||
})();
|
||||
|
||||
export const extremeCorruptFrame = (() => {
|
||||
const frame = Float32Array.from(healthyPortraitFrame);
|
||||
frame[256] = 32;
|
||||
return frame;
|
||||
})();
|
||||
@@ -0,0 +1,100 @@
|
||||
import { ASSET_DRAG_MIME, STICKERS } from "../config/editor.js";
|
||||
|
||||
export function createAssetDragControls(deps) {
|
||||
const findAssetById = (id) => {
|
||||
if (!id) return null;
|
||||
return [...deps.userAssets, ...deps.builtInAssets].find((asset) => asset.id === id) ||
|
||||
deps.getStickerDragAsset(STICKERS.find((sticker) => sticker.id === id));
|
||||
};
|
||||
const getDraggedAsset = (event) => findAssetById(event.dataTransfer?.getData(ASSET_DRAG_MIME) || event.dataTransfer?.getData("text/plain") || deps.draggedAssetIdRef.current || deps.draggedAssetId);
|
||||
const getActiveDraggedAsset = () => findAssetById(deps.draggedAssetIdRef.current || deps.draggedAssetId);
|
||||
const getTimelineDropPercent = (clientX, rect) => rect?.width ? Math.max(8, Math.min(92, ((clientX - rect.left) / rect.width) * 100)) : 50;
|
||||
const canDropAssetOnTrack = (asset, track) => {
|
||||
if (!asset || deps.trackLocks[track]) return false;
|
||||
if (track === "image") return asset.type === "image" || asset.type === "video";
|
||||
if (track === "sticker") return asset.type === "sticker";
|
||||
if (track === "audio" || track === "music") return asset.type === "audio";
|
||||
return track === "source" && asset.type === "video";
|
||||
};
|
||||
const handleAssetDragStart = (event, asset) => {
|
||||
deps.draggedAssetIdRef.current = asset.id; deps.setDraggedAssetId(asset.id); deps.setAssetDropTargetTrack("");
|
||||
event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData(ASSET_DRAG_MIME, asset.id); event.dataTransfer.setData("text/plain", asset.id);
|
||||
};
|
||||
const handleAssetDragEnd = () => {
|
||||
deps.draggedAssetIdRef.current = ""; deps.setDraggedAssetId(""); deps.setAssetDropTargetTrack("");
|
||||
deps.setAssetDropPosition({ track: "", percent: 50 });
|
||||
};
|
||||
const getDropTrackInfoFromPoint = (clientX, clientY) => {
|
||||
const element = document.elementFromPoint(clientX, clientY);
|
||||
if (!(element instanceof Element)) return { track: "", percent: 50 };
|
||||
const timeline = element.closest(".track-scroll, .tracks");
|
||||
if (getActiveDraggedAsset()?.type === "sticker" && timeline instanceof HTMLElement) {
|
||||
const rect = deps.trackScrollRef.current?.getBoundingClientRect() ?? timeline.getBoundingClientRect();
|
||||
return { track: "sticker", percent: getTimelineDropPercent(clientX, rect) };
|
||||
}
|
||||
const trackElement = element.closest("[data-asset-drop-track]");
|
||||
const track = trackElement?.dataset.assetDropTrack ?? "";
|
||||
return !track || !(trackElement instanceof HTMLElement) ? { track, percent: 50 }
|
||||
: { track, percent: getTimelineDropPercent(clientX, trackElement.getBoundingClientRect()) };
|
||||
};
|
||||
const triggerAssetDropPulse = (track) => {
|
||||
if (!track) return;
|
||||
clearTimeout(deps.assetDropPulseTimerRef.current); deps.setAssetDropPulseTrack("");
|
||||
requestAnimationFrame(() => { deps.setAssetDropPulseTrack(track); deps.assetDropPulseTimerRef.current = setTimeout(() => deps.setAssetDropPulseTrack(""), 620); });
|
||||
};
|
||||
const handleAssetPointerDown = (event, asset) => {
|
||||
if (event.button !== 0 || (event.target instanceof Element && event.target.closest(".asset-delete"))) return;
|
||||
deps.setSelectedLibraryAssetId(asset.id);
|
||||
deps.pointerAssetDragRef.current = { assetId: asset.id, startX: event.clientX, startY: event.clientY, dragging: false };
|
||||
const move = (e) => {
|
||||
const state = deps.pointerAssetDragRef.current;
|
||||
if (!state || state.assetId !== asset.id || (!state.dragging && Math.hypot(e.clientX - state.startX, e.clientY - state.startY) < 7)) return;
|
||||
e.preventDefault();
|
||||
if (!state.dragging) { state.dragging = true; deps.draggedAssetIdRef.current = asset.id; deps.setDraggedAssetId(asset.id); }
|
||||
const info = getDropTrackInfoFromPoint(e.clientX, e.clientY); const dragged = findAssetById(state.assetId);
|
||||
const track = dragged?.type === "sticker" && info.track ? "sticker" : info.track;
|
||||
const accepted = canDropAssetOnTrack(dragged, track) ? track : "";
|
||||
deps.setAssetDropTargetTrack(accepted); deps.setAssetDropPosition(accepted ? { track: accepted, percent: info.percent } : { track: "", percent: 50 });
|
||||
deps.setAssetDragPreview({ id: asset.id, name: asset.name, type: asset.type, src: asset.src, x: e.clientX, y: e.clientY });
|
||||
};
|
||||
const cleanup = () => {
|
||||
removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup);
|
||||
deps.pointerAssetDragRef.current = null; deps.setAssetDragPreview(null); deps.setAssetDropTargetTrack("");
|
||||
deps.setAssetDropPosition({ track: "", percent: 50 }); deps.draggedAssetIdRef.current = ""; deps.setDraggedAssetId("");
|
||||
};
|
||||
const up = (e) => {
|
||||
const state = deps.pointerAssetDragRef.current; const info = getDropTrackInfoFromPoint(e.clientX, e.clientY); cleanup();
|
||||
if (!state?.dragging) return;
|
||||
deps.suppressAssetClickRef.current = state.assetId; setTimeout(() => { if (deps.suppressAssetClickRef.current === state.assetId) deps.suppressAssetClickRef.current = ""; }, 300);
|
||||
const dragged = findAssetById(state.assetId); const track = dragged?.type === "sticker" && info.track ? "sticker" : info.track;
|
||||
if (canDropAssetOnTrack(dragged, track)) { triggerAssetDropPulse(track); void deps.applyAssetToTrack(dragged, track, { percent: info.percent }); }
|
||||
};
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
};
|
||||
const handleAssetClick = (event, asset) => {
|
||||
if (deps.suppressAssetClickRef.current === asset.id) { deps.suppressAssetClickRef.current = ""; event.preventDefault(); event.stopPropagation(); return; }
|
||||
deps.setSelectedLibraryAssetId(asset.id);
|
||||
if (event.detail >= 2) return void deps.applyAssetToTrack(asset, asset.type === "audio" ? "music" : "image");
|
||||
deps.notify("素材已选中,请拖到对应轨道使用");
|
||||
};
|
||||
const handleStickerClick = (event, sticker) => {
|
||||
if (deps.suppressAssetClickRef.current === sticker.id) { deps.suppressAssetClickRef.current = ""; event.preventDefault(); event.stopPropagation(); return; }
|
||||
deps.setSelectedStickerId(sticker.id); deps.setSelectedStickerSegmentId(""); deps.notify(deps.t("stickerApplied"));
|
||||
};
|
||||
const handleTrackAssetDragOver = (event, track) => {
|
||||
const asset = getDraggedAsset(event); const target = asset?.type === "sticker" ? "sticker" : track;
|
||||
if (!canDropAssetOnTrack(asset, target)) return;
|
||||
event.preventDefault(); event.dataTransfer.dropEffect = "copy";
|
||||
const rect = target === "sticker" ? deps.trackScrollRef.current?.getBoundingClientRect() ?? event.currentTarget.getBoundingClientRect() : event.currentTarget.getBoundingClientRect();
|
||||
deps.setAssetDropTargetTrack(target); deps.setAssetDropPosition({ track: target, percent: getTimelineDropPercent(event.clientX, rect) });
|
||||
};
|
||||
const handleTrackAssetDragLeave = (event, track) => {
|
||||
if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return;
|
||||
const target = getActiveDraggedAsset()?.type === "sticker" ? "sticker" : track;
|
||||
deps.setAssetDropTargetTrack((current) => current === target ? "" : current);
|
||||
deps.setAssetDropPosition((current) => current.track === target ? { track: "", percent: 50 } : current);
|
||||
};
|
||||
return { canDropAssetOnTrack, findAssetById, getActiveDraggedAsset, getDraggedAsset, getTimelineDropPercent,
|
||||
handleAssetClick, handleAssetDragEnd, handleAssetDragStart, handleAssetPointerDown, handleStickerClick,
|
||||
handleTrackAssetDragLeave, handleTrackAssetDragOver, triggerAssetDropPulse };
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { decodeWaveform } from "./media.js";
|
||||
|
||||
export function createAssetDropActions(d) {
|
||||
async function applyAssetToTrack(asset, track, options = {}) {
|
||||
if (!d.canDropAssetOnTrack(asset, track)) {
|
||||
d.notify("请把素材拖到匹配的轨道");
|
||||
return;
|
||||
}
|
||||
d.setSelectedLibraryAssetId(asset.id);
|
||||
if (track === "sticker") {
|
||||
d.addStickerAssetToTimeline(asset, options);
|
||||
return;
|
||||
}
|
||||
if (track === "image") {
|
||||
d.appendVisualAssetToTimeline(asset);
|
||||
return;
|
||||
}
|
||||
if (track === "music") {
|
||||
await d.selectAsset(asset);
|
||||
return;
|
||||
}
|
||||
if (track === "audio") {
|
||||
if (!asset.blob) {
|
||||
d.notify("当前音频素材不可用,请重新上传");
|
||||
return;
|
||||
}
|
||||
const decoded = asset.peaks?.length
|
||||
? { duration: asset.duration, peaks: asset.peaks }
|
||||
: await decodeWaveform(asset.blob, 96);
|
||||
d.replaceAudio(asset.blob, decoded.duration, decoded.peaks, "音频已写入配音轨");
|
||||
d.setSelectedTrack("audio");
|
||||
d.setActiveTool("audio");
|
||||
d.notify("音频已拖入配音音频轨");
|
||||
return;
|
||||
}
|
||||
if (track === "source") {
|
||||
d.setSelectedTrack("source");
|
||||
d.setActiveTool("audio");
|
||||
await d.extractVideoSourceAudio(asset);
|
||||
}
|
||||
}
|
||||
|
||||
function handleTrackAssetDrop(event, track) {
|
||||
const asset = d.getDraggedAsset(event);
|
||||
const targetTrack = asset?.type === "sticker" ? "sticker" : track;
|
||||
if (!d.canDropAssetOnTrack(asset, targetTrack)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const rect = targetTrack === "sticker"
|
||||
? d.trackScrollRef.current?.getBoundingClientRect() ??
|
||||
event.currentTarget.getBoundingClientRect()
|
||||
: event.currentTarget.getBoundingClientRect();
|
||||
const percent = d.getTimelineDropPercent(event.clientX, rect);
|
||||
d.draggedAssetIdRef.current = "";
|
||||
d.setDraggedAssetId("");
|
||||
d.setAssetDropTargetTrack("");
|
||||
d.setAssetDropPosition({ track: "", percent: 50 });
|
||||
d.triggerAssetDropPulse(targetTrack);
|
||||
void applyAssetToTrack(asset, targetTrack, { percent });
|
||||
}
|
||||
|
||||
function handleVisualStyleDrop(event) {
|
||||
const payload = event.dataTransfer?.getData("application/x-timeline-visual-style") || "";
|
||||
const [kind, styleId] = payload.split(":");
|
||||
if (!styleId || (kind !== "effect" && kind !== "transition")) {
|
||||
handleTrackAssetDrop(event, "image");
|
||||
return;
|
||||
}
|
||||
const clip = event.target.closest?.("[data-timeline-segment-id]");
|
||||
const segmentId = clip?.dataset.timelineSegmentId;
|
||||
if (!segmentId) {
|
||||
d.notify("请将效果或转场拖到具体的画面片段上");
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
d.setVisualSegments((segments) => segments.map((segment) =>
|
||||
segment.id === segmentId
|
||||
? { ...segment, [kind === "effect" ? "filterId" : "transitionId"]: styleId }
|
||||
: segment,
|
||||
));
|
||||
d.setSelectedVisualSegmentId(segmentId);
|
||||
d.setSelectedTrack("image");
|
||||
if (kind === "effect") d.setSelectedFilterId(styleId);
|
||||
else d.setSelectedTransitionId(styleId);
|
||||
d.notify(kind === "effect" ? "效果已应用到该画面片段" : "转场已绑定到该片段的结尾");
|
||||
}
|
||||
|
||||
return { applyAssetToTrack, handleTrackAssetDrop, handleVisualStyleDrop };
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { decodeWaveform } from "./media.js";
|
||||
|
||||
export function createAssetLibraryActions(deps) {
|
||||
async function selectAsset(asset) {
|
||||
if (asset.type === "audio") {
|
||||
if (!asset.blob) return void deps.notify("当前音频素材不可用,请重新上传");
|
||||
const decoded = asset.peaks?.length ? { duration: asset.duration, peaks: asset.peaks } : await decodeWaveform(asset.blob, 96);
|
||||
deps.replaceMusic(asset.blob, decoded.duration, decoded.peaks, asset.name);
|
||||
return;
|
||||
}
|
||||
deps.replaceVisualTimeline(asset, deps.getVisualDurationForAsset(asset));
|
||||
deps.notify(`${asset.type === "video" ? "视频" : "图片"}素材已应用到预览和时间线`);
|
||||
if (asset.type === "video") deps.extractVideoSourceAudio(asset);
|
||||
}
|
||||
|
||||
function deleteUserAsset(asset) {
|
||||
deps.removeVisionRecordsForAsset(asset);
|
||||
const urlInUse = deps.userAssets.some((item) => item.id !== asset.id && item.src === asset.src);
|
||||
if (deps.selectedLibraryAssetId === asset.id) deps.setSelectedLibraryAssetId("");
|
||||
deps.setUserAssets((items) => items.filter((item) => item.id !== asset.id));
|
||||
if (!urlInUse && deps.imageUrlRefs.current.has(asset.src)) {
|
||||
URL.revokeObjectURL(asset.src); deps.imageUrlRefs.current.delete(asset.src);
|
||||
}
|
||||
if (asset.type === "audio" && asset.blob === deps.musicBlob) {
|
||||
deps.clearMusicTrack("背景音乐素材已删除,时间线已同步清空");
|
||||
return;
|
||||
}
|
||||
const isActiveVisual = asset.type !== "audio" && (asset.src === deps.imageSrc ||
|
||||
deps.visualSegments.some((segment) => segment.assetId === asset.id || segment.src === asset.src));
|
||||
if (!isActiveVisual) return void deps.notify("素材已删除");
|
||||
const segments = deps.visualSegments.filter((segment) => segment.assetId !== asset.id && segment.src !== asset.src);
|
||||
if (asset.type === "video" && deps.sourceAudioBlob && asset.src === deps.imageSrc) deps.clearSourceAudioTrack(null);
|
||||
if (segments.length) deps.commitVisualSegments(segments, "素材已删除,对应视觉片段已移除");
|
||||
else deps.clearImageTrack("视觉素材已删除,时间线已同步清空");
|
||||
}
|
||||
return { deleteUserAsset, selectAsset };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { reverseAudioBlob } from "./media.js";
|
||||
|
||||
export function createAudioClipActions(d) {
|
||||
const updateAudioSegment = (id, patch) => d.setAudioSegments((segments) => segments.map((segment) => {
|
||||
if (segment.id !== id) return segment;
|
||||
const next = { ...segment, ...patch };
|
||||
if (Number.isFinite(patch.start) && patch.start !== segment.start) {
|
||||
const delta = patch.start - segment.start;
|
||||
d.setCaptionSegments((captions) => captions.map((caption) => caption.audioSegmentId === id
|
||||
? { ...caption, start: caption.start + delta, end: caption.end + delta } : caption));
|
||||
}
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((next.start + next.duration + 5) / 10) * 10));
|
||||
return next;
|
||||
}));
|
||||
const toggleAudioSegmentReverse = async (id) => {
|
||||
const segment = d.audioSegments.find((item) => item.id === id); if (!segment || segment.reversing) return;
|
||||
d.audioSegmentRefs.current.get(id)?.pause();
|
||||
d.setAudioSegments((items) => items.map((item) => item.id === id ? { ...item, reversing: true } : item));
|
||||
try {
|
||||
const originalBlob = segment.originalBlob || segment.blob; const originalPeaks = segment.originalPeaks || segment.peaks;
|
||||
const blob = segment.reversed ? originalBlob : await reverseAudioBlob(originalBlob);
|
||||
const peaks = segment.reversed ? originalPeaks : [...originalPeaks].reverse(); const url = URL.createObjectURL(blob);
|
||||
URL.revokeObjectURL(segment.url);
|
||||
d.setAudioSegments((items) => items.map((item) => item.id === id ? { ...item, blob, url, peaks,
|
||||
reversed: !segment.reversed, reversing: false, originalBlob, originalPeaks } : item));
|
||||
d.notify(segment.reversed ? d.t("audioReverseRestored") : d.t("audioReversed"));
|
||||
} catch (error) {
|
||||
d.setAudioSegments((items) => items.map((item) => item.id === id ? { ...item, reversing: false } : item));
|
||||
d.notify(`${d.t("audioReverseFailed")}:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
};
|
||||
const deleteAudioSegment = (id) => {
|
||||
const segment = d.audioSegments.find((item) => item.id === id); if (segment) URL.revokeObjectURL(segment.url);
|
||||
d.setAudioSegments((items) => items.filter((item) => item.id !== id));
|
||||
d.setCaptionSegments((items) => items.filter((item) => item.audioSegmentId !== id));
|
||||
d.setSelectedAudioSegmentId((current) => current === id ? "" : current); d.notify(d.t("audioClipDeleted"));
|
||||
};
|
||||
return { deleteAudioSegment, toggleAudioSegmentReverse, updateAudioSegment };
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { decodeWaveform } from "./media.js";
|
||||
import {
|
||||
createCaptionSegments,
|
||||
estimateDuration,
|
||||
formatSavedTime,
|
||||
getCaptionTimeline,
|
||||
} from "./timeline.js";
|
||||
|
||||
export function createAudioTrackActions(d) {
|
||||
function replaceAudio(blob, duration, nextPeaks, nextStatusText) {
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
const nextDuration = duration || estimateDuration(d.script);
|
||||
const start = Math.max(0, d.currentTimeRef.current || 0);
|
||||
const id = crypto.randomUUID();
|
||||
const segment = {
|
||||
id,
|
||||
blob,
|
||||
url: nextUrl,
|
||||
start,
|
||||
duration: nextDuration,
|
||||
peaks: nextPeaks,
|
||||
volume: 1,
|
||||
fadeIn: 0,
|
||||
fadeOut: 0,
|
||||
reversed: false,
|
||||
name: d.selectedVoice?.name || d.t("voiceTrack"),
|
||||
};
|
||||
d.setAudioSegments((segments) => [...segments, segment]);
|
||||
d.setSelectedAudioSegmentId(id);
|
||||
d.setSelectedTrack("audio");
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((start + nextDuration + 5) / 10) * 10));
|
||||
d.setCurrentTime(start);
|
||||
d.setStatus("done");
|
||||
d.setStatusText(nextStatusText);
|
||||
d.setProgress(100);
|
||||
return segment;
|
||||
}
|
||||
|
||||
function clearAudioTrack(message = "配音音频已从时间线移除") {
|
||||
d.audioSegmentRefs.current.forEach((audio) => audio.pause());
|
||||
d.audioSegments.forEach((segment) => URL.revokeObjectURL(segment.url));
|
||||
d.setAudioSegments([]);
|
||||
d.setSelectedAudioSegmentId("");
|
||||
d.setCurrentTime(0);
|
||||
d.setIsPlaying(false);
|
||||
d.setStatus("ready");
|
||||
d.setStatusText("音频轨已清空");
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function replaceMusic(blob, duration, nextPeaks, nextName, message = "背景音乐已添加到时间线") {
|
||||
if (d.musicUrlRef.current) URL.revokeObjectURL(d.musicUrlRef.current);
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
d.musicUrlRef.current = nextUrl;
|
||||
d.setMusicBlob(blob);
|
||||
d.setMusicUrl(nextUrl);
|
||||
d.setMusicName(nextName);
|
||||
d.setMusicDuration(duration || 0);
|
||||
d.setMusicPeaks(nextPeaks);
|
||||
d.setSelectedTrack("music");
|
||||
d.setActiveTool("audio");
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function replaceSourceAudio(
|
||||
blob,
|
||||
duration,
|
||||
nextPeaks,
|
||||
nextName,
|
||||
message = "视频原声已分离到时间线",
|
||||
timelineStart = 0,
|
||||
) {
|
||||
if (d.sourceAudioUrlRef.current) URL.revokeObjectURL(d.sourceAudioUrlRef.current);
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
d.sourceAudioUrlRef.current = nextUrl;
|
||||
const nextStart = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS, timelineStart || 0));
|
||||
d.setSourceAudioBlob(blob);
|
||||
d.setSourceAudioUrl(nextUrl);
|
||||
d.setSourceAudioName(nextName);
|
||||
d.setSourceAudioDuration(duration || 0);
|
||||
d.setSourceAudioPeaks(nextPeaks);
|
||||
d.setSourceAudioVolume(1);
|
||||
d.setSourceAudioStart(nextStart);
|
||||
d.setSelectedTrack("source");
|
||||
d.setActiveTool("audio");
|
||||
d.setStatus("done");
|
||||
d.setStatusText("视频原声已分离");
|
||||
d.setProgress(100);
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function clearSourceAudioTrack(message = "视频原声已从时间线移除") {
|
||||
d.sourceAudioRef.current?.pause();
|
||||
if (d.sourceAudioUrlRef.current) {
|
||||
URL.revokeObjectURL(d.sourceAudioUrlRef.current);
|
||||
d.sourceAudioUrlRef.current = "";
|
||||
}
|
||||
d.setSourceAudioBlob(null);
|
||||
d.setSourceAudioUrl("");
|
||||
d.setSourceAudioName("");
|
||||
d.setSourceAudioDuration(0);
|
||||
d.setSourceAudioPeaks([]);
|
||||
d.setSourceAudioStart(0);
|
||||
d.setCurrentTime((time) => Math.min(time, Math.max(
|
||||
d.audioBlob ? d.audioDuration : 0,
|
||||
d.captionDuration,
|
||||
d.musicBlob ? d.musicDuration : 0,
|
||||
d.imageSrc ? d.imageDuration : 0,
|
||||
estimateDuration(d.script),
|
||||
)));
|
||||
d.setIsPlaying(false);
|
||||
d.setSelectedTrack("source");
|
||||
if (message) d.notify(message);
|
||||
}
|
||||
|
||||
function clearMusicTrack(message = "背景音乐已从时间线移除") {
|
||||
d.musicRef.current?.pause();
|
||||
if (d.musicUrlRef.current) {
|
||||
URL.revokeObjectURL(d.musicUrlRef.current);
|
||||
d.musicUrlRef.current = "";
|
||||
}
|
||||
d.setMusicBlob(null);
|
||||
d.setMusicUrl("");
|
||||
d.setMusicName("");
|
||||
d.setMusicDuration(0);
|
||||
d.setMusicPeaks([]);
|
||||
d.setCurrentTime((time) => Math.min(time, Math.max(
|
||||
d.audioBlob ? d.audioDuration : 0,
|
||||
d.captionDuration,
|
||||
d.sourceAudioBlob ? d.sourceAudioStart + d.sourceAudioDuration : 0,
|
||||
d.imageSrc ? d.imageDuration : 0,
|
||||
estimateDuration(d.script),
|
||||
)));
|
||||
d.setIsPlaying(false);
|
||||
d.setSelectedTrack("music");
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
async function commitAudio(blob, nextStatusText) {
|
||||
const decoded = await decodeWaveform(blob);
|
||||
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText);
|
||||
const generatedCaptions = createCaptionSegments(d.script);
|
||||
const generatedTimeline = getCaptionTimeline(generatedCaptions, audioSegment.duration);
|
||||
const boundCaptions = generatedCaptions.map((segment, index) => ({
|
||||
...segment,
|
||||
audioSegmentId: audioSegment.id,
|
||||
start: audioSegment.start + generatedTimeline[index].start,
|
||||
end: audioSegment.start + generatedTimeline[index].end,
|
||||
}));
|
||||
d.setCaptionSegments((segments) => [
|
||||
...segments.filter((segment) => segment.audioSegmentId),
|
||||
...boundCaptions,
|
||||
].sort((a, b) => (a.start || 0) - (b.start || 0)));
|
||||
d.setSelectedSegmentId(boundCaptions[0]?.id ?? "");
|
||||
d.setHistoryItems((items) => [{
|
||||
id: crypto.randomUUID(),
|
||||
blob,
|
||||
voiceId: d.selectedVoiceId,
|
||||
voiceName: d.selectedVoice.name,
|
||||
script: d.script,
|
||||
duration: decoded.duration || estimateDuration(d.script),
|
||||
peaks: decoded.peaks,
|
||||
createdAt: formatSavedTime(),
|
||||
}, ...items.slice(0, 8)]);
|
||||
}
|
||||
|
||||
return {
|
||||
clearAudioTrack,
|
||||
clearMusicTrack,
|
||||
clearSourceAudioTrack,
|
||||
commitAudio,
|
||||
replaceAudio,
|
||||
replaceMusic,
|
||||
replaceSourceAudio,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { createCaptionSegments, getCaptionScript } from "./timeline.js";
|
||||
|
||||
export function createCaptionEditingActions(d) {
|
||||
function updateScript(nextScript) {
|
||||
d.setScript(nextScript);
|
||||
if (!d.audioSegments.length) {
|
||||
const nextSegments = createCaptionSegments(nextScript);
|
||||
d.setCaptionSegments(nextSegments);
|
||||
d.setSelectedSegmentId(nextSegments[0]?.id ?? "");
|
||||
}
|
||||
}
|
||||
|
||||
function updateCaptionSegmentText(segmentId, text) {
|
||||
if (d.trackLocks.caption) {
|
||||
d.notify("字幕轨已锁定,无法编辑");
|
||||
return;
|
||||
}
|
||||
d.setCaptionSegments((items) => {
|
||||
const nextSegments = items.map((segment) =>
|
||||
segment.id === segmentId ? { ...segment, text } : segment,
|
||||
);
|
||||
d.setScript(getCaptionScript(nextSegments));
|
||||
return nextSegments;
|
||||
});
|
||||
}
|
||||
|
||||
function toggleCaptionSegmentHidden(segmentId) {
|
||||
if (d.trackLocks.caption) {
|
||||
d.notify("字幕轨已锁定,无法隐藏");
|
||||
return;
|
||||
}
|
||||
d.setCaptionSegments((items) =>
|
||||
items.map((segment) =>
|
||||
segment.id === segmentId ? { ...segment, hidden: !segment.hidden } : segment,
|
||||
),
|
||||
);
|
||||
d.notify("字幕显示状态已更新");
|
||||
}
|
||||
|
||||
function disableSmartCaptionAvoidance() {
|
||||
if (!d.previewVisionKey || !d.previewVisionRecord?.options?.avoidCaptions) return false;
|
||||
d.setVisionRecords((records) => {
|
||||
const record = records[d.previewVisionKey];
|
||||
return record
|
||||
? {
|
||||
...records,
|
||||
[d.previewVisionKey]: {
|
||||
...record,
|
||||
options: { ...record.options, avoidCaptions: false },
|
||||
},
|
||||
}
|
||||
: records;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCaptionPositionChange(position) {
|
||||
const placementMap = {
|
||||
top: { x: 50, y: 18 },
|
||||
middle: { x: 50, y: 50 },
|
||||
bottom: { x: 50, y: 78 },
|
||||
};
|
||||
d.setCaptionPosition(position);
|
||||
d.setCaptionPlacement(placementMap[position] ?? placementMap.bottom);
|
||||
if (disableSmartCaptionAvoidance()) {
|
||||
d.notify("已切回手动字幕位置,智能避让已关闭");
|
||||
}
|
||||
}
|
||||
|
||||
function startCaptionDrag(event) {
|
||||
if (event.button !== 0) return;
|
||||
if (d.trackLocks.caption) {
|
||||
d.notify("字幕轨已锁定,无法拖动");
|
||||
return;
|
||||
}
|
||||
|
||||
event.stopPropagation();
|
||||
const disabledSmartAvoidance = disableSmartCaptionAvoidance();
|
||||
d.setSelectedTrack("caption");
|
||||
if (d.currentCaptionSegment) d.setSelectedSegmentId(d.currentCaptionSegment.id);
|
||||
|
||||
const applyPlacement = (clientX, clientY) => {
|
||||
const rect = d.previewCanvasRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
const x = Math.max(10, Math.min(90, ((clientX - rect.left) / rect.width) * 100));
|
||||
const y = Math.max(10, Math.min(90, ((clientY - rect.top) / rect.height) * 100));
|
||||
d.setCaptionPlacement({ x, y });
|
||||
d.setCaptionPosition("custom");
|
||||
};
|
||||
|
||||
applyPlacement(event.clientX, event.clientY);
|
||||
const handlePointerMove = (moveEvent) => applyPlacement(moveEvent.clientX, moveEvent.clientY);
|
||||
const handlePointerUp = () => {
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
d.notify(disabledSmartAvoidance
|
||||
? "字幕位置已手动调整,智能避让已关闭"
|
||||
: "字幕位置已调整");
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp, { once: true });
|
||||
}
|
||||
|
||||
function commitCaptionSegments(nextSegments, message, nextSelectedIndex = 0) {
|
||||
if (d.trackLocks.caption) {
|
||||
d.notify("字幕轨已锁定,无法修改片段");
|
||||
return;
|
||||
}
|
||||
d.setCaptionSegments(nextSegments);
|
||||
d.setScript(getCaptionScript(nextSegments));
|
||||
d.setSelectedTrack("caption");
|
||||
d.setSelectedSegmentId(
|
||||
nextSegments.length
|
||||
? nextSegments[Math.min(nextSelectedIndex, nextSegments.length - 1)]?.id ?? ""
|
||||
: "",
|
||||
);
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function deleteCaptionSegment(segmentId = d.selectedSegmentId) {
|
||||
if (d.trackLocks.caption) {
|
||||
d.notify("字幕轨已锁定,无法删除");
|
||||
return;
|
||||
}
|
||||
if (!d.captionSegments.length) {
|
||||
d.notify("当前没有字幕片段可删除");
|
||||
return;
|
||||
}
|
||||
const fallbackIndex = d.focusedSegmentIndex >= 0 ? d.focusedSegmentIndex : 0;
|
||||
const segmentIndex = d.captionSegments.findIndex((segment) => segment.id === segmentId);
|
||||
const index = segmentIndex >= 0 ? segmentIndex : fallbackIndex;
|
||||
const nextSegments = d.captionSegments.filter((_, currentIndex) => currentIndex !== index);
|
||||
commitCaptionSegments(nextSegments, "已删除当前字幕片段", Math.max(0, index - 1));
|
||||
}
|
||||
|
||||
return {
|
||||
commitCaptionSegments,
|
||||
deleteCaptionSegment,
|
||||
handleCaptionPositionChange,
|
||||
startCaptionDrag,
|
||||
toggleCaptionSegmentHidden,
|
||||
updateCaptionSegmentText,
|
||||
updateScript,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { saveLanguagePreference } from "../i18n.js";
|
||||
import { revokeVisionObjectUrls } from "./editorRuntime.js";
|
||||
import { createCaptionSegments } from "./timeline.js";
|
||||
|
||||
export function createEditorCommandActions(d) {
|
||||
function clearAllVisionState() {
|
||||
d.visionJobGenerationRef.current += 1;
|
||||
d.visionAbortControllerRef.current?.abort();
|
||||
d.visionAbortControllerRef.current = null;
|
||||
d.visionObjectUrlsRef.current.forEach((urls) => revokeVisionObjectUrls(urls));
|
||||
d.visionObjectUrlsRef.current.clear();
|
||||
d.setVisionRecords({});
|
||||
d.setVisionJob({ running: false, key: "", progress: 0, phase: "" });
|
||||
}
|
||||
|
||||
function selectTool(toolId) {
|
||||
d.setActiveTool(toolId);
|
||||
if (toolId !== "smart") d.setAvatarPanelOpen(false);
|
||||
if (toolId === "audio") {
|
||||
d.setSelectedTrack("audio");
|
||||
d.setVoiceTab("synthesis");
|
||||
}
|
||||
if (toolId === "caption") d.setSelectedTrack("caption");
|
||||
}
|
||||
|
||||
function chooseInterfaceLanguage(languageId) {
|
||||
saveLanguagePreference(languageId);
|
||||
d.setIntroClosing(true);
|
||||
window.setTimeout(() => {
|
||||
d.setUiLanguage(languageId);
|
||||
d.setIntroClosing(false);
|
||||
}, 520);
|
||||
}
|
||||
|
||||
function toggleTrackVisibility(track) {
|
||||
d.setTrackVisibility((visibility) => ({ ...visibility, [track]: !visibility[track] }));
|
||||
}
|
||||
|
||||
function toggleTrackLock(track) {
|
||||
d.setTrackLocks((locks) => ({ ...locks, [track]: !locks[track] }));
|
||||
}
|
||||
|
||||
function useHistoryItem(item) {
|
||||
d.replaceAudio(item.blob, item.duration, item.peaks, `${item.voiceName} 已恢复`);
|
||||
d.setScript(item.script);
|
||||
const nextSegments = createCaptionSegments(item.script);
|
||||
d.setCaptionSegments(nextSegments);
|
||||
d.setSelectedSegmentId(nextSegments[0]?.id ?? "");
|
||||
d.setSelectedVoiceId(item.voiceId);
|
||||
d.notify("历史配音已恢复到时间线");
|
||||
}
|
||||
|
||||
return {
|
||||
chooseInterfaceLanguage, clearAllVisionState, selectTool, toggleTrackLock,
|
||||
toggleTrackVisibility, useHistoryItem,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createEditorHistory,
|
||||
pushEditorHistory,
|
||||
redoEditorHistory,
|
||||
undoEditorHistory,
|
||||
} from "./editorHistoryCore.ts";
|
||||
|
||||
describe("editor history core", () => {
|
||||
it("undoes and redoes complete values", () => {
|
||||
let history = createEditorHistory({ clips: ["a"] });
|
||||
history = pushEditorHistory(history, { clips: ["a", "b"] });
|
||||
const undone = undoEditorHistory(history);
|
||||
expect(undone.changed).toBe(true);
|
||||
expect(undone.value.clips).toEqual(["a"]);
|
||||
const redone = redoEditorHistory(undone.history);
|
||||
expect(redone.value.clips).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("clears redo entries after a new edit", () => {
|
||||
let history = createEditorHistory("a");
|
||||
history = pushEditorHistory(history, "b");
|
||||
history = undoEditorHistory(history).history;
|
||||
history = pushEditorHistory(history, "c");
|
||||
expect(history.future).toEqual([]);
|
||||
expect(redoEditorHistory(history).changed).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds retained history", () => {
|
||||
let history = createEditorHistory(0);
|
||||
for (let value = 1; value <= 8; value += 1) {
|
||||
history = pushEditorHistory(history, value, 3);
|
||||
}
|
||||
expect(history.past).toEqual([5, 6, 7]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
export interface EditorHistory<T> {
|
||||
past: T[];
|
||||
current: T;
|
||||
future: T[];
|
||||
}
|
||||
|
||||
export interface HistoryTransition<T> {
|
||||
history: EditorHistory<T>;
|
||||
value: T;
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
export function createEditorHistory<T>(initial: T): EditorHistory<T> {
|
||||
return { past: [], current: initial, future: [] };
|
||||
}
|
||||
|
||||
export function pushEditorHistory<T>(
|
||||
history: EditorHistory<T>,
|
||||
next: T,
|
||||
limit = 50,
|
||||
): EditorHistory<T> {
|
||||
const safeLimit = Math.max(1, Math.floor(limit));
|
||||
return {
|
||||
past: [...history.past, history.current].slice(-safeLimit),
|
||||
current: next,
|
||||
future: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function undoEditorHistory<T>(history: EditorHistory<T>): HistoryTransition<T> {
|
||||
const previous = history.past.at(-1);
|
||||
if (previous === undefined) return { history, value: history.current, changed: false };
|
||||
const nextHistory = {
|
||||
past: history.past.slice(0, -1),
|
||||
current: previous,
|
||||
future: [history.current, ...history.future],
|
||||
};
|
||||
return { history: nextHistory, value: previous, changed: true };
|
||||
}
|
||||
|
||||
export function redoEditorHistory<T>(history: EditorHistory<T>): HistoryTransition<T> {
|
||||
const next = history.future[0];
|
||||
if (next === undefined) return { history, value: history.current, changed: false };
|
||||
const nextHistory = {
|
||||
past: [...history.past, history.current],
|
||||
current: next,
|
||||
future: history.future.slice(1),
|
||||
};
|
||||
return { history: nextHistory, value: next, changed: true };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { RATIO_OPTIONS } from "../config/editor.js";
|
||||
|
||||
export const PLAYBACK_UI_FRAME_MS = 50;
|
||||
export const DEFAULT_VISION_OPTIONS = Object.freeze({ showDetections: true, removeBackground: false, avoidCaptions: true, smartCrop: true });
|
||||
export const EMPTY_VISION_OPTIONS = Object.freeze({ showDetections: false, removeBackground: false, avoidCaptions: false, smartCrop: false });
|
||||
|
||||
export function getAudioSegmentPreviewVolume(segment, timelineTime) {
|
||||
const volume = Math.max(0, Math.min(1, segment.volume ?? 1));
|
||||
const localTime = Math.max(0, Math.min(segment.duration, timelineTime - segment.start));
|
||||
const fadeIn = Math.max(0, Math.min(segment.duration, segment.fadeIn || 0));
|
||||
const fadeOut = Math.max(0, Math.min(segment.duration, segment.fadeOut || 0));
|
||||
const fadeInGain = fadeIn > 0 ? Math.min(1, localTime / fadeIn) : 1;
|
||||
const fadeOutGain = fadeOut > 0 ? Math.min(1, (segment.duration - localTime) / fadeOut) : 1;
|
||||
return volume * Math.max(0, Math.min(fadeInGain, fadeOutGain));
|
||||
}
|
||||
|
||||
export async function decodeAvatarAudio16k(blob) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) throw new Error("当前浏览器不支持音频解码");
|
||||
const context = new AudioContextClass();
|
||||
try {
|
||||
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
|
||||
const mono = new Float32Array(decoded.length);
|
||||
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
|
||||
const values = decoded.getChannelData(channel);
|
||||
for (let i = 0; i < mono.length; i += 1) mono[i] += values[i] / decoded.numberOfChannels;
|
||||
}
|
||||
const outputLength = Math.min(64_000, Math.ceil(decoded.duration * 16_000));
|
||||
const resampled = new Float32Array(64_000);
|
||||
for (let i = 0; i < outputLength; i += 1) {
|
||||
const position = (i * decoded.sampleRate) / 16_000;
|
||||
const left = Math.min(mono.length - 1, Math.floor(position));
|
||||
const right = Math.min(mono.length - 1, left + 1);
|
||||
const ratio = position - left;
|
||||
resampled[i] = mono[left] * (1 - ratio) + mono[right] * ratio;
|
||||
}
|
||||
return resampled;
|
||||
} finally { await context.close().catch(() => {}); }
|
||||
}
|
||||
|
||||
export function runAvatarWorkerTask(worker, message, transfer, terminalType, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
worker.onmessage = (event) => {
|
||||
if (event.data?.type === "progress") return void onProgress?.(event.data);
|
||||
if (event.data?.type === "error") return void reject(new Error(event.data.message));
|
||||
if (event.data?.type === terminalType) resolve(event.data);
|
||||
};
|
||||
worker.onerror = (event) => reject(new Error(event.message || "Worker error"));
|
||||
worker.postMessage(message, transfer);
|
||||
});
|
||||
}
|
||||
|
||||
export function formatAvatarProgress(t, progress) {
|
||||
const template = progress.phaseKey ? t(progress.phaseKey) : progress.phase || t("avatarGenerating");
|
||||
return Object.entries(progress.phaseParams || {}).reduce((text, [key, value]) => text.replaceAll(`{${key}}`, String(value)), template);
|
||||
}
|
||||
|
||||
export async function encodeAvatarFrames(blobs, width, height, fps, keyframeTimes = [], duration = blobs.length / fps) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width; canvas.height = height;
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
const stream = canvas.captureStream(fps);
|
||||
const mimeType = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
|
||||
const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);
|
||||
const chunks = [];
|
||||
recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
|
||||
const stopped = new Promise((resolve, reject) => {
|
||||
recorder.onstop = () => resolve(new Blob(chunks, { type: recorder.mimeType || "video/webm" }));
|
||||
recorder.onerror = () => reject(recorder.error || new Error("数字人视频编码失败"));
|
||||
});
|
||||
recorder.start();
|
||||
const bitmaps = await Promise.all(blobs.map((blob) => createImageBitmap(blob)));
|
||||
const totalFrames = Math.max(1, Math.ceil(duration * fps));
|
||||
for (let frame = 0; frame < totalFrames; frame += 1) {
|
||||
const frameTime = frame / fps;
|
||||
let nearestIndex = 0; let nearestDistance = Number.POSITIVE_INFINITY;
|
||||
for (let index = 0; index < bitmaps.length; index += 1) {
|
||||
const time = keyframeTimes[index] ?? (index * duration) / Math.max(1, bitmaps.length - 1);
|
||||
const distance = Math.abs(time - frameTime);
|
||||
if (distance < nearestDistance) { nearestDistance = distance; nearestIndex = index; }
|
||||
}
|
||||
context.drawImage(bitmaps[nearestIndex], 0, 0, width, height);
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 1000 / fps));
|
||||
}
|
||||
bitmaps.forEach((bitmap) => bitmap.close());
|
||||
recorder.stop();
|
||||
const output = await stopped;
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
if (!output.size) throw new Error("数字人视频编码结果为空");
|
||||
return output;
|
||||
}
|
||||
|
||||
export function getNearestRatioIdForSize(width, height) {
|
||||
const w = Number(width); const h = Number(height);
|
||||
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return "";
|
||||
const mediaRatio = w / h;
|
||||
return RATIO_OPTIONS.reduce((best, option) => {
|
||||
const distance = Math.abs(Math.log(mediaRatio / (option.width / option.height)));
|
||||
return distance < best.distance ? { id: option.id, distance } : best;
|
||||
}, { id: RATIO_OPTIONS[0]?.id ?? "", distance: Number.POSITIVE_INFINITY }).id;
|
||||
}
|
||||
|
||||
export function getObjectPositionForCrop(cropRect) {
|
||||
const normalized = cropRect?.normalized;
|
||||
if (!normalized) return "50% 50%";
|
||||
const horizontalRange = Math.max(0, 1 - normalized.width);
|
||||
const verticalRange = Math.max(0, 1 - normalized.height);
|
||||
const x = horizontalRange > 0.0001 ? (normalized.xMin / horizontalRange) * 100 : 50;
|
||||
const y = verticalRange > 0.0001 ? (normalized.yMin / verticalRange) * 100 : 50;
|
||||
return `${Math.max(0, Math.min(100, x))}% ${Math.max(0, Math.min(100, y))}%`;
|
||||
}
|
||||
|
||||
export function isSameVisionDetection(detection, subject) {
|
||||
if (!detection?.box || !subject?.box || detection.label !== subject.label) return false;
|
||||
return [["xMin", "xmin"], ["yMin", "ymin"], ["xMax", "xmax"], ["yMax", "ymax"]].every(([camel, lower]) =>
|
||||
Math.abs((detection.box[camel] ?? detection.box[lower] ?? 0) - (subject.box[camel] ?? subject.box[lower] ?? 0)) < 0.004);
|
||||
}
|
||||
|
||||
export function revokeVisionObjectUrls(value) {
|
||||
(Array.isArray(value) ? value : value ? [value] : []).forEach((url) => URL.revokeObjectURL(url));
|
||||
}
|
||||
export function getTimelineTrackLocalTime(time, start = 0, duration = 0) { return Math.max(0, Math.min(duration || 0, time - start)); }
|
||||
export function isTimelineTimeInsideTrack(time, start = 0, duration = 0) { return duration > 0 && time >= start && time <= start + duration; }
|
||||
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
IMAGE_RESIZE_OVERFLOW_SECONDS_PER_PIXEL, IMAGE_SNAP_THRESHOLD_PIXELS,
|
||||
MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS,
|
||||
} from "../config/editor.js";
|
||||
import { createVisualSegment, estimateDuration, getImageThumbnailCount, getVisualSegmentsTotal } from "./timeline.js";
|
||||
|
||||
export function createImageResizeControl(d) {
|
||||
return function startImageResize(event, segmentId = "", segmentIndex = -1) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (d.trackLocks.image) return void d.notify("图片轨已锁定,无法拉长片段");
|
||||
if (!d.imageSrc || d.timelineDuration <= 0) return void d.notify("请先上传或选择图片/视频素材");
|
||||
d.setSelectedTrack("image");
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect();
|
||||
const segments = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 4, d.getCurrentVisualAssetSnapshot())];
|
||||
const idIndex = segments.findIndex((segment) => segment.id === segmentId);
|
||||
const index = idIndex >= 0 ? idIndex : segmentIndex >= 0 && segmentIndex < segments.length ? segmentIndex : Math.max(0, segments.length - 1);
|
||||
const resizeId = segments[index]?.id ?? "";
|
||||
const before = getVisualSegmentsTotal(segments.slice(0, index));
|
||||
const after = getVisualSegmentsTotal(segments.slice(index + 1));
|
||||
const startDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, d.imageDuration);
|
||||
const timelineDuration = Math.max(10, startDuration, d.timelineDurationRef.current || d.timelineDuration);
|
||||
d.setSelectedVisualSegmentId(resizeId);
|
||||
const secondsPerPixel = rect ? timelineDuration / Math.max(rect.width, 1) : IMAGE_RESIZE_OVERFLOW_SECONDS_PER_PIXEL;
|
||||
const overflowRate = Math.max(secondsPerPixel, IMAGE_RESIZE_OVERFLOW_SECONDS_PER_PIXEL);
|
||||
const snapPoints = [
|
||||
d.audioBlob && d.audioDuration > 0 ? { time: Math.min(MAX_TIMELINE_DURATION_SECONDS, d.audioDuration), label: "配音结尾" } : null,
|
||||
d.sourceAudioBlob && d.sourceAudioDuration > 0 ? { time: Math.min(MAX_TIMELINE_DURATION_SECONDS, d.sourceAudioStart + d.sourceAudioDuration), label: "原声结尾" } : null,
|
||||
d.musicBlob && d.musicDuration > 0 ? { time: Math.min(MAX_TIMELINE_DURATION_SECONDS, d.musicDuration), label: "音乐结尾" } : null,
|
||||
].filter(Boolean);
|
||||
let activeLabel = "";
|
||||
const apply = (clientX) => {
|
||||
if (!rect) return;
|
||||
const pointerX = clientX - rect.left;
|
||||
const inTrackX = Math.max(0, Math.min(rect.width, pointerX));
|
||||
const raw = (inTrackX / Math.max(rect.width, 1)) * timelineDuration + Math.max(0, pointerX - rect.width) * overflowRate;
|
||||
const clamped = Math.max(0.5, Math.min(MAX_TIMELINE_DURATION_SECONDS, raw));
|
||||
const snap = snapPoints.map((point) => ({ ...point, distance: Math.abs(pointerX - (point.time / timelineDuration) * rect.width) }))
|
||||
.filter((point) => point.distance <= IMAGE_SNAP_THRESHOLD_PIXELS).sort((a, b) => a.distance - b.distance)[0] ?? null;
|
||||
const target = snap?.time ?? clamped;
|
||||
const maxDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS - before - after);
|
||||
const resized = Math.min(maxDuration, Math.max(MIN_VISUAL_SEGMENT_SECONDS, target - before));
|
||||
const next = segments.map((segment, position) => position === index ? { ...segment, duration: resized } : segment);
|
||||
const visualDuration = getVisualSegmentsTotal(next);
|
||||
const projectDuration = Math.max(d.audioBlob ? d.audioDuration : 0, d.captionDuration,
|
||||
d.sourceAudioBlob ? d.sourceAudioStart + d.sourceAudioDuration : 0,
|
||||
d.musicBlob ? d.musicDuration : 0, estimateDuration(d.script), visualDuration);
|
||||
activeLabel = snap?.label ?? ""; d.setSnapGuide(snap); d.setVisualSegments(next);
|
||||
d.setImageDuration(visualDuration); d.setImageClipCount(getImageThumbnailCount(visualDuration));
|
||||
d.setCurrentTime((time) => Math.min(time, projectDuration));
|
||||
};
|
||||
apply(event.clientX);
|
||||
const move = (e) => apply(e.clientX);
|
||||
const up = () => {
|
||||
removeEventListener("pointermove", move); removeEventListener("pointerup", up); d.setSnapGuide(null);
|
||||
d.notify(activeLabel === "配音结尾" ? "图片已吸附到配音结尾" : activeLabel === "原声结尾" ? "图片已吸附到视频原声结尾" : activeLabel === "音乐结尾" ? "图片已吸附到音乐结尾" : "图片片段时长已调整");
|
||||
};
|
||||
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
evaluateLivePortraitFrameQuality,
|
||||
getLivePortraitFrameDistanceThreshold,
|
||||
isLivePortraitFrameDistanceAcceptable,
|
||||
} from "./livePortraitQuality.ts";
|
||||
import {
|
||||
extremeCorruptFrame,
|
||||
flatCorruptFrame,
|
||||
healthyPortraitFrame,
|
||||
nonFiniteCorruptFrame,
|
||||
} from "./__fixtures__/livePortraitFrameSamples.js";
|
||||
|
||||
describe("LivePortrait frame quality policy", () => {
|
||||
it("allows a wider distance for the first generated frame", () => {
|
||||
expect(getLivePortraitFrameDistanceThreshold(false)).toBe(0.34);
|
||||
expect(getLivePortraitFrameDistanceThreshold(true)).toBe(0.22);
|
||||
});
|
||||
|
||||
it("rejects non-finite and negative distances", () => {
|
||||
expect(isLivePortraitFrameDistanceAcceptable(Number.NaN, false)).toBe(false);
|
||||
expect(isLivePortraitFrameDistanceAcceptable(Number.POSITIVE_INFINITY, true)).toBe(false);
|
||||
expect(isLivePortraitFrameDistanceAcceptable(-0.01, true)).toBe(false);
|
||||
});
|
||||
|
||||
it("applies the temporal threshold inclusively", () => {
|
||||
expect(isLivePortraitFrameDistanceAcceptable(0.22, true)).toBe(true);
|
||||
expect(isLivePortraitFrameDistanceAcceptable(0.221, true)).toBe(false);
|
||||
expect(isLivePortraitFrameDistanceAcceptable(0.3, false)).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a healthy generated-frame sample", () => {
|
||||
expect(evaluateLivePortraitFrameQuality(healthyPortraitFrame, 0.12, true)).toMatchObject({
|
||||
accepted: true,
|
||||
reason: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["flat-frame", flatCorruptFrame],
|
||||
["non-finite-samples", nonFiniteCorruptFrame],
|
||||
["extreme-samples", extremeCorruptFrame],
|
||||
])("rejects the %s fixture", (reason, frame) => {
|
||||
expect(evaluateLivePortraitFrameQuality(frame, 0.1, true)).toMatchObject({
|
||||
accepted: false,
|
||||
reason,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a visually valid frame with an implausible temporal jump", () => {
|
||||
expect(evaluateLivePortraitFrameQuality(healthyPortraitFrame, 0.4, true)).toMatchObject({
|
||||
accepted: false,
|
||||
reason: "invalid-distance",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
export const LIVE_PORTRAIT_FRAME_QUALITY = Object.freeze({
|
||||
firstFrameMaxSampledDistance: 0.34,
|
||||
temporalFrameMaxSampledDistance: 0.22,
|
||||
minimumSampleVariance: 1e-6,
|
||||
maximumAbsoluteSampleValue: 8,
|
||||
maximumSamples: 512,
|
||||
});
|
||||
|
||||
export type LivePortraitFrameRejectionReason =
|
||||
| "invalid-distance"
|
||||
| "non-finite-samples"
|
||||
| "extreme-samples"
|
||||
| "flat-frame"
|
||||
| null;
|
||||
|
||||
export interface LivePortraitFrameQualityResult {
|
||||
accepted: boolean;
|
||||
reason: LivePortraitFrameRejectionReason;
|
||||
distance: number;
|
||||
threshold: number;
|
||||
sampledValues: number;
|
||||
variance: number;
|
||||
maximumAbsoluteValue: number;
|
||||
}
|
||||
|
||||
export function getLivePortraitFrameDistanceThreshold(hasPreviousFrame: boolean): number {
|
||||
return hasPreviousFrame
|
||||
? LIVE_PORTRAIT_FRAME_QUALITY.temporalFrameMaxSampledDistance
|
||||
: LIVE_PORTRAIT_FRAME_QUALITY.firstFrameMaxSampledDistance;
|
||||
}
|
||||
|
||||
export function isLivePortraitFrameDistanceAcceptable(
|
||||
distance: number,
|
||||
hasPreviousFrame: boolean,
|
||||
): boolean {
|
||||
return Number.isFinite(distance) &&
|
||||
distance >= 0 &&
|
||||
distance <= getLivePortraitFrameDistanceThreshold(hasPreviousFrame);
|
||||
}
|
||||
|
||||
function getSampleStatistics(pixels: ArrayLike<number>) {
|
||||
const sampleCount = Math.min(pixels.length, LIVE_PORTRAIT_FRAME_QUALITY.maximumSamples);
|
||||
const stride = Math.max(1, Math.floor(pixels.length / Math.max(1, sampleCount)));
|
||||
let count = 0;
|
||||
let sum = 0;
|
||||
let squaredSum = 0;
|
||||
let maximumAbsoluteValue = 0;
|
||||
for (let index = 0; index < pixels.length && count < sampleCount; index += stride) {
|
||||
const value = Number(pixels[index]);
|
||||
if (!Number.isFinite(value)) {
|
||||
return { count, finite: false, variance: 0, maximumAbsoluteValue: Infinity };
|
||||
}
|
||||
count += 1;
|
||||
sum += value;
|
||||
squaredSum += value * value;
|
||||
maximumAbsoluteValue = Math.max(maximumAbsoluteValue, Math.abs(value));
|
||||
}
|
||||
const mean = count ? sum / count : 0;
|
||||
const variance = count ? Math.max(0, squaredSum / count - mean * mean) : 0;
|
||||
return { count, finite: true, variance, maximumAbsoluteValue };
|
||||
}
|
||||
|
||||
export function evaluateLivePortraitFrameQuality(
|
||||
pixels: ArrayLike<number>,
|
||||
distance: number,
|
||||
hasPreviousFrame: boolean,
|
||||
): LivePortraitFrameQualityResult {
|
||||
const threshold = getLivePortraitFrameDistanceThreshold(hasPreviousFrame);
|
||||
const statistics = getSampleStatistics(pixels);
|
||||
let reason: LivePortraitFrameRejectionReason = null;
|
||||
if (!statistics.finite || !pixels.length) reason = "non-finite-samples";
|
||||
else if (statistics.maximumAbsoluteValue > LIVE_PORTRAIT_FRAME_QUALITY.maximumAbsoluteSampleValue) {
|
||||
reason = "extreme-samples";
|
||||
} else if (statistics.variance < LIVE_PORTRAIT_FRAME_QUALITY.minimumSampleVariance) {
|
||||
reason = "flat-frame";
|
||||
} else if (!isLivePortraitFrameDistanceAcceptable(distance, hasPreviousFrame)) {
|
||||
reason = "invalid-distance";
|
||||
}
|
||||
return {
|
||||
accepted: reason === null,
|
||||
reason,
|
||||
distance,
|
||||
threshold,
|
||||
sampledValues: statistics.count,
|
||||
variance: statistics.variance,
|
||||
maximumAbsoluteValue: statistics.maximumAbsoluteValue,
|
||||
};
|
||||
}
|
||||
+9
-16
@@ -1,9 +1,8 @@
|
||||
import {
|
||||
AUDIO_RECORDING_FORMATS,
|
||||
EXPORT_RECORDING_FORMATS,
|
||||
FFMPEG_CLASS_WORKER_URL,
|
||||
FFMPEG_CORE_BASE_URL,
|
||||
} from "../config/editor.js";
|
||||
import ffmpegCoreURL from "@ffmpeg/core?url";
|
||||
import ffmpegCoreWasmURL from "@ffmpeg/core/wasm?url";
|
||||
import ffmpegClassWorkerURL from "@ffmpeg/ffmpeg/worker?url";
|
||||
|
||||
import { AUDIO_RECORDING_FORMATS, EXPORT_RECORDING_FORMATS } from "../config/editor.js";
|
||||
import {
|
||||
createCaptionSegments,
|
||||
getSegmentIndexAtTime,
|
||||
@@ -979,18 +978,12 @@ export async function exportBrowserVideo({
|
||||
async function getFfmpeg() {
|
||||
if (!ffmpegLoadPromise) {
|
||||
ffmpegLoadPromise = (async () => {
|
||||
const [{ FFmpeg }, { toBlobURL }] = await Promise.all([
|
||||
import("@ffmpeg/ffmpeg"),
|
||||
import("@ffmpeg/util"),
|
||||
]);
|
||||
const { FFmpeg } = await import("@ffmpeg/ffmpeg");
|
||||
const ffmpeg = new FFmpeg();
|
||||
const classWorkerURL = URL.createObjectURL(
|
||||
new Blob([`import "${FFMPEG_CLASS_WORKER_URL}";`], { type: "text/javascript" }),
|
||||
);
|
||||
await ffmpeg.load({
|
||||
classWorkerURL,
|
||||
coreURL: await toBlobURL(`${FFMPEG_CORE_BASE_URL}/ffmpeg-core.js`, "text/javascript"),
|
||||
wasmURL: await toBlobURL(`${FFMPEG_CORE_BASE_URL}/ffmpeg-core.wasm`, "application/wasm"),
|
||||
classWorkerURL: ffmpegClassWorkerURL,
|
||||
coreURL: ffmpegCoreURL,
|
||||
wasmURL: ffmpegCoreWasmURL,
|
||||
});
|
||||
return ffmpeg;
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack } from "./editorRuntime.js";
|
||||
import { getVisualSegmentIndexAtTime } from "./timeline.js";
|
||||
|
||||
export function createPlaybackControls(deps) {
|
||||
const pauseTimelineMedia = () => {
|
||||
deps.audioSegmentRefs.current.forEach((audio) => audio.pause()); deps.sourceAudioRef.current?.pause();
|
||||
deps.musicRef.current?.pause(); deps.previewVideoRef.current?.pause();
|
||||
};
|
||||
const seekTo = (time) => {
|
||||
const clamped = Math.max(0, Math.min(deps.timelineDurationRef.current || MAX_TIMELINE_DURATION_SECONDS, time));
|
||||
deps.currentTimeRef.current = clamped; deps.setCurrentTime(clamped);
|
||||
deps.audioSegments.forEach((segment) => {
|
||||
const audio = deps.audioSegmentRefs.current.get(segment.id);
|
||||
if (audio) audio.currentTime = getTimelineTrackLocalTime(clamped, segment.start, segment.duration);
|
||||
});
|
||||
if (deps.sourceAudioRef.current) deps.sourceAudioRef.current.currentTime = getTimelineTrackLocalTime(clamped, deps.sourceAudioStart, deps.sourceAudioDuration);
|
||||
if (deps.musicRef.current) deps.musicRef.current.currentTime = clamped;
|
||||
};
|
||||
const getTimelineTimeFromClientX = (clientX) => {
|
||||
const rect = deps.trackScrollRef.current?.getBoundingClientRect(); const duration = deps.timelineDurationRef.current;
|
||||
if (!rect || duration <= 0) return 0;
|
||||
return Math.max(0, Math.min(duration, ((clientX - rect.left) / Math.max(rect.width, 1)) * duration));
|
||||
};
|
||||
const startTimelineSeek = (event) => {
|
||||
if (event.button !== 0 || deps.timelineDuration <= 0) return;
|
||||
event.preventDefault(); event.stopPropagation(); seekTo(getTimelineTimeFromClientX(event.clientX));
|
||||
const move = (e) => seekTo(getTimelineTimeFromClientX(e.clientX));
|
||||
const up = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); };
|
||||
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
|
||||
};
|
||||
const handlePlayToggle = () => {
|
||||
const video = deps.previewVideoRef.current;
|
||||
const voices = deps.trackVisibility.audio ? deps.audioSegments.map((segment) => ({ segment, audio: deps.audioSegmentRefs.current.get(segment.id) })).filter(({ audio }) => audio) : [];
|
||||
const source = deps.trackVisibility.source ? deps.sourceAudioRef.current : null;
|
||||
const music = deps.trackVisibility.music ? deps.musicRef.current : null;
|
||||
if (deps.isPlaying) { pauseTimelineMedia(); deps.setIsPlaying(false); return; }
|
||||
if (!deps.canPreview) return void deps.notify("请先上传图片/视频素材、生成配音或上传背景音乐");
|
||||
if (deps.currentTimeRef.current >= deps.estimatedDuration - 0.02) seekTo(0);
|
||||
const timelineTime = deps.currentTimeRef.current;
|
||||
const playIf = (media, ready) => ready ? media?.play().catch(() => {}) : media?.pause();
|
||||
voices.forEach(({ segment, audio }) => {
|
||||
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
|
||||
audio.currentTime = getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
|
||||
audio.volume = getAudioSegmentPreviewVolume(segment, timelineTime); audio.playbackRate = 1; playIf(audio, active);
|
||||
});
|
||||
if (source && deps.sourceAudioUrl) {
|
||||
source.currentTime = getTimelineTrackLocalTime(timelineTime, deps.sourceAudioStart, deps.sourceAudioDuration);
|
||||
playIf(source, isTimelineTimeInsideTrack(timelineTime, deps.sourceAudioStart, deps.sourceAudioDuration));
|
||||
}
|
||||
if (music && deps.musicUrl) { music.currentTime = Math.max(0, Math.min(deps.musicDuration || timelineTime, timelineTime)); playIf(music, timelineTime <= (deps.musicDuration || timelineTime)); }
|
||||
if (video && deps.previewVisualType === "video") {
|
||||
const index = getVisualSegmentIndexAtTime(deps.visualSegments, timelineTime);
|
||||
const range = deps.visualTimeline[Math.max(0, index)] ?? deps.currentVisualRange;
|
||||
const local = range ? Math.max(0, timelineTime - range.start) : timelineTime;
|
||||
video.currentTime = Math.min(local, video.duration || local); playIf(video, true);
|
||||
}
|
||||
deps.setIsPlaying(true);
|
||||
};
|
||||
return { getTimelineTimeFromClientX, handlePlayToggle, pauseTimelineMedia, seekTo, startTimelineSeek };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
} from "../config/editor.js";
|
||||
import { createStickerSegment } from "./timeline.js";
|
||||
|
||||
export function createStickerTimelineActions(d) {
|
||||
function getTimelineTimeFromDropPercent(percent = 0) {
|
||||
const safePercent = Math.max(0, Math.min(100, Number.isFinite(percent) ? percent : 0));
|
||||
const duration = d.timelineDurationRef.current || Math.max(d.estimatedDuration, 10);
|
||||
return Math.max(
|
||||
0,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, (safePercent / 100) * duration),
|
||||
);
|
||||
}
|
||||
|
||||
function commitStickerSegments(nextSegments, message, selectedId = "") {
|
||||
const normalizedSegments = nextSegments
|
||||
.filter((segment) => segment?.src && segment.duration > 0.05)
|
||||
.map((segment) => {
|
||||
const duration = Math.max(
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, segment.duration),
|
||||
);
|
||||
return {
|
||||
...segment,
|
||||
duration,
|
||||
start: Math.max(
|
||||
0,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS - duration, segment.start || 0),
|
||||
),
|
||||
};
|
||||
});
|
||||
d.setStickerSegments(normalizedSegments);
|
||||
d.setSelectedTrack("sticker");
|
||||
d.setActiveTool("stickers");
|
||||
const selectedSegment =
|
||||
normalizedSegments.find((segment) => segment.id === selectedId) ??
|
||||
normalizedSegments[Math.max(0, normalizedSegments.length - 1)] ??
|
||||
null;
|
||||
d.setSelectedStickerSegmentId(selectedSegment?.id ?? "");
|
||||
if (selectedSegment?.stickerId) d.setSelectedStickerId(selectedSegment.stickerId);
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function addStickerAssetToTimeline(asset, options = {}) {
|
||||
if (d.trackLocks.sticker) {
|
||||
d.notify("贴纸轨已锁定,无法添加贴纸");
|
||||
return;
|
||||
}
|
||||
if (!asset?.src) {
|
||||
d.notify("当前贴纸素材不可用");
|
||||
return;
|
||||
}
|
||||
const startTime = Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS - DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
getTimelineTimeFromDropPercent(options.percent ?? 0),
|
||||
);
|
||||
const nextSegment = createStickerSegment(
|
||||
asset,
|
||||
startTime,
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
);
|
||||
commitStickerSegments(
|
||||
[...d.stickerSegments, nextSegment],
|
||||
"贴纸已添加到贴纸轨",
|
||||
nextSegment.id,
|
||||
);
|
||||
d.seekTo(startTime);
|
||||
}
|
||||
|
||||
return {
|
||||
addStickerAssetToTimeline,
|
||||
commitStickerSegments,
|
||||
getTimelineTimeFromDropPercent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createCaptionSegments,
|
||||
createStickerSegment,
|
||||
getCaptionScript,
|
||||
getCaptionTimeline,
|
||||
getTimedSegmentIndexAtTime,
|
||||
getTimedSegmentsEnd,
|
||||
getVisualSegmentIndexAtTime,
|
||||
getVisualSegmentTimeline,
|
||||
reorderTimelineItems,
|
||||
} from "./timeline.js";
|
||||
|
||||
describe("timeline primitives", () => {
|
||||
it("reorders without mutating the source array", () => {
|
||||
const source = [{ id: "a" }, { id: "b" }, { id: "c" }];
|
||||
const result = reorderTimelineItems(source, 0, 2);
|
||||
expect(result.map((item) => item.id)).toEqual(["b", "c", "a"]);
|
||||
expect(source.map((item) => item.id)).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("returns the original array for an invalid reorder", () => {
|
||||
const source = [{ id: "a" }];
|
||||
expect(reorderTimelineItems(source, -1, 0)).toBe(source);
|
||||
expect(reorderTimelineItems(source, 0, 3)).toBe(source);
|
||||
});
|
||||
|
||||
it("builds a contiguous visual timeline", () => {
|
||||
const segments = [{ id: "a", duration: 2 }, { id: "b", duration: 3.5 }];
|
||||
expect(getVisualSegmentTimeline(segments)).toEqual([
|
||||
{ id: "a", start: 0, end: 2, duration: 2 },
|
||||
{ id: "b", start: 2, end: 5.5, duration: 3.5 },
|
||||
]);
|
||||
expect(getVisualSegmentIndexAtTime(segments, 2)).toBe(1);
|
||||
expect(getVisualSegmentIndexAtTime(segments, 99)).toBe(1);
|
||||
});
|
||||
|
||||
it("prefers the last overlapping timed segment", () => {
|
||||
const segments = [
|
||||
{ start: 0, duration: 4 },
|
||||
{ start: 2, duration: 4 },
|
||||
];
|
||||
expect(getTimedSegmentIndexAtTime(segments, 3)).toBe(1);
|
||||
expect(getTimedSegmentsEnd(segments)).toBe(6);
|
||||
});
|
||||
|
||||
it("scales untimed captions to the target duration", () => {
|
||||
const captions = createCaptionSegments("第一句。第二句更长一些。");
|
||||
const timeline = getCaptionTimeline(captions, 12);
|
||||
expect(timeline[0].start).toBe(0);
|
||||
expect(timeline.at(-1).end).toBeCloseTo(12, 8);
|
||||
expect(getCaptionScript(captions)).toBe("第一句\n第二句更长一些");
|
||||
});
|
||||
|
||||
it("keeps explicit caption timings", () => {
|
||||
const timeline = getCaptionTimeline([
|
||||
{ text: "a", start: 2, end: 3 },
|
||||
{ text: "b", start: 5, end: 7 },
|
||||
], 20);
|
||||
expect(timeline).toEqual([
|
||||
{ start: 2, end: 3, duration: 1 },
|
||||
{ start: 5, end: 7, duration: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("clamps sticker start and duration to timeline limits", () => {
|
||||
const sticker = createStickerSegment({ id: "spark", src: "/spark.png" }, -5, 0.1);
|
||||
expect(sticker.start).toBe(0);
|
||||
expect(sticker.duration).toBeGreaterThanOrEqual(0.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { downloadBlob } from "./media.js";
|
||||
import { createVisualSegment, makeId } from "./timeline.js";
|
||||
|
||||
export function createTimelineClipboardActions(d) {
|
||||
const focusedStickerIndex = () => {
|
||||
if (!d.stickerSegments.length) return -1;
|
||||
const selected = d.selectedStickerSegmentId && d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId);
|
||||
return selected >= 0 ? selected : d.currentStickerSegmentIndex >= 0 ? d.currentStickerSegmentIndex : 0;
|
||||
};
|
||||
const deleteSticker = () => {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法删除");
|
||||
const index = focusedStickerIndex(); if (index < 0) return void d.notify("当前没有贴纸片段可删除");
|
||||
const next = d.stickerSegments.filter((_, position) => position !== index);
|
||||
d.commitStickerSegments(next, next.length ? "已删除当前贴纸片段" : "已删除最后一个贴纸片段", next[Math.max(0, index - 1)]?.id ?? "");
|
||||
};
|
||||
const handleDeleteTrack = () => {
|
||||
if (d.trackLocks[d.selectedTrack]) return void d.notify("当前轨道已锁定,无法删除");
|
||||
if (d.selectedTrack === "caption") return void d.handleRemoveSegment();
|
||||
if (d.selectedTrack === "sticker") return void deleteSticker();
|
||||
if (d.selectedTrack === "image") {
|
||||
if (!d.imageSrc || d.imageClipCount === 0) return void d.notify("当前没有视觉片段可删除");
|
||||
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 0, d.getCurrentVisualAssetSnapshot())];
|
||||
const index = d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId)
|
||||
? d.selectedVisualSegmentIndex : d.currentVisualSegmentIndex >= 0 ? d.currentVisualSegmentIndex : 0;
|
||||
const next = source.filter((_, position) => position !== index);
|
||||
return void (next.length ? d.commitVisualSegments(next, "已删除当前视觉片段", Math.max(0, index - 1)) : d.clearImageTrack("已删除当前视觉片段"));
|
||||
}
|
||||
if (d.selectedTrack === "audio") {
|
||||
const id = d.selectedAudioSegmentId || d.selectedAudioSegment?.id;
|
||||
return id ? void d.deleteAudioSegment(id) : void d.notify("当前没有选中的配音片段");
|
||||
}
|
||||
if (d.selectedTrack === "source") return void d.clearSourceAudioTrack();
|
||||
if (d.selectedTrack === "music") return void d.clearMusicTrack();
|
||||
d.clearImageTrack();
|
||||
};
|
||||
const handleDuplicateTrack = () => {
|
||||
if (d.selectedTrack === "sticker") {
|
||||
const source = d.stickerSegments[focusedStickerIndex()]; if (!source) return void d.notify("请先选择一个贴纸片段");
|
||||
const copy = { ...source, id: makeId("sticker"), start: Math.min(MAX_TIMELINE_DURATION_SECONDS - source.duration, source.start + source.duration + 0.2) };
|
||||
return void d.commitStickerSegments([...d.stickerSegments, copy], "已复制当前贴纸片段", copy.id);
|
||||
}
|
||||
if (d.selectedTrack === "caption") {
|
||||
if (!d.captionSegments.length) return void d.notify("当前没有可复制的字幕片段");
|
||||
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
|
||||
const source = d.captionSegments[index] ?? d.captionSegments[d.focusedSegmentIndex];
|
||||
const next = [...d.captionSegments]; next.splice(index + 1, 0, { ...source, id: makeId("caption"), text: `${source.text} 副本` });
|
||||
return void d.commitCaptionSegments(next, "已复制当前字幕片段", index + 1);
|
||||
}
|
||||
if (d.selectedTrack === "image") {
|
||||
if (!d.imageSrc) return void d.notify("当前没有可复制的图片素材");
|
||||
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 4, d.getCurrentVisualAssetSnapshot())];
|
||||
const segment = source[d.selectedVisualSegmentId && source.some((item) => item.id === d.selectedVisualSegmentId) ? d.selectedVisualSegmentIndex : Math.max(0, d.currentVisualSegmentIndex)] ?? d.getCurrentVisualAssetSnapshot();
|
||||
d.setUserAssets((assets) => [{ id: crypto.randomUUID(), type: segment.type || d.visualType, src: segment.src || d.imageSrc,
|
||||
name: `${(segment.name || d.imageName).replace(/\.[^.]+$/, "")}-copy.${(segment.type || d.visualType) === "video" ? "mp4" : "png"}`,
|
||||
meta: segment.meta || d.imageMeta, duration: segment.duration || d.imageDuration, blob: segment.blob || null }, ...assets]);
|
||||
return void d.notify("当前图片已复制到我的素材");
|
||||
}
|
||||
if (d.selectedTrack === "audio") {
|
||||
const source = d.selectedAudioSegment; if (!source) return void d.notify(d.t("audioClipMissing"));
|
||||
const id = crypto.randomUUID(); const start = Math.min(MAX_TIMELINE_DURATION_SECONDS - source.duration, source.start + 0.2);
|
||||
const copy = { ...source, id, url: URL.createObjectURL(source.blob), start, name: `${source.name || d.t("audioClip")} ${d.t("copySuffix")}` };
|
||||
const delta = start - source.start;
|
||||
const captions = d.captionSegments.filter((caption) => caption.audioSegmentId === source.id)
|
||||
.map((caption) => ({ ...caption, id: makeId("caption"), audioSegmentId: id, start: caption.start + delta, end: caption.end + delta }));
|
||||
d.setAudioSegments((items) => [...items, copy]); d.setCaptionSegments((items) => [...items, ...captions].sort((a, b) => (a.start || 0) - (b.start || 0)));
|
||||
d.setSelectedAudioSegmentId(id); return void d.notify(d.t("audioClipDuplicated"));
|
||||
}
|
||||
const blob = d.selectedTrack === "music" ? d.musicBlob : d.selectedTrack === "source" ? d.sourceAudioBlob : d.audioBlob;
|
||||
const name = d.selectedTrack === "music" ? d.musicName || "background-music.wav" : d.selectedTrack === "source" ? d.sourceAudioName || "source-audio.wav" : "ai-voiceover-copy.wav";
|
||||
if (blob) { downloadBlob(blob, name); d.notify("当前音频副本已下载"); } else d.notify("当前没有可复制的音频");
|
||||
};
|
||||
return { handleDeleteTrack, handleDuplicateTrack };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { createVisualSegment, getVisualSegmentTimeline, getVisualSegmentsTotal, hasExplicitCaptionTiming, makeId } from "./timeline.js";
|
||||
|
||||
export function createTimelineCutActions(d) {
|
||||
const handleCutVisualSegment = () => {
|
||||
if (d.trackLocks.image) return void d.notify("图片轨已锁定,无法剪切");
|
||||
if (!d.imageSrc) return void d.notify("请先上传或选择图片/视频素材");
|
||||
const segments = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 0, d.getCurrentVisualAssetSnapshot())];
|
||||
const duration = getVisualSegmentsTotal(segments);
|
||||
if (duration < MIN_VISUAL_SEGMENT_SECONDS * 2) return void d.notify("当前视觉片段太短,不适合继续剪切");
|
||||
const time = Math.max(0, Math.min(duration, d.currentTime));
|
||||
if (time <= MIN_VISUAL_SEGMENT_SECONDS || time >= duration - MIN_VISUAL_SEGMENT_SECONDS) return void d.notify("请把播放头放在视觉片段中间再剪切");
|
||||
const timeline = getVisualSegmentTimeline(segments);
|
||||
const index = timeline.findIndex((range) => time > range.start && time < range.end);
|
||||
const range = timeline[index]; const source = segments[index];
|
||||
if (!source || !range) return void d.notify("请先选中要剪切的视觉片段");
|
||||
const firstDuration = time - range.start; const secondDuration = range.end - time;
|
||||
if (firstDuration < MIN_VISUAL_SEGMENT_SECONDS || secondDuration < MIN_VISUAL_SEGMENT_SECONDS) return void d.notify("切点离片段边缘太近,先把播放头移到片段中间");
|
||||
const first = { ...source, id: makeId("visual"), duration: firstDuration };
|
||||
const second = { ...source, id: makeId("visual"), duration: secondDuration,
|
||||
sourceStart: source.type === "video" ? Math.max(0, Number(source.sourceStart) || 0) + firstDuration : Math.max(0, Number(source.sourceStart) || 0) };
|
||||
const next = [...segments]; next.splice(index, 1, first, second);
|
||||
d.commitVisualSegments(next, "已在播放头位置切开视觉片段", index + 1);
|
||||
};
|
||||
const handleCutCaption = () => {
|
||||
if (d.trackLocks.caption) return void d.notify("字幕轨已锁定,无法剪切");
|
||||
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
|
||||
const source = d.captionSegments[index];
|
||||
if (!source || source.text.length < 6) return void d.notify("当前字幕太短,不适合继续拆分");
|
||||
const splitAt = Math.max(2, Math.ceil(source.text.length / 2));
|
||||
const splitTime = hasExplicitCaptionTiming(source) && source.end - source.start > 0.4 ? source.start + (source.end - source.start) / 2 : null;
|
||||
const next = [...d.captionSegments]; next.splice(index, 1,
|
||||
{ ...source, id: makeId("caption"), text: source.text.slice(0, splitAt), weight: Math.max(0.7, (source.weight ?? 1) / 2), ...(splitTime ? { end: splitTime } : {}) },
|
||||
{ ...source, id: makeId("caption"), text: source.text.slice(splitAt), weight: Math.max(0.7, (source.weight ?? 1) / 2), ...(splitTime ? { start: splitTime } : {}) });
|
||||
d.commitCaptionSegments(next, "已把当前字幕片段拆成两段", index + 1);
|
||||
};
|
||||
const handleCutTrack = () => {
|
||||
if (d.selectedTrack === "image") return void handleCutVisualSegment();
|
||||
if (d.selectedTrack === "caption") return void handleCutCaption();
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法剪切");
|
||||
const selected = d.selectedStickerSegmentId && d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId);
|
||||
const index = selected >= 0 ? selected : d.currentStickerSegmentIndex >= 0 ? d.currentStickerSegmentIndex : 0;
|
||||
const source = d.stickerSegments[index]; if (!source) return void d.notify("请先选择一个贴纸片段");
|
||||
const time = Math.max(source.start, Math.min(source.start + source.duration, d.currentTime));
|
||||
if (time <= source.start + 0.35 || time >= source.start + source.duration - 0.35) return void d.notify("请把播放头放在贴纸片段中间再剪切");
|
||||
const first = { ...source, id: makeId("sticker"), duration: time - source.start };
|
||||
const second = { ...source, id: makeId("sticker"), start: time, duration: source.start + source.duration - time };
|
||||
const next = [...d.stickerSegments]; next.splice(index, 1, first, second);
|
||||
return void d.commitStickerSegments(next, "已在播放头位置切开贴纸片段", second.id);
|
||||
}
|
||||
d.notify("当前轨道暂不支持剪切片段");
|
||||
};
|
||||
return { handleCutTrack };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { createVisualSegment, getVisualSegmentsTotal, hasExplicitCaptionTiming } from "./timeline.js";
|
||||
|
||||
export function createTimelineDurationActions(d) {
|
||||
return function adjustSelectedSegmentWeight(delta) {
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法调整片段长度");
|
||||
const selected = d.selectedStickerSegmentId ? d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId) : -1;
|
||||
const index = selected >= 0 ? selected : d.currentStickerSegmentIndex >= 0 ? d.currentStickerSegmentIndex : 0;
|
||||
const source = d.stickerSegments[index]; if (!source) return void d.notify("请先选择一个贴纸片段");
|
||||
const duration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, Math.min(MAX_TIMELINE_DURATION_SECONDS - source.start, source.duration + (delta > 0 ? 0.5 : -0.5)));
|
||||
if (Math.abs(duration - source.duration) < 0.001) return void d.notify(delta > 0 ? "当前贴纸片段已到最大长度" : "当前贴纸片段已到最短时长");
|
||||
const next = d.stickerSegments.map((segment, position) => position === index ? { ...segment, duration } : segment);
|
||||
return void d.commitStickerSegments(next, delta > 0 ? "当前贴纸片段已加长" : "当前贴纸片段已缩短", source.id);
|
||||
}
|
||||
if (d.selectedTrack === "image") {
|
||||
if (d.trackLocks.image) return void d.notify("图片轨已锁定,无法调整片段长度");
|
||||
if (!d.imageSrc) return void d.notify("请先上传或选择图片/视频素材");
|
||||
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 4, d.getCurrentVisualAssetSnapshot())];
|
||||
const index = d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId)
|
||||
? d.selectedVisualSegmentIndex : d.currentVisualSegmentIndex >= 0 ? d.currentVisualSegmentIndex : source.length - 1;
|
||||
const target = source[index]; const without = getVisualSegmentsTotal(source) - target.duration;
|
||||
const max = Math.max(MIN_VISUAL_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS - without);
|
||||
const duration = Math.min(max, Math.max(MIN_VISUAL_SEGMENT_SECONDS, target.duration + (delta > 0 ? 1 : -1)));
|
||||
if (duration === target.duration) return void d.notify(delta > 0 ? "视觉轨道已经达到 30 分钟上限" : "当前视觉片段已到最短时长");
|
||||
const next = source.map((segment, position) => position === index ? { ...segment, duration } : segment);
|
||||
return void d.commitVisualSegments(next, delta > 0 ? "当前视觉片段已加长" : "当前视觉片段已缩短", index);
|
||||
}
|
||||
if (d.selectedTrack === "music") return void d.notify("背景音乐长度由素材决定,下一版会支持裁剪和淡入淡出");
|
||||
if (d.selectedTrack === "source") return void d.notify("视频原声长度由视频决定,下一版会支持分段裁剪");
|
||||
if (d.selectedTrack !== "caption") return void d.notify("请先选择字幕片段,再调整片段长短");
|
||||
if (!d.captionSegments.length) return void d.notify("当前没有字幕片段可调整");
|
||||
if (d.trackLocks.caption) return void d.notify("字幕轨已锁定,无法调整片段长度");
|
||||
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
|
||||
const target = d.captionSegments[index];
|
||||
if (hasExplicitCaptionTiming(target)) {
|
||||
const nextTimed = d.captionSegments.slice(index + 1).find(hasExplicitCaptionTiming);
|
||||
const maxEnd = Math.min(MAX_TIMELINE_DURATION_SECONDS, nextTimed?.start ?? MAX_TIMELINE_DURATION_SECONDS);
|
||||
const end = Math.max(target.start + 0.45, Math.min(maxEnd, target.end + (delta > 0 ? 0.6 : -0.6)));
|
||||
if (Math.abs(end - target.end) < 0.001) return void d.notify(delta > 0 ? "当前字幕已贴近下一段" : "当前字幕已到最短时长");
|
||||
const next = d.captionSegments.map((segment, position) => position === index ? { ...segment, end } : segment);
|
||||
return void d.commitCaptionSegments(next, delta > 0 ? "当前字幕片段已加长" : "当前字幕片段已缩短", index);
|
||||
}
|
||||
const next = d.captionSegments.map((segment, position) => position === index
|
||||
? { ...segment, weight: Math.max(0.5, Math.min(5, (segment.weight ?? 1) + delta)) } : segment);
|
||||
d.commitCaptionSegments(next, delta > 0 ? "当前字幕片段已加长" : "当前字幕片段已缩短", index);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { DEFAULT_STICKER_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
|
||||
export function createTimelineMoveControls(d) {
|
||||
const startAudioSegmentMove = (event, id = "") => {
|
||||
if (event.button !== 0) return;
|
||||
const segment = d.audioSegments.find((item) => item.id === id); if (!segment) return;
|
||||
if (d.trackLocks.audio) return void d.notify(d.t("audioTrackLockedMove"));
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect(); const duration = d.timelineDurationRef.current || 10;
|
||||
if (!rect) return;
|
||||
event.stopPropagation(); d.setSelectedTrack("audio"); d.setSelectedAudioSegmentId(segment.id);
|
||||
const startX = event.clientX; const start = segment.start || 0;
|
||||
const captions = d.captionSegments.filter((caption) => caption.audioSegmentId === segment.id);
|
||||
let moved = false; let latest = start;
|
||||
const move = (e) => {
|
||||
if (!moved && Math.abs(e.clientX - startX) < 4) return;
|
||||
moved = true; e.preventDefault();
|
||||
latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segment.duration, start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration));
|
||||
d.setAudioSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start: latest } : item));
|
||||
const delta = latest - start;
|
||||
d.setCaptionSegments((items) => items.map((caption) => {
|
||||
const original = captions.find((item) => item.id === caption.id);
|
||||
return original ? { ...caption, start: original.start + delta, end: original.end + delta } : caption;
|
||||
}));
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((latest + segment.duration + 5) / 10) * 10));
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); };
|
||||
const up = () => { cleanup(); if (moved) { d.seekTo(latest); d.notify(d.t("audioClipMoved")); } };
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
};
|
||||
const startStickerSegmentMove = (event, id = "") => {
|
||||
if (event.button !== 0) return;
|
||||
const segment = d.stickerSegments.find((item) => item.id === id); if (!segment) return;
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法移动贴纸");
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect();
|
||||
const duration = d.timelineDurationRef.current || Math.max(d.estimatedDuration, segment.start + segment.duration, 10);
|
||||
if (!rect || duration <= 0) return;
|
||||
event.preventDefault(); event.stopPropagation(); d.setSelectedTrack("sticker"); d.setActiveTool("stickers"); d.setSelectedStickerSegmentId(segment.id);
|
||||
if (segment.stickerId) d.setSelectedStickerId(segment.stickerId);
|
||||
const startX = event.clientX; const startY = event.clientY; const start = segment.start || 0;
|
||||
const segmentDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, segment.duration || DEFAULT_STICKER_SEGMENT_SECONDS);
|
||||
let moved = false; let latest = start;
|
||||
const move = (e) => {
|
||||
if (!moved && Math.hypot(e.clientX - startX, e.clientY - startY) < 4) return;
|
||||
moved = true; e.preventDefault();
|
||||
latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segmentDuration, start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration));
|
||||
d.setStickerSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start: latest } : item));
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); };
|
||||
const up = () => {
|
||||
cleanup(); if (!moved) return;
|
||||
d.suppressTimelineClipClickRef.current = segment.id;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segment.id) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
d.seekTo(latest); d.notify("贴纸片段位置已调整");
|
||||
};
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
};
|
||||
return { startAudioSegmentMove, startStickerSegmentMove };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { getSegmentStartTime, getVisualSegmentTimeline, reorderTimelineItems } from "./timeline.js";
|
||||
|
||||
export function createTimelineReorderControls(d) {
|
||||
const getTimelineReorderIndex = (track, x, y) => {
|
||||
const element = document.querySelector(`[data-timeline-reorder-track="${track}"]`);
|
||||
if (!element) return d.timelineClipDragRef.current?.overIndex ?? 0;
|
||||
const trackRect = element.getBoundingClientRect();
|
||||
if (y < trackRect.top - 28 || y > trackRect.bottom + 28) return d.timelineClipDragRef.current?.overIndex ?? 0;
|
||||
const segments = Array.from(element.querySelectorAll(`[data-timeline-segment-track="${track}"]`));
|
||||
if (!segments.length) return 0;
|
||||
for (let index = 0; index < segments.length; index += 1) {
|
||||
const rect = segments[index].getBoundingClientRect(); if (x < rect.left + rect.width / 2) return index;
|
||||
}
|
||||
return segments.length - 1;
|
||||
};
|
||||
const commitTimelineClipReorder = (track, fromIndex, toIndex) => {
|
||||
if (fromIndex === toIndex) return;
|
||||
if (track === "image") {
|
||||
const source = d.visualSegments.length ? d.visualSegments : d.renderedVisualSegments;
|
||||
if (source.length < 2) return;
|
||||
const next = reorderTimelineItems(source, fromIndex, toIndex);
|
||||
d.commitVisualSegments(next, "已调整视觉片段顺序", toIndex); d.seekTo(getVisualSegmentTimeline(next)[toIndex]?.start ?? 0); return;
|
||||
}
|
||||
if (track === "caption" && d.captionSegments.length >= 2) {
|
||||
const next = reorderTimelineItems(d.captionSegments, fromIndex, toIndex);
|
||||
d.commitCaptionSegments(next, "已调整字幕片段顺序", toIndex);
|
||||
d.seekTo(getSegmentStartTime(next, toIndex, d.captionTargetDuration));
|
||||
}
|
||||
};
|
||||
const startTimelineClipDrag = (event, track, segmentId, index) => {
|
||||
if (event.button !== 0 || event.target.closest(".image-resize-handle")) return;
|
||||
if (d.trackLocks[track]) return void d.notify(track === "image" ? "图片轨已锁定,无法拖动片段" : "字幕轨已锁定,无法拖动片段");
|
||||
if (track === "image") { d.setSelectedTrack("image"); d.setSelectedVisualSegmentId(segmentId); }
|
||||
else { d.setSelectedTrack("caption"); d.setSelectedSegmentId(segmentId); }
|
||||
const count = track === "image" ? d.renderedVisualSegments.length : d.captionSegments.length;
|
||||
if (count < 2) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const initial = { track, segmentId, fromIndex: index, overIndex: index, startX: event.clientX, startY: event.clientY, x: event.clientX, y: event.clientY, dragging: false };
|
||||
d.timelineClipDragRef.current = initial; d.setTimelineClipDrag(initial);
|
||||
const move = (e) => {
|
||||
const state = d.timelineClipDragRef.current; if (!state || state.segmentId !== segmentId) return;
|
||||
if (!state.dragging && Math.hypot(e.clientX - state.startX, e.clientY - state.startY) < 6) return;
|
||||
const overIndex = Math.max(0, Math.min(count - 1, getTimelineReorderIndex(track, e.clientX, e.clientY)));
|
||||
const next = { ...state, overIndex, x: e.clientX, y: e.clientY, dragging: true };
|
||||
d.timelineClipDragRef.current = next; d.setTimelineClipDrag(next);
|
||||
};
|
||||
const up = () => {
|
||||
removeEventListener("pointermove", move); removeEventListener("pointerup", up);
|
||||
const state = d.timelineClipDragRef.current; d.timelineClipDragRef.current = null; d.setTimelineClipDrag(null);
|
||||
if (!state?.dragging) return;
|
||||
d.suppressTimelineClipClickRef.current = segmentId;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segmentId) d.suppressTimelineClipClickRef.current = ""; }, 120);
|
||||
commitTimelineClipReorder(track, state.fromIndex, state.overIndex);
|
||||
};
|
||||
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
|
||||
};
|
||||
return { commitTimelineClipReorder, getTimelineReorderIndex, startTimelineClipDrag };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { DEFAULT_STICKER_SEGMENT_SECONDS, IMAGE_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { createStickerSegment, createVisualSegment, getVisualSegmentsTotal, hasExplicitCaptionTiming, makeId } from "./timeline.js";
|
||||
|
||||
export function createTimelineSegmentCountActions(d) {
|
||||
const stickerIndex = () => {
|
||||
const selected = d.selectedStickerSegmentId ? d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId) : -1;
|
||||
return selected >= 0 ? selected : d.currentStickerSegmentIndex >= 0 ? d.currentStickerSegmentIndex : 0;
|
||||
};
|
||||
const deleteSticker = () => {
|
||||
if (!d.stickerSegments.length) return void d.notify("当前没有贴纸片段可删除");
|
||||
const index = stickerIndex(); const next = d.stickerSegments.filter((_, position) => position !== index);
|
||||
d.commitStickerSegments(next, next.length ? "已删除当前贴纸片段" : "已删除最后一个贴纸片段", next[Math.max(0, index - 1)]?.id ?? "");
|
||||
};
|
||||
const handleAddSegment = () => {
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法新增贴纸片段");
|
||||
const source = d.stickerSegments[stickerIndex()] ?? d.getStickerDragAsset(d.selectedSticker);
|
||||
if (!source?.src) return void d.notify("请先选择一个贴纸");
|
||||
const segment = createStickerSegment(source, d.currentTime, DEFAULT_STICKER_SEGMENT_SECONDS);
|
||||
return void d.commitStickerSegments([...d.stickerSegments, segment], "已新增贴纸片段", segment.id);
|
||||
}
|
||||
if (d.selectedTrack === "image") {
|
||||
if (d.trackLocks.image) return void d.notify("图片轨已锁定,无法新增片段");
|
||||
if (!d.imageSrc) return void d.notify("请先上传或选择图片/视频素材");
|
||||
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 4, d.getCurrentVisualAssetSnapshot())];
|
||||
const available = MAX_TIMELINE_DURATION_SECONDS - getVisualSegmentsTotal(source);
|
||||
if (available < MIN_VISUAL_SEGMENT_SECONDS) return void d.notify("视觉轨道已经达到 30 分钟上限");
|
||||
const asset = source[d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId) ? d.selectedVisualSegmentIndex : source.length - 1] ?? d.getCurrentVisualAssetSnapshot();
|
||||
const segment = createVisualSegment(Math.min(IMAGE_SEGMENT_SECONDS, available), asset);
|
||||
return void d.commitVisualSegments([...source, segment], "已新增一个视觉片段", source.length);
|
||||
}
|
||||
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐暂不支持切片,请删除后重新上传" : d.selectedTrack === "source" ? "视频原声暂不支持切片,可删除后重新上传视频" : "音频片段由生成结果决定,请重新生成或复制 WAV");
|
||||
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
|
||||
const previous = d.captionSegments[index]; const nextCaption = d.captionSegments[index + 1];
|
||||
const start = hasExplicitCaptionTiming(previous) ? previous.end : null;
|
||||
const end = start !== null && hasExplicitCaptionTiming(nextCaption) && nextCaption.start - start > 0.45 ? nextCaption.start
|
||||
: start !== null ? Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8) : null;
|
||||
const next = [...d.captionSegments]; next.splice(d.captionSegments.length ? index + 1 : 0, 0,
|
||||
{ id: makeId("caption"), text: "新的字幕片段", weight: d.captionSegments[index]?.weight ?? 1, hidden: false,
|
||||
...(start !== null && end !== null ? { start, end: Math.max(start + 0.45, end) } : {}) });
|
||||
d.commitCaptionSegments(next, "已新增字幕片段", index + 1);
|
||||
};
|
||||
const handleRemoveSegment = () => {
|
||||
if (d.selectedTrack === "sticker") return void deleteSticker();
|
||||
if (d.selectedTrack === "image") {
|
||||
if (d.trackLocks.image) return void d.notify("图片轨已锁定,无法减少片段");
|
||||
if (!d.imageSrc || d.imageClipCount === 0) return void d.notify("当前没有视觉片段可减少");
|
||||
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 0, d.getCurrentVisualAssetSnapshot())];
|
||||
if (source.length > 1) {
|
||||
const index = d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId) ? d.selectedVisualSegmentIndex : d.currentVisualSegmentIndex >= 0 ? d.currentVisualSegmentIndex : source.length - 1;
|
||||
return void d.commitVisualSegments(source.filter((_, position) => position !== index), "已删除当前视觉片段", Math.max(0, index - 1));
|
||||
}
|
||||
if (source[0].duration <= IMAGE_SEGMENT_SECONDS) return void d.clearImageTrack("已删除最后一个视觉片段");
|
||||
return void d.commitVisualSegments([{ ...source[0], duration: source[0].duration - IMAGE_SEGMENT_SECONDS }], "已缩短当前视觉片段", 0);
|
||||
}
|
||||
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐可整轨删除,暂不支持局部减少" : d.selectedTrack === "source" ? "视频原声可整轨删除,暂不支持局部减少" : "音频片段不能单独减少;可以删除音频轨或重新生成");
|
||||
if (!d.captionSegments.length) return void d.notify("当前没有字幕片段可删除");
|
||||
d.deleteCaptionSegment(d.selectedSegmentId);
|
||||
};
|
||||
return { handleAddSegment, handleRemoveSegment };
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
getCaptionTimeline,
|
||||
getVisualAssetPayload,
|
||||
getVisualSegmentTimeline,
|
||||
reorderTimelineItems,
|
||||
} from "./timeline.js";
|
||||
|
||||
export function createTimelineViewModel(d) {
|
||||
const progressPercent = Math.max(0, Math.min(100, d.progress));
|
||||
const playheadPercent = Math.max(
|
||||
0,
|
||||
Math.min(100, ((d.currentTime || 0) / Math.max(d.timelineDuration, 1)) * 100),
|
||||
);
|
||||
const previewRatio = `${d.ratio.width} / ${d.ratio.height}`;
|
||||
const renderedVisualSegments = d.imageSrc
|
||||
? d.visualSegments.length
|
||||
? d.visualSegments
|
||||
: [{
|
||||
id: "visual-fallback",
|
||||
duration: d.imageDuration,
|
||||
...getVisualAssetPayload(d.getCurrentVisualAssetSnapshot()),
|
||||
}]
|
||||
: [];
|
||||
const activeTimelineClipDrag = d.timelineClipDrag?.dragging ? d.timelineClipDrag : null;
|
||||
const draggedAsset = d.draggedAssetId ? d.findAssetById(d.draggedAssetId) : null;
|
||||
const showStickerTrack =
|
||||
d.stickerSegments.length > 0 ||
|
||||
d.selectedTrack === "sticker" ||
|
||||
d.assetDropTargetTrack === "sticker" ||
|
||||
d.assetDragPreview?.type === "sticker" ||
|
||||
draggedAsset?.type === "sticker";
|
||||
const displayedVisualSegments = activeTimelineClipDrag?.track === "image"
|
||||
? reorderTimelineItems(
|
||||
renderedVisualSegments,
|
||||
activeTimelineClipDrag.fromIndex,
|
||||
activeTimelineClipDrag.overIndex,
|
||||
)
|
||||
: renderedVisualSegments;
|
||||
const renderedVisualTimeline = getVisualSegmentTimeline(displayedVisualSegments);
|
||||
const displayedCaptionSegments = activeTimelineClipDrag?.track === "caption"
|
||||
? reorderTimelineItems(
|
||||
d.captionSegments,
|
||||
activeTimelineClipDrag.fromIndex,
|
||||
activeTimelineClipDrag.overIndex,
|
||||
)
|
||||
: d.captionSegments;
|
||||
const displayedCaptionTimeline = activeTimelineClipDrag?.track === "caption"
|
||||
? getCaptionTimeline(displayedCaptionSegments, d.captionTargetDuration)
|
||||
: d.captionTimeline;
|
||||
const audioClipPercent = d.audioBlob && d.timelineDuration > 0
|
||||
? Math.max(0.01, Math.min(100, (d.audioDuration / d.timelineDuration) * 100))
|
||||
: 0;
|
||||
const sourceAudioStartPercent = d.sourceAudioBlob && d.timelineDuration > 0
|
||||
? Math.max(0, Math.min(100, (d.sourceAudioStart / d.timelineDuration) * 100))
|
||||
: 0;
|
||||
const sourceAudioClipPercent = d.sourceAudioBlob && d.timelineDuration > 0
|
||||
? Math.max(
|
||||
0.01,
|
||||
Math.min(
|
||||
100 - sourceAudioStartPercent,
|
||||
(d.sourceAudioDuration / d.timelineDuration) * 100,
|
||||
),
|
||||
)
|
||||
: 0;
|
||||
const musicClipPercent = d.musicBlob && d.timelineDuration > 0
|
||||
? Math.max(0.01, Math.min(100, (d.musicDuration / d.timelineDuration) * 100))
|
||||
: 0;
|
||||
const exportPercent = Math.max(0, Math.min(100, Math.round(d.exportProgress)));
|
||||
const previewFrameStyle = d.previewFrameSize.width > 0 && d.previewFrameSize.height > 0
|
||||
? {
|
||||
"--preview-ratio": previewRatio,
|
||||
width: `${d.previewFrameSize.width}px`,
|
||||
height: `${d.previewFrameSize.height}px`,
|
||||
}
|
||||
: { "--preview-ratio": previewRatio };
|
||||
|
||||
return {
|
||||
activeTimelineClipDrag, audioClipPercent, displayedCaptionSegments,
|
||||
displayedCaptionTimeline, displayedVisualSegments, exportPercent, musicClipPercent,
|
||||
playheadPercent, previewFrameStyle, previewRatio, progressPercent,
|
||||
renderedVisualSegments, renderedVisualTimeline, showStickerTrack,
|
||||
sourceAudioClipPercent, sourceAudioStartPercent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { downloadBlob } from "./media.js";
|
||||
import { revokeVisionObjectUrls } from "./editorRuntime.js";
|
||||
|
||||
export function createVisionControls(deps) {
|
||||
function toggleVisionOption(optionId) {
|
||||
if (!deps.previewVisionKey || !deps.previewVisionRecord) return;
|
||||
const hasMatting = Boolean(deps.previewVisionAnalysis?.cutoutUrl) ||
|
||||
Boolean(deps.previewVisionBaseAnalysis?.samples?.some((sample) => sample.cutoutUrl));
|
||||
if (optionId === "removeBackground" && !hasMatting) return void deps.notify("请先完成当前图片或整段视频的 MODNet 分析");
|
||||
const enabled = !deps.previewVisionOptions[optionId];
|
||||
deps.setVisionRecords((records) => {
|
||||
const record = records[deps.previewVisionKey];
|
||||
return record ? { ...records, [deps.previewVisionKey]: { ...record, options: { ...record.options, [optionId]: enabled } } } : records;
|
||||
});
|
||||
const labels = { showDetections: "主体识别框", removeBackground: "MODNet 抠图", avoidCaptions: "字幕智能避让", smartCrop: "主体智能裁切" };
|
||||
deps.notify(`${labels[optionId] ?? "智能画面"}已${enabled ? "开启" : "关闭"}`);
|
||||
}
|
||||
|
||||
function setFitModeFromUser(nextModeOrUpdater) {
|
||||
deps.setFitMode(nextModeOrUpdater);
|
||||
if (!deps.previewVisionKey || !deps.previewVisionRecord?.options?.smartCrop) return;
|
||||
deps.setVisionRecords((records) => {
|
||||
const record = records[deps.previewVisionKey];
|
||||
return record ? { ...records, [deps.previewVisionKey]: { ...record, options: { ...record.options, smartCrop: false } } } : records;
|
||||
});
|
||||
}
|
||||
|
||||
function clearVisionAnalysis() {
|
||||
if (!deps.previewVisionKey) return;
|
||||
if (deps.visionJob.running && deps.visionJob.key === deps.previewVisionKey) {
|
||||
deps.visionJobGenerationRef.current += 1; deps.visionAbortControllerRef.current?.abort();
|
||||
deps.visionAbortControllerRef.current = null;
|
||||
}
|
||||
const urls = deps.visionObjectUrlsRef.current.get(deps.previewVisionKey);
|
||||
if (urls) { revokeVisionObjectUrls(urls); deps.visionObjectUrlsRef.current.delete(deps.previewVisionKey); }
|
||||
deps.setVisionRecords((records) => { const next = { ...records }; delete next[deps.previewVisionKey]; return next; });
|
||||
deps.setVisionJob({ running: false, key: "", progress: 0, phase: "" });
|
||||
deps.notify("当前素材的视觉分析已清除");
|
||||
}
|
||||
|
||||
function downloadVisionCutout() {
|
||||
if (deps.previewVisualType === "video") return void deps.notify("视频 MODNet 遮罩会随时间变化,并随视频一起预览和导出");
|
||||
const blob = deps.previewVisionAnalysis?.cutoutBlob;
|
||||
if (!blob) return void deps.notify("当前素材还没有透明抠图");
|
||||
const baseName = (deps.previewVisualSegment?.name || deps.imageName || "subject").replace(/\.[^.]+$/, "").replace(/[^\w\u3400-\u9fff-]+/g, "-");
|
||||
downloadBlob(blob, `${baseName || "subject"}-modnet.png`); deps.notify("透明 PNG 已下载");
|
||||
}
|
||||
|
||||
function removeVisionRecordsForAsset(asset) {
|
||||
if (!asset?.id && !asset?.src) return;
|
||||
const belongs = (key) => Boolean((asset.id && key.startsWith(`${asset.id}::`)) || (asset.src && key.includes(`::${asset.src}`)));
|
||||
if (deps.visionJob.running && belongs(deps.visionJob.key)) {
|
||||
deps.visionJobGenerationRef.current += 1; deps.visionAbortControllerRef.current?.abort();
|
||||
deps.visionAbortControllerRef.current = null; deps.setVisionJob({ running: false, key: "", progress: 0, phase: "" });
|
||||
}
|
||||
deps.setVisionRecords((records) => {
|
||||
const next = { ...records };
|
||||
Object.keys(records).forEach((key) => {
|
||||
if (!belongs(key)) return;
|
||||
const urls = deps.visionObjectUrlsRef.current.get(key);
|
||||
if (urls) { revokeVisionObjectUrls(urls); deps.visionObjectUrlsRef.current.delete(key); }
|
||||
delete next[key];
|
||||
});
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return { clearVisionAnalysis, downloadVisionCutout, removeVisionRecordsForAsset, setFitModeFromUser, toggleVisionOption };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getSmartCropRect,
|
||||
normalizeBoundingBox,
|
||||
selectPrimarySubject,
|
||||
} from "./visualGeometry.js";
|
||||
|
||||
describe("visual geometry", () => {
|
||||
it("normalizes pixel coordinates", () => {
|
||||
const box = normalizeBoundingBox(
|
||||
{ xMin: 100, yMin: 50, xMax: 500, yMax: 450 },
|
||||
{ width: 1000, height: 500 },
|
||||
);
|
||||
expect(box).toMatchObject({ xMin: 0.1, yMin: 0.1, xMax: 0.5, yMax: 0.9 });
|
||||
});
|
||||
|
||||
it("clamps normalized coordinates into the frame", () => {
|
||||
const box = normalizeBoundingBox({
|
||||
xMin: -0.2,
|
||||
yMin: 0.1,
|
||||
xMax: 1.4,
|
||||
yMax: 0.8,
|
||||
coordinateSpace: "normalized",
|
||||
});
|
||||
expect(box).toMatchObject({ xMin: 0, yMin: 0.1, xMax: 1, yMax: 0.8 });
|
||||
});
|
||||
|
||||
it("prefers a person subject over a similarly scored object", () => {
|
||||
const subject = selectPrimarySubject([
|
||||
{ label: "chair", score: 0.95, box: { xMin: 0.2, yMin: 0.2, xMax: 0.8, yMax: 0.8 } },
|
||||
{ label: "person", score: 0.82, box: { xMin: 0.35, yMin: 0.1, xMax: 0.65, yMax: 0.9 } },
|
||||
]);
|
||||
expect(subject.label).toBe("person");
|
||||
});
|
||||
|
||||
it("creates an in-bounds crop with the requested aspect ratio", () => {
|
||||
const crop = getSmartCropRect(
|
||||
{ width: 1920, height: 1080 },
|
||||
{ width: 1080, height: 1920 },
|
||||
{ xMin: 0.7, yMin: 0.1, xMax: 0.95, yMax: 0.9 },
|
||||
);
|
||||
expect(crop.x).toBeGreaterThanOrEqual(0);
|
||||
expect(crop.x + crop.width).toBeLessThanOrEqual(1920);
|
||||
expect(crop.height).toBeLessThanOrEqual(1080);
|
||||
expect(crop.width / crop.height).toBeCloseTo(1080 / 1920, 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
} from "../config/editor.js";
|
||||
import {
|
||||
createVisualSegment,
|
||||
estimateDuration,
|
||||
getImageThumbnailCount,
|
||||
getVisualSegmentsTotal,
|
||||
} from "./timeline.js";
|
||||
|
||||
export function createVisualTimelineActions(d) {
|
||||
function getVisualDurationForAsset(asset, fallbackDuration = 4) {
|
||||
if (asset?.type === "video" && asset.duration) {
|
||||
return Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(MIN_VISUAL_SEGMENT_SECONDS, asset.duration),
|
||||
);
|
||||
}
|
||||
return Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(MIN_VISUAL_SEGMENT_SECONDS, asset?.duration || fallbackDuration),
|
||||
);
|
||||
}
|
||||
|
||||
function getCurrentVisualAssetSnapshot() {
|
||||
return {
|
||||
id: d.previewVisualSegment?.assetId || "",
|
||||
assetId: d.previewVisualSegment?.assetId || "",
|
||||
type: d.previewVisualSegment?.type || d.visualType,
|
||||
src: d.previewVisualSegment?.src || d.imageSrc,
|
||||
name: d.previewVisualSegment?.name || d.imageName,
|
||||
meta: d.previewVisualSegment?.meta || d.imageMeta,
|
||||
blob: d.previewVisualSegment?.blob || null,
|
||||
width: d.previewVisualSegment?.width || 0,
|
||||
height: d.previewVisualSegment?.height || 0,
|
||||
sourceStart: Math.max(0, Number(d.previewVisualSegment?.sourceStart) || 0),
|
||||
trackFrames: d.previewVisualSegment?.trackFrames || [],
|
||||
};
|
||||
}
|
||||
|
||||
function setCurrentVisualAsset(asset) {
|
||||
d.setImageSrc(asset?.src ?? "");
|
||||
d.setImageName(asset?.name ?? "");
|
||||
d.setImageMeta(asset?.meta ?? "");
|
||||
d.setVisualType(asset?.type ?? "image");
|
||||
}
|
||||
|
||||
function commitVisualSegments(nextSegments, message, selectedIndex = 0) {
|
||||
const normalizedSegments = nextSegments
|
||||
.filter((segment) => segment.duration > 0.05)
|
||||
.map((segment) => ({
|
||||
...segment,
|
||||
duration: Math.max(
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, segment.duration),
|
||||
),
|
||||
}));
|
||||
const nextDuration = Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
getVisualSegmentsTotal(normalizedSegments),
|
||||
);
|
||||
d.setVisualSegments(normalizedSegments);
|
||||
d.setImageDuration(nextDuration);
|
||||
d.setImageClipCount(getImageThumbnailCount(nextDuration));
|
||||
d.setSelectedTrack("image");
|
||||
const selectedSegment = normalizedSegments.length
|
||||
? normalizedSegments[Math.min(Math.max(0, selectedIndex), normalizedSegments.length - 1)]
|
||||
: null;
|
||||
d.setSelectedVisualSegmentId(selectedSegment?.id ?? "");
|
||||
if (selectedSegment?.src) setCurrentVisualAsset(selectedSegment);
|
||||
d.setCurrentTime((time) => Math.min(
|
||||
time,
|
||||
Math.max(nextDuration, d.captionDuration, estimateDuration(d.script)),
|
||||
));
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function replaceVisualTimeline(asset, duration = getVisualDurationForAsset(asset)) {
|
||||
const segment = createVisualSegment(duration, asset);
|
||||
d.setFitMode("contain");
|
||||
setCurrentVisualAsset(asset);
|
||||
d.setVisualSegments([segment]);
|
||||
d.setSelectedVisualSegmentId(segment.id);
|
||||
d.setImageDuration(segment.duration);
|
||||
d.setImageClipCount(getImageThumbnailCount(segment.duration));
|
||||
}
|
||||
|
||||
function appendVisualAssetToTimeline(asset) {
|
||||
if (d.trackLocks.image) {
|
||||
d.notify("图片轨已锁定,无法添加素材");
|
||||
return;
|
||||
}
|
||||
const sourceSegments = d.visualSegments.length
|
||||
? d.visualSegments
|
||||
: d.imageSrc
|
||||
? [createVisualSegment(d.imageDuration || 4, getCurrentVisualAssetSnapshot())]
|
||||
: [];
|
||||
const totalDuration = getVisualSegmentsTotal(sourceSegments);
|
||||
const availableDuration = MAX_TIMELINE_DURATION_SECONDS - totalDuration;
|
||||
if (availableDuration < MIN_VISUAL_SEGMENT_SECONDS) {
|
||||
d.notify("视觉轨道已经达到 30 分钟上限");
|
||||
return;
|
||||
}
|
||||
const segmentDuration = Math.min(getVisualDurationForAsset(asset), availableDuration);
|
||||
const nextSegment = createVisualSegment(segmentDuration, asset);
|
||||
d.setFitMode("contain");
|
||||
setCurrentVisualAsset(asset);
|
||||
commitVisualSegments(
|
||||
[...sourceSegments, nextSegment],
|
||||
`${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
|
||||
sourceSegments.length,
|
||||
);
|
||||
d.seekTo(totalDuration);
|
||||
if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration);
|
||||
}
|
||||
|
||||
function updateVisualAssetInTimeline(assetId, updates) {
|
||||
if (!assetId) return;
|
||||
d.setVisualSegments((segments) => {
|
||||
const nextSegments = segments.map((segment) =>
|
||||
segment.assetId === assetId
|
||||
? {
|
||||
...segment,
|
||||
...updates,
|
||||
duration: updates.duration
|
||||
? Math.max(
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, updates.duration),
|
||||
)
|
||||
: segment.duration,
|
||||
}
|
||||
: segment,
|
||||
);
|
||||
const nextDuration = getVisualSegmentsTotal(nextSegments);
|
||||
d.setImageDuration(nextDuration);
|
||||
d.setImageClipCount(getImageThumbnailCount(nextDuration));
|
||||
return nextSegments;
|
||||
});
|
||||
if (d.previewVisualSegment?.assetId === assetId || d.previewVisualSegment?.src === updates.src) {
|
||||
d.setImageMeta(updates.meta ?? d.imageMeta);
|
||||
if (updates.type) d.setVisualType(updates.type);
|
||||
}
|
||||
}
|
||||
|
||||
function clearImageTrack(message = "图片素材已从时间线移除") {
|
||||
const remainingDuration = Math.max(
|
||||
d.audioBlob ? d.audioDuration : 0,
|
||||
d.captionDuration,
|
||||
d.sourceAudioBlob ? d.sourceAudioStart + d.sourceAudioDuration : 0,
|
||||
d.musicBlob ? d.musicDuration : 0,
|
||||
estimateDuration(d.script),
|
||||
);
|
||||
d.setImageSrc("");
|
||||
d.setImageName("");
|
||||
d.setImageMeta("");
|
||||
d.setVisualType("image");
|
||||
d.setImageClipCount(0);
|
||||
d.setImageDuration(0);
|
||||
d.setVisualSegments([]);
|
||||
d.setSelectedVisualSegmentId("");
|
||||
d.setCurrentTime((time) => Math.min(time, remainingDuration));
|
||||
d.setSelectedTrack("image");
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
return {
|
||||
appendVisualAssetToTimeline,
|
||||
clearImageTrack,
|
||||
commitVisualSegments,
|
||||
getCurrentVisualAssetSnapshot,
|
||||
getVisualDurationForAsset,
|
||||
replaceVisualTimeline,
|
||||
setCurrentVisualAsset,
|
||||
updateVisualAssetInTimeline,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user