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
+474
-4921
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
import { formatClock } from "../lib/timeline.js";
|
||||
|
||||
export function AssetDragPreview({ preview, t }) {
|
||||
if (!preview) return null;
|
||||
const label = preview.type === "audio" ? t("assetAudio") : preview.type === "video" ? t("assetVideo") : preview.type === "sticker" ? t("assetSticker") : t("assetImage");
|
||||
return <div className={`asset-drag-preview type-${preview.type}`} style={{ left: preview.x, top: preview.y }}>
|
||||
{preview.src ? <div className="asset-drag-thumb">
|
||||
{preview.type === "video" ? <video src={preview.src} muted playsInline preload="metadata" draggable={false} />
|
||||
: preview.type === "audio" ? <span>{label}</span> : <img src={preview.src} alt="" draggable={false} />}
|
||||
</div> : null}
|
||||
<span>{label}</span><strong>{preview.name}</strong>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function ExportProgressOverlay({ exporting, percent, phase, elapsedSeconds, t }) {
|
||||
if (!exporting) return null;
|
||||
return <div className="export-progress-overlay" role="status" aria-live="polite"><div className="export-progress-card">
|
||||
<div className="export-progress-header"><span>{t("exportInProgress")}</span><strong>{percent}%</strong></div>
|
||||
<div className="export-progress-bar" role="progressbar" aria-label={t("exportProgress")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent}>
|
||||
<span style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
<div className="export-progress-meta"><span>{phase || t("preparingExport")}</span><span>{formatClock(elapsedSeconds)}</span></div>
|
||||
</div></div>;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { TOOL_RAIL } from "../config/editor.js";
|
||||
import { MediaPanel, ToolPanel } from "./panels.jsx";
|
||||
|
||||
export function EditorSidebar({ model: d }) {
|
||||
return (
|
||||
<>
|
||||
<aside className={`tool-rail ${d.compactRail ? "is-compact" : ""}`} aria-label={d.t("toolbar")}>
|
||||
{TOOL_RAIL.map(({ id, label, icon: Icon }) => (
|
||||
<button
|
||||
className={`rail-tool ${d.activeTool === id ? "is-active" : ""}`}
|
||||
type="button"
|
||||
key={id}
|
||||
onClick={() => d.selectTool(id)}
|
||||
>
|
||||
<Icon size={23} />
|
||||
<span>{d.t(id, label)}</span>
|
||||
</button>
|
||||
))}
|
||||
</aside>
|
||||
|
||||
<aside className="media-panel">
|
||||
{d.activeTool === "media" ? (
|
||||
<MediaPanel
|
||||
t={d.t}
|
||||
mediaTab={d.mediaTab}
|
||||
setMediaTab={d.setMediaTab}
|
||||
isDragging={d.isDragging}
|
||||
setIsDragging={d.setIsDragging}
|
||||
fileInputRef={d.fileInputRef}
|
||||
handleFiles={d.handleFiles}
|
||||
imageSrc={d.imageSrc}
|
||||
builtInAssets={d.builtInAssets}
|
||||
userAssets={d.userAssets}
|
||||
selectedLibraryAssetId={d.selectedLibraryAssetId}
|
||||
deleteUserAsset={d.deleteUserAsset}
|
||||
draggedAssetId={d.draggedAssetId}
|
||||
handleAssetPointerDown={d.handleAssetPointerDown}
|
||||
handleAssetClick={d.handleAssetClick}
|
||||
/>
|
||||
) : (
|
||||
<ToolPanel
|
||||
activeTool={d.activeTool}
|
||||
uiLanguage={d.activeLanguage}
|
||||
script={d.script}
|
||||
updateScript={d.updateScript}
|
||||
segments={d.segments}
|
||||
currentSegmentIndex={d.currentSegmentIndex}
|
||||
captionSegments={d.captionSegments}
|
||||
captionTargetDuration={d.captionTargetDuration}
|
||||
selectedCaptionSegment={d.selectedCaptionSegment}
|
||||
selectedSegmentId={d.selectedSegmentId}
|
||||
setSelectedSegmentId={d.setSelectedSegmentId}
|
||||
updateCaptionSegmentText={d.updateCaptionSegmentText}
|
||||
toggleCaptionSegmentHidden={d.toggleCaptionSegmentHidden}
|
||||
deleteCaptionSegment={d.deleteCaptionSegment}
|
||||
seekTo={d.seekTo}
|
||||
estimatedDuration={d.estimatedDuration}
|
||||
captionPosition={d.captionPosition}
|
||||
setCaptionPosition={d.handleCaptionPositionChange}
|
||||
captionSize={d.captionSize}
|
||||
setCaptionSize={d.setCaptionSize}
|
||||
captionStyle={d.captionStyle}
|
||||
setCaptionStyle={d.setCaptionStyle}
|
||||
captionsEnabled={d.captionsEnabled}
|
||||
setCaptionsEnabled={d.setCaptionsEnabled}
|
||||
selectedFilterId={d.selectedFilterId}
|
||||
setSelectedFilterId={d.setSelectedFilterId}
|
||||
selectedTransitionId={d.selectedTransitionId}
|
||||
setSelectedTransitionId={d.setSelectedTransitionId}
|
||||
selectedStickerId={d.selectedStickerId}
|
||||
setSelectedStickerId={d.setSelectedStickerId}
|
||||
handleStickerPointerDown={d.handleAssetPointerDown}
|
||||
handleStickerClick={d.handleStickerClick}
|
||||
audioBlob={d.audioBlob}
|
||||
audioDuration={d.audioDuration}
|
||||
sourceAudioBlob={d.sourceAudioBlob}
|
||||
sourceAudioName={d.sourceAudioName}
|
||||
sourceAudioDuration={d.sourceAudioDuration}
|
||||
sourceAudioVolume={d.sourceAudioVolume}
|
||||
setSourceAudioVolume={d.setSourceAudioVolume}
|
||||
clearSourceAudioTrack={d.clearSourceAudioTrack}
|
||||
generateCaptionsFromSourceAudio={d.generateCaptionsFromSourceAudio}
|
||||
isGeneratingCaptions={d.status === "captioning"}
|
||||
automaticCaptionProgress={d.status === "captioning" ? d.progress : 0}
|
||||
hasVisual={Boolean(d.previewVisualSrc)}
|
||||
visualType={d.previewVisualType}
|
||||
visionAnalysis={d.previewVisionAnalysis}
|
||||
visionOptions={d.previewVisionOptions}
|
||||
visionRunning={d.visionJob.running && d.visionJob.key === d.previewVisionKey}
|
||||
visionProgress={d.visionJob.key === d.previewVisionKey ? d.visionJob.progress : 0}
|
||||
visionPhase={d.visionJob.key === d.previewVisionKey ? d.visionJob.phase : ""}
|
||||
analyzeCurrentVisual={d.analyzeCurrentVisual}
|
||||
toggleVisionOption={d.toggleVisionOption}
|
||||
clearVisionAnalysis={d.clearVisionAnalysis}
|
||||
downloadVisionCutout={d.downloadVisionCutout}
|
||||
openAvatarPanel={d.openAvatarPanel}
|
||||
musicBlob={d.musicBlob}
|
||||
musicName={d.musicName}
|
||||
musicDuration={d.musicDuration}
|
||||
musicVolume={d.musicVolume}
|
||||
setMusicVolume={d.setMusicVolume}
|
||||
clearMusicTrack={d.clearMusicTrack}
|
||||
selectedVoice={d.selectedVoice}
|
||||
setVoiceTab={d.setVoiceTab}
|
||||
downloadBlob={d.downloadBlob}
|
||||
notify={d.notify}
|
||||
t={d.t}
|
||||
trOption={d.trOption}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1135,7 +1135,7 @@ export function MyVoicesPanel({
|
||||
recordingElapsed,
|
||||
startVoiceRecording,
|
||||
stopVoiceRecording,
|
||||
useRecordedVoice,
|
||||
useRecordedVoice: onUseRecordedVoice,
|
||||
downloadBlob,
|
||||
}) {
|
||||
const favorites = VOICES.filter((voice) => favoriteVoiceIds.includes(voice.id));
|
||||
@@ -1170,7 +1170,7 @@ export function MyVoicesPanel({
|
||||
{recording.createdAt} · {formatTime(recording.duration)}
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" onClick={() => useRecordedVoice(recording)}>
|
||||
<button type="button" onClick={() => onUseRecordedVoice(recording)}>
|
||||
{t("use")}
|
||||
</button>
|
||||
<button
|
||||
@@ -1215,7 +1215,7 @@ export function MyVoicesPanel({
|
||||
);
|
||||
}
|
||||
|
||||
export function HistoryPanel({ historyItems, useHistoryItem, setHistoryItems, downloadBlob, t }) {
|
||||
export function HistoryPanel({ historyItems, useHistoryItem: onUseHistoryItem, setHistoryItems, downloadBlob, t }) {
|
||||
return (
|
||||
<div className="history-panel">
|
||||
{historyItems.length ? (
|
||||
@@ -1227,7 +1227,7 @@ export function HistoryPanel({ historyItems, useHistoryItem, setHistoryItems, do
|
||||
{item.createdAt} · {formatTime(item.duration)} · {item.script.slice(0, 18)}
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" onClick={() => useHistoryItem(item)}>
|
||||
<button type="button" onClick={() => onUseHistoryItem(item)}>
|
||||
{t("use")}
|
||||
</button>
|
||||
<button type="button" onClick={() => downloadBlob(item.blob, `history-${item.voiceName}.wav`)}>
|
||||
|
||||
@@ -13,8 +13,6 @@ import {
|
||||
export { MODEL_ID, AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "./models.js";
|
||||
|
||||
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
|
||||
export const FFMPEG_CLASS_WORKER_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/ffmpeg@0.12.15/dist/esm/worker.js";
|
||||
export const FFMPEG_CORE_BASE_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.10/dist/esm";
|
||||
export const DEFAULT_TIMELINE_DURATION_SECONDS = 30 * 60;
|
||||
export const MAX_TIMELINE_DURATION_SECONDS = 24 * 60 * 60;
|
||||
export const IMAGE_SEGMENT_SECONDS = 2;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { DEFAULT_TIMELINE_DURATION_SECONDS, VOICES } from "../config/editor.js";
|
||||
|
||||
export function useAudioTrackState() {
|
||||
const [selectedVoiceId, setSelectedVoiceId] = useState(VOICES[0].id);
|
||||
const [speed, setSpeed] = useState(1);
|
||||
const [volume, setVolume] = useState(1);
|
||||
const [audioSegments, setAudioSegments] = useState([]);
|
||||
const [selectedAudioSegmentId, setSelectedAudioSegmentId] = useState("");
|
||||
const [timelineHorizon, setTimelineHorizon] = useState(DEFAULT_TIMELINE_DURATION_SECONDS);
|
||||
const [musicBlob, setMusicBlob] = useState(null);
|
||||
const [musicUrl, setMusicUrl] = useState("");
|
||||
const [musicName, setMusicName] = useState("");
|
||||
const [musicDuration, setMusicDuration] = useState(0);
|
||||
const [musicPeaks, setMusicPeaks] = useState([]);
|
||||
const [musicVolume, setMusicVolume] = useState(0.35);
|
||||
const [sourceAudioBlob, setSourceAudioBlob] = useState(null);
|
||||
const [sourceAudioUrl, setSourceAudioUrl] = useState("");
|
||||
const [sourceAudioName, setSourceAudioName] = useState("");
|
||||
const [sourceAudioDuration, setSourceAudioDuration] = useState(0);
|
||||
const [sourceAudioPeaks, setSourceAudioPeaks] = useState([]);
|
||||
const [sourceAudioVolume, setSourceAudioVolume] = useState(1);
|
||||
const [sourceAudioStart, setSourceAudioStart] = useState(0);
|
||||
const [favoriteVoiceIds, setFavoriteVoiceIds] = useState(["zh_CN-huayan-medium"]);
|
||||
const [historyItems, setHistoryItems] = useState([]);
|
||||
const [recordedVoices, setRecordedVoices] = useState([]);
|
||||
const [recordingState, setRecordingState] = useState("idle");
|
||||
const [recordingElapsed, setRecordingElapsed] = useState(0);
|
||||
|
||||
return {
|
||||
audioSegments, favoriteVoiceIds, historyItems, musicBlob, musicDuration, musicName,
|
||||
musicPeaks, musicUrl, musicVolume, recordedVoices, recordingElapsed, recordingState,
|
||||
selectedAudioSegmentId, selectedVoiceId, setAudioSegments, setFavoriteVoiceIds,
|
||||
setHistoryItems, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks,
|
||||
setMusicUrl, setMusicVolume, setRecordedVoices, setRecordingElapsed,
|
||||
setRecordingState, setSelectedAudioSegmentId, setSelectedVoiceId, setSourceAudioBlob,
|
||||
setSourceAudioDuration, setSourceAudioName, setSourceAudioPeaks, setSourceAudioStart,
|
||||
setSourceAudioUrl, setSourceAudioVolume, setSpeed, setTimelineHorizon, setVolume,
|
||||
sourceAudioBlob, sourceAudioDuration, sourceAudioName, sourceAudioPeaks,
|
||||
sourceAudioStart, sourceAudioUrl, sourceAudioVolume, speed, timelineHorizon, volume,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useCallback } from "react";
|
||||
import { transcribeAudioToCaptionSegments } from "../lib/asr.js";
|
||||
|
||||
export function useAutoCaptions(d) {
|
||||
return useCallback(async () => {
|
||||
if (d.status === "generating" || d.status === "captioning") return;
|
||||
if (d.trackLocks.caption) return void d.notify("字幕轨已锁定,无法生成自动字幕");
|
||||
if (!d.sourceAudioBlob) return void d.notify("请先上传视频或把音频拖到原声轨");
|
||||
d.setStatus("captioning"); d.setStatusText("准备自动字幕模型"); d.setProgress(4); d.setActiveTool("audio");
|
||||
try {
|
||||
const result = await transcribeAudioToCaptionSegments(d.sourceAudioBlob, {
|
||||
preferredLanguage: d.uiLanguage, timelineOffset: d.sourceAudioStart,
|
||||
onProgress: ({ progress, phase }) => { d.setProgress((current) => Math.max(current, progress)); d.setStatusText(phase); },
|
||||
});
|
||||
d.setCaptionSegments(result.segments); d.setScript(result.text);
|
||||
d.setSelectedSegmentId(result.segments[0]?.id ?? ""); d.setSelectedTrack("caption"); d.setActiveTool("caption");
|
||||
d.setCaptionsEnabled(true); d.setTrackVisibility((visibility) => ({ ...visibility, caption: true }));
|
||||
d.setStatus("done"); d.setStatusText(`已生成 ${result.segments.length} 条自动字幕`); d.setProgress(100);
|
||||
d.seekTo(result.segments[0]?.start ?? 0); d.notify(`已生成 ${result.segments.length} 条自动字幕`);
|
||||
} catch (error) {
|
||||
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : "自动字幕生成失败");
|
||||
d.setProgress(0); d.notify("自动字幕生成失败,请换一段有清晰人声的音频试试");
|
||||
}
|
||||
}, [d]);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { formatSavedTime } from "../lib/timeline.js";
|
||||
|
||||
export function useAutosaveTimestamp(values, delay = 450) {
|
||||
const [lastSaved, setLastSaved] = useState(formatSavedTime);
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => setLastSaved(formatSavedTime()), delay);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [...values, delay]);
|
||||
return lastSaved;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useCallback } from "react";
|
||||
import { MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { JOYVASA_PROJECT_MODEL_BASE_URL } from "../config/joyVasa.js";
|
||||
import { LIVE_PORTRAIT_WEBGPU_PROJECT_MODEL_BASE_URL } from "../config/livePortrait.js";
|
||||
import { decodeAvatarAudio16k, encodeAvatarFrames, formatAvatarProgress, runAvatarWorkerTask } from "../lib/editorRuntime.js";
|
||||
|
||||
const createMotionWorker = () => new Worker(new URL("../workers/joyvasa.worker.js", import.meta.url), { type: "module" });
|
||||
const createRenderWorker = () => new Worker(new URL("../workers/liveportrait.worker.js", import.meta.url), { type: "module" });
|
||||
|
||||
export function useAvatarGeneration(d) {
|
||||
const openAvatarPanel = useCallback(() => {
|
||||
d.setAvatarPanelOpen(true);
|
||||
if (!d.avatarMotionWorkerRef.current) d.avatarMotionWorkerRef.current = createMotionWorker();
|
||||
if (!d.avatarRenderWorkerRef.current) d.avatarRenderWorkerRef.current = createRenderWorker();
|
||||
}, [d]);
|
||||
const generateAvatarAcceptanceFrame = useCallback(async (quality = "preview") => {
|
||||
if (d.avatarJob.running) return;
|
||||
if (!d.previewVisualSrc || d.previewVisualType !== "image") return void d.notify(d.t("avatarNeedsPortrait"));
|
||||
if (!d.audioBlob) return void d.notify(d.t("avatarNeedsAudio"));
|
||||
d.setAvatarJob({ running: true, progress: 1, phase: d.t("avatarPreparing") });
|
||||
try {
|
||||
const portrait = d.previewVisualSegment?.blob instanceof Blob ? d.previewVisualSegment.blob : await fetch(d.previewVisualSrc).then((response) => {
|
||||
if (!response.ok) throw new Error(`读取肖像失败(HTTP ${response.status})`); return response.blob();
|
||||
});
|
||||
const testDuration = import.meta.env.DEV ? Number(import.meta.env.VITE_AVATAR_TEST_DURATION || 0) : 0;
|
||||
const duration = testDuration > 0 ? Math.max(0.5, Math.min(4, testDuration))
|
||||
: Math.max(MIN_VISUAL_SEGMENT_SECONDS, Math.min(4, d.audioDuration || d.imageDuration || 4));
|
||||
let motionBuffer;
|
||||
if (d.avatarMotionCacheRef.current.audioBlob === d.audioBlob && d.avatarMotionCacheRef.current.motion) {
|
||||
motionBuffer = d.avatarMotionCacheRef.current.motion.slice(0);
|
||||
d.setAvatarJob({ running: true, progress: 65, phase: d.t("avatarProgressReuseMotion") });
|
||||
} else {
|
||||
if (d.avatarRenderWorkerRef.current) await runAvatarWorkerTask(d.avatarRenderWorkerRef.current, { type: "releaseGpuSessions" }, [], "gpuReleased");
|
||||
const samples = await decodeAvatarAudio16k(d.audioBlob);
|
||||
if (!d.avatarMotionWorkerRef.current) d.avatarMotionWorkerRef.current = createMotionWorker();
|
||||
const result = await runAvatarWorkerTask(d.avatarMotionWorkerRef.current,
|
||||
{ type: "generate", audioSamples: samples.buffer, modelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL }, [samples.buffer], "motion",
|
||||
(progress) => d.setAvatarJob({ running: true, progress: progress.progress, phase: formatAvatarProgress(d.t, progress) }));
|
||||
d.avatarMotionCacheRef.current = { audioBlob: d.audioBlob, motion: result.motion.slice(0) }; motionBuffer = result.motion;
|
||||
await runAvatarWorkerTask(d.avatarMotionWorkerRef.current, { type: "release", modelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL }, [], "released");
|
||||
}
|
||||
if (!d.avatarRenderWorkerRef.current) d.avatarRenderWorkerRef.current = createRenderWorker();
|
||||
const result = await runAvatarWorkerTask(d.avatarRenderWorkerRef.current, {
|
||||
type: "generateVideo", portraitBlob: portrait, motionBuffer,
|
||||
modelBaseUrl: import.meta.env.VITE_LIVE_PORTRAIT_MODEL_BASE_URL || "",
|
||||
joyVasaModelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL, webGpuModelBaseUrl: LIVE_PORTRAIT_WEBGPU_PROJECT_MODEL_BASE_URL,
|
||||
quality, renderFps: Math.max(1, Number(import.meta.env.VITE_AVATAR_RENDER_FPS || 8)),
|
||||
neuralFps: Math.max(1, Number(import.meta.env.VITE_AVATAR_NEURAL_FPS || 2)), duration,
|
||||
portraitKey: d.previewVisualSegment?.id || d.previewVisualSrc,
|
||||
}, [motionBuffer], "videoFrames",
|
||||
(progress) => d.setAvatarJob({ running: true, progress: progress.progress, phase: formatAvatarProgress(d.t, progress) }));
|
||||
d.setAvatarJob({ running: true, progress: 99, phase: d.t("avatarProgressEncodeVideo") });
|
||||
const blob = await encodeAvatarFrames(result.blobs, result.width, result.height, result.fps, result.keyframeTimes, result.duration);
|
||||
const src = URL.createObjectURL(blob); d.imageUrlRefs.current.add(src);
|
||||
const asset = { id: crypto.randomUUID(), type: "video", src, name: "liveportrait-joyvasa.webm",
|
||||
meta: `${result.width} x ${result.height} · JoyVASA + LivePortrait FP16 WebGPU`, blob, duration, width: result.width, height: result.height, trackFrames: [] };
|
||||
d.setUserAssets((assets) => [asset, ...assets]); d.replaceVisualTimeline(asset, duration); d.setCurrentTime(0);
|
||||
d.setAvatarJob({ running: false, progress: 100, phase: d.t("avatarAcceptanceDone") }); d.notify(d.t("avatarTrackReplaced"));
|
||||
} catch (error) {
|
||||
d.setAvatarJob({ running: false, progress: 0, phase: "" }); d.notify(`${d.t("avatarGenerationFailed")}:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}, [d]);
|
||||
return { generateAvatarAcceptanceFrame, openAvatarPanel };
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { DEFAULT_SCRIPT } from "../config/editor.js";
|
||||
import { createCaptionSegments } from "../lib/timeline.js";
|
||||
|
||||
const DEFAULT_CAPTION_STYLE = {
|
||||
backgroundColor: "#05080d",
|
||||
backgroundOpacity: 0.62,
|
||||
textColor: "#f5fbff",
|
||||
borderColor: "#35f0dd",
|
||||
borderWidth: 0,
|
||||
radius: 7,
|
||||
paddingX: 22,
|
||||
paddingY: 12,
|
||||
shadowOpacity: 0.45,
|
||||
effect: "normal",
|
||||
};
|
||||
|
||||
export function useCaptionState() {
|
||||
const [script, setScript] = useState(DEFAULT_SCRIPT);
|
||||
const [captionPosition, setCaptionPosition] = useState("bottom");
|
||||
const [captionPlacement, setCaptionPlacement] = useState({ x: 50, y: 78 });
|
||||
const [captionSize, setCaptionSize] = useState(12);
|
||||
const [captionStyle, setCaptionStyle] = useState(DEFAULT_CAPTION_STYLE);
|
||||
const [captionsEnabled, setCaptionsEnabled] = useState(true);
|
||||
const [captionSegments, setCaptionSegments] = useState(() => createCaptionSegments(DEFAULT_SCRIPT));
|
||||
const [selectedSegmentId, setSelectedSegmentId] = useState("");
|
||||
|
||||
return {
|
||||
captionPlacement, captionPosition, captionSegments, captionSize, captionStyle,
|
||||
captionsEnabled, script, selectedSegmentId, setCaptionPlacement,
|
||||
setCaptionPosition, setCaptionSegments, setCaptionSize, setCaptionStyle,
|
||||
setCaptionsEnabled, setScript, setSelectedSegmentId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useMemo } from "react";
|
||||
import { SAMPLE_IMAGE, VOICES } from "../config/editor.js";
|
||||
|
||||
export function useEditorCatalog(voiceFilter) {
|
||||
const filteredVoices = useMemo(() => VOICES.filter((voice) => {
|
||||
if (voiceFilter === "all") return true;
|
||||
if (voiceFilter === "中文") return voice.language === "中文";
|
||||
if (voiceFilter === "English") return voice.language === "English";
|
||||
return voice.engine === voiceFilter;
|
||||
}), [voiceFilter]);
|
||||
const builtInAssets = useMemo(() => [
|
||||
{ id: "sample", type: "image", src: SAMPLE_IMAGE, name: "sample-portrait.png", meta: "1920 x 1080", width: 1920, height: 1080 },
|
||||
{ id: "sample-motion", type: "video", src: "/assets/sample-motion.mp4", name: "sample-motion.mp4", meta: "640 x 360 · 00:02.50", duration: 2.5, width: 640, height: 360, trackFrames: [] },
|
||||
], []);
|
||||
return { builtInAssets, filteredVoices };
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
import {
|
||||
createEditorHistory,
|
||||
pushEditorHistory,
|
||||
redoEditorHistory,
|
||||
undoEditorHistory,
|
||||
} from "../lib/editorHistoryCore.ts";
|
||||
|
||||
const HISTORY_LIMIT = 50;
|
||||
const HISTORY_DEBOUNCE_MS = 180;
|
||||
|
||||
function cloneItems(items) {
|
||||
return items.map((item) => ({ ...item }));
|
||||
}
|
||||
|
||||
function createSnapshot(d) {
|
||||
return {
|
||||
script: d.script,
|
||||
captionSegments: cloneItems(d.captionSegments),
|
||||
captionPosition: d.captionPosition,
|
||||
captionPlacement: { ...d.captionPlacement },
|
||||
captionSize: d.captionSize,
|
||||
captionStyle: { ...d.captionStyle },
|
||||
captionsEnabled: d.captionsEnabled,
|
||||
visualSegments: cloneItems(d.visualSegments),
|
||||
imageSrc: d.imageSrc,
|
||||
imageName: d.imageName,
|
||||
imageMeta: d.imageMeta,
|
||||
visualType: d.visualType,
|
||||
imageDuration: d.imageDuration,
|
||||
imageClipCount: d.imageClipCount,
|
||||
fitMode: d.fitMode,
|
||||
selectedFilterId: d.selectedFilterId,
|
||||
selectedTransitionId: d.selectedTransitionId,
|
||||
stickerSegments: cloneItems(d.stickerSegments),
|
||||
selectedStickerId: d.selectedStickerId,
|
||||
audioSegments: cloneItems(d.audioSegments),
|
||||
timelineHorizon: d.timelineHorizon,
|
||||
musicBlob: d.musicBlob,
|
||||
musicUrl: d.musicUrl,
|
||||
musicName: d.musicName,
|
||||
musicDuration: d.musicDuration,
|
||||
musicPeaks: d.musicPeaks,
|
||||
musicVolume: d.musicVolume,
|
||||
sourceAudioBlob: d.sourceAudioBlob,
|
||||
sourceAudioUrl: d.sourceAudioUrl,
|
||||
sourceAudioName: d.sourceAudioName,
|
||||
sourceAudioDuration: d.sourceAudioDuration,
|
||||
sourceAudioPeaks: d.sourceAudioPeaks,
|
||||
sourceAudioVolume: d.sourceAudioVolume,
|
||||
sourceAudioStart: d.sourceAudioStart,
|
||||
trackVisibility: { ...d.trackVisibility },
|
||||
trackLocks: { ...d.trackLocks },
|
||||
userAssets: cloneItems(d.userAssets),
|
||||
selectedTrack: d.selectedTrack,
|
||||
selectedSegmentId: d.selectedSegmentId,
|
||||
selectedVisualSegmentId: d.selectedVisualSegmentId,
|
||||
selectedStickerSegmentId: d.selectedStickerSegmentId,
|
||||
selectedAudioSegmentId: d.selectedAudioSegmentId,
|
||||
currentTime: d.currentTime,
|
||||
};
|
||||
}
|
||||
|
||||
function mediaIdentity(item) {
|
||||
const { blob, url, src, peaks, trackFrames, cutoutVisual, ...serializable } = item;
|
||||
return {
|
||||
...serializable,
|
||||
media: blob ? "blob" : src || url || "",
|
||||
hasPeaks: Boolean(peaks?.length),
|
||||
hasTrackFrames: Boolean(trackFrames?.length),
|
||||
hasCutout: Boolean(cutoutVisual),
|
||||
};
|
||||
}
|
||||
|
||||
export function createEditorSnapshotSignature(snapshot) {
|
||||
return JSON.stringify({
|
||||
script: snapshot.script,
|
||||
captions: snapshot.captionSegments,
|
||||
captionPosition: snapshot.captionPosition,
|
||||
captionPlacement: snapshot.captionPlacement,
|
||||
captionSize: snapshot.captionSize,
|
||||
captionStyle: snapshot.captionStyle,
|
||||
captionsEnabled: snapshot.captionsEnabled,
|
||||
visuals: snapshot.visualSegments.map(mediaIdentity),
|
||||
image: {
|
||||
name: snapshot.imageName,
|
||||
meta: snapshot.imageMeta,
|
||||
type: snapshot.visualType,
|
||||
duration: snapshot.imageDuration,
|
||||
clipCount: snapshot.imageClipCount,
|
||||
fitMode: snapshot.fitMode,
|
||||
filter: snapshot.selectedFilterId,
|
||||
transition: snapshot.selectedTransitionId,
|
||||
},
|
||||
stickers: snapshot.stickerSegments,
|
||||
selectedStickerId: snapshot.selectedStickerId,
|
||||
audio: snapshot.audioSegments.map(mediaIdentity),
|
||||
timelineHorizon: snapshot.timelineHorizon,
|
||||
music: {
|
||||
present: Boolean(snapshot.musicBlob),
|
||||
name: snapshot.musicName,
|
||||
duration: snapshot.musicDuration,
|
||||
volume: snapshot.musicVolume,
|
||||
},
|
||||
source: {
|
||||
present: Boolean(snapshot.sourceAudioBlob),
|
||||
name: snapshot.sourceAudioName,
|
||||
duration: snapshot.sourceAudioDuration,
|
||||
volume: snapshot.sourceAudioVolume,
|
||||
start: snapshot.sourceAudioStart,
|
||||
},
|
||||
trackVisibility: snapshot.trackVisibility,
|
||||
trackLocks: snapshot.trackLocks,
|
||||
assets: snapshot.userAssets.map(mediaIdentity),
|
||||
});
|
||||
}
|
||||
|
||||
function createObjectUrl(blob) {
|
||||
return blob ? URL.createObjectURL(blob) : "";
|
||||
}
|
||||
|
||||
function restoreSnapshot(snapshot, d) {
|
||||
const blobUrls = new Map();
|
||||
const getBlobUrl = (blob) => {
|
||||
if (!blob) return "";
|
||||
if (!blobUrls.has(blob)) blobUrls.set(blob, createObjectUrl(blob));
|
||||
return blobUrls.get(blob);
|
||||
};
|
||||
const restoreAsset = (item) => {
|
||||
if (!item.blob) return { ...item };
|
||||
const nextUrl = getBlobUrl(item.blob);
|
||||
if (nextUrl) d.imageUrlRefs.current.add(nextUrl);
|
||||
return { ...item, src: item.src ? nextUrl : item.src, url: item.url ? nextUrl : item.url };
|
||||
};
|
||||
const visualSegments = snapshot.visualSegments.map(restoreAsset);
|
||||
const userAssets = snapshot.userAssets.map(restoreAsset);
|
||||
const restoredImage = visualSegments.find((item) => item.id === snapshot.selectedVisualSegmentId)
|
||||
?? visualSegments.find((item) => item.src)
|
||||
?? null;
|
||||
|
||||
d.setScript(snapshot.script);
|
||||
d.setCaptionSegments(cloneItems(snapshot.captionSegments));
|
||||
d.setCaptionPosition(snapshot.captionPosition);
|
||||
d.setCaptionPlacement({ ...snapshot.captionPlacement });
|
||||
d.setCaptionSize(snapshot.captionSize);
|
||||
d.setCaptionStyle({ ...snapshot.captionStyle });
|
||||
d.setCaptionsEnabled(snapshot.captionsEnabled);
|
||||
d.setVisualSegments(visualSegments);
|
||||
d.setImageSrc(restoredImage?.src || snapshot.imageSrc);
|
||||
d.setImageName(snapshot.imageName);
|
||||
d.setImageMeta(snapshot.imageMeta);
|
||||
d.setVisualType(snapshot.visualType);
|
||||
d.setImageDuration(snapshot.imageDuration);
|
||||
d.setImageClipCount(snapshot.imageClipCount);
|
||||
d.setFitMode(snapshot.fitMode);
|
||||
d.setSelectedFilterId(snapshot.selectedFilterId);
|
||||
d.setSelectedTransitionId(snapshot.selectedTransitionId);
|
||||
d.setStickerSegments(cloneItems(snapshot.stickerSegments));
|
||||
d.setSelectedStickerId(snapshot.selectedStickerId);
|
||||
d.setAudioSegments(snapshot.audioSegments.map((item) => ({
|
||||
...item,
|
||||
url: item.blob ? getBlobUrl(item.blob) : item.url,
|
||||
})));
|
||||
d.setTimelineHorizon(snapshot.timelineHorizon);
|
||||
const musicUrl = getBlobUrl(snapshot.musicBlob) || snapshot.musicUrl;
|
||||
d.musicUrlRef.current = musicUrl;
|
||||
d.setMusicBlob(snapshot.musicBlob);
|
||||
d.setMusicUrl(musicUrl);
|
||||
d.setMusicName(snapshot.musicName);
|
||||
d.setMusicDuration(snapshot.musicDuration);
|
||||
d.setMusicPeaks(snapshot.musicPeaks);
|
||||
d.setMusicVolume(snapshot.musicVolume);
|
||||
const sourceAudioUrl = getBlobUrl(snapshot.sourceAudioBlob) || snapshot.sourceAudioUrl;
|
||||
d.sourceAudioUrlRef.current = sourceAudioUrl;
|
||||
d.setSourceAudioBlob(snapshot.sourceAudioBlob);
|
||||
d.setSourceAudioUrl(sourceAudioUrl);
|
||||
d.setSourceAudioName(snapshot.sourceAudioName);
|
||||
d.setSourceAudioDuration(snapshot.sourceAudioDuration);
|
||||
d.setSourceAudioPeaks(snapshot.sourceAudioPeaks);
|
||||
d.setSourceAudioVolume(snapshot.sourceAudioVolume);
|
||||
d.setSourceAudioStart(snapshot.sourceAudioStart);
|
||||
d.setTrackVisibility({ ...snapshot.trackVisibility });
|
||||
d.setTrackLocks({ ...snapshot.trackLocks });
|
||||
d.setUserAssets(userAssets);
|
||||
d.setSelectedTrack(snapshot.selectedTrack);
|
||||
d.setSelectedSegmentId(snapshot.selectedSegmentId);
|
||||
d.setSelectedVisualSegmentId(snapshot.selectedVisualSegmentId);
|
||||
d.setSelectedStickerSegmentId(snapshot.selectedStickerSegmentId);
|
||||
d.setSelectedAudioSegmentId(snapshot.selectedAudioSegmentId);
|
||||
d.setCurrentTime(snapshot.currentTime);
|
||||
d.setIsPlaying(false);
|
||||
}
|
||||
|
||||
export function useEditorHistory(d) {
|
||||
const snapshot = createSnapshot(d);
|
||||
const signature = createEditorSnapshotSignature(snapshot);
|
||||
const historyRef = useRef(null);
|
||||
const latestSnapshotRef = useRef(snapshot);
|
||||
const pendingRef = useRef(null);
|
||||
const timerRef = useRef(0);
|
||||
const restoredSignatureRef = useRef("");
|
||||
latestSnapshotRef.current = snapshot;
|
||||
if (!historyRef.current) historyRef.current = createEditorHistory(snapshot);
|
||||
|
||||
const commitPending = useCallback(() => {
|
||||
window.clearTimeout(timerRef.current);
|
||||
timerRef.current = 0;
|
||||
if (!pendingRef.current) return;
|
||||
historyRef.current = pushEditorHistory(historyRef.current, pendingRef.current, HISTORY_LIMIT);
|
||||
pendingRef.current = null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const latestSnapshot = latestSnapshotRef.current;
|
||||
if (restoredSignatureRef.current === signature) {
|
||||
restoredSignatureRef.current = "";
|
||||
historyRef.current = { ...historyRef.current, current: latestSnapshot };
|
||||
return;
|
||||
}
|
||||
const currentSignature = createEditorSnapshotSignature(historyRef.current.current);
|
||||
if (signature === currentSignature) return;
|
||||
pendingRef.current = latestSnapshot;
|
||||
window.clearTimeout(timerRef.current);
|
||||
timerRef.current = window.setTimeout(commitPending, HISTORY_DEBOUNCE_MS);
|
||||
return () => window.clearTimeout(timerRef.current);
|
||||
}, [commitPending, signature]);
|
||||
|
||||
useEffect(() => () => window.clearTimeout(timerRef.current), []);
|
||||
|
||||
const undo = useCallback(() => {
|
||||
commitPending();
|
||||
const transition = undoEditorHistory(historyRef.current);
|
||||
if (!transition.changed) return void d.notify("没有可撤销的编辑操作");
|
||||
historyRef.current = transition.history;
|
||||
restoredSignatureRef.current = createEditorSnapshotSignature(transition.value);
|
||||
restoreSnapshot(transition.value, d);
|
||||
d.notify("已撤销上一步编辑");
|
||||
}, [commitPending, d]);
|
||||
|
||||
const redo = useCallback(() => {
|
||||
commitPending();
|
||||
const transition = redoEditorHistory(historyRef.current);
|
||||
if (!transition.changed) return void d.notify("没有可重做的编辑操作");
|
||||
historyRef.current = transition.history;
|
||||
restoredSignatureRef.current = createEditorSnapshotSignature(transition.value);
|
||||
restoreSnapshot(transition.value, d);
|
||||
d.notify("已重做编辑");
|
||||
}, [commitPending, d]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleHistoryShortcut = (event) => {
|
||||
const target = event.target;
|
||||
const isTyping = target instanceof HTMLElement && (
|
||||
target.tagName === "INPUT" ||
|
||||
target.tagName === "TEXTAREA" ||
|
||||
target.tagName === "SELECT" ||
|
||||
target.isContentEditable
|
||||
);
|
||||
if (isTyping || (!event.metaKey && !event.ctrlKey) || event.altKey) return;
|
||||
if (event.key.toLowerCase() !== "z") return;
|
||||
event.preventDefault();
|
||||
if (event.shiftKey) redo();
|
||||
else undo();
|
||||
};
|
||||
window.addEventListener("keydown", handleHistoryShortcut);
|
||||
return () => window.removeEventListener("keydown", handleHistoryShortcut);
|
||||
}, [redo, undo]);
|
||||
|
||||
return { redo, undo };
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { RATIO_OPTIONS } from "../config/editor.js";
|
||||
import { decodeWaveform } from "../lib/media.js";
|
||||
import { disposeVisionWorker } from "../lib/vision.js";
|
||||
import {
|
||||
getNearestRatioIdForSize,
|
||||
revokeVisionObjectUrls,
|
||||
} from "../lib/editorRuntime.js";
|
||||
|
||||
export function useEditorLifecycle(d) {
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = d.activeLanguage === "zh" ? "zh-CN" : d.activeLanguage;
|
||||
}, [d.activeLanguage]);
|
||||
|
||||
useEffect(() => () => {
|
||||
d.avatarMotionWorkerRef.current?.terminate();
|
||||
d.avatarRenderWorkerRef.current?.terminate();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
d.setFitMode("contain");
|
||||
}, [d.ratioId]);
|
||||
|
||||
useEffect(() => {
|
||||
const testImageUrl = import.meta.env.DEV ? import.meta.env.VITE_AVATAR_TEST_IMAGE_URL : "";
|
||||
if (!testImageUrl || d.avatarTestImportedRef.current) return;
|
||||
d.avatarTestImportedRef.current = true;
|
||||
fetch(testImageUrl)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.blob();
|
||||
})
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
d.imageUrlRefs.current.add(url);
|
||||
const asset = {
|
||||
id: crypto.randomUUID(),
|
||||
type: "image",
|
||||
src: url,
|
||||
name: "老外戴眼镜中年人物肖像生成-modnet.png",
|
||||
meta: "819 x 1024 · E2E test",
|
||||
blob,
|
||||
duration: 4,
|
||||
width: 819,
|
||||
height: 1024,
|
||||
trackFrames: [],
|
||||
};
|
||||
d.setUserAssets((assets) => [asset, ...assets]);
|
||||
d.replaceVisualTimeline(asset, 4);
|
||||
d.notify("端到端测试肖像已载入画面轨");
|
||||
})
|
||||
.catch((error) => {
|
||||
d.avatarTestImportedRef.current = false;
|
||||
console.error("Avatar E2E test image import failed", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!import.meta.env.DEV ||
|
||||
!import.meta.env.VITE_AVATAR_TEST_IMAGE_URL ||
|
||||
d.avatarTestAudioImportedRef.current
|
||||
) return;
|
||||
d.avatarTestAudioImportedRef.current = true;
|
||||
fetch("/assets/avatar-e2e-16k.wav")
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.blob();
|
||||
})
|
||||
.then(async (blob) => {
|
||||
const waveform = await decodeWaveform(blob);
|
||||
d.replaceAudio(blob, waveform.duration, waveform.peaks, "端到端测试配音已载入");
|
||||
d.notify("端到端测试配音已载入配音轨");
|
||||
})
|
||||
.catch((error) => {
|
||||
d.avatarTestAudioImportedRef.current = false;
|
||||
console.error("Avatar E2E test audio import failed", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const ratioSource = d.visualSegments.find((segment) => segment.width > 0 && segment.height > 0);
|
||||
if (!ratioSource) {
|
||||
d.autoRatioSourceKeyRef.current = "";
|
||||
return;
|
||||
}
|
||||
const sourceKey = `${ratioSource.assetId || ratioSource.id}:${ratioSource.width}x${ratioSource.height}`;
|
||||
if (d.autoRatioSourceKeyRef.current === sourceKey) return;
|
||||
d.autoRatioSourceKeyRef.current = sourceKey;
|
||||
const nextRatioId = getNearestRatioIdForSize(ratioSource.width, ratioSource.height);
|
||||
if (!nextRatioId || nextRatioId === d.ratioId) return;
|
||||
const nextRatio = RATIO_OPTIONS.find((option) => option.id === nextRatioId);
|
||||
d.setRatioId(nextRatioId);
|
||||
d.notify(`已根据素材自动切换为 ${nextRatio?.label ?? nextRatioId}`);
|
||||
}, [d.ratioId, d.visualSegments]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!d.captionSegments.length) {
|
||||
d.setSelectedSegmentId("");
|
||||
return;
|
||||
}
|
||||
if (!d.captionSegments.some((segment) => segment.id === d.selectedSegmentId)) {
|
||||
d.setSelectedSegmentId(d.captionSegments[0].id);
|
||||
}
|
||||
}, [d.captionSegments, d.selectedSegmentId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!d.visualSegments.length) {
|
||||
d.setSelectedVisualSegmentId("");
|
||||
return;
|
||||
}
|
||||
if (!d.visualSegments.some((segment) => segment.id === d.selectedVisualSegmentId)) {
|
||||
d.setSelectedVisualSegmentId(d.visualSegments[0].id);
|
||||
}
|
||||
}, [d.selectedVisualSegmentId, d.visualSegments]);
|
||||
|
||||
useEffect(() => {
|
||||
if (d.currentVisualSegment?.src) d.setCurrentVisualAsset(d.currentVisualSegment);
|
||||
}, [d.currentVisualSegment]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event) => {
|
||||
const target = event.target;
|
||||
const isTyping = target instanceof HTMLElement && (
|
||||
target.tagName === "INPUT" ||
|
||||
target.tagName === "TEXTAREA" ||
|
||||
target.tagName === "SELECT" ||
|
||||
target.isContentEditable
|
||||
);
|
||||
if (
|
||||
isTyping || event.metaKey || event.ctrlKey || event.altKey ||
|
||||
(event.key !== "Delete" && event.key !== "Backspace")
|
||||
) return;
|
||||
const hasSelectedTimelineItem =
|
||||
(d.selectedTrack === "caption" && d.selectedSegmentId && d.captionSegments.some((segment) => segment.id === d.selectedSegmentId)) ||
|
||||
(d.selectedTrack === "sticker" && d.selectedStickerSegmentId && d.stickerSegments.some((segment) => segment.id === d.selectedStickerSegmentId)) ||
|
||||
(d.selectedTrack === "image" && d.selectedVisualSegmentId && d.visualSegments.some((segment) => segment.id === d.selectedVisualSegmentId)) ||
|
||||
(d.selectedTrack === "audio" && d.selectedAudioSegmentId && d.audioSegments.some((segment) => segment.id === d.selectedAudioSegmentId)) ||
|
||||
(d.selectedTrack === "source" && d.sourceAudioBlob) ||
|
||||
(d.selectedTrack === "music" && d.musicBlob);
|
||||
if (hasSelectedTimelineItem) {
|
||||
event.preventDefault();
|
||||
d.handleDeleteTrack();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
});
|
||||
|
||||
useEffect(() => () => {
|
||||
if (d.audioUrlRef.current) URL.revokeObjectURL(d.audioUrlRef.current);
|
||||
if (d.sourceAudioUrlRef.current) URL.revokeObjectURL(d.sourceAudioUrlRef.current);
|
||||
if (d.musicUrlRef.current) URL.revokeObjectURL(d.musicUrlRef.current);
|
||||
d.imageUrlRefs.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
d.imageUrlRefs.current.clear();
|
||||
d.visionAbortControllerRef.current?.abort();
|
||||
d.visionObjectUrlsRef.current.forEach((urls) => revokeVisionObjectUrls(urls));
|
||||
d.visionObjectUrlsRef.current.clear();
|
||||
disposeVisionWorker();
|
||||
d.voiceRecorderStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
window.clearInterval(d.voiceRecorderTimerRef.current);
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useRef } from "react";
|
||||
|
||||
export function useEditorRefs() {
|
||||
return {
|
||||
assetDropPulseTimerRef: useRef(0),
|
||||
audioRef: useRef(null),
|
||||
audioSegmentRefs: useRef(new Map()),
|
||||
audioUrlRef: useRef(""),
|
||||
autoRatioSourceKeyRef: useRef(""),
|
||||
avatarMotionCacheRef: useRef({ audioBlob: null, motion: null }),
|
||||
avatarMotionWorkerRef: useRef(null),
|
||||
avatarRenderWorkerRef: useRef(null),
|
||||
avatarTestAudioImportedRef: useRef(false),
|
||||
avatarTestImportedRef: useRef(false),
|
||||
currentTimeRef: useRef(0),
|
||||
draggedAssetIdRef: useRef(""),
|
||||
exportStartRef: useRef(0),
|
||||
fileInputRef: useRef(null),
|
||||
imageUrlRefs: useRef(new Set()),
|
||||
musicRef: useRef(null),
|
||||
musicUrlRef: useRef(""),
|
||||
pointerAssetDragRef: useRef(null),
|
||||
previewCanvasRef: useRef(null),
|
||||
previewShellRef: useRef(null),
|
||||
previewVideoRef: useRef(null),
|
||||
projectFileInputRef: useRef(null),
|
||||
sourceAudioRef: useRef(null),
|
||||
sourceAudioUrlRef: useRef(""),
|
||||
suppressAssetClickRef: useRef(""),
|
||||
suppressTimelineClipClickRef: useRef(""),
|
||||
timelineClipDragRef: useRef(null),
|
||||
timelineDurationRef: useRef(0),
|
||||
trackScrollRef: useRef(null),
|
||||
visionAbortControllerRef: useRef(null),
|
||||
visionJobGenerationRef: useRef(0),
|
||||
visionObjectUrlsRef: useRef(new Map()),
|
||||
visualPlaybackFrameRef: useRef(0),
|
||||
visualPlaybackLastUpdateRef: useRef(0),
|
||||
visualPlaybackStartedAtRef: useRef(0),
|
||||
visualPlaybackStartTimeRef: useRef(0),
|
||||
voiceRecorderChunksRef: useRef([]),
|
||||
voiceRecorderRef: useRef(null),
|
||||
voiceRecorderStartedAtRef: useRef(0),
|
||||
voiceRecorderStreamRef: useRef(null),
|
||||
voiceRecorderTimerRef: useRef(0),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState } from "react";
|
||||
|
||||
const DEFAULT_TRACK_VISIBILITY = {
|
||||
image: true, caption: true, sticker: true, source: true, audio: true, music: true,
|
||||
};
|
||||
|
||||
const DEFAULT_TRACK_LOCKS = {
|
||||
image: false, caption: false, sticker: false, source: false, audio: false, music: false,
|
||||
};
|
||||
|
||||
export function useEditorUiState() {
|
||||
const [status, setStatus] = useState("ready");
|
||||
const [statusText, setStatusText] = useState("模型待命");
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [draggedAssetId, setDraggedAssetId] = useState("");
|
||||
const [assetDropTargetTrack, setAssetDropTargetTrack] = useState("");
|
||||
const [assetDropPosition, setAssetDropPosition] = useState({ track: "", percent: 50 });
|
||||
const [assetDropPulseTrack, setAssetDropPulseTrack] = useState("");
|
||||
const [assetDragPreview, setAssetDragPreview] = useState(null);
|
||||
const [selectedLibraryAssetId, setSelectedLibraryAssetId] = useState("");
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [exportProgress, setExportProgress] = useState(0);
|
||||
const [exportPhase, setExportPhase] = useState("");
|
||||
const [activeTool, setActiveTool] = useState("media");
|
||||
const [mediaTab, setMediaTab] = useState("upload");
|
||||
const [voiceTab, setVoiceTab] = useState("synthesis");
|
||||
const [voiceFilter, setVoiceFilter] = useState("all");
|
||||
const [showVoiceFilter, setShowVoiceFilter] = useState(false);
|
||||
const [ratioId, setRatioId] = useState("16:9");
|
||||
const [showRatioMenu, setShowRatioMenu] = useState(false);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const [showFileMenu, setShowFileMenu] = useState(false);
|
||||
const [compactRail, setCompactRail] = useState(false);
|
||||
const [selectedTrack, setSelectedTrack] = useState("image");
|
||||
const [timelineZoom, setTimelineZoom] = useState(0.25);
|
||||
const [trackVisibility, setTrackVisibility] = useState(DEFAULT_TRACK_VISIBILITY);
|
||||
const [trackLocks, setTrackLocks] = useState(DEFAULT_TRACK_LOCKS);
|
||||
const [timelineClipDrag, setTimelineClipDrag] = useState(null);
|
||||
const [snapGuide, setSnapGuide] = useState(null);
|
||||
|
||||
return {
|
||||
activeTool, assetDragPreview, assetDropPosition, assetDropPulseTrack,
|
||||
assetDropTargetTrack, compactRail, currentTime, draggedAssetId, exporting,
|
||||
exportPhase, exportProgress, isDragging, isPlaying, mediaTab, progress, ratioId,
|
||||
selectedLibraryAssetId, selectedTrack, setActiveTool, setAssetDragPreview,
|
||||
setAssetDropPosition, setAssetDropPulseTrack, setAssetDropTargetTrack, setCompactRail,
|
||||
setCurrentTime, setDraggedAssetId, setExporting, setExportPhase, setExportProgress,
|
||||
setIsDragging, setIsPlaying, setMediaTab, setProgress, setRatioId,
|
||||
setSelectedLibraryAssetId, setSelectedTrack, setShowFileMenu, setShowRatioMenu,
|
||||
setShowSettings, setShowVoiceFilter, setSnapGuide, setStatus, setStatusText,
|
||||
setTimelineClipDrag, setTimelineZoom, setTrackLocks, setTrackVisibility, setVoiceFilter,
|
||||
setVoiceTab, showFileMenu, showRatioMenu, showSettings, showVoiceFilter, snapGuide,
|
||||
status, statusText, timelineClipDrag, timelineZoom, trackLocks, trackVisibility,
|
||||
voiceFilter, voiceTab,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
export function useExportElapsed(exporting, startRef) {
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!exporting) return undefined;
|
||||
const update = () => setElapsed((performance.now() - (startRef.current || performance.now())) / 1000);
|
||||
update(); const timer = setInterval(update, 250); return () => clearInterval(timer);
|
||||
}, [exporting, startRef]);
|
||||
return elapsed;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useCallback } from "react";
|
||||
import { MAX_TIMELINE_DURATION_SECONDS, SUPPORTED_MEDIA_TYPES } from "../config/editor.js";
|
||||
import { decodeWaveform, extractVideoTrackFrames } from "../lib/media.js";
|
||||
import { formatClock, formatTime } from "../lib/timeline.js";
|
||||
|
||||
export function useFileUpload(deps) {
|
||||
return useCallback((files) => {
|
||||
const mediaFiles = Array.from(files ?? []).filter((file) => SUPPORTED_MEDIA_TYPES.some((type) => file.type.startsWith(type)));
|
||||
if (!mediaFiles.length) return void deps.notify("请选择图片、视频或音频素材");
|
||||
const assets = mediaFiles.map((file) => {
|
||||
const src = URL.createObjectURL(file); deps.imageUrlRefs.current.add(src);
|
||||
const type = file.type.startsWith("video/") ? "video" : file.type.startsWith("audio/") ? "audio" : "image";
|
||||
return { id: crypto.randomUUID(), type, src, name: file.name, meta: "读取中", blob: file,
|
||||
duration: type === "video" ? 0 : 4, width: 0, height: 0, trackFrames: [] };
|
||||
});
|
||||
const primary = assets[0]; deps.setSelectedLibraryAssetId(primary.id); deps.setUserAssets((current) => [...assets, ...current]);
|
||||
const update = (id, patch) => deps.setUserAssets((current) => current.map((item) => item.id === id ? { ...item, ...patch } : item));
|
||||
assets.forEach((asset) => {
|
||||
if (asset.type === "audio") {
|
||||
decodeWaveform(asset.blob, 96).then((decoded) => update(asset.id, { meta: `音频 · ${formatTime(decoded.duration)}`, duration: decoded.duration, peaks: decoded.peaks }))
|
||||
.catch(() => update(asset.id, { meta: "音频读取失败" }));
|
||||
return;
|
||||
}
|
||||
if (asset.type === "video") {
|
||||
const video = document.createElement("video"); video.preload = "metadata";
|
||||
video.onloadedmetadata = () => {
|
||||
const duration = Math.min(MAX_TIMELINE_DURATION_SECONDS, Math.max(0.5, video.duration || 1));
|
||||
const width = video.videoWidth || 0; const height = video.videoHeight || 0;
|
||||
const patch = { meta: `${width || "?"} x ${height || "?"} · ${formatClock(duration)}`, duration, width, height, type: "video" };
|
||||
update(asset.id, patch); deps.updateVisualAssetInTimeline(asset.id, patch);
|
||||
extractVideoTrackFrames(asset.src, { duration, width, height }).then((trackFrames) => {
|
||||
if (!trackFrames.length) return;
|
||||
update(asset.id, { trackFrames }); deps.updateVisualAssetInTimeline(asset.id, { trackFrames });
|
||||
}).catch((error) => console.warn("Video timeline frame extraction failed", error));
|
||||
};
|
||||
video.onerror = () => update(asset.id, { meta: "视频读取失败" }); video.src = asset.src; return;
|
||||
}
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
const patch = { meta: `${image.naturalWidth || 0} x ${image.naturalHeight || 0}`, width: image.naturalWidth || 0, height: image.naturalHeight || 0, type: "image" };
|
||||
update(asset.id, patch); deps.updateVisualAssetInTimeline(asset.id, patch);
|
||||
};
|
||||
image.onerror = () => update(asset.id, { meta: "读取失败" }); image.src = asset.src;
|
||||
});
|
||||
deps.notify(mediaFiles.length > 1 ? `已上传 ${mediaFiles.length} 个素材,拖到对应轨道后使用`
|
||||
: `${primary.type === "audio" ? "音频" : primary.type === "video" ? "视频" : "图片"}已上传到素材库,请拖到轨道使用`);
|
||||
}, [deps]);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useEffect } from "react";
|
||||
import { PLAYBACK_UI_FRAME_MS, getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack } from "../lib/editorRuntime.js";
|
||||
|
||||
export function useMediaSync(d) {
|
||||
useEffect(() => { d.audioSegments.forEach((s) => { const a = d.audioSegmentRefs.current.get(s.id); if (a) a.volume = getAudioSegmentPreviewVolume(s, d.currentTime); }); }, [d.audioSegments, d.currentTime]);
|
||||
useEffect(() => {
|
||||
if (!d.isPlaying || !d.trackVisibility.audio) return;
|
||||
d.audioSegments.forEach((s) => {
|
||||
const a = d.audioSegmentRefs.current.get(s.id); if (!a) return;
|
||||
const active = isTimelineTimeInsideTrack(d.currentTime, s.start, s.duration);
|
||||
if (active) { const expected = getTimelineTrackLocalTime(d.currentTime, s.start, s.duration); if (Math.abs(a.currentTime - expected) > 0.2) a.currentTime = expected; if (a.paused) a.play().catch(() => {}); }
|
||||
else if (!a.paused) a.pause();
|
||||
});
|
||||
}, [d.audioSegments, d.currentTime, d.isPlaying, d.trackVisibility.audio]);
|
||||
useEffect(() => { if (d.sourceAudioRef.current) d.sourceAudioRef.current.volume = d.sourceAudioVolume; }, [d.sourceAudioVolume, d.sourceAudioUrl]);
|
||||
useEffect(() => {
|
||||
const a = d.sourceAudioRef.current; if (!a || !d.sourceAudioUrl) return;
|
||||
const local = getTimelineTrackLocalTime(d.currentTime, d.sourceAudioStart, d.sourceAudioDuration);
|
||||
if (Math.abs(a.currentTime - local) > 0.22) a.currentTime = local;
|
||||
const play = d.isPlaying && d.trackVisibility.source && isTimelineTimeInsideTrack(d.currentTime, d.sourceAudioStart, d.sourceAudioDuration);
|
||||
if (play && a.paused) a.play().catch(() => {}); else if (!play && !a.paused) a.pause();
|
||||
}, [d.currentTime, d.isPlaying, d.sourceAudioDuration, d.sourceAudioStart, d.sourceAudioUrl, d.trackVisibility.source]);
|
||||
useEffect(() => { if (d.musicRef.current) d.musicRef.current.volume = d.musicVolume; }, [d.musicVolume, d.musicUrl]);
|
||||
useEffect(() => { d.currentTimeRef.current = d.currentTime; }, [d.currentTime]);
|
||||
useEffect(() => { d.setPreviewVideoMediaTime(d.previewVisualType === "video" ? Math.max(0, Number(d.previewVisualSegment?.sourceStart) || 0) : 0); }, [d.previewVisualSegment?.id, d.previewVisualSrc, d.previewVisualType]);
|
||||
useEffect(() => {
|
||||
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
|
||||
const max = Math.max(0, (Number(v.duration) || d.previewVisualSourceTime) - 0.001);
|
||||
const time = Math.min(Math.max(0, d.previewVisualSourceTime), max);
|
||||
if (Number.isFinite(time) && Math.abs(v.currentTime - time) > 0.2) { v.currentTime = time; d.setPreviewVideoMediaTime(time); }
|
||||
if (d.isPlaying && d.trackVisibility.image && v.paused) v.play().catch(() => {});
|
||||
}, [d.isPlaying, d.previewVisualSourceTime, d.previewVisualSrc, d.previewVisualType, d.trackVisibility.image]);
|
||||
useEffect(() => {
|
||||
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
|
||||
if (!d.isPlaying || !d.trackVisibility.image) v.pause(); else v.play().catch(() => {});
|
||||
}, [d.isPlaying, d.previewVisualSrc, d.previewVisualType, d.trackVisibility.image]);
|
||||
useEffect(() => {
|
||||
if (!d.isPlaying || d.estimatedDuration <= 0) return undefined;
|
||||
const start = d.currentTimeRef.current >= d.estimatedDuration - 0.02 ? 0 : Math.max(0, d.currentTimeRef.current);
|
||||
if (start !== d.currentTimeRef.current) { d.setCurrentTime(start); d.currentTimeRef.current = start; }
|
||||
d.visualPlaybackStartTimeRef.current = start; d.visualPlaybackStartedAtRef.current = performance.now(); d.visualPlaybackLastUpdateRef.current = 0;
|
||||
const tick = (now) => {
|
||||
const next = Math.min(d.estimatedDuration, d.visualPlaybackStartTimeRef.current + (now - d.visualPlaybackStartedAtRef.current) / 1000);
|
||||
d.currentTimeRef.current = next;
|
||||
if (now - d.visualPlaybackLastUpdateRef.current > PLAYBACK_UI_FRAME_MS || next >= d.estimatedDuration) { d.visualPlaybackLastUpdateRef.current = now; d.setCurrentTime(next); }
|
||||
if (next >= d.estimatedDuration) { d.pauseTimelineMedia(); d.setIsPlaying(false); d.visualPlaybackFrameRef.current = 0; return; }
|
||||
d.visualPlaybackFrameRef.current = requestAnimationFrame(tick);
|
||||
};
|
||||
d.visualPlaybackFrameRef.current = requestAnimationFrame(tick);
|
||||
return () => { if (d.visualPlaybackFrameRef.current) { cancelAnimationFrame(d.visualPlaybackFrameRef.current); d.visualPlaybackFrameRef.current = 0; } };
|
||||
}, [d.estimatedDuration, d.isPlaying]);
|
||||
useEffect(() => { d.setCurrentTime((time) => {
|
||||
const clamped = Math.min(time, d.timelineDuration);
|
||||
if (d.audioRef.current && clamped !== time) d.audioRef.current.currentTime = clamped;
|
||||
if (d.sourceAudioRef.current && clamped !== time) d.sourceAudioRef.current.currentTime = getTimelineTrackLocalTime(clamped, d.sourceAudioStart, d.sourceAudioDuration);
|
||||
if (d.musicRef.current && clamped !== time) d.musicRef.current.currentTime = clamped;
|
||||
return clamped;
|
||||
}); }, [d.timelineDuration, d.sourceAudioDuration, d.sourceAudioStart]);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useEffect, useState } from "react";
|
||||
export function usePreviewFrameSize(shellRef, ratio, compactRail) {
|
||||
const [size, setSize] = useState({ width: 0, height: 0 });
|
||||
useEffect(() => {
|
||||
const shell = shellRef.current;
|
||||
if (!shell) return undefined;
|
||||
const update = () => {
|
||||
const style = getComputedStyle(shell);
|
||||
const aw = Math.max(1, shell.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
|
||||
const ah = Math.max(1, shell.clientHeight - parseFloat(style.paddingTop || 0) - parseFloat(style.paddingBottom || 0));
|
||||
const width = Math.max(1, Math.floor(Math.min(aw, ah * ratio.width / ratio.height)));
|
||||
const height = Math.max(1, Math.floor(width * ratio.height / ratio.width));
|
||||
setSize((old) => old.width === width && old.height === height ? old : { width, height });
|
||||
};
|
||||
update();
|
||||
if (window.ResizeObserver) { const observer = new ResizeObserver(update); observer.observe(shell); return () => observer.disconnect(); }
|
||||
addEventListener("resize", update); return () => removeEventListener("resize", update);
|
||||
}, [compactRail, ratio.height, ratio.width, shellRef]);
|
||||
return size;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { getCaptionTextLayout } from "../lib/captionLayout.js";
|
||||
import {
|
||||
EMPTY_VISION_OPTIONS,
|
||||
getObjectPositionForCrop,
|
||||
isSameVisionDetection,
|
||||
} from "../lib/editorRuntime.js";
|
||||
import {
|
||||
getCaptionAvoidancePlacement,
|
||||
getSmartCropRect,
|
||||
mapNormalizedBoxToFrame,
|
||||
} from "../lib/visualGeometry.js";
|
||||
import { resolveVisionAnalysisAtTime } from "../lib/vision.js";
|
||||
|
||||
export function usePreviewModel(d) {
|
||||
const previewVisionAnalysis = useMemo(
|
||||
() => resolveVisionAnalysisAtTime(
|
||||
d.previewVisionBaseAnalysis,
|
||||
d.previewVisualType === "video" ? d.previewVideoMediaTime : d.previewVisualSourceTime,
|
||||
),
|
||||
[
|
||||
d.previewVideoMediaTime, d.previewVisionBaseAnalysis, d.previewVisualSourceTime,
|
||||
d.previewVisualType,
|
||||
],
|
||||
);
|
||||
const previewVisionOptions = d.previewVisionRecord?.options ?? EMPTY_VISION_OPTIONS;
|
||||
const previewVisionFrameSize = useMemo(() => ({
|
||||
width: d.previewFrameSize.width || d.ratio.width,
|
||||
height: d.previewFrameSize.height || d.ratio.height,
|
||||
}), [d.previewFrameSize.height, d.previewFrameSize.width, d.ratio.height, d.ratio.width]);
|
||||
const previewSmartCropRect = useMemo(() => {
|
||||
if (
|
||||
!previewVisionOptions.smartCrop ||
|
||||
!previewVisionAnalysis?.subject?.box ||
|
||||
!previewVisionAnalysis?.sourceSize
|
||||
) return null;
|
||||
return getSmartCropRect(
|
||||
previewVisionAnalysis.sourceSize,
|
||||
previewVisionFrameSize,
|
||||
previewVisionAnalysis.subject.box,
|
||||
{ padding: 0.14 },
|
||||
);
|
||||
}, [previewVisionAnalysis, previewVisionFrameSize, previewVisionOptions.smartCrop]);
|
||||
const previewVisionOverlayBoxes = useMemo(() => {
|
||||
if (!previewVisionOptions.showDetections || !previewVisionAnalysis?.sourceSize) return [];
|
||||
return (previewVisionAnalysis.detections ?? []).map((detection) => {
|
||||
const mapped = mapNormalizedBoxToFrame(
|
||||
detection.box,
|
||||
previewVisionAnalysis.sourceSize,
|
||||
previewVisionFrameSize,
|
||||
{
|
||||
fitMode: d.fitMode,
|
||||
smartCrop: previewSmartCropRect || false,
|
||||
outputSize: previewVisionFrameSize,
|
||||
},
|
||||
);
|
||||
if (!mapped?.normalized || mapped.width < 1 || mapped.height < 1) return null;
|
||||
return {
|
||||
...mapped.normalized,
|
||||
label: detection.label,
|
||||
score: detection.score,
|
||||
isSubject: isSameVisionDetection(detection, previewVisionAnalysis.subject),
|
||||
};
|
||||
}).filter(Boolean);
|
||||
}, [
|
||||
d.fitMode, previewSmartCropRect, previewVisionAnalysis, previewVisionFrameSize,
|
||||
previewVisionOptions.showDetections,
|
||||
]);
|
||||
const previewCaptionLayout = useMemo(() => getCaptionTextLayout({
|
||||
text: d.currentCaption,
|
||||
captionSize: d.captionSize,
|
||||
captionStyle: d.captionStyle,
|
||||
referenceFrame: previewVisionFrameSize,
|
||||
renderFrame: previewVisionFrameSize,
|
||||
}), [d.captionSize, d.captionStyle, d.currentCaption, previewVisionFrameSize]);
|
||||
const effectiveCaptionPlacement = useMemo(() => {
|
||||
if (
|
||||
!previewVisionOptions.avoidCaptions ||
|
||||
!previewVisionAnalysis?.subject?.box ||
|
||||
!previewVisionAnalysis?.sourceSize
|
||||
) return d.captionPlacement;
|
||||
return getCaptionAvoidancePlacement(previewVisionAnalysis.subject.box, {
|
||||
sourceSize: previewVisionAnalysis.sourceSize,
|
||||
frameSize: previewVisionFrameSize,
|
||||
fitMode: d.fitMode,
|
||||
smartCrop: previewSmartCropRect || false,
|
||||
basePlacement: d.captionPlacement,
|
||||
previousPlacement: d.captionPlacement,
|
||||
captionSize: {
|
||||
width: previewCaptionLayout.width / Math.max(1, previewVisionFrameSize.width),
|
||||
height: previewCaptionLayout.height,
|
||||
},
|
||||
safeMargin: 0.045,
|
||||
});
|
||||
}, [
|
||||
d.captionPlacement, d.fitMode, previewCaptionLayout, previewSmartCropRect,
|
||||
previewVisionAnalysis, previewVisionFrameSize, previewVisionOptions.avoidCaptions,
|
||||
]);
|
||||
const previewVisualRenderSrc =
|
||||
previewVisionOptions.removeBackground &&
|
||||
d.previewVisualType === "image" &&
|
||||
previewVisionAnalysis?.cutoutUrl
|
||||
? previewVisionAnalysis.cutoutUrl
|
||||
: d.previewVisualSrc;
|
||||
const previewVisionMaskUrl =
|
||||
previewVisionOptions.removeBackground && d.previewVisualType === "video"
|
||||
? previewVisionAnalysis?.cutoutUrl ?? ""
|
||||
: "";
|
||||
const previewVisualObjectFit = previewSmartCropRect ? "cover" : d.fitMode;
|
||||
const previewVisualObjectPosition = previewSmartCropRect
|
||||
? getObjectPositionForCrop(previewSmartCropRect)
|
||||
: "50% 50%";
|
||||
|
||||
return {
|
||||
effectiveCaptionPlacement, previewSmartCropRect, previewVisionAnalysis,
|
||||
previewVisionFrameSize, previewVisionMaskUrl, previewVisionOptions,
|
||||
previewVisionOverlayBoxes, previewVisualObjectFit, previewVisualObjectPosition,
|
||||
previewVisualRenderSrc,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useCallback } from "react";
|
||||
import { DEFAULT_SCRIPT, RATIO_OPTIONS, VOICES } from "../config/editor.js";
|
||||
import { decodeWaveform, downloadBlob } from "../lib/media.js";
|
||||
import { createProjectArchive, readProjectArchive, readProjectFileAsText } from "../lib/projectArchive.js";
|
||||
import { createCaptionSegments, getImageThumbnailCount, getVisualSegmentsTotal } from "../lib/timeline.js";
|
||||
|
||||
export function useProjectFiles(deps) {
|
||||
const getProjectSnapshot = useCallback(() => {
|
||||
const visualSegments = deps.visualSegments.map(({ blob, trackFrames, src, cutoutVisual, ...segment }) => segment);
|
||||
return {
|
||||
script: deps.script, selectedVoiceId: deps.selectedVoiceId, speed: deps.speed, volume: deps.volume,
|
||||
ratioId: deps.ratioId, fitMode: deps.fitMode, captionPosition: deps.captionPosition,
|
||||
captionPlacement: deps.captionPlacement, captionSize: deps.captionSize, captionStyle: deps.captionStyle,
|
||||
captionsEnabled: deps.captionsEnabled, captionSegments: deps.captionSegments, visualSegments,
|
||||
stickerSegments: deps.stickerSegments, selectedFilterId: deps.selectedFilterId,
|
||||
selectedTransitionId: deps.selectedTransitionId, selectedStickerId: deps.selectedStickerId,
|
||||
trackVisibility: deps.trackVisibility, timelineZoom: deps.timelineZoom, audioDuration: deps.audioDuration,
|
||||
musicName: deps.musicName, musicDuration: deps.musicDuration, musicVolume: deps.musicVolume,
|
||||
sourceAudioName: deps.sourceAudioName, sourceAudioDuration: deps.sourceAudioDuration,
|
||||
sourceAudioStart: deps.sourceAudioStart, sourceAudioVolume: deps.sourceAudioVolume,
|
||||
};
|
||||
}, [deps]);
|
||||
|
||||
const handleExportProject = useCallback(async () => {
|
||||
deps.setShowFileMenu(false);
|
||||
try {
|
||||
deps.notify("正在打包工程与媒体素材…");
|
||||
const archive = await createProjectArchive({
|
||||
project: getProjectSnapshot(), visualSegments: deps.visualSegments,
|
||||
audio: deps.audioBlob ? { blob: deps.audioBlob, name: "ai-voiceover" } : null,
|
||||
sourceAudio: deps.sourceAudioBlob ? { blob: deps.sourceAudioBlob, name: deps.sourceAudioName || "source-audio" } : null,
|
||||
music: deps.musicBlob ? { blob: deps.musicBlob, name: deps.musicName || "background-music" } : null,
|
||||
});
|
||||
downloadBlob(archive, "AI-配音项目.timeline");
|
||||
deps.notify("工程包已导出(含媒体素材)");
|
||||
} catch (error) { deps.notify(error instanceof Error ? `工程导出失败:${error.message}` : "工程导出失败"); }
|
||||
}, [deps, getProjectSnapshot]);
|
||||
|
||||
const handleNewProject = useCallback(() => {
|
||||
if (!window.confirm("新建工程将清空当前时间线,是否继续?")) return;
|
||||
deps.setScript(DEFAULT_SCRIPT); deps.setCaptionSegments(createCaptionSegments(DEFAULT_SCRIPT));
|
||||
deps.setSelectedSegmentId(""); deps.clearImageTrack(""); deps.clearAudioTrack("");
|
||||
deps.clearSourceAudioTrack(""); deps.clearMusicTrack(""); deps.setStickerSegments([]);
|
||||
deps.setSelectedStickerSegmentId(""); deps.clearAllVisionState(); deps.setCurrentTime(0);
|
||||
deps.setShowFileMenu(false); deps.notify("已新建空白工程");
|
||||
}, [deps]);
|
||||
|
||||
const handleImportProject = useCallback(async (file) => {
|
||||
if (!file) { deps.projectFileInputRef.current?.click(); return; }
|
||||
try {
|
||||
let archive;
|
||||
try { archive = await readProjectArchive(file); }
|
||||
catch (archiveError) {
|
||||
const legacy = JSON.parse(await readProjectFileAsText(file));
|
||||
if (legacy?.format !== "timeline-studio-project" || !legacy.project) throw archiveError;
|
||||
archive = { payload: { ...legacy, media: { visuals: [] } }, visualMedia: new Map(), audio: null, sourceAudio: null, music: null, legacy: true };
|
||||
}
|
||||
const { payload, visualMedia, audio, sourceAudio, music } = archive;
|
||||
const data = payload.project;
|
||||
deps.setScript(typeof data.script === "string" ? data.script : DEFAULT_SCRIPT);
|
||||
const captions = Array.isArray(data.captionSegments) ? data.captionSegments : createCaptionSegments(data.script || DEFAULT_SCRIPT);
|
||||
deps.setCaptionSegments(captions); deps.setSelectedSegmentId(captions[0]?.id ?? "");
|
||||
deps.setSelectedVoiceId(data.selectedVoiceId || VOICES[0].id); deps.setSpeed(Number(data.speed) || 1);
|
||||
deps.setVolume(Number(data.volume) || 1); deps.setRatioId(RATIO_OPTIONS.some((option) => option.id === data.ratioId) ? data.ratioId : "16:9");
|
||||
deps.setFitMode(data.fitMode || "contain"); deps.setCaptionPosition(data.captionPosition || "bottom");
|
||||
deps.setCaptionPlacement(data.captionPlacement || { x: 50, y: 78 }); deps.setCaptionSize(Number(data.captionSize) || 12);
|
||||
deps.setCaptionStyle(data.captionStyle || deps.captionStyle); deps.setCaptionsEnabled(data.captionsEnabled !== false);
|
||||
deps.setTrackVisibility(data.trackVisibility || deps.trackVisibility); deps.setTimelineZoom(Number(data.timelineZoom) || 1);
|
||||
deps.setSelectedFilterId(data.selectedFilterId || "none"); deps.setSelectedTransitionId(data.selectedTransitionId || "none");
|
||||
deps.setSelectedStickerId(data.selectedStickerId || "none"); deps.setStickerSegments(Array.isArray(data.stickerSegments) ? data.stickerSegments : []);
|
||||
const visuals = Array.isArray(data.visualSegments) ? data.visualSegments.map((segment) => {
|
||||
const media = visualMedia.get(segment.id);
|
||||
return media?.blob ? { ...segment, src: URL.createObjectURL(media.blob), blob: media.blob } : segment?.src ? segment : null;
|
||||
}).filter(Boolean) : [];
|
||||
visuals.filter((segment) => segment.src?.startsWith("blob:")).forEach((segment) => deps.imageUrlRefs.current.add(segment.src));
|
||||
deps.setVisualSegments(visuals); deps.setImageDuration(getVisualSegmentsTotal(visuals));
|
||||
deps.setImageClipCount(getImageThumbnailCount(getVisualSegmentsTotal(visuals))); deps.setCurrentVisualAsset(visuals[0] || null);
|
||||
if (audio) { const decoded = await decodeWaveform(audio); deps.replaceAudio(audio, Number(data.audioDuration) || decoded.duration, decoded.peaks, "已恢复工程配音"); } else deps.clearAudioTrack("");
|
||||
if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0); } else deps.clearSourceAudioTrack("");
|
||||
if (music) { const decoded = await decodeWaveform(music); deps.replaceMusic(music, Number(data.musicDuration) || decoded.duration, decoded.peaks, data.musicName || "background-music", ""); } else deps.clearMusicTrack("");
|
||||
deps.setMusicVolume(Number(data.musicVolume) || 0.35); deps.setSourceAudioVolume(Number(data.sourceAudioVolume) || 1);
|
||||
deps.setCurrentTime(0); deps.clearAllVisionState(); deps.setShowFileMenu(false);
|
||||
deps.notify(archive.legacy ? "旧版工程已导入;请重新添加未嵌入的本地媒体,然后导出为 .timeline 工程包" : "工程包已导入,媒体素材已恢复");
|
||||
} catch (error) { deps.notify(`无法读取工程文件${error instanceof Error && error.message ? `:${error.message}` : ""}`); }
|
||||
if (deps.projectFileInputRef.current) deps.projectFileInputRef.current.value = "";
|
||||
}, [deps]);
|
||||
|
||||
return { handleExportProject, handleImportProject, handleNewProject };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useCallback } from "react";
|
||||
import { decodeWaveform, extractAudioFromVideo } from "../lib/media.js";
|
||||
|
||||
export function useSourceAudioExtraction(d) {
|
||||
return useCallback(async (asset, timelineStart = 0) => {
|
||||
if (!asset?.blob) { d.clearSourceAudioTrack(null); d.notify("当前视频素材缺少原文件,无法分离原声"); return; }
|
||||
d.setStatus("generating"); d.setStatusText("加载 FFmpeg WASM 分离视频原声"); d.setProgress(12);
|
||||
try {
|
||||
const blob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
|
||||
const decoded = await decodeWaveform(blob, 96); if (!decoded.duration) throw new Error("视频没有可识别的音频轨");
|
||||
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart);
|
||||
} catch (error) {
|
||||
console.warn(error); d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
|
||||
d.setProgress(0); d.notify("视频画面已添加,但没有可分离的原声音轨");
|
||||
}
|
||||
}, [d]);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import {
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
DEFAULT_TIMELINE_DURATION_SECONDS,
|
||||
FILTER_OPTIONS,
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
RATIO_OPTIONS,
|
||||
STICKERS,
|
||||
VISUAL_STYLE_OPTIONS,
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import {
|
||||
estimateDuration,
|
||||
getCaptionTimeline,
|
||||
getSegmentIndexAtTime,
|
||||
getTimedSegmentIndexAtTime,
|
||||
getTimedSegmentsEnd,
|
||||
getVisualSegmentIndexAtTime,
|
||||
getVisualSegmentTimeline,
|
||||
} from "../lib/timeline.js";
|
||||
import { getVisionKey } from "../lib/vision.js";
|
||||
|
||||
export function useTimelineModel(d) {
|
||||
const selectedVoice = useMemo(
|
||||
() => VOICES.find((voice) => voice.id === d.selectedVoiceId) ?? VOICES[0],
|
||||
[d.selectedVoiceId],
|
||||
);
|
||||
const selectedAudioSegment =
|
||||
d.audioSegments.find((segment) => segment.id === d.selectedAudioSegmentId) ??
|
||||
d.audioSegments.at(-1) ??
|
||||
null;
|
||||
const audioBlob = selectedAudioSegment?.blob ?? null;
|
||||
const audioUrl = selectedAudioSegment?.url ?? "";
|
||||
const audioDuration = selectedAudioSegment?.duration ?? 0;
|
||||
const peaks = selectedAudioSegment?.peaks ?? [];
|
||||
const ratio = useMemo(
|
||||
() => RATIO_OPTIONS.find((option) => option.id === d.ratioId) ?? RATIO_OPTIONS[0],
|
||||
[d.ratioId],
|
||||
);
|
||||
const selectedFilter = useMemo(
|
||||
() => VISUAL_STYLE_OPTIONS.find((filter) => filter.id === d.selectedFilterId) ?? FILTER_OPTIONS[0],
|
||||
[d.selectedFilterId],
|
||||
);
|
||||
const selectedSticker = useMemo(
|
||||
() => STICKERS.find((sticker) => sticker.id === d.selectedStickerId) ?? STICKERS[0],
|
||||
[d.selectedStickerId],
|
||||
);
|
||||
const getStickerDragAsset = (sticker) => sticker?.id && sticker.id !== "none"
|
||||
? {
|
||||
...sticker,
|
||||
type: "sticker",
|
||||
meta: "贴纸",
|
||||
duration: DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
}
|
||||
: null;
|
||||
const segments = useMemo(
|
||||
() => d.captionSegments.map((segment) => segment.text),
|
||||
[d.captionSegments],
|
||||
);
|
||||
const voiceTrackDuration = useMemo(
|
||||
() => getTimedSegmentsEnd(d.audioSegments),
|
||||
[d.audioSegments],
|
||||
);
|
||||
const captionTargetDuration = voiceTrackDuration;
|
||||
const captionTimeline = useMemo(
|
||||
() => getCaptionTimeline(d.captionSegments, captionTargetDuration),
|
||||
[d.captionSegments, captionTargetDuration],
|
||||
);
|
||||
const captionDuration = captionTimeline.at(-1)?.end ?? 0;
|
||||
const visualTimeline = useMemo(
|
||||
() => getVisualSegmentTimeline(d.visualSegments),
|
||||
[d.visualSegments],
|
||||
);
|
||||
const stickerDuration = useMemo(
|
||||
() => getTimedSegmentsEnd(d.stickerSegments),
|
||||
[d.stickerSegments],
|
||||
);
|
||||
const estimatedDuration = useMemo(() => Math.max(
|
||||
voiceTrackDuration,
|
||||
captionDuration,
|
||||
d.sourceAudioBlob ? d.sourceAudioStart + d.sourceAudioDuration : 0,
|
||||
d.musicBlob ? d.musicDuration : 0,
|
||||
stickerDuration,
|
||||
estimateDuration(d.script),
|
||||
d.imageSrc ? d.imageDuration : 0,
|
||||
), [
|
||||
voiceTrackDuration, captionDuration, d.imageDuration, d.imageSrc, d.musicBlob,
|
||||
d.musicDuration, d.script, d.sourceAudioBlob, d.sourceAudioDuration,
|
||||
d.sourceAudioStart, stickerDuration,
|
||||
]);
|
||||
const timelineDuration = useMemo(() => Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(
|
||||
d.timelineHorizon,
|
||||
DEFAULT_TIMELINE_DURATION_SECONDS,
|
||||
Math.ceil((estimatedDuration + 1) / 10) * 10,
|
||||
),
|
||||
), [estimatedDuration, d.timelineHorizon]);
|
||||
d.timelineDurationRef.current = timelineDuration;
|
||||
|
||||
const currentSegmentIndex = getSegmentIndexAtTime(
|
||||
d.captionSegments,
|
||||
d.currentTime,
|
||||
captionTargetDuration,
|
||||
);
|
||||
const selectedSegmentIndex = Math.max(
|
||||
0,
|
||||
d.captionSegments.findIndex((segment) => segment.id === d.selectedSegmentId),
|
||||
);
|
||||
const focusedSegmentIndex = currentSegmentIndex >= 0
|
||||
? currentSegmentIndex
|
||||
: Math.max(0, selectedSegmentIndex);
|
||||
const currentCaptionSegment = currentSegmentIndex >= 0
|
||||
? d.captionSegments[currentSegmentIndex] ?? null
|
||||
: null;
|
||||
const selectedCaptionSegment =
|
||||
d.captionSegments.find((segment) => segment.id === d.selectedSegmentId) ??
|
||||
currentCaptionSegment;
|
||||
const currentCaption = currentCaptionSegment && !currentCaptionSegment.hidden
|
||||
? currentCaptionSegment.text
|
||||
: "";
|
||||
const currentStickerSegmentIndex = getTimedSegmentIndexAtTime(d.stickerSegments, d.currentTime);
|
||||
const currentStickerSegment = currentStickerSegmentIndex >= 0
|
||||
? d.stickerSegments[currentStickerSegmentIndex] ?? null
|
||||
: null;
|
||||
const selectedStickerSegmentIndex = Math.max(
|
||||
0,
|
||||
d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId),
|
||||
);
|
||||
const previewSticker = d.trackVisibility.sticker && currentStickerSegment
|
||||
? currentStickerSegment
|
||||
: d.stickerSegments.length
|
||||
? STICKERS[0]
|
||||
: selectedSticker;
|
||||
const currentVisualSegmentIndex = getVisualSegmentIndexAtTime(d.visualSegments, d.currentTime);
|
||||
const currentVisualSegment = currentVisualSegmentIndex >= 0
|
||||
? d.visualSegments[currentVisualSegmentIndex] ?? null
|
||||
: null;
|
||||
const currentVisualRange = currentVisualSegmentIndex >= 0
|
||||
? visualTimeline[currentVisualSegmentIndex] ?? null
|
||||
: null;
|
||||
const previewVisualSegmentIndex = currentVisualSegmentIndex >= 0
|
||||
? currentVisualSegmentIndex
|
||||
: d.visualSegments.length
|
||||
? d.currentTime >= d.imageDuration ? d.visualSegments.length - 1 : 0
|
||||
: -1;
|
||||
const previewVisualSegment = previewVisualSegmentIndex >= 0
|
||||
? d.visualSegments[previewVisualSegmentIndex] ?? null
|
||||
: null;
|
||||
const previewVisualRange = previewVisualSegmentIndex >= 0
|
||||
? visualTimeline[previewVisualSegmentIndex] ?? null
|
||||
: null;
|
||||
const previewVisualSrc = previewVisualSegment?.src || d.imageSrc;
|
||||
const previewVisualType = previewVisualSegment?.type || d.visualType;
|
||||
const activePreviewFilter = useMemo(
|
||||
() => VISUAL_STYLE_OPTIONS.find(
|
||||
(filter) => filter.id === (previewVisualSegment?.filterId || d.selectedFilterId),
|
||||
) ?? FILTER_OPTIONS[0],
|
||||
[previewVisualSegment?.filterId, d.selectedFilterId],
|
||||
);
|
||||
const previewVisualLocalTime = previewVisualRange
|
||||
? Math.max(0, d.currentTime - previewVisualRange.start)
|
||||
: d.currentTime;
|
||||
const previewVisualSourceTime = previewVisualType === "video"
|
||||
? Math.max(0, Number(previewVisualSegment?.sourceStart) || 0) + previewVisualLocalTime
|
||||
: previewVisualLocalTime;
|
||||
const previewVisionKey = getVisionKey(previewVisualSegment ?? (previewVisualSrc ? {
|
||||
id: "visual-fallback",
|
||||
src: previewVisualSrc,
|
||||
type: previewVisualType,
|
||||
width: previewVisualSegment?.width ?? 0,
|
||||
height: previewVisualSegment?.height ?? 0,
|
||||
} : null));
|
||||
const previewVisionRecord = previewVisionKey ? d.visionRecords[previewVisionKey] ?? null : null;
|
||||
const previewVisionBaseAnalysis = previewVisionRecord?.analysis ?? null;
|
||||
const selectedVisualSegmentIndex = Math.max(
|
||||
0,
|
||||
d.visualSegments.findIndex((segment) => segment.id === d.selectedVisualSegmentId),
|
||||
);
|
||||
const hasPlayableVisualTimeline = Boolean(
|
||||
previewVisualSrc && d.trackVisibility.image && d.imageDuration > 0,
|
||||
);
|
||||
const hasPlayableAudioTimeline = Boolean(
|
||||
(d.trackVisibility.audio && audioBlob && audioUrl) ||
|
||||
(d.trackVisibility.source && d.sourceAudioBlob && d.sourceAudioUrl) ||
|
||||
(d.trackVisibility.music && d.musicBlob && d.musicUrl),
|
||||
);
|
||||
|
||||
return {
|
||||
activePreviewFilter, audioBlob, audioDuration, audioUrl, canPreview:
|
||||
hasPlayableVisualTimeline || hasPlayableAudioTimeline,
|
||||
captionDuration, captionTargetDuration, captionTimeline, currentCaption,
|
||||
currentCaptionSegment, currentSegmentIndex, currentStickerSegment,
|
||||
currentStickerSegmentIndex, currentVisualRange, currentVisualSegment,
|
||||
currentVisualSegmentIndex, estimatedDuration, focusedSegmentIndex, getStickerDragAsset,
|
||||
peaks, previewSticker, previewVisionBaseAnalysis, previewVisionKey,
|
||||
previewVisionRecord, previewVisualLocalTime, previewVisualRange, previewVisualSegment,
|
||||
previewVisualSegmentIndex, previewVisualSourceTime, previewVisualSrc, previewVisualType,
|
||||
ratio, segments, selectedAudioSegment, selectedCaptionSegment, selectedFilter,
|
||||
selectedSegmentIndex, selectedSticker, selectedStickerSegmentIndex,
|
||||
selectedVisualSegmentIndex, selectedVoice, stickerDuration, timelineDuration, visualTimeline,
|
||||
voiceTrackDuration,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
export function useToast(timeout = 2600) {
|
||||
const [toast, setToast] = useState("");
|
||||
const timerRef = useRef(0);
|
||||
const notify = useCallback((message) => {
|
||||
setToast(message); clearTimeout(timerRef.current);
|
||||
timerRef.current = setTimeout(() => setToast(""), timeout);
|
||||
}, [timeout]);
|
||||
useEffect(() => () => clearTimeout(timerRef.current), []);
|
||||
return { notify, toast };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useCallback } from "react";
|
||||
import { downloadBlob, exportBrowserVideo, getSupportedRecordingFormat, transcodeWebmToMp4 } from "../lib/media.js";
|
||||
import { estimateDuration } from "../lib/timeline.js";
|
||||
import { getVisionKey } from "../lib/vision.js";
|
||||
|
||||
export function useVideoExport(d) {
|
||||
return useCallback(async () => {
|
||||
if (d.exporting) return;
|
||||
if (!d.imageSrc) return void d.notify("请先上传或选择图片/视频素材再导出");
|
||||
d.setExporting(true); d.exportStartRef.current = performance.now(); d.setExportProgress(1);
|
||||
d.setExportPhase("准备导出"); d.setStatus("generating");
|
||||
const format = getSupportedRecordingFormat(); d.setStatusText(`录制 ${format.label} 视频流`); d.setExportPhase(`录制 ${format.label} 视频流`);
|
||||
const progress = ({ progress, phase }) => {
|
||||
d.setExportProgress((current) => Math.max(current, Math.min(100, Math.max(0, Math.round(progress)))));
|
||||
if (phase) d.setExportPhase(phase);
|
||||
};
|
||||
const finish = async (phase) => { d.setExportPhase(phase); d.setExportProgress(100); await new Promise((resolve) => setTimeout(resolve, 450)); };
|
||||
try {
|
||||
const video = await exportBrowserVideo({
|
||||
imageSrc: d.imageSrc, visualType: d.visualType,
|
||||
visualSegments: d.renderedVisualSegments.map((segment) => {
|
||||
const record = d.visionRecords[getVisionKey(segment)];
|
||||
return record ? { ...segment, vision: { ...record.analysis, options: record.options } } : segment;
|
||||
}),
|
||||
audioBlob: null, voiceAudioSegments: d.trackVisibility.audio ? d.audioSegments : [], voiceVolume: d.volume,
|
||||
sourceAudioBlob: d.trackVisibility.source ? d.sourceAudioBlob : null, sourceAudioVolume: d.sourceAudioVolume,
|
||||
sourceAudioStart: d.sourceAudioStart, musicBlob: d.trackVisibility.music ? d.musicBlob : null,
|
||||
musicVolume: d.musicVolume, text: d.script, captionSegments: d.captionSegments,
|
||||
duration: Math.max(d.trackVisibility.audio ? d.voiceTrackDuration : 0, d.captionDuration,
|
||||
d.trackVisibility.source && d.sourceAudioBlob ? d.sourceAudioStart + d.sourceAudioDuration : 0,
|
||||
d.trackVisibility.music && d.musicBlob ? d.musicDuration : 0,
|
||||
d.trackVisibility.sticker ? d.stickerDuration : 0, d.imageDuration, estimateDuration(d.script)),
|
||||
ratio: d.ratio, fitMode: d.fitMode, filter: d.selectedFilter.css,
|
||||
captionsEnabled: d.captionsEnabled && d.trackVisibility.caption,
|
||||
captionPosition: d.captionPosition, captionPlacement: d.captionPlacement,
|
||||
captionSize: d.captionSize, captionStyle: d.captionStyle,
|
||||
captionReferenceSize: d.previewFrameSize.width > 0 && d.previewFrameSize.height > 0 ? d.previewFrameSize
|
||||
: { width: (360 * d.ratio.width) / d.ratio.height, height: 360 },
|
||||
sticker: d.stickerSegments.length ? null : d.selectedSticker,
|
||||
stickerSegments: d.trackVisibility.sticker ? d.stickerSegments : [],
|
||||
transitionId: d.selectedTransitionId, onProgress: progress,
|
||||
});
|
||||
const name = `ai-voiceover-${d.ratio.id.replace(":", "x")}`;
|
||||
if (video.nativeMp4) {
|
||||
progress({ progress: 98, phase: "保存 MP4 文件" }); downloadBlob(video.blob, `${name}.mp4`);
|
||||
d.setStatus("done"); d.setStatusText("MP4 已导出"); await finish("导出完成"); d.notify("已用浏览器原生 MP4 快速导出"); return;
|
||||
}
|
||||
d.setStatusText("当前浏览器不支持原生 MP4,加载 FFmpeg WASM"); progress({ progress: 95, phase: "加载 FFmpeg 转码器" });
|
||||
try {
|
||||
d.setStatusText("转码 MP4"); progress({ progress: 96, phase: "转码 MP4" });
|
||||
const mp4 = await transcodeWebmToMp4(video.blob); progress({ progress: 99, phase: "保存 MP4 文件" });
|
||||
downloadBlob(mp4, `${name}.mp4`); d.setStatus("done"); d.setStatusText("MP4 已导出"); await finish("导出完成"); d.notify("MP4 视频已导出");
|
||||
} catch (error) {
|
||||
console.error(error); progress({ progress: 99, phase: "保存 WebM 兜底文件" }); downloadBlob(video.blob, `${name}.webm`);
|
||||
d.setStatus("done"); d.setStatusText("WebM 兜底已导出"); await finish("WebM 兜底已导出"); d.notify("MP4 转码失败,已导出 WebM 兜底");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : "视频导出失败"); d.setExportPhase("导出失败");
|
||||
} finally { d.setExporting(false); d.setExportProgress(0); }
|
||||
}, [d]);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useCallback } from "react";
|
||||
import { DEFAULT_VISION_OPTIONS, revokeVisionObjectUrls } from "../lib/editorRuntime.js";
|
||||
import { analyzeVideoVisualTrack, analyzeVisualSubject, captureVisualFrame } from "../lib/vision.js";
|
||||
|
||||
export function useVisionAnalysis(deps) {
|
||||
return useCallback(async () => {
|
||||
if (!deps.previewVisualSrc || !deps.previewVisionKey) return void deps.notify("请先把图片或视频放到图片轨");
|
||||
if (deps.visionJob.running && deps.visionJob.key === deps.previewVisionKey) {
|
||||
deps.visionJobGenerationRef.current += 1;
|
||||
deps.visionAbortControllerRef.current?.abort(); deps.visionAbortControllerRef.current = null;
|
||||
deps.setVisionJob({ running: false, key: deps.previewVisionKey, progress: 0, phase: "分析已取消" });
|
||||
return void deps.notify("已取消当前视觉分析");
|
||||
}
|
||||
deps.visionAbortControllerRef.current?.abort();
|
||||
const controller = new AbortController(); deps.visionAbortControllerRef.current = controller;
|
||||
const generation = deps.visionJobGenerationRef.current + 1;
|
||||
deps.visionJobGenerationRef.current = generation;
|
||||
const key = deps.previewVisionKey; const type = deps.previewVisualType;
|
||||
deps.setVisionJob({ running: true, key, progress: 1, phase: type === "video" ? "准备分析整段视频" : "截取当前视觉画面" });
|
||||
try {
|
||||
const onProgress = ({ progress, phase }) => deps.setVisionJob((job) => job.key === key
|
||||
? { ...job, progress: Math.max(job.progress, progress), phase: phase || job.phase } : job);
|
||||
const source = deps.previewVisualSegment?.blob || deps.previewVisualSrc;
|
||||
let analysis; let objectUrls = [];
|
||||
if (type === "video") {
|
||||
const duration = Math.max(0.05, Number(deps.previewVideoRef.current?.duration) || Number(deps.previewVisualSegment?.duration) || 0.05);
|
||||
const result = await analyzeVideoVisualTrack({
|
||||
src: source, duration, includeMatting: true, fps: 2, maxSamples: 180,
|
||||
maxDimension: 512, threshold: 0.32,
|
||||
preferredLabels: ["person", "cat", "dog", "car", "bottle", "chair"],
|
||||
signal: controller.signal, onProgress,
|
||||
});
|
||||
const samples = result.samples.map(({ cutoutBlob, ...sample }) => {
|
||||
const cutoutUrl = cutoutBlob ? URL.createObjectURL(cutoutBlob) : "";
|
||||
if (cutoutUrl) objectUrls.push(cutoutUrl);
|
||||
return { ...sample, cutoutUrl };
|
||||
});
|
||||
analysis = { ...result, samples, analyzedAt: Date.now(), visualType: type };
|
||||
} else {
|
||||
const blob = await captureVisualFrame({ src: source, type, maxDimension: 1024, outputType: "image/png", quality: 0.92, signal: controller.signal });
|
||||
const result = await analyzeVisualSubject({
|
||||
blob, includeMatting: true, threshold: 0.32,
|
||||
preferredLabels: ["person", "cat", "dog", "car", "bottle", "chair"],
|
||||
signal: controller.signal, onProgress,
|
||||
});
|
||||
const cutoutUrl = result.cutoutBlob ? URL.createObjectURL(result.cutoutBlob) : "";
|
||||
if (cutoutUrl) objectUrls = [cutoutUrl];
|
||||
analysis = { ...result, cutoutUrl, analyzedAt: Date.now(), visualType: type };
|
||||
}
|
||||
if (controller.signal.aborted || generation !== deps.visionJobGenerationRef.current) return;
|
||||
revokeVisionObjectUrls(deps.visionObjectUrlsRef.current.get(key));
|
||||
deps.visionObjectUrlsRef.current.set(key, objectUrls);
|
||||
deps.setVisionRecords((records) => ({
|
||||
...records,
|
||||
[key]: { analysis, options: records[key]?.options ?? { ...DEFAULT_VISION_OPTIONS, removeBackground: false } },
|
||||
}));
|
||||
deps.setVisionJob({ running: false, key, progress: 100, phase: "视觉主体分析完成" });
|
||||
deps.notify(type === "image" ? "YOLOS tiny 主体识别与 MODNet 抠图已就绪" : `全视频分析完成:YOLOS + MODNet 已覆盖 ${analysis.samples.length} 个时序帧`);
|
||||
} catch (error) {
|
||||
if (error?.name === "AbortError") return;
|
||||
console.error(error);
|
||||
deps.setVisionJob({ running: false, key, progress: 0, phase: "视觉分析失败" });
|
||||
deps.notify(error?.message || "视觉主体分析失败,请重试");
|
||||
} finally {
|
||||
if (deps.visionAbortControllerRef.current === controller) {
|
||||
deps.visionAbortControllerRef.current = null;
|
||||
deps.setVisionJob((job) => job.running && job.key === key ? { ...job, running: false } : job);
|
||||
}
|
||||
}
|
||||
}, [deps]);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useState } from "react";
|
||||
|
||||
export function useVisualTrackState() {
|
||||
const [imageSrc, setImageSrc] = useState("");
|
||||
const [imageName, setImageName] = useState("");
|
||||
const [imageMeta, setImageMeta] = useState("");
|
||||
const [visualType, setVisualType] = useState("image");
|
||||
const [fitMode, setFitMode] = useState("contain");
|
||||
const [imageClipCount, setImageClipCount] = useState(0);
|
||||
const [imageDuration, setImageDuration] = useState(0);
|
||||
const [visualSegments, setVisualSegments] = useState([]);
|
||||
const [selectedVisualSegmentId, setSelectedVisualSegmentId] = useState("");
|
||||
const [selectedFilterId, setSelectedFilterId] = useState("none");
|
||||
const [selectedTransitionId, setSelectedTransitionId] = useState("none");
|
||||
const [selectedStickerId, setSelectedStickerId] = useState("none");
|
||||
const [stickerSegments, setStickerSegments] = useState([]);
|
||||
const [selectedStickerSegmentId, setSelectedStickerSegmentId] = useState("");
|
||||
|
||||
return {
|
||||
fitMode, imageClipCount, imageDuration, imageMeta, imageName, imageSrc,
|
||||
selectedFilterId, selectedStickerId, selectedStickerSegmentId,
|
||||
selectedTransitionId, selectedVisualSegmentId, setFitMode, setImageClipCount,
|
||||
setImageDuration, setImageMeta, setImageName, setImageSrc, setSelectedFilterId,
|
||||
setSelectedStickerId, setSelectedStickerSegmentId, setSelectedTransitionId,
|
||||
setSelectedVisualSegmentId, setStickerSegments, setVisualSegments, setVisualType,
|
||||
stickerSegments, visualSegments, visualType,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useCallback } from "react";
|
||||
import { MODEL_ID } from "../config/editor.js";
|
||||
import { clearPiperCacheIfStorageTight, isPiperSymbolError, isStorageQuotaError, prepareTextForVoice, TtsInputError } from "../lib/ttsText.js";
|
||||
|
||||
export function useVoiceGeneration(d) {
|
||||
return useCallback(async () => {
|
||||
const rawText = d.script.trim();
|
||||
if (!rawText || d.status === "generating" || d.status === "captioning") return;
|
||||
let prepared;
|
||||
try { prepared = prepareTextForVoice(rawText, d.selectedVoice); }
|
||||
catch (error) {
|
||||
const message = error instanceof TtsInputError ? d.t(error.code) : error instanceof Error ? error.message : d.t("ttsErrorVoiceMismatch");
|
||||
d.setStatus("error"); d.setStatusText(message); d.setProgress(0); d.notify(message); return;
|
||||
}
|
||||
d.setVoiceTab("synthesis"); d.setStatus("generating"); d.setStatusText(d.t("ttsStatusPreparingModel")); d.setProgress(6);
|
||||
if (prepared.warningKey) d.notify(d.t(prepared.warningKey));
|
||||
try {
|
||||
let blob;
|
||||
if (d.selectedVoice.engine === "piper") {
|
||||
const tts = await import("@diffusionstudio/vits-web");
|
||||
if (await clearPiperCacheIfStorageTight(tts)) d.notify(d.t("ttsNoticePiperCacheCleared"));
|
||||
d.setStatusText(d.t("ttsStatusLoadingChineseModel"));
|
||||
const progress = (event) => { if (event?.total) d.setProgress((current) => Math.max(current, Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))))); };
|
||||
const input = { text: prepared.text, voiceId: d.selectedVoice.id };
|
||||
try { blob = await tts.predict(input, progress); }
|
||||
catch (error) {
|
||||
if (!isStorageQuotaError(error)) throw error;
|
||||
d.setStatusText(d.t("ttsStatusClearingCache")); await tts.flush?.(); blob = await tts.predict(input, progress);
|
||||
}
|
||||
} else {
|
||||
const { KokoroTTS } = await import("kokoro-js"); d.setStatusText(d.t("ttsStatusLoadingKokoro"));
|
||||
const tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "q8", device: "wasm",
|
||||
progress_callback: (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); } });
|
||||
d.setStatusText(d.t("ttsStatusGeneratingEnglish"));
|
||||
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
|
||||
}
|
||||
d.setStatusText(d.t("ttsStatusDecodingWaveform"));
|
||||
await d.commitAudio(blob, `${d.selectedVoice.name} · ${d.t("ttsGenerated")}`); d.notify(d.t("ttsNoticeGenerated"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
const message = error instanceof TtsInputError ? d.t(error.code)
|
||||
: d.selectedVoice.engine === "piper" && isPiperSymbolError(error) ? d.t("ttsErrorUnsupportedPiperSymbols")
|
||||
: isStorageQuotaError(error) ? d.t("ttsErrorStorageQuota") : error instanceof Error ? error.message : d.t("ttsErrorGenerationFailed");
|
||||
d.setStatus("error"); d.setStatusText(message); d.setProgress(0); d.notify(message);
|
||||
}
|
||||
}, [d]);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useCallback } from "react";
|
||||
import { decodeWaveform, getAudioRecordingFormat } from "../lib/media.js";
|
||||
import { formatSavedTime } from "../lib/timeline.js";
|
||||
|
||||
export function useVoiceRecorder(d) {
|
||||
const commitRecording = useCallback(async (blob, extension = "webm") => {
|
||||
d.setRecordingState("processing"); d.setStatus("generating"); d.setStatusText(d.t("recording")); d.setProgress(72);
|
||||
try {
|
||||
const decoded = await decodeWaveform(blob); const createdAt = formatSavedTime();
|
||||
const recording = { id: crypto.randomUUID(), blob, name: `${d.t("recordVoice")} ${createdAt}`,
|
||||
duration: decoded.duration, peaks: decoded.peaks, createdAt, extension };
|
||||
d.replaceAudio(blob, decoded.duration, decoded.peaks, d.t("recordingReady"));
|
||||
d.setRecordedVoices((items) => [recording, ...items.slice(0, 8)]);
|
||||
d.setSelectedTrack("audio"); d.setActiveTool("audio"); d.setVoiceTab("mine"); d.notify(d.t("recordingReady"));
|
||||
} catch (error) {
|
||||
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : d.t("recordingPermissionDenied"));
|
||||
d.notify(d.t("recordingPermissionDenied"));
|
||||
} finally { d.setRecordingState("idle"); d.setProgress(0); }
|
||||
}, [d]);
|
||||
const startVoiceRecording = useCallback(async () => {
|
||||
if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") return void d.notify(d.t("recordingUnsupported"));
|
||||
if (d.recordingState === "recording") return;
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
|
||||
const format = getAudioRecordingFormat();
|
||||
const recorder = format?.mimeType ? new MediaRecorder(stream, { mimeType: format.mimeType }) : new MediaRecorder(stream);
|
||||
d.voiceRecorderStreamRef.current = stream; d.voiceRecorderChunksRef.current = []; d.voiceRecorderRef.current = recorder;
|
||||
d.voiceRecorderStartedAtRef.current = performance.now(); d.setRecordingElapsed(0); d.setRecordingState("recording");
|
||||
d.setStatus("generating"); d.setStatusText(d.t("recording")); d.setProgress(0);
|
||||
d.setSelectedTrack("audio"); d.setActiveTool("audio"); d.setVoiceTab("mine");
|
||||
recorder.ondataavailable = (event) => { if (event.data?.size) d.voiceRecorderChunksRef.current.push(event.data); };
|
||||
recorder.onstop = () => {
|
||||
const blob = new Blob(d.voiceRecorderChunksRef.current, { type: recorder.mimeType || format?.mimeType || "audio/webm" });
|
||||
stream.getTracks().forEach((track) => track.stop()); d.voiceRecorderStreamRef.current = null; d.voiceRecorderRef.current = null;
|
||||
clearInterval(d.voiceRecorderTimerRef.current); d.voiceRecorderTimerRef.current = 0;
|
||||
d.setRecordingElapsed((performance.now() - d.voiceRecorderStartedAtRef.current) / 1000);
|
||||
if (blob.size > 0) void commitRecording(blob, format?.extension ?? "webm");
|
||||
else { d.setRecordingState("idle"); d.notify(d.t("recordingPermissionDenied")); }
|
||||
};
|
||||
recorder.start(250);
|
||||
d.voiceRecorderTimerRef.current = setInterval(() => d.setRecordingElapsed((performance.now() - d.voiceRecorderStartedAtRef.current) / 1000), 250);
|
||||
} catch (error) {
|
||||
console.error(error); d.setRecordingState("idle"); d.setStatus("error"); d.setStatusText(d.t("recordingPermissionDenied")); d.notify(d.t("recordingPermissionDenied"));
|
||||
d.voiceRecorderStreamRef.current?.getTracks().forEach((track) => track.stop()); d.voiceRecorderStreamRef.current = null;
|
||||
}
|
||||
}, [commitRecording, d]);
|
||||
const stopVoiceRecording = () => {
|
||||
const recorder = d.voiceRecorderRef.current; if (!recorder || recorder.state === "inactive") return;
|
||||
d.setRecordingState("processing"); recorder.stop();
|
||||
};
|
||||
const useRecordedVoice = (recording) => {
|
||||
d.replaceAudio(recording.blob, recording.duration, recording.peaks, recording.name);
|
||||
d.setSelectedTrack("audio"); d.setActiveTool("audio"); d.setVoiceTab("mine"); d.notify(d.t("recordingReady"));
|
||||
};
|
||||
return { startVoiceRecording, stopVoiceRecording, useRecordedVoice };
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?u
|
||||
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
|
||||
|
||||
import { LIVE_PORTRAIT_WEB_MODEL, getLivePortraitModelUrl } from "../config/livePortrait.js";
|
||||
import { evaluateLivePortraitFrameQuality } from "../lib/livePortraitQuality.ts";
|
||||
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
@@ -406,13 +407,18 @@ async function generateVideo({
|
||||
const reference = previousFramePixels || portraitPixels;
|
||||
const referenceDims = previousFrameDims || [1, 3, 256, 256];
|
||||
const distance = sampledFrameDistance(pixels, dims, reference, referenceDims);
|
||||
const threshold = previousFramePixels ? 0.22 : 0.34;
|
||||
disposeOutputs(generated);
|
||||
if (distance <= threshold) {
|
||||
const frameQuality = evaluateLivePortraitFrameQuality(
|
||||
pixels,
|
||||
distance,
|
||||
Boolean(previousFramePixels),
|
||||
);
|
||||
if (frameQuality.accepted) {
|
||||
acceptedPixels = pixels;
|
||||
acceptedDims = dims;
|
||||
break;
|
||||
}
|
||||
console.warn("LivePortrait generated frame rejected", frameQuality);
|
||||
postProgress(68 + (outputFrame / frameCount) * 31, "avatarProgressRetryCorruptFrame", { current: outputFrame + 1, total: frameCount, attempt: attempt + 1 });
|
||||
}
|
||||
postProgress(68 + (outputFrame / frameCount) * 31, "avatarProgressKeyframe", { current: outputFrame + 1, total: frameCount, seconds: (inferenceMs / 1000).toFixed(1) });
|
||||
|
||||
Reference in new issue
Block a user