release Timeline Studio v0.4.1
This commit is contained in:
1 parent
47d5f6315d
commit
20e9f265d8
46 files changed
+2666
-202
No files matched your search
+55
-17
@@ -7,6 +7,8 @@ import { Timeline } from "./components/Timeline.jsx";
|
||||
import { Topbar } from "./components/Topbar.jsx";
|
||||
import { AssetDragPreview, ExportProgressOverlay } from "./components/EditorOverlays.jsx";
|
||||
import { EditorSidebar } from "./components/EditorSidebar.jsx";
|
||||
import { FirstVisualGuide } from "./components/FirstVisualGuide.jsx";
|
||||
import { hasSeenFirstVisualGuide, markFirstVisualGuideSeen } from "./lib/firstVisualGuide.js";
|
||||
import { useExportElapsed } from "./hooks/useExportElapsed.js";
|
||||
import { usePreviewFrameSize } from "./hooks/usePreviewFrameSize.js";
|
||||
import { useEditorCatalog } from "./hooks/useEditorCatalog.js";
|
||||
@@ -68,6 +70,8 @@ export function App() {
|
||||
const [captionVoiceFocusRequest, setCaptionVoiceFocusRequest] = useState(0);
|
||||
const [selectedSourceAudioSegmentId, setSelectedSourceAudioSegmentId] = useState("");
|
||||
const [canvasVisualTarget, setCanvasVisualTarget] = useState("");
|
||||
const [showFirstVisualGuide, setShowFirstVisualGuide] = useState(false);
|
||||
const firstVisualGuideShownRef = useRef(false);
|
||||
const timelineImportRestoreRef = useRef(false);
|
||||
const [introClosing, setIntroClosing] = useState(false);
|
||||
const {
|
||||
@@ -77,11 +81,11 @@ export function App() {
|
||||
setCaptionsEnabled, setScript, setSelectedSegmentId,
|
||||
} = useCaptionState();
|
||||
const {
|
||||
audioSegments, favoriteVoiceIds, historyItems, musicBlob, musicDuration, musicName, musicStart,
|
||||
audioSegments, favoriteVoiceIds, historyItems, musicBlob, musicDuration, musicName, musicSegments, musicStart,
|
||||
musicPeaks, musicUrl, musicVolume, recordedVoices, recordingElapsed, recordingState,
|
||||
selectedAudioSegmentId, selectedVoiceId, setAudioSegments, setFavoriteVoiceIds,
|
||||
setHistoryItems, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks, setMusicStart,
|
||||
setMusicUrl, setMusicVolume, setRecordedVoices, setRecordingElapsed,
|
||||
setMusicSegments, setMusicUrl, setMusicVolume, setRecordedVoices, setRecordingElapsed,
|
||||
setRecordingState, setSelectedAudioSegmentId, setSelectedVoiceId, setSourceAudioBlob,
|
||||
setSourceAudioAssetId, setSourceAudioDuration, setSourceAudioLinked, setSourceAudioName, setSourceAudioPeaks, setSourceAudioStart,
|
||||
setSourceAudioUrl, setSourceAudioVolume, setSpeed, setTimelineHorizon, setVolume,
|
||||
@@ -178,6 +182,11 @@ export function App() {
|
||||
return activeLanguage !== "zh" && option?.nameEn ? option.nameEn : translateOptionName(activeLanguage, name);
|
||||
};
|
||||
const shouldShowLanguageIntro = !uiLanguage;
|
||||
const requestFirstVisualGuide = () => {
|
||||
if (firstVisualGuideShownRef.current || hasSeenFirstVisualGuide()) return;
|
||||
firstVisualGuideShownRef.current = true;
|
||||
setShowFirstVisualGuide(true);
|
||||
};
|
||||
|
||||
const linkedSourceAudioSegments = useMemo(
|
||||
() => sourceAudioLinked && sourceAudioBlob
|
||||
@@ -313,7 +322,8 @@ export function App() {
|
||||
previewVisualSourceTime, previewVisualSrc, previewVisualType, ratio,
|
||||
});
|
||||
|
||||
const { builtInAssets, filteredVoices } = useEditorCatalog(voiceFilter);
|
||||
const { builtInAssets, filteredVoices, libraryType, libraryQuery, setLibraryQuery,
|
||||
selectLibraryType, libraryStatus, libraryError, libraryProvider, assetDownloadStates, prefetchLibraryAsset } = useEditorCatalog(voiceFilter);
|
||||
|
||||
const {
|
||||
canDropAssetOnTrack, findAssetById, getActiveDraggedAsset, getDraggedAsset,
|
||||
@@ -322,7 +332,7 @@ export function App() {
|
||||
handleTrackAssetDragOver, triggerAssetDropPulse,
|
||||
} = createAssetDragControls({
|
||||
addStickerAssetToTimeline: (...args) => addStickerAssetToTimeline(...args), applyAssetToTrack: (...args) => applyAssetToTrack(...args), assetDropPulseTimerRef, builtInAssets, currentTime, draggedAssetId,
|
||||
draggedAssetIdRef, getStickerDragAsset, notify, pointerAssetDragRef,
|
||||
draggedAssetIdRef, getStickerDragAsset, notify, pointerAssetDragRef, prefetchAsset: prefetchLibraryAsset,
|
||||
setAssetDragPreview, setAssetDropPosition, setAssetDropPulseTrack,
|
||||
setAssetDropTargetTrack, setDraggedAssetId, setSelectedLibraryAssetId,
|
||||
setSelectedStickerId, setSelectedStickerSegmentId, suppressAssetClickRef,
|
||||
@@ -368,16 +378,27 @@ export function App() {
|
||||
currentTimeRef, imageDuration, imageSrc, musicBlob, musicDuration, musicRef,
|
||||
musicUrlRef, notify, script, selectedVoice, selectedVoiceId, setActiveTool,
|
||||
setAudioSegments, setCaptionSegments, setCurrentTime, setHistoryItems,
|
||||
setIsPlaying, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks,
|
||||
setIsPlaying, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks, setMusicSegments,
|
||||
setMusicStart, setMusicUrl, setProgress, setSelectedAudioSegmentId, setSelectedSegmentId,
|
||||
setSelectedTrack, setSourceAudioAssetId, setSourceAudioBlob, setSourceAudioDuration, setSourceAudioLinked, setSourceAudioName,
|
||||
setSourceAudioPeaks, setSourceAudioStart, setSourceAudioUrl, setSourceAudioVolume,
|
||||
setStatus, setStatusText, setTimelineHorizon, sourceAudioBlob, sourceAudioDuration,
|
||||
sourceAudioAssetId, sourceAudioRef, sourceAudioStart, sourceAudioUrlRef, t,
|
||||
});
|
||||
const { separateSourceVocals, vocalSeparationJob } = useVocalSeparation({
|
||||
sourceAudioBlob, sourceAudioName, replaceSourceAudio, replaceMusic, notify, t,
|
||||
const { separateAudioClipVocals, separateSourceVocals, vocalSeparationJob } = useVocalSeparation({
|
||||
sourceAudioBlob, sourceAudioName, replaceAudio, replaceSourceAudio, replaceMusic, notify, t,
|
||||
});
|
||||
const selectedSourceAudioPiece = linkedSourceAudioSegments.find((segment) => segment.id === selectedSourceAudioSegmentId) ?? null;
|
||||
const selectedAudioToolTarget = selectedTrack === "audio" && selectedAudioSegmentId && selectedAudioSegment
|
||||
? { blob: selectedAudioSegment.blob, name: selectedAudioSegment.name, start: selectedAudioSegment.start, sourceStart: selectedAudioSegment.sourceStart || 0, duration: selectedAudioSegment.duration, segmentId: selectedAudioSegment.id, track: "audio" }
|
||||
: selectedTrack === "music" && musicBlob
|
||||
? { blob: musicBlob, name: musicName || t("musicTrack"), start: musicStart, sourceStart: 0, duration: musicDuration, segmentId: musicSegments[0]?.id || "music-audio", track: "music" }
|
||||
: selectedTrack === "source" && sourceAudioBlob
|
||||
? { blob: sourceAudioBlob, name: sourceAudioName, start: selectedSourceAudioPiece?.start ?? sourceAudioStart, sourceStart: selectedSourceAudioPiece?.sourceStart ?? 0, duration: selectedSourceAudioPiece?.duration ?? sourceAudioDuration, segmentId: selectedSourceAudioSegmentId || "source-audio", track: "source" }
|
||||
: null;
|
||||
const separateSelectedAudioVocals = () => selectedAudioToolTarget?.track === "source"
|
||||
? separateSourceVocals()
|
||||
: selectedAudioToolTarget && separateAudioClipVocals(selectedAudioToolTarget);
|
||||
|
||||
const {
|
||||
chooseInterfaceLanguage, clearAllVisionState, selectTool, toggleTrackLock,
|
||||
@@ -510,8 +531,9 @@ export function App() {
|
||||
audioSegments, captionSegments, commitCaptionSegments, commitStickerSegments, commitVisualSegments,
|
||||
currentStickerSegmentIndex, currentTime, focusedSegmentIndex,
|
||||
getCurrentVisualAssetSnapshot, imageDuration, imageSrc, notify,
|
||||
musicBlob, musicDuration, musicPeaks, musicSegments, musicStart,
|
||||
selectedAudioSegmentId, selectedSegmentId, selectedSegmentIndex, selectedStickerSegmentId,
|
||||
setAudioSegments, setCaptionSegments, setSelectedAudioSegmentId,
|
||||
setAudioSegments, setCaptionSegments, setMusicSegments, setSelectedAudioSegmentId,
|
||||
selectedTrack, stickerSegments, trackLocks, visualSegments,
|
||||
});
|
||||
|
||||
@@ -544,7 +566,7 @@ export function App() {
|
||||
audioSegments, captionSegments, captionTargetDuration, estimatedDuration, notify, seekTo, setActiveTool,
|
||||
setAudioSegments, setCaptionSegments, setSelectedAudioSegmentId, setSelectedStickerId,
|
||||
setSelectedStickerSegmentId, setSelectedTrack, setStickerSegments, setTimelineHorizon,
|
||||
setMusicStart, setSourceAudioLinked, setSourceAudioStart, musicDuration, musicStart,
|
||||
setMusicStart, setSourceAudioLinked, setSourceAudioStart, musicDuration, musicSegments, musicStart, setMusicSegments,
|
||||
sourceAudioDuration, sourceAudioStart, stickerSegments, suppressTimelineClipClickRef, t, timelineDurationRef,
|
||||
trackLocks, trackScrollRef, pauseForTimelineEdit, visualSegments, setSnapGuide,
|
||||
});
|
||||
@@ -567,12 +589,13 @@ export function App() {
|
||||
notify, script, seekTo, setActiveTool, setCaptionSegments,
|
||||
setCaptionsEnabled, setProgress, setScript, setSelectedSegmentId,
|
||||
setSelectedTrack, setStatus, setStatusText, setTrackVisibility, sourceAudioBlob,
|
||||
sourceAudioStart, status, trackLocks, uiLanguage,
|
||||
sourceAudioStart, status, t, trackLocks, uiLanguage,
|
||||
});
|
||||
|
||||
const handleFiles = useFileUpload({
|
||||
appendVisualAssetToTimeline, imageUrlRefs, notify, setSelectedLibraryAssetId, setSelectedTrack, setUserAssets,
|
||||
updateVisualAssetInTimeline, visualSegments,
|
||||
onFirstVisualAutoAdded: requestFirstVisualGuide,
|
||||
});
|
||||
|
||||
const { deleteUserAsset, selectAsset } = createAssetLibraryActions({
|
||||
@@ -584,13 +607,13 @@ export function App() {
|
||||
});
|
||||
|
||||
const { applyAssetToTrack, handleTrackAssetDrop, handleVisualStyleDrop } = createAssetDropActions({
|
||||
addStickerAssetToTimeline, addVisualOverlay: (...args) => addVisualOverlay(...args), appendVisualAssetToTimeline, canDropAssetOnTrack,
|
||||
draggedAssetIdRef, extractVideoSourceAudio, getDraggedAsset, getTimelineDropPercent,
|
||||
notify, replaceAudio, selectAsset, setActiveTool, setAssetDropPosition,
|
||||
addStickerAssetToTimeline, addVisualOverlay: (...args) => addVisualOverlay(...args), appendVisualAssetToTimeline, canDropAssetOnTrack, clearImageTrack,
|
||||
draggedAssetIdRef, extractVideoSourceAudio, getDraggedAsset, getTimelineDropPercent, imageUrlRefs,
|
||||
notify, onFirstVisualDropped: requestFirstVisualGuide, replaceAudio, selectAsset, setActiveTool, setAssetDropPosition,
|
||||
setAssetDropTargetTrack, setDraggedAssetId, setSelectedFilterId,
|
||||
setSelectedLibraryAssetId, setSelectedTrack, setSelectedTransitionId,
|
||||
setSelectedVisualSegmentId, setVisualSegments, trackScrollRef, resolveVisualDropIntent,
|
||||
triggerAssetDropPulse,
|
||||
setSelectedVisualSegmentId, setVisualSegments, trackScrollRef, resolveVisualDropIntent, updateVisualAssetInTimeline,
|
||||
t, triggerAssetDropPulse, visualSegments,
|
||||
});
|
||||
const addVisualOverlay = (asset, options = {}) => {
|
||||
if (!asset?.src || (asset.type !== "image" && asset.type !== "video")) return;
|
||||
@@ -743,6 +766,8 @@ export function App() {
|
||||
estimatedDuration, fileInputRef, generateCaptionsFromSourceAudio, handleAssetClick,
|
||||
handleAssetPointerDown, handleCaptionPositionChange, handleFiles, handleStickerClick,
|
||||
imageSrc, isDragging, mediaTab, musicBlob, musicDuration, musicName, musicVolume,
|
||||
libraryType, libraryQuery, setLibraryQuery, selectLibraryType, libraryStatus, libraryError, libraryProvider,
|
||||
assetDownloadStates, prefetchLibraryAsset,
|
||||
notify, openAvatarPanel, previewVisionAnalysis, previewVisionKey, smartMode, setSmartMode,
|
||||
previewVisionOptions, previewVisualSrc, previewVisualType, progress, script,
|
||||
seekTo, segments, selectTool, selectedCaptionSegment, selectedFilterId,
|
||||
@@ -751,7 +776,7 @@ export function App() {
|
||||
setMediaTab, setMusicVolume, setSelectedAudioSegmentId, setSelectedFilterId, setSelectedSegmentId,
|
||||
setSelectedStickerId, setSelectedTrack, setSelectedTransitionId, setSourceAudioVolume, setVoiceTab,
|
||||
sourceAudioBlob, sourceAudioDuration, sourceAudioLinked, sourceAudioName, sourceAudioVolume, status, t,
|
||||
separateSourceVocals, vocalSeparationJob,
|
||||
selectedAudioToolTarget, separateSelectedAudioVocals, separateSourceVocals, vocalSeparationJob,
|
||||
toggleCaptionSegmentHidden, toggleVisionOption, trOption, updateCaptionSegmentText,
|
||||
updateScript, userAssets, visionJob,
|
||||
selectedVisualSegment, visualLocalTime, updateSelectedVisualEffects,
|
||||
@@ -1022,6 +1047,9 @@ export function App() {
|
||||
builtInImageCaptionAvailable={autoEdit.support.availability === "available"}
|
||||
generateImageCaption={autoEdit.generateImageCaption}
|
||||
extractVideoSourceAudio={extractVideoSourceAudio}
|
||||
generateCaptionsFromAudioClip={generateCaptionsFromSourceAudio}
|
||||
separateAudioClipVocals={separateAudioClipVocals}
|
||||
audioProcessingBusy={vocalSeparationJob.running || status === "captioning"}
|
||||
setSelectedVisualSegmentId={setSelectedVisualSegmentId}
|
||||
seekTo={seekTo}
|
||||
suppressTimelineClipClickRef={suppressTimelineClipClickRef}
|
||||
@@ -1055,8 +1083,8 @@ export function App() {
|
||||
startAudioSegmentMove={startAudioSegmentMove}
|
||||
startSourceAudioMove={startSourceAudioMove}
|
||||
musicBlob={musicBlob}
|
||||
musicSegments={musicSegments}
|
||||
musicPeaks={musicPeaks}
|
||||
musicClipPercent={musicClipPercent}
|
||||
musicStartPercent={musicStartPercent}
|
||||
musicDuration={musicDuration}
|
||||
startMusicMove={startMusicMove}
|
||||
@@ -1064,6 +1092,16 @@ export function App() {
|
||||
|
||||
<AssetDragPreview preview={assetDragPreview} t={t} />
|
||||
<ExportProgressOverlay exporting={exporting} percent={exportPercent} phase={exportPhase} elapsedSeconds={exportElapsedSeconds} t={t} />
|
||||
{showFirstVisualGuide && !shouldShowLanguageIntro ? (
|
||||
<FirstVisualGuide
|
||||
language={activeLanguage}
|
||||
onClose={() => setShowFirstVisualGuide(false)}
|
||||
onComplete={() => {
|
||||
markFirstVisualGuideSeen();
|
||||
setShowFirstVisualGuide(false);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{shouldShowLanguageIntro ? (
|
||||
<LanguageIntro t={t} closing={introClosing} onChoose={chooseInterfaceLanguage} />
|
||||
) : null}
|
||||
|
||||
@@ -30,6 +30,15 @@ export function EditorSidebar({ model: d }) {
|
||||
handleFiles={d.handleFiles}
|
||||
imageSrc={d.imageSrc}
|
||||
builtInAssets={d.builtInAssets}
|
||||
libraryType={d.libraryType}
|
||||
libraryQuery={d.libraryQuery}
|
||||
setLibraryQuery={d.setLibraryQuery}
|
||||
selectLibraryType={d.selectLibraryType}
|
||||
libraryStatus={d.libraryStatus}
|
||||
libraryError={d.libraryError}
|
||||
libraryProvider={d.libraryProvider}
|
||||
assetDownloadStates={d.assetDownloadStates}
|
||||
prefetchLibraryAsset={d.prefetchLibraryAsset}
|
||||
userAssets={d.userAssets}
|
||||
selectedLibraryAssetId={d.selectedLibraryAssetId}
|
||||
deleteUserAsset={d.deleteUserAsset}
|
||||
@@ -86,6 +95,8 @@ export function EditorSidebar({ model: d }) {
|
||||
isGeneratingCaptions={d.status === "captioning"}
|
||||
automaticCaptionProgress={d.status === "captioning" ? d.progress : 0}
|
||||
separateSourceVocals={d.separateSourceVocals}
|
||||
selectedAudioToolTarget={d.selectedAudioToolTarget}
|
||||
separateSelectedAudioVocals={d.separateSelectedAudioVocals}
|
||||
vocalSeparationJob={d.vocalSeparationJob}
|
||||
hasVisual={Boolean(d.previewVisualSrc)}
|
||||
visualType={d.previewVisualType}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
import { ArrowsOutCardinal, Cursor, MouseRightClick, X } from "@phosphor-icons/react";
|
||||
|
||||
const COPY = {
|
||||
zh: { title: "两个常用操作", timeline: "在轨道片段上右键,可以打开剪切、复制、静音等快捷操作。", canvas: "点击画面后,可直接拖动位置,并用控制点缩放或旋转。", done: "知道了" },
|
||||
en: { title: "Two useful shortcuts", timeline: "Right-click a timeline clip to open quick actions such as cut, duplicate, and mute.", canvas: "Click the visual, then drag to move it or use the handles to resize and rotate.", done: "Got it" },
|
||||
ja: { title: "便利な2つの操作", timeline: "タイムラインのクリップを右クリックすると、カット、複製、ミュートなどを操作できます。", canvas: "画面をクリックしてドラッグすると移動でき、ハンドルで拡大縮小や回転ができます。", done: "わかりました" },
|
||||
ko: { title: "유용한 두 가지 조작", timeline: "타임라인 클립을 마우스 오른쪽 버튼으로 클릭하면 자르기, 복제, 음소거 등의 메뉴가 열립니다.", canvas: "화면을 클릭한 뒤 드래그해 이동하고 핸들로 크기와 회전을 조절하세요.", done: "확인" },
|
||||
es: { title: "Dos controles útiles", timeline: "Haz clic derecho en un clip para abrir acciones como cortar, duplicar y silenciar.", canvas: "Haz clic en la imagen y arrástrala; usa los controles para cambiar su tamaño o girarla.", done: "Entendido" },
|
||||
fr: { title: "Deux gestes utiles", timeline: "Faites un clic droit sur un clip pour accéder aux actions de coupe, duplication et sourdine.", canvas: "Cliquez sur l’image, puis faites-la glisser ou utilisez les poignées pour la redimensionner et la faire pivoter.", done: "Compris" },
|
||||
de: { title: "Zwei nützliche Aktionen", timeline: "Klicke mit der rechten Maustaste auf einen Clip, um Aktionen wie Schneiden, Duplizieren und Stummschalten zu öffnen.", canvas: "Klicke auf das Bild und ziehe es; mit den Griffen kannst du Größe und Drehung ändern.", done: "Verstanden" },
|
||||
pt: { title: "Dois controles úteis", timeline: "Clique com o botão direito em um clipe para abrir ações como cortar, duplicar e silenciar.", canvas: "Clique na imagem e arraste para mover; use as alças para redimensionar e girar.", done: "Entendi" },
|
||||
th: { title: "สองวิธีใช้งานที่มีประโยชน์", timeline: "คลิกขวาที่คลิปบนไทม์ไลน์เพื่อเปิดเมนูตัด ทำสำเนา และปิดเสียง", canvas: "คลิกภาพแล้วลากเพื่อย้าย หรือใช้จุดควบคุมเพื่อปรับขนาดและหมุน", done: "เข้าใจแล้ว" },
|
||||
vi: { title: "Hai thao tác hữu ích", timeline: "Nhấp chuột phải vào clip để mở các thao tác như cắt, nhân bản và tắt tiếng.", canvas: "Nhấp vào hình rồi kéo để di chuyển; dùng các tay nắm để đổi kích thước và xoay.", done: "Đã hiểu" },
|
||||
ru: { title: "Два полезных действия", timeline: "Щёлкните клип правой кнопкой мыши, чтобы открыть команды обрезки, дублирования и отключения звука.", canvas: "Нажмите на изображение и перетащите его; маркеры позволяют менять размер и поворот.", done: "Понятно" },
|
||||
};
|
||||
|
||||
function getTargetRect(selector) {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) return null;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return { top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom, width: rect.width, height: rect.height };
|
||||
}
|
||||
|
||||
export function FirstVisualGuide({ language = "zh", onClose, onComplete }) {
|
||||
const [targets, setTargets] = useState({ canvas: null, timeline: null });
|
||||
const copy = COPY[language] ?? COPY.en;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const update = () => setTargets({
|
||||
canvas: getTargetRect(".preview-frame"),
|
||||
timeline: getTargetRect('.image-clip[data-timeline-segment-track="image"]'),
|
||||
});
|
||||
const frame = requestAnimationFrame(update);
|
||||
window.addEventListener("resize", update);
|
||||
window.addEventListener("scroll", update, true);
|
||||
return () => { cancelAnimationFrame(frame); window.removeEventListener("resize", update); window.removeEventListener("scroll", update, true); };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const closeOnEscape = (event) => { if (event.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", closeOnEscape);
|
||||
return () => window.removeEventListener("keydown", closeOnEscape);
|
||||
}, [onClose]);
|
||||
|
||||
const timelineStyle = targets.timeline ? {
|
||||
left: Math.max(16, Math.min(window.innerWidth - 336, targets.timeline.left)),
|
||||
bottom: Math.max(16, window.innerHeight - targets.timeline.top + 14),
|
||||
} : undefined;
|
||||
const canvasStyle = targets.canvas ? {
|
||||
left: Math.max(16, Math.min(window.innerWidth - 336, targets.canvas.right + 14)),
|
||||
top: Math.max(70, Math.min(window.innerHeight - 160, targets.canvas.top + targets.canvas.height * 0.24)),
|
||||
} : undefined;
|
||||
|
||||
return (
|
||||
<div className="first-visual-guide" role="dialog" aria-modal="true" aria-labelledby="first-visual-guide-title">
|
||||
<button className="first-visual-guide-dismiss" type="button" aria-label={copy.done} onClick={onClose}><X size={18} /></button>
|
||||
<div className="first-visual-guide-heading">
|
||||
<strong id="first-visual-guide-title">{copy.title}</strong>
|
||||
<button type="button" onClick={onComplete}>{copy.done}</button>
|
||||
</div>
|
||||
{targets.canvas ? <div className="first-visual-guide-highlight is-canvas" style={{ left: targets.canvas.left - 5, top: targets.canvas.top - 5, width: targets.canvas.width + 10, height: targets.canvas.height + 10 }} /> : null}
|
||||
{targets.timeline ? <div className="first-visual-guide-highlight is-timeline" style={{ left: targets.timeline.left - 4, top: targets.timeline.top - 4, width: targets.timeline.width + 8, height: targets.timeline.height + 8 }} /> : null}
|
||||
{targets.canvas ? (
|
||||
<div className="first-visual-guide-demo is-transform" aria-hidden="true" style={{ left: targets.canvas.left, top: targets.canvas.top, width: targets.canvas.width, height: targets.canvas.height }}>
|
||||
<div className="first-visual-guide-demo-box"><i /><i /><i /><i /></div>
|
||||
<Cursor className="first-visual-guide-demo-cursor" size={27} weight="fill" />
|
||||
</div>
|
||||
) : null}
|
||||
{targets.timeline ? (
|
||||
<div className="first-visual-guide-demo is-context" aria-hidden="true" style={{ left: targets.timeline.left, top: targets.timeline.top, width: targets.timeline.width, height: targets.timeline.height }}>
|
||||
<MouseRightClick className="first-visual-guide-demo-mouse" size={29} weight="fill" />
|
||||
<span className="first-visual-guide-click-ring" />
|
||||
<div className="first-visual-guide-mini-menu"><i /><i /><i /></div>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="first-visual-guide-card is-canvas" style={canvasStyle}><ArrowsOutCardinal size={21} /><span>{copy.canvas}</span></div>
|
||||
<div className="first-visual-guide-card is-timeline" style={timelineStyle}><MouseRightClick size={21} /><span>{copy.timeline}</span></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { CaptionOverlay } from "./CaptionOverlay.jsx";
|
||||
import { IconButton } from "./ui.jsx";
|
||||
import { getVisualOverlayPixelBox, snapVisualOverlayTransform } from "../lib/visualOverlayTimeline.js";
|
||||
import { getAnchoredResize } from "../lib/anchoredResize.js";
|
||||
import { getVisualFitRect } from "../lib/visualGeometry.js";
|
||||
|
||||
export function PreviewStage({
|
||||
t,
|
||||
@@ -127,6 +128,25 @@ export function PreviewStage({
|
||||
transform: `translate(${visualTransform.x + visualAnimation.x}%, ${visualTransform.y + visualAnimation.y}%) scale(${visualTransform.scale * visualAnimation.scale}) rotate(${visualTransform.rotation}deg)`,
|
||||
opacity: visualTransform.opacity * visualAnimation.opacity,
|
||||
};
|
||||
const visualContentBox = activeObjectFit === "contain"
|
||||
? getVisualFitRect(
|
||||
{ width: visualEffects?.width, height: visualEffects?.height },
|
||||
{ width: frameWidth, height: frameHeight },
|
||||
"contain",
|
||||
)
|
||||
: { x: 0, y: 0, width: frameWidth, height: frameHeight };
|
||||
const hasVisualContentBox = visualContentBox.width > 0 && visualContentBox.height > 0;
|
||||
const transformBox = hasVisualContentBox
|
||||
? visualContentBox
|
||||
: { x: 0, y: 0, width: frameWidth, height: frameHeight };
|
||||
const visualTransformBoxStyle = {
|
||||
left: `${transformBox.x + transformBox.width / 2 + (visualTransform.x + visualAnimation.x) / 100 * frameWidth}px`,
|
||||
top: `${transformBox.y + transformBox.height / 2 + (visualTransform.y + visualAnimation.y) / 100 * frameHeight}px`,
|
||||
width: `${transformBox.width}px`,
|
||||
height: `${transformBox.height}px`,
|
||||
transform: `translate(-50%, -50%) scale(${visualTransform.scale * visualAnimation.scale}) rotate(${visualTransform.rotation}deg)`,
|
||||
opacity: visualTransform.opacity * visualAnimation.opacity,
|
||||
};
|
||||
const visualMaskStyle = {
|
||||
clipPath: ["rectangle", "rounded"].includes(visualMask.type) && !usesAlphaMask
|
||||
? `inset(${maskInsets.top}% ${maskInsets.right}% ${maskInsets.bottom}% ${maskInsets.left}%${visualMask.type === "rounded" ? ` round ${roundedRadius}px` : ""})`
|
||||
@@ -227,10 +247,10 @@ export function PreviewStage({
|
||||
});
|
||||
if (mode.startsWith("scale-")) {
|
||||
const handle = mode.slice(6);
|
||||
let candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: rect.width, height: rect.height }, transform: initial });
|
||||
let candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: transformBox.width, height: transformBox.height }, transform: initial });
|
||||
candidate = { ...candidate, scale: Math.max(0.1, Math.min(4, candidate.scale)) };
|
||||
const snapped = snapVisualScaleToFrameEdges(candidate, { width: rect.width, height: rect.height });
|
||||
candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: rect.width, height: rect.height }, transform: initial, scale: snapped.transform.scale });
|
||||
const snapped = snapVisualScaleToFrameEdges(candidate, { width: rect.width, height: rect.height }, 8, transformBox);
|
||||
candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: transformBox.width, height: transformBox.height }, transform: initial, scale: snapped.transform.scale });
|
||||
setOverlaySnapGuides(snapped.guides);
|
||||
onUpdateVisualTransform({ ...candidate, x: round(candidate.x), y: round(candidate.y), scale: round(candidate.scale) });
|
||||
}
|
||||
@@ -450,7 +470,7 @@ export function PreviewStage({
|
||||
</div>
|
||||
) : null}
|
||||
{renderedVisualSrc && trackVisibility.image && visualTransformEditable && (!visualMask.type || visualMask.type === "none") ? (
|
||||
<div className="visual-transform-box" style={visualTransformStyle} onPointerDown={(event) => startVisualTransform(event, "move")}>
|
||||
<div className="visual-transform-box" style={visualTransformBoxStyle} onPointerDown={(event) => startVisualTransform(event, "move")}>
|
||||
<span className="visual-transform-label">{t("visualBasic", "画面")}</span>
|
||||
<button className="visual-transform-rotate" type="button" aria-label={t("visualRotation", "旋转")} onPointerDown={(event) => startVisualTransform(event, "rotate")} />
|
||||
{['nw', 'ne', 'sw', 'se'].map((corner) => <button key={corner} className={`visual-transform-handle is-${corner}`} type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startVisualTransform(event, `scale-${corner}`)} />)}
|
||||
|
||||
+61
-27
@@ -7,6 +7,7 @@ import {
|
||||
CopySimple,
|
||||
Crop,
|
||||
CircleNotch,
|
||||
ClosedCaptioning,
|
||||
Eye,
|
||||
EyeSlash,
|
||||
LockKey,
|
||||
@@ -169,6 +170,9 @@ export function Timeline({
|
||||
builtInImageCaptionAvailable = false,
|
||||
generateImageCaption,
|
||||
extractVideoSourceAudio,
|
||||
generateCaptionsFromAudioClip,
|
||||
separateAudioClipVocals,
|
||||
audioProcessingBusy = false,
|
||||
setSelectedVisualSegmentId,
|
||||
seekTo,
|
||||
suppressTimelineClipClickRef,
|
||||
@@ -202,8 +206,8 @@ export function Timeline({
|
||||
startAudioSegmentMove,
|
||||
startSourceAudioMove,
|
||||
musicBlob,
|
||||
musicSegments = [],
|
||||
musicPeaks,
|
||||
musicClipPercent,
|
||||
musicStartPercent,
|
||||
musicDuration,
|
||||
startMusicMove,
|
||||
@@ -291,6 +295,13 @@ export function Timeline({
|
||||
const contextOverlaySegment = contextMenu?.track === "overlay" && contextMenu.segmentId
|
||||
? visualOverlaySegments.find((segment) => segment.id === contextMenu.segmentId)
|
||||
: null;
|
||||
const contextAudioSegment = contextMenu?.track === "audio" && contextMenu.segmentId
|
||||
? audioSegments.find((segment) => segment.id === contextMenu.segmentId)
|
||||
: null;
|
||||
const contextMusicSegment = contextMenu?.track === "music" && contextMenu.segmentId
|
||||
? (musicSegments.length ? musicSegments : [{ id: "music-audio", start: musicStartPercent / 100 * timelineDuration, duration: musicDuration, peaks: musicPeaks }])
|
||||
.find((segment) => segment.id === contextMenu.segmentId)
|
||||
: null;
|
||||
const trackTool = (track) => ({ image: "media", overlay: "media", sticker: "stickers", caption: "caption", source: "audio", audio: "audio", music: "audio" })[track] || "media";
|
||||
const openTrackPanel = (track) => {
|
||||
setSelectedTrack(track);
|
||||
@@ -1057,19 +1068,20 @@ export function Timeline({
|
||||
? Math.max(0.01, Math.min(100, ((promotionOverlay?.duration || 0.5) / timelineDuration) * 100))
|
||||
: 0;
|
||||
const videoTrackFrames = Array.isArray(segment.trackFrames) ? segment.trackFrames : [];
|
||||
const visibleVideoFrames =
|
||||
segmentType === "video" && videoTrackFrames.length
|
||||
? getSampledVideoFrames(
|
||||
videoTrackFrames,
|
||||
getTimelineThumbnailCount({
|
||||
duration: segment.duration,
|
||||
timelineDuration,
|
||||
contentWidth: rulerViewport.contentWidth,
|
||||
timelineZoom: localTimelineZoom,
|
||||
availableFrames: MAX_IMAGE_THUMBNAILS,
|
||||
}),
|
||||
)
|
||||
: [];
|
||||
const desiredVideoFrameCount = getTimelineThumbnailCount({
|
||||
duration: segment.duration,
|
||||
timelineDuration,
|
||||
contentWidth: rulerViewport.contentWidth,
|
||||
timelineZoom: localTimelineZoom,
|
||||
availableFrames: videoTrackFrames.length || MAX_IMAGE_THUMBNAILS,
|
||||
});
|
||||
const visibleVideoFrames = segmentType === "video"
|
||||
? videoTrackFrames.length
|
||||
? getSampledVideoFrames(videoTrackFrames, desiredVideoFrameCount)
|
||||
: segment.thumbnail
|
||||
? Array.from({ length: desiredVideoFrameCount }, () => segment.thumbnail)
|
||||
: []
|
||||
: [];
|
||||
const isPortraitVideo = segmentType === "video" && (segment.height || 0) > (segment.width || 0);
|
||||
|
||||
return (
|
||||
@@ -1091,8 +1103,10 @@ export function Timeline({
|
||||
isDraggingVisualSegment ? "is-reorder-dragging" : ""
|
||||
} ${isReorderTarget ? "is-reorder-target" : ""} ${
|
||||
isOverlayPromotionInsertTarget ? "is-overlay-promotion-insert-target" : ""
|
||||
}`}
|
||||
onPointerDown={(event) => startTimelineClipDrag(event, "image", segment.id, index)}
|
||||
} ${segment.preparing ? "is-preparing" : ""}`}
|
||||
onPointerDown={(event) => {
|
||||
if (!segment.preparing) startTimelineClipDrag(event, "image", segment.id, index);
|
||||
}}
|
||||
onContextMenu={(event) => showTrackContextMenu(event, "image", segment.id)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -1112,7 +1126,13 @@ export function Timeline({
|
||||
}
|
||||
}}
|
||||
>
|
||||
{segmentType === "video" ? (
|
||||
{segment.preparing ? (
|
||||
<div className="timeline-media-preparing" aria-live="polite">
|
||||
<i className="timeline-media-spinner" />
|
||||
<strong>{t("timelineMediaPreparing", "正在准备素材")}</strong>
|
||||
<em>{Math.round((segment.prepareProgress || 0) * 100)}%</em>
|
||||
</div>
|
||||
) : segmentType === "video" ? (
|
||||
<button
|
||||
className="clip-mute-toggle"
|
||||
type="button"
|
||||
@@ -1127,7 +1147,7 @@ export function Timeline({
|
||||
{segment.sourceAudioDisabled ? <SpeakerSlash size={13} /> : <SpeakerHigh size={13} />}
|
||||
</button>
|
||||
) : null}
|
||||
<div
|
||||
{!segment.preparing ? <div
|
||||
className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${
|
||||
isPortraitVideo ? "is-portrait-video" : ""
|
||||
}`}
|
||||
@@ -1166,9 +1186,9 @@ export function Timeline({
|
||||
),
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<span className="image-clip-duration">{formatClock(segment.duration)}</span>
|
||||
{!activeTimelineClipDrag ? (
|
||||
</div> : null}
|
||||
{!segment.preparing ? <span className="image-clip-duration">{formatClock(segment.duration)}</span> : null}
|
||||
{!segment.preparing && !activeTimelineClipDrag ? (
|
||||
<button
|
||||
className="image-resize-handle"
|
||||
type="button"
|
||||
@@ -1343,7 +1363,9 @@ export function Timeline({
|
||||
onPointerDown={startSourceAudioMove}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === "source") return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("source");
|
||||
setActiveTool("audio");
|
||||
clearClipSelections("source");
|
||||
setSelectedSourceAudioSegmentId(segment.id);
|
||||
}}
|
||||
@@ -1362,7 +1384,9 @@ export function Timeline({
|
||||
onPointerDown={startSourceAudioMove}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === "source") return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("source");
|
||||
setActiveTool("audio");
|
||||
clearClipSelections("source");
|
||||
setSelectedSourceAudioSegmentId("source-audio");
|
||||
}}
|
||||
@@ -1404,7 +1428,9 @@ export function Timeline({
|
||||
onContextMenu={(event) => showTrackContextMenu(event, "audio", segment.id)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === segment.id) return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("audio");
|
||||
setActiveTool("audio");
|
||||
clearClipSelections("voice");
|
||||
setSelectedAudioSegmentId(segment.id);
|
||||
seekTo(segment.start);
|
||||
@@ -1438,12 +1464,12 @@ export function Timeline({
|
||||
<div className="track-drop-hint">{t("dropMusicHere")}</div>
|
||||
) : null}
|
||||
{renderAssetDropSlot("music")}
|
||||
{musicBlob ? (
|
||||
<div className={`audio-clip is-music ${musicClipSelected ? "is-selected" : ""}`} style={{ width: `${musicClipPercent}%`, left: `${musicStartPercent}%` }} onPointerDown={startMusicMove} onContextMenu={(event) => showTrackContextMenu(event, "music", "music-audio")} onClick={(event) => { event.stopPropagation(); setSelectedTrack("music"); clearClipSelections("music"); setMusicClipSelected(true); }}>
|
||||
<WaveformStrip peaks={musicPeaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(musicDuration)}</span>
|
||||
{musicBlob ? (musicSegments.length ? musicSegments : [{ id: "music-audio", start: musicStartPercent / 100 * timelineDuration, duration: musicDuration, peaks: musicPeaks }]).map((segment) => (
|
||||
<div className={`audio-clip is-music ${musicClipSelected ? "is-selected" : ""}`} key={segment.id} style={{ width: `${timelineDuration > 0 ? segment.duration / timelineDuration * 100 : 0}%`, left: `${timelineDuration > 0 ? segment.start / timelineDuration * 100 : 0}%` }} onPointerDown={startMusicMove} onContextMenu={(event) => showTrackContextMenu(event, "music", segment.id)} onClick={(event) => { event.stopPropagation(); if (suppressTimelineClipClickRef.current === "music") return void (suppressTimelineClipClickRef.current = ""); setSelectedTrack("music"); setActiveTool("audio"); clearClipSelections("music"); setMusicClipSelected(true); }}>
|
||||
<WaveformStrip peaks={segment.peaks?.length ? segment.peaks : musicPeaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
)) : null}
|
||||
</button> : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1474,7 +1500,7 @@ export function Timeline({
|
||||
) : null}
|
||||
{contextMenu ? (
|
||||
<div className="timeline-context-menu" role="menu" aria-label={t("timelineContextMenu")} style={{ left: contextMenu.x, top: contextMenu.y }} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}<span>{t({ image: "imageTrack", overlay: "overlayTrack", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", voice: "voiceTrack", music: "musicTrack" }[contextMenu.track], contextMenu.track)}</span></div>
|
||||
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}<span>{t({ image: "imageTrack", overlay: "overlayTrack", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", audio: "voiceTrack", music: "musicTrack" }[contextMenu.track], contextMenu.track)}</span></div>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => openTrackPanel(contextMenu.track))}><SlidersHorizontal size={16} />{t("openTrackPanel")}</button>
|
||||
{contextMenu.kind === "clip" ? (
|
||||
<>
|
||||
@@ -1500,6 +1526,14 @@ export function Timeline({
|
||||
{contextMenu.track === "overlay" && contextOverlaySegment?.type === "video" ? (
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => setVisualOverlaySegments((items) => items.map((item) => item.id === contextOverlaySegment.id ? { ...item, muted: !item.muted } : item)))}>{contextOverlaySegment.muted ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextOverlaySegment.muted ? "unmuteClip" : "muteClip", contextOverlaySegment.muted ? "取消静音" : "静音")}</button>
|
||||
) : null}
|
||||
{contextMenu.track === "audio" && contextAudioSegment ? <>
|
||||
<button type="button" role="menuitem" disabled={audioProcessingBusy} onClick={() => runContextAction(() => separateAudioClipVocals?.({ blob: contextAudioSegment.blob, name: contextAudioSegment.name, start: contextAudioSegment.start, sourceStart: contextAudioSegment.sourceStart || 0, duration: contextAudioSegment.duration, segmentId: contextAudioSegment.id, track: "audio" }))}><Waveform size={16} />{t("separateVocalsFromClip")}</button>
|
||||
<button type="button" role="menuitem" disabled={audioProcessingBusy} onClick={() => runContextAction(() => generateCaptionsFromAudioClip?.({ blob: contextAudioSegment.blob, start: contextAudioSegment.start, sourceStart: contextAudioSegment.sourceStart || 0, duration: contextAudioSegment.duration, append: true }))}><ClosedCaptioning size={16} />{t("generateCaptionsFromClip")}</button>
|
||||
</> : null}
|
||||
{contextMenu.track === "music" && contextMusicSegment && musicBlob ? <>
|
||||
<button type="button" role="menuitem" disabled={audioProcessingBusy} onClick={() => runContextAction(() => separateAudioClipVocals?.({ blob: musicBlob, name: t("musicTrack"), start: contextMusicSegment.start, sourceStart: contextMusicSegment.sourceStart || 0, duration: contextMusicSegment.duration, segmentId: contextMusicSegment.id, track: "music" }))}><Waveform size={16} />{t("separateVocalsFromClip")}</button>
|
||||
<button type="button" role="menuitem" disabled={audioProcessingBusy} onClick={() => runContextAction(() => generateCaptionsFromAudioClip?.({ blob: musicBlob, start: contextMusicSegment.start, sourceStart: contextMusicSegment.sourceStart || 0, duration: contextMusicSegment.duration, append: true }))}><ClosedCaptioning size={16} />{t("generateCaptionsFromClip")}</button>
|
||||
</> : null}
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />{t("splitAtPlayhead")}</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleDuplicateTrack)}><CopySimple size={16} />{t("duplicateClip")}</button>
|
||||
<div className="timeline-context-divider" />
|
||||
|
||||
+232
-15
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createPortal, flushSync } from "react-dom";
|
||||
|
||||
import {
|
||||
BoundingBox,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
MicrophoneStage,
|
||||
MusicNote,
|
||||
Pause,
|
||||
PlayCircle,
|
||||
PersonSimpleRun,
|
||||
Scan,
|
||||
Scissors,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
Target,
|
||||
Trash,
|
||||
Waveform,
|
||||
X,
|
||||
} from "@phosphor-icons/react";
|
||||
|
||||
import {
|
||||
@@ -33,6 +35,7 @@ import {
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import { APP_LANGUAGES } from "../i18n.js";
|
||||
import { getRemoteAssetBlob } from "../lib/remoteAssetCache.js";
|
||||
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js";
|
||||
import { DEFAULT_VISUAL_ANIMATION_DURATION, normalizeVisualClipAnimation, VISUAL_CLIP_ANIMATION_OPTIONS } from "../lib/visualClipAnimations.js";
|
||||
@@ -80,6 +83,15 @@ export function MediaPanel({
|
||||
handleFiles,
|
||||
selectedLibraryAssetId,
|
||||
builtInAssets,
|
||||
libraryType,
|
||||
libraryQuery,
|
||||
setLibraryQuery,
|
||||
selectLibraryType,
|
||||
libraryStatus,
|
||||
libraryError,
|
||||
libraryProvider,
|
||||
assetDownloadStates,
|
||||
prefetchLibraryAsset,
|
||||
userAssets,
|
||||
deleteUserAsset,
|
||||
draggedAssetId,
|
||||
@@ -87,9 +99,27 @@ export function MediaPanel({
|
||||
handleAssetClick,
|
||||
}) {
|
||||
const assets = mediaTab === "library" ? builtInAssets : userAssets;
|
||||
const assetIntentTimerRef = useRef(null);
|
||||
const [previewAsset, setPreviewAsset] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!previewAsset) return undefined;
|
||||
const handleKeyDown = (event) => {
|
||||
if (event.key === "Escape") setPreviewAsset(null);
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [previewAsset]);
|
||||
|
||||
const openAssetPreview = (event, asset) => {
|
||||
handleAssetClick(event, asset);
|
||||
if (!event.defaultPrevented) setPreviewAsset(asset);
|
||||
};
|
||||
const renderAssetList = (items, { deletable = false } = {}) => (
|
||||
<div className={`asset-list ${mediaTab === "upload" ? "upload-assets" : ""}`}>
|
||||
{items.length ? (
|
||||
{libraryStatus === "loading" && mediaTab === "library" ? (
|
||||
<LibraryLoadingGrid label={t("libraryLoading")} />
|
||||
) : items.length ? (
|
||||
items.map((asset) => (
|
||||
<div
|
||||
className={`asset-row-wrap ${draggedAssetId === asset.id ? "is-dragging" : ""}`}
|
||||
@@ -99,9 +129,15 @@ export function MediaPanel({
|
||||
type="button"
|
||||
className="asset-row-button"
|
||||
onPointerDown={(event) => handleAssetPointerDown(event, asset)}
|
||||
onClick={(event) => handleAssetClick(event, asset)}
|
||||
onPointerEnter={() => {
|
||||
if (mediaTab !== "library") return;
|
||||
clearTimeout(assetIntentTimerRef.current);
|
||||
assetIntentTimerRef.current = setTimeout(() => void prefetchLibraryAsset?.(asset), 180);
|
||||
}}
|
||||
onPointerLeave={() => clearTimeout(assetIntentTimerRef.current)}
|
||||
onClick={(event) => openAssetPreview(event, asset)}
|
||||
>
|
||||
<AssetRow asset={asset} selected={asset.id === selectedLibraryAssetId} t={t} />
|
||||
<AssetRow asset={asset} selected={asset.id === selectedLibraryAssetId} t={t} downloadState={assetDownloadStates?.[asset.id]} />
|
||||
</button>
|
||||
{deletable ? (
|
||||
<button
|
||||
@@ -119,7 +155,7 @@ export function MediaPanel({
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="empty-state">{t("emptyAssets")}</div>
|
||||
<div className="empty-state">{mediaTab === "library" ? (libraryError || t("libraryEmpty")) : t("emptyAssets")}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -174,33 +210,206 @@ export function MediaPanel({
|
||||
|
||||
{renderAssetList(userAssets, { deletable: true })}
|
||||
</>
|
||||
) : mediaTab === "library" ? (
|
||||
<>
|
||||
<div className="library-type-tabs" role="tablist" aria-label={t("libraryMediaType")}>
|
||||
{["image", "video", "audio"].map((type) => (
|
||||
<button type="button" role="tab" aria-selected={libraryType === type} className={libraryType === type ? "is-active" : ""} key={type} onClick={() => selectLibraryType(type)}>
|
||||
{t(`library${type[0].toUpperCase()}${type.slice(1)}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<form className="library-search" onSubmit={(event) => event.preventDefault()}>
|
||||
<input value={libraryQuery} onChange={(event) => setLibraryQuery(event.target.value)} placeholder={t(libraryType === "audio" ? "librarySearchMusicPlaceholder" : "librarySearchPlaceholder")} aria-label={t(libraryType === "audio" ? "librarySearchMusicPlaceholder" : "librarySearchPlaceholder")} />
|
||||
</form>
|
||||
<div className="library-provider">{t("libraryProvidedBy")} <strong>{libraryProvider}</strong></div>
|
||||
{renderAssetList(assets)}
|
||||
</>
|
||||
) : (
|
||||
renderAssetList(assets, { deletable: mediaTab === "mine" })
|
||||
)}
|
||||
|
||||
{previewAsset ? createPortal(
|
||||
<AssetPreviewDialog asset={previewAsset} t={t} onClose={() => setPreviewAsset(null)} />,
|
||||
document.body,
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetRow({ asset, selected, t }) {
|
||||
function AssetPreviewDialog({ asset, t, onClose }) {
|
||||
const mediaSrc = asset.type === "image" ? (asset.originalSrc || asset.src) : (asset.previewSrc || asset.src);
|
||||
const [audioPreviewStatus, setAudioPreviewStatus] = useState(asset.type === "audio" ? "loading" : "ready");
|
||||
const [audioPreviewProgress, setAudioPreviewProgress] = useState(0);
|
||||
const [audioPreviewSrc, setAudioPreviewSrc] = useState(asset.type === "audio" && !/^https?:/i.test(mediaSrc) ? mediaSrc : "");
|
||||
const audioFallbacksRef = useRef([]);
|
||||
const audioFallbackIndexRef = useRef(-1);
|
||||
const tryNextAudioFallback = () => {
|
||||
const nextIndex = audioFallbackIndexRef.current + 1;
|
||||
const nextSrc = audioFallbacksRef.current[nextIndex];
|
||||
if (!nextSrc) {
|
||||
setAudioPreviewStatus("error");
|
||||
return;
|
||||
}
|
||||
audioFallbackIndexRef.current = nextIndex;
|
||||
setAudioPreviewStatus("loading");
|
||||
setAudioPreviewProgress(0.03);
|
||||
setAudioPreviewSrc(nextSrc);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (asset.type !== "audio" || !/^https?:/i.test(mediaSrc)) return undefined;
|
||||
let canceled = false;
|
||||
let objectUrl = "";
|
||||
setAudioPreviewStatus("loading");
|
||||
setAudioPreviewProgress(0);
|
||||
setAudioPreviewSrc("");
|
||||
audioFallbacksRef.current = [];
|
||||
audioFallbackIndexRef.current = -1;
|
||||
try {
|
||||
const sourceUrl = new URL(mediaSrc);
|
||||
const trackId = sourceUrl.searchParams.get("trackid");
|
||||
if (trackId && sourceUrl.hostname.endsWith("storage.jamendo.com")) {
|
||||
audioFallbacksRef.current = ["mp31", "ogg", "mp32"].map((format) => {
|
||||
const fallbackUrl = new URL(sourceUrl);
|
||||
fallbackUrl.searchParams.set("format", format);
|
||||
return fallbackUrl.toString();
|
||||
});
|
||||
} else {
|
||||
audioFallbacksRef.current = [mediaSrc];
|
||||
}
|
||||
} catch {
|
||||
audioFallbacksRef.current = [mediaSrc];
|
||||
}
|
||||
getRemoteAssetBlob({ ...asset, src: mediaSrc }, (progress) => {
|
||||
if (!canceled) setAudioPreviewProgress(Math.min(0.96, Math.max(0.01, progress || 0)));
|
||||
}).then((blob) => {
|
||||
if (canceled || !blob) return;
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setAudioPreviewProgress(0.98);
|
||||
setAudioPreviewSrc(objectUrl);
|
||||
}).catch((error) => {
|
||||
console.warn("Music preview download failed", error);
|
||||
if (!canceled) tryNextAudioFallback();
|
||||
});
|
||||
return () => {
|
||||
canceled = true;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
}, [asset, mediaSrc]);
|
||||
return (
|
||||
<div className="asset-preview-backdrop" onPointerDown={(event) => {
|
||||
if (event.target === event.currentTarget) onClose();
|
||||
}}>
|
||||
<section className="asset-preview-dialog" role="dialog" aria-modal="true" aria-labelledby="asset-preview-title">
|
||||
<header>
|
||||
<div>
|
||||
<span>{t("assetPreview", "素材预览")}</span>
|
||||
<strong id="asset-preview-title">{asset.name}</strong>
|
||||
</div>
|
||||
<button type="button" onClick={onClose} aria-label={t("closeAssetPreview", "关闭预览")}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</header>
|
||||
<div className={`asset-preview-media type-${asset.type}`}>
|
||||
{asset.type === "video" ? (
|
||||
<video key={mediaSrc} src={mediaSrc} poster={asset.thumbnail} controls autoPlay playsInline />
|
||||
) : asset.type === "audio" ? (
|
||||
<div className="asset-preview-audio">
|
||||
<MusicNote size={58} weight="duotone" />
|
||||
<strong>{asset.name}</strong>
|
||||
{audioPreviewStatus === "loading" ? (
|
||||
<div className="asset-preview-audio-loading" role="status" aria-live="polite">
|
||||
<i style={{ "--audio-preview-progress": `${Math.round(audioPreviewProgress * 100)}%` }}>
|
||||
<b>{Math.round(audioPreviewProgress * 100)}%</b>
|
||||
</i>
|
||||
<span>{t("audioPreviewLoading", "正在加载音乐预览…")}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{audioPreviewStatus === "error" ? (
|
||||
<div className="asset-preview-audio-error" role="alert">{t("audioPreviewFailed", "音乐预览加载失败,请稍后重试")}</div>
|
||||
) : null}
|
||||
{audioPreviewSrc ? <audio
|
||||
className={audioPreviewStatus === "ready" ? "is-ready" : "is-waiting"}
|
||||
key={audioPreviewSrc}
|
||||
src={audioPreviewSrc}
|
||||
controls
|
||||
autoPlay
|
||||
preload="metadata"
|
||||
onLoadedMetadata={() => setAudioPreviewProgress((progress) => Math.max(progress, 0.99))}
|
||||
onCanPlay={() => { setAudioPreviewProgress(1); setAudioPreviewStatus("ready"); }}
|
||||
onError={tryNextAudioFallback}
|
||||
/> : null}
|
||||
</div>
|
||||
) : (
|
||||
<img src={mediaSrc} alt={asset.name} />
|
||||
)}
|
||||
</div>
|
||||
{asset.meta ? <footer>{asset.meta}</footer> : null}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryLoadingGrid({ label }) {
|
||||
return (
|
||||
<div className="library-loading-grid" aria-label={label} aria-busy="true">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<div className="library-skeleton-card" key={index}>
|
||||
<div className="library-skeleton-thumb"><i /></div>
|
||||
<span /><small />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetRow({ asset, selected, t, downloadState }) {
|
||||
const [mediaLoaded, setMediaLoaded] = useState(asset.type === "audio");
|
||||
const [previewSrc, setPreviewSrc] = useState(asset.thumbnail || asset.src);
|
||||
useEffect(() => {
|
||||
setPreviewSrc(asset.thumbnail || asset.src);
|
||||
setMediaLoaded(asset.type === "audio");
|
||||
}, [asset.id, asset.src, asset.thumbnail, asset.type]);
|
||||
const handlePreviewError = () => {
|
||||
if (previewSrc !== asset.src) {
|
||||
setPreviewSrc(asset.src);
|
||||
return;
|
||||
}
|
||||
if (asset.originalSrc && previewSrc !== asset.originalSrc) {
|
||||
setPreviewSrc(asset.originalSrc);
|
||||
return;
|
||||
}
|
||||
setMediaLoaded(true);
|
||||
};
|
||||
return (
|
||||
<div className={`asset-card ${selected ? "is-selected" : ""}`}>
|
||||
<div className="asset-thumb">
|
||||
{!mediaLoaded ? <div className="asset-media-loading" aria-hidden="true"><i /></div> : null}
|
||||
{asset.type === "video" ? (
|
||||
<video src={asset.src} muted playsInline preload="metadata" draggable={false} />
|
||||
asset.thumbnail ? <img src={previewSrc} alt="" draggable={false} onLoad={() => setMediaLoaded(true)} onError={handlePreviewError} /> : <video src={asset.src} muted playsInline preload="metadata" draggable={false} onLoadedData={() => setMediaLoaded(true)} onError={() => setMediaLoaded(true)} />
|
||||
) : asset.type === "audio" ? (
|
||||
<div className="asset-audio-thumb">
|
||||
<MusicNote size={28} weight="duotone" />
|
||||
</div>
|
||||
) : (
|
||||
<img src={asset.src} alt="" draggable={false} />
|
||||
<img src={previewSrc} alt="" draggable={false} onLoad={() => setMediaLoaded(true)} onError={handlePreviewError} />
|
||||
)}
|
||||
<span>
|
||||
{asset.type === "audio"
|
||||
? t("assetAudio")
|
||||
? t(asset.kind === "music" ? "libraryAudio" : "assetAudio")
|
||||
: asset.type === "video"
|
||||
? t("assetVideo")
|
||||
: t("assetImage")}
|
||||
</span>
|
||||
{downloadState?.status === "loading" ? (
|
||||
<div className="asset-download-progress" aria-label={t("libraryPreparingAsset")}>
|
||||
<i style={{ "--asset-progress": `${Math.max(8, Math.round((downloadState.progress || 0) * 100))}%` }} />
|
||||
</div>
|
||||
) : downloadState?.status === "ready" ? <i className="asset-ready-dot" title={t("libraryAssetReady")} /> : null}
|
||||
<span className="asset-preview-hover" aria-hidden="true">
|
||||
<PlayCircle size={30} weight="fill" />
|
||||
<em>{t("assetPreview", "素材预览")}</em>
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>{asset.name}</strong>
|
||||
@@ -259,6 +468,8 @@ export function ToolPanel(props) {
|
||||
isGeneratingCaptions,
|
||||
automaticCaptionProgress,
|
||||
separateSourceVocals,
|
||||
selectedAudioToolTarget,
|
||||
separateSelectedAudioVocals,
|
||||
vocalSeparationJob,
|
||||
hasVisual,
|
||||
visualType,
|
||||
@@ -392,26 +603,32 @@ export function ToolPanel(props) {
|
||||
<button
|
||||
className="audio-entry-card separation-entry-card"
|
||||
type="button"
|
||||
disabled={!sourceAudioBlob || vocalSeparationJob.running}
|
||||
onClick={separateSourceVocals}
|
||||
disabled={!selectedAudioToolTarget || vocalSeparationJob.running}
|
||||
onClick={separateSelectedAudioVocals || separateSourceVocals}
|
||||
>
|
||||
<Waveform size={24} weight="duotone" />
|
||||
<span>
|
||||
<strong>{vocalSeparationJob.running ? t("vocalSeparationRunning") : t("vocalSeparationTitle")}</strong>
|
||||
<em>{sourceAudioBlob ? (vocalSeparationJob.phase || t("vocalSeparationDesc")) : t("vocalSeparationNeedsSource")}</em>
|
||||
<em>{selectedAudioToolTarget ? (vocalSeparationJob.phase || t("vocalSeparationDesc")) : t("vocalSeparationNeedsSource")}</em>
|
||||
</span>
|
||||
{vocalSeparationJob.running ? <span className="inline-progress" aria-hidden="true"><span style={{ width: `${vocalSeparationJob.progress}%` }} /></span> : null}
|
||||
</button>
|
||||
<button
|
||||
className="audio-entry-card caption-entry-card"
|
||||
type="button"
|
||||
disabled={!sourceAudioBlob || isGeneratingCaptions}
|
||||
onClick={generateCaptionsFromSourceAudio}
|
||||
disabled={!selectedAudioToolTarget || isGeneratingCaptions}
|
||||
onClick={() => selectedAudioToolTarget && generateCaptionsFromSourceAudio({
|
||||
blob: selectedAudioToolTarget.blob,
|
||||
start: selectedAudioToolTarget.start,
|
||||
sourceStart: selectedAudioToolTarget.sourceStart,
|
||||
duration: selectedAudioToolTarget.duration,
|
||||
append: selectedAudioToolTarget.track !== "source",
|
||||
})}
|
||||
>
|
||||
<ClosedCaptioning size={24} weight="duotone" />
|
||||
<span>
|
||||
<strong>{isGeneratingCaptions ? t("autoCaptionsRunning") : t("autoCaptionsTitle")}</strong>
|
||||
<em>{sourceAudioBlob ? t("autoCaptionsDesc") : t("autoCaptionsNeedsSource")}</em>
|
||||
<em>{selectedAudioToolTarget ? t("autoCaptionsDesc") : t("autoCaptionsNeedsSource")}</em>
|
||||
</span>
|
||||
{isGeneratingCaptions ? (
|
||||
<span className="inline-progress" aria-hidden="true">
|
||||
|
||||
@@ -154,6 +154,51 @@ export const VOICES = [
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/pt_BR-faber-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "ko_KR-mms-medium",
|
||||
name: "Minseo",
|
||||
language: "한국어",
|
||||
detail: "MMS VITS ONNX · 한국어",
|
||||
gender: "Natural voice",
|
||||
engine: "mms",
|
||||
badge: "ONNX",
|
||||
},
|
||||
{
|
||||
id: "ja_JP-supertonic-f1",
|
||||
name: "Hikari",
|
||||
language: "日本語",
|
||||
detail: "Supertonic 3 ONNX · 日本語",
|
||||
gender: "Natural female",
|
||||
engine: "supertonic",
|
||||
badge: "ONNX",
|
||||
},
|
||||
{
|
||||
id: "vi_VN-mms-medium",
|
||||
name: "Linh",
|
||||
language: "Tiếng Việt",
|
||||
detail: "MMS VITS ONNX · Tiếng Việt",
|
||||
gender: "Natural voice",
|
||||
engine: "mms",
|
||||
badge: "ONNX",
|
||||
},
|
||||
{
|
||||
id: "ru_RU-mms-medium",
|
||||
name: "Irina",
|
||||
language: "Русский",
|
||||
detail: "MMS VITS ONNX · Русский",
|
||||
gender: "Natural voice",
|
||||
engine: "mms",
|
||||
badge: "ONNX",
|
||||
},
|
||||
{
|
||||
id: "th_TH-mms-medium",
|
||||
name: "Malee",
|
||||
language: "ไทย",
|
||||
detail: "MMS VITS ONNX · ภาษาไทย",
|
||||
gender: "Natural voice",
|
||||
engine: "mms",
|
||||
badge: "ONNX",
|
||||
},
|
||||
];
|
||||
|
||||
export const TOOL_RAIL = [
|
||||
|
||||
@@ -15,6 +15,7 @@ export function useAudioTrackState() {
|
||||
const [musicDuration, setMusicDuration] = useState(0);
|
||||
const [musicStart, setMusicStart] = useState(0);
|
||||
const [musicPeaks, setMusicPeaks] = useState([]);
|
||||
const [musicSegments, setMusicSegments] = useState([]);
|
||||
const [musicVolume, setMusicVolume] = useState(0.35);
|
||||
const [sourceAudioBlob, setSourceAudioBlob] = useState(null);
|
||||
const [sourceAudioUrl, setSourceAudioUrl] = useState("");
|
||||
@@ -33,9 +34,9 @@ export function useAudioTrackState() {
|
||||
|
||||
return {
|
||||
audioSegments, favoriteVoiceIds, historyItems, musicBlob, musicDuration, musicName,
|
||||
musicPeaks, musicStart, musicUrl, musicVolume, recordedVoices, recordingElapsed, recordingState,
|
||||
musicPeaks, musicSegments, musicStart, musicUrl, musicVolume, recordedVoices, recordingElapsed, recordingState,
|
||||
selectedAudioSegmentId, selectedVoiceId, setAudioSegments, setFavoriteVoiceIds,
|
||||
setHistoryItems, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks,
|
||||
setHistoryItems, setMusicBlob, setMusicDuration, setMusicName, setMusicPeaks, setMusicSegments,
|
||||
setMusicStart, setMusicUrl, setMusicVolume, setRecordedVoices, setRecordingElapsed,
|
||||
setRecordingState, setSelectedAudioSegmentId, setSelectedVoiceId, setSourceAudioBlob,
|
||||
setSourceAudioAssetId, setSourceAudioDuration, setSourceAudioLinked, setSourceAudioName, setSourceAudioPeaks, setSourceAudioStart,
|
||||
|
||||
@@ -1,25 +1,55 @@
|
||||
import { useCallback } from "react";
|
||||
import { transcribeAudioToCaptionSegments } from "../lib/asr.js";
|
||||
import { sliceAudioBlob } from "../lib/media.js";
|
||||
|
||||
export function localizeAutoCaptionPhase(phase, t) {
|
||||
const text = String(phase || "");
|
||||
const format = (key, fallback, values = {}) => Object.entries(values).reduce(
|
||||
(result, [name, value]) => result.replace(`{${name}}`, value),
|
||||
t(key, fallback),
|
||||
);
|
||||
if (text.includes("下载或读取") && text.includes("Whisper")) return t("asrDownloadingModel", text);
|
||||
if (text.includes("识别音频语言")) return t("asrDetectingLanguage", text);
|
||||
if (text.includes("初始化 WebGPU")) return t("asrInitializingWebGpu", text);
|
||||
if (text.includes("初始化 WASM")) return t("asrInitializingWasm", text);
|
||||
if (text.includes("WebGPU 初始化失败")) return t("asrFallingBackWasm", text);
|
||||
if (text.includes("解码原声音频")) return t("asrDecodingAudio", text);
|
||||
if (text.includes("Worker 不可用")) return t("asrWorkerFallback", text);
|
||||
if (text.includes("Worker 结果异常")) return t("asrRetryingWasm", text);
|
||||
if (text.includes("写入字幕轨道")) return t("asrWritingCaptions", text);
|
||||
const languageMatch = text.match(/(?:检测为|按)\s+(.+?)\s+转写字幕/);
|
||||
if (languageMatch) return format("asrTranscribingLanguage", text, { language: languageMatch[1] });
|
||||
return text;
|
||||
}
|
||||
|
||||
export function useAutoCaptions(d) {
|
||||
return useCallback(async () => {
|
||||
return useCallback(async (options = {}) => {
|
||||
const inputBlob = options.blob ?? d.sourceAudioBlob;
|
||||
const timelineOffset = Number.isFinite(options.start) ? options.start : d.sourceAudioStart;
|
||||
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");
|
||||
if (d.trackLocks.caption) return void d.notify(d.t("captionTrackLocked"));
|
||||
if (!inputBlob) return void d.notify(d.t("autoCaptionsNeedsSource"));
|
||||
d.setStatus("captioning"); d.setStatusText(d.t("autoCaptionsPreparing")); 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); },
|
||||
const clipBlob = Number.isFinite(options.duration)
|
||||
? await sliceAudioBlob(inputBlob, options.sourceStart || 0, options.duration)
|
||||
: inputBlob;
|
||||
const result = await transcribeAudioToCaptionSegments(clipBlob, {
|
||||
preferredLanguage: d.uiLanguage, timelineOffset,
|
||||
onProgress: ({ progress, phase }) => { d.setProgress((current) => Math.max(current, progress)); d.setStatusText(localizeAutoCaptionPhase(phase, d.t)); },
|
||||
});
|
||||
d.setCaptionSegments(result.segments); d.setScript(result.text);
|
||||
d.setCaptionSegments((segments) => options.append
|
||||
? [...segments, ...result.segments].sort((a, b) => (a.start || 0) - (b.start || 0))
|
||||
: result.segments);
|
||||
d.setScript((script) => options.append && script ? `${script}\n${result.text}` : 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} 条自动字幕`);
|
||||
const complete = d.t("autoCaptionsComplete").replace("{count}", result.segments.length);
|
||||
d.setStatus("done"); d.setStatusText(complete); d.setProgress(100);
|
||||
d.seekTo(result.segments[0]?.start ?? timelineOffset); d.notify(complete);
|
||||
} catch (error) {
|
||||
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : "自动字幕生成失败");
|
||||
d.setProgress(0); d.notify("自动字幕生成失败,请换一段有清晰人声的音频试试");
|
||||
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : d.t("autoCaptionsFailed"));
|
||||
d.setProgress(0); d.notify(d.t("autoCaptionsFailedHint"));
|
||||
}
|
||||
}, [d]);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTranslator } from "../i18n.js";
|
||||
import { localizeAutoCaptionPhase } from "./useAutoCaptions.js";
|
||||
|
||||
describe("automatic caption progress localization", () => {
|
||||
it("localizes Whisper download progress in English", () => {
|
||||
expect(localizeAutoCaptionPhase(
|
||||
"下载或读取 Whisper small ONNX",
|
||||
createTranslator("en"),
|
||||
)).toBe("Downloading or loading Whisper small ONNX");
|
||||
});
|
||||
|
||||
it("keeps the detected language label in localized transcription progress", () => {
|
||||
expect(localizeAutoCaptionPhase(
|
||||
"检测为 English 转写字幕",
|
||||
createTranslator("en"),
|
||||
)).toBe("Transcribing captions in English");
|
||||
});
|
||||
});
|
||||
+156
-11
@@ -1,14 +1,159 @@
|
||||
import { useMemo } from "react";
|
||||
import { SAMPLE_IMAGE, VOICES } from "../config/editor.js";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { VOICES } from "../config/editor.js";
|
||||
import { getRemoteAssetBlob } from "../lib/remoteAssetCache.js";
|
||||
|
||||
const DEFAULT_QUERY = { image: "nature", video: "nature", audio: "ambient" };
|
||||
|
||||
const formatDuration = (seconds = 0) => {
|
||||
const value = Math.max(0, Number(seconds) || 0);
|
||||
const minutes = Math.floor(value / 60);
|
||||
return `${String(minutes).padStart(2, "0")}:${String(Math.floor(value % 60)).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
function mapPexelsPhoto(photo) {
|
||||
return {
|
||||
id: `pexels-image-${photo.id}`, type: "image", src: photo.src?.large2x || photo.src?.large,
|
||||
thumbnail: photo.src?.medium, name: photo.alt || `Pexels photo ${photo.id}`,
|
||||
meta: `${photo.width} × ${photo.height} · Pexels`, width: photo.width, height: photo.height,
|
||||
provider: "Pexels", creator: photo.photographer, creatorUrl: photo.photographer_url,
|
||||
sourceUrl: photo.url, license: "Pexels License", licenseUrl: "https://www.pexels.com/license/",
|
||||
};
|
||||
}
|
||||
|
||||
function mapPexelsVideo(video) {
|
||||
const files = [...(video.video_files || [])].filter((file) => file.link).sort((a, b) => (b.width || 0) - (a.width || 0));
|
||||
const source = files.find((file) => (file.width || 0) <= 1920) || files[0];
|
||||
return {
|
||||
id: `pexels-video-${video.id}`, type: "video", src: source?.link, thumbnail: video.image,
|
||||
name: `Pexels video ${video.id}`, meta: `${source?.width || video.width} × ${source?.height || video.height} · ${formatDuration(video.duration)}`,
|
||||
width: source?.width || video.width, height: source?.height || video.height, duration: video.duration,
|
||||
trackFrames: [], provider: "Pexels", creator: video.user?.name, creatorUrl: video.user?.url,
|
||||
sourceUrl: video.url, license: "Pexels License", licenseUrl: "https://www.pexels.com/license/",
|
||||
};
|
||||
}
|
||||
|
||||
function stripHtml(value = "") {
|
||||
const element = document.createElement("div"); element.innerHTML = value; return element.textContent || "";
|
||||
}
|
||||
|
||||
function mapCommonsPage(page, type) {
|
||||
const info = page.imageinfo?.[0] || page.videoinfo?.[0] || {};
|
||||
const metadata = info.extmetadata || {};
|
||||
const duration = Number.parseFloat(info.duration ?? metadata.Duration?.value) || 0;
|
||||
const license = metadata.LicenseShortName?.value || "Free license";
|
||||
const derivative = type === "video"
|
||||
? [...(info.derivatives || [])].filter((item) => item.src && item.type?.startsWith("video/") && item.width <= 1280).sort((a, b) => Math.abs((a.width || 0) - 854) - Math.abs((b.width || 0) - 854))[0]
|
||||
: type === "audio"
|
||||
? (info.derivatives || []).find((item) => item.src && item.type?.startsWith("audio/"))
|
||||
: null;
|
||||
const editorSrc = type === "image" ? info.thumburl || info.url : derivative?.src || info.url;
|
||||
// Wikimedia only serves a fixed allowlist of thumbnail widths. Keep the
|
||||
// API-provided URL intact instead of rewriting it to an unsupported size.
|
||||
const thumbnail = type === "image" ? editorSrc : type === "video" ? info.thumburl : "";
|
||||
return {
|
||||
id: `commons-${type}-${page.pageid}`, type, src: editorSrc, originalSrc: info.url, thumbnail,
|
||||
name: page.title?.replace(/^File:/, "") || `Commons ${type}`,
|
||||
meta: type === "audio" ? `${formatDuration(duration)} · ${license}` : `${info.width || "—"} × ${info.height || "—"} · ${license}`,
|
||||
width: info.width, height: info.height, duration: duration || undefined, trackFrames: type === "video" ? [] : undefined,
|
||||
provider: "Wikimedia Commons", creator: stripHtml(metadata.Artist?.value || ""),
|
||||
sourceUrl: info.descriptionurl, license,
|
||||
licenseUrl: metadata.LicenseUrl?.value || info.descriptionurl,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapOpenverseAudio(item) {
|
||||
const source = item.url || item.alt_files?.find((file) => file.url)?.url;
|
||||
const duration = Math.max(0, (Number(item.duration) || 0) / 1000);
|
||||
return {
|
||||
id: `openverse-audio-${item.id}`, type: "audio", kind: "music", src: source, previewSrc: source,
|
||||
thumbnail: item.thumbnail || "", name: item.title || `Openverse music ${item.id}`, duration,
|
||||
meta: `${formatDuration(duration)} · ${String(item.license || "CC").toUpperCase()}`,
|
||||
provider: "Openverse", creator: item.creator, creatorUrl: item.creator_url,
|
||||
sourceUrl: item.foreign_landing_url, license: String(item.license || "").toUpperCase(),
|
||||
licenseUrl: item.license_url, attribution: item.attribution,
|
||||
};
|
||||
}
|
||||
|
||||
async function searchCommons(type, query, signal) {
|
||||
const filetype = type === "image" ? "bitmap" : type;
|
||||
const timedMedia = type === "video" || type === "audio";
|
||||
const params = new URLSearchParams({
|
||||
action: "query", generator: "search", gsrsearch: `${query} filetype:${filetype}`,
|
||||
gsrnamespace: "6", gsrlimit: "24", prop: timedMedia ? "videoinfo" : "imageinfo",
|
||||
[timedMedia ? "viprop" : "iiprop"]: "url|size|mime|extmetadata|derivatives",
|
||||
[timedMedia ? "viurlwidth" : "iiurlwidth"]: "1280", format: "json", origin: "*",
|
||||
});
|
||||
const response = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`, { signal });
|
||||
if (!response.ok) throw new Error(`Commons ${response.status}`);
|
||||
const data = await response.json();
|
||||
return Object.values(data.query?.pages || {}).map((page) => mapCommonsPage(page, type)).filter((asset) => asset.src);
|
||||
}
|
||||
|
||||
async function searchPexels(type, query, key, signal) {
|
||||
const path = type === "video" ? "videos/search" : "search";
|
||||
const params = new URLSearchParams({ query, per_page: "24", orientation: "all" });
|
||||
const response = await fetch(`https://api.pexels.com/v1/${path}?${params}`, { headers: { Authorization: key }, signal });
|
||||
if (!response.ok) throw new Error(`Pexels ${response.status}`);
|
||||
const data = await response.json();
|
||||
return type === "video" ? (data.videos || []).map(mapPexelsVideo) : (data.photos || []).map(mapPexelsPhoto);
|
||||
}
|
||||
|
||||
async function searchOpenverseAudio(query, signal) {
|
||||
const params = new URLSearchParams({ q: query, page_size: "20", license: "cc0,by,pdm", categories: "music" });
|
||||
const response = await fetch(`https://api.openverse.org/v1/audio/?${params}`, { signal });
|
||||
if (!response.ok) throw new Error(`Openverse ${response.status}`);
|
||||
const data = await response.json();
|
||||
return (data.results || []).map(mapOpenverseAudio)
|
||||
.filter((asset) => asset.src && asset.duration >= 15 && asset.duration <= 600)
|
||||
.slice(0, 24);
|
||||
}
|
||||
|
||||
export function useEditorCatalog(voiceFilter) {
|
||||
const filteredVoices = useMemo(() => VOICES.filter((voice) => {
|
||||
if (voiceFilter === "all") return true;
|
||||
return voice.language === 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 };
|
||||
const [libraryType, setLibraryType] = useState("image");
|
||||
const [libraryQuery, setLibraryQuery] = useState(DEFAULT_QUERY.image);
|
||||
const [builtInAssets, setBuiltInAssets] = useState([]);
|
||||
const [libraryStatus, setLibraryStatus] = useState("loading");
|
||||
const [libraryError, setLibraryError] = useState("");
|
||||
const [assetDownloadStates, setAssetDownloadStates] = useState({});
|
||||
const pexelsKey = String(import.meta.env.VITE_PEXELS_API_KEY || "").trim();
|
||||
|
||||
const filteredVoices = useMemo(() => VOICES.filter((voice) => voiceFilter === "all" || voice.language === voiceFilter), [voiceFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLibraryStatus("loading"); setLibraryError("");
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const query = libraryQuery.trim() || DEFAULT_QUERY[libraryType];
|
||||
const assets = libraryType === "audio"
|
||||
? await searchOpenverseAudio(query, controller.signal)
|
||||
: pexelsKey
|
||||
? await searchPexels(libraryType, query, pexelsKey, controller.signal)
|
||||
: await searchCommons(libraryType, query, controller.signal);
|
||||
setBuiltInAssets(assets); setLibraryStatus("ready");
|
||||
} catch (error) {
|
||||
if (error.name === "AbortError") return;
|
||||
setBuiltInAssets([]); setLibraryStatus("error"); setLibraryError(error.message || "Unable to load media");
|
||||
}
|
||||
}, 320);
|
||||
return () => { clearTimeout(timer); controller.abort(); };
|
||||
}, [libraryQuery, libraryType, pexelsKey]);
|
||||
|
||||
const selectLibraryType = (type) => { setLibraryType(type); setLibraryQuery(DEFAULT_QUERY[type]); };
|
||||
const prefetchLibraryAsset = async (asset) => {
|
||||
if (!asset?.src || !/^https?:/i.test(asset.src) || assetDownloadStates[asset.id]?.status === "ready") return;
|
||||
setAssetDownloadStates((states) => ({ ...states, [asset.id]: { status: "loading", progress: states[asset.id]?.progress || 0 } }));
|
||||
try {
|
||||
let lastProgressBucket = -1;
|
||||
await getRemoteAssetBlob(asset, (progress) => {
|
||||
const progressBucket = progress >= 1 ? 20 : Math.floor(progress * 20);
|
||||
if (progressBucket === lastProgressBucket) return;
|
||||
lastProgressBucket = progressBucket;
|
||||
setAssetDownloadStates((states) => ({ ...states, [asset.id]: { status: progress >= 1 ? "ready" : "loading", progress } }));
|
||||
});
|
||||
} catch {
|
||||
setAssetDownloadStates((states) => ({ ...states, [asset.id]: { status: "error", progress: 0 } }));
|
||||
}
|
||||
};
|
||||
return { builtInAssets, filteredVoices, libraryType, libraryQuery, setLibraryQuery, selectLibraryType, libraryStatus, libraryError, assetDownloadStates, prefetchLibraryAsset, libraryProvider: libraryType === "audio" ? "Openverse Music" : pexelsKey ? "Pexels" : "Wikimedia Commons" };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mapOpenverseAudio } from "./useEditorCatalog.js";
|
||||
|
||||
describe("mapOpenverseAudio", () => {
|
||||
it("normalizes Openverse millisecond durations for timeline use", () => {
|
||||
const asset = mapOpenverseAudio({
|
||||
id: "track-1",
|
||||
title: "Ambient Flight",
|
||||
duration: 264000,
|
||||
url: "https://example.com/track.mp3",
|
||||
license: "by",
|
||||
});
|
||||
expect(asset.duration).toBe(264);
|
||||
expect(asset.meta).toBe("04:24 · BY");
|
||||
expect(asset.type).toBe("audio");
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,7 @@ export function useFileUpload(deps) {
|
||||
if (shouldAutoAddFirstVisual) {
|
||||
deps.appendVisualAssetToTimeline(primaryVisual);
|
||||
deps.setSelectedTrack("image");
|
||||
deps.onFirstVisualAutoAdded?.();
|
||||
}
|
||||
const update = (id, patch) => deps.setUserAssets((current) => current.map((item) => item.id === id ? { ...item, ...patch } : item));
|
||||
assets.forEach((asset) => {
|
||||
|
||||
+43
-15
@@ -1,16 +1,47 @@
|
||||
import { startTransition, useEffect } from "react";
|
||||
import { PLAYBACK_UI_FRAME_MS, getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack, shouldCorrectPreviewMediaTime } from "../lib/editorRuntime.js";
|
||||
import { PLAYBACK_UI_FRAME_MS, getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack, requestTimelineMediaPlay, shouldCorrectPreviewMediaTime } from "../lib/editorRuntime.js";
|
||||
import { getLinkedSourceAudioState } from "../lib/sourceAudioSync.js";
|
||||
|
||||
export function syncTimelineAudioElement(media, { active, shouldPlay, expectedTime, playbackRate = 1 }) {
|
||||
if (!media) return;
|
||||
media.playbackRate = playbackRate;
|
||||
if (!shouldPlay || !active) {
|
||||
if (!media.paused) media.pause();
|
||||
return;
|
||||
}
|
||||
// React's timeline clock is intentionally throttled. Chasing it while the
|
||||
// native media clock is running causes repeated seeks and audible stutter.
|
||||
// Align only when starting (or entering a new segment), then let the browser
|
||||
// audio clock run continuously until an explicit seek or pause.
|
||||
if (media.paused && !media.__timelinePlayPending) {
|
||||
if (Math.abs(media.currentTime - expectedTime) > 0.04) media.currentTime = expectedTime;
|
||||
requestTimelineMediaPlay(media);
|
||||
}
|
||||
}
|
||||
|
||||
export function syncVoiceAudioSegments({ segments, refs, timelineTime, isPlaying, audible }) {
|
||||
segments.forEach((segment) => {
|
||||
const audio = refs.current.get(segment.id);
|
||||
if (!audio) return;
|
||||
if (!isPlaying || !audible) {
|
||||
if (!audio.paused) audio.pause();
|
||||
return;
|
||||
}
|
||||
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
|
||||
const expected = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
|
||||
syncTimelineAudioElement(audio, { active, shouldPlay: true, expectedTime: expected });
|
||||
});
|
||||
}
|
||||
|
||||
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 = Math.max(0, Number(s.sourceStart) || 0) + 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();
|
||||
syncVoiceAudioSegments({
|
||||
segments: d.audioSegments,
|
||||
refs: d.audioSegmentRefs,
|
||||
timelineTime: d.currentTime,
|
||||
isPlaying: d.isPlaying,
|
||||
audible: d.trackVisibility?.audio !== false,
|
||||
});
|
||||
}, [d.audioSegments, d.currentTime, d.isPlaying, d.trackVisibility.audio]);
|
||||
useEffect(() => { if (d.sourceAudioRef.current) d.sourceAudioRef.current.volume = d.sourceAudioVolume; }, [d.sourceAudioVolume, d.sourceAudioUrl]);
|
||||
@@ -19,19 +50,16 @@ export function useMediaSync(d) {
|
||||
const state = d.sourceAudioLinked && d.linkedSourceAudioSegments?.length
|
||||
? getLinkedSourceAudioState(d.linkedSourceAudioSegments, d.currentTime)
|
||||
: { active: isTimelineTimeInsideTrack(d.currentTime, d.sourceAudioStart, d.sourceAudioDuration), sourceTime: getTimelineTrackLocalTime(d.currentTime, d.sourceAudioStart, d.sourceAudioDuration), playbackRate: 1 };
|
||||
a.playbackRate = state.playbackRate;
|
||||
if (Math.abs(a.currentTime - state.sourceTime) > 0.22) a.currentTime = state.sourceTime;
|
||||
const play = d.isPlaying && d.trackVisibility.source && state.active;
|
||||
if (play && a.paused) a.play().catch(() => {}); else if (!play && !a.paused) a.pause();
|
||||
const play = d.isPlaying && d.trackVisibility?.source !== false && state.active;
|
||||
syncTimelineAudioElement(a, { active: state.active, shouldPlay: play, expectedTime: state.sourceTime, playbackRate: state.playbackRate });
|
||||
}, [d.currentTime, d.isPlaying, d.linkedSourceAudioSegments, d.sourceAudioDuration, d.sourceAudioLinked, d.sourceAudioStart, d.sourceAudioUrl, d.trackVisibility.source]);
|
||||
useEffect(() => { if (d.musicRef.current) d.musicRef.current.volume = d.musicVolume; }, [d.musicVolume, d.musicUrl]);
|
||||
useEffect(() => {
|
||||
const music = d.musicRef.current; if (!music || !d.musicUrl) return;
|
||||
const active = isTimelineTimeInsideTrack(d.currentTime, d.musicStart, d.musicDuration);
|
||||
const expected = getTimelineTrackLocalTime(d.currentTime, d.musicStart, d.musicDuration);
|
||||
if (Math.abs(music.currentTime - expected) > 0.22) music.currentTime = expected;
|
||||
const play = d.isPlaying && d.trackVisibility.music && active;
|
||||
if (play && music.paused) music.play().catch(() => {}); else if (!play && !music.paused) music.pause();
|
||||
const play = d.isPlaying && d.trackVisibility?.music !== false && active;
|
||||
syncTimelineAudioElement(music, { active, shouldPlay: play, expectedTime: expected });
|
||||
}, [d.currentTime, d.isPlaying, d.musicDuration, d.musicStart, d.musicUrl, d.trackVisibility.music]);
|
||||
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]);
|
||||
@@ -60,7 +88,7 @@ export function useMediaSync(d) {
|
||||
}, [d.isPlaying, d.previewVisualSegment?.id, d.previewVisualSourceTime, d.previewVisualSrc, d.previewVisualType]);
|
||||
useEffect(() => {
|
||||
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
|
||||
if (!d.isPlaying || !d.trackVisibility.image) v.pause(); else v.play().catch(() => {});
|
||||
if (!d.isPlaying || d.trackVisibility?.image === false) v.pause(); else v.play().catch(() => {});
|
||||
}, [d.isPlaying, d.previewVisualSrc, d.previewVisualType, d.trackVisibility.image]);
|
||||
useEffect(() => {
|
||||
if (!d.isPlaying || d.estimatedDuration <= 0) return undefined;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { syncTimelineAudioElement, syncVoiceAudioSegments } from "./useMediaSync.js";
|
||||
|
||||
function makeMedia(overrides = {}) {
|
||||
return {
|
||||
currentTime: 0,
|
||||
paused: true,
|
||||
playbackRate: 1,
|
||||
play: vi.fn(() => Promise.resolve()),
|
||||
pause: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("syncTimelineAudioElement", () => {
|
||||
it("immediately pauses every playing voice when the track is hidden", () => {
|
||||
const first = makeMedia({ paused: false });
|
||||
const second = makeMedia({ paused: false });
|
||||
syncVoiceAudioSegments({
|
||||
segments: [{ id: "one", start: 0, duration: 8 }, { id: "two", start: 0, duration: 8 }],
|
||||
refs: { current: new Map([["one", first], ["two", second]]) },
|
||||
timelineTime: 2,
|
||||
isPlaying: true,
|
||||
audible: false,
|
||||
});
|
||||
expect(first.pause).toHaveBeenCalledOnce();
|
||||
expect(second.pause).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("restarts an active voice at the current timeline time when made audible", () => {
|
||||
const media = makeMedia({ paused: true });
|
||||
syncVoiceAudioSegments({
|
||||
segments: [{ id: "one", start: 1, duration: 8 }],
|
||||
refs: { current: new Map([["one", media]]) },
|
||||
timelineTime: 4,
|
||||
isPlaying: true,
|
||||
audible: true,
|
||||
});
|
||||
expect(media.currentTime).toBe(3);
|
||||
expect(media.play).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("aligns once when native playback starts", () => {
|
||||
const media = makeMedia({ currentTime: 0.2 });
|
||||
syncTimelineAudioElement(media, { active: true, shouldPlay: true, expectedTime: 3.5 });
|
||||
expect(media.currentTime).toBe(3.5);
|
||||
expect(media.play).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not seek media that is already playing", () => {
|
||||
const media = makeMedia({ currentTime: 5.8, paused: false });
|
||||
syncTimelineAudioElement(media, { active: true, shouldPlay: true, expectedTime: 5.1 });
|
||||
expect(media.currentTime).toBe(5.8);
|
||||
expect(media.play).not.toHaveBeenCalled();
|
||||
expect(media.pause).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not interrupt a background music play request that is still pending", () => {
|
||||
const media = makeMedia({ currentTime: 0, paused: true, __timelinePlayPending: true });
|
||||
syncTimelineAudioElement(media, { active: true, shouldPlay: true, expectedTime: 1.2 });
|
||||
expect(media.currentTime).toBe(0);
|
||||
expect(media.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pauses media after it leaves its timeline range", () => {
|
||||
const media = makeMedia({ paused: false });
|
||||
syncTimelineAudioElement(media, { active: false, shouldPlay: true, expectedTime: 0 });
|
||||
expect(media.pause).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,10 @@ import { getTimelineProjectDuration } from "../lib/timelineScale.js";
|
||||
import { getActiveVisualOverlays } from "../lib/visualOverlayTimeline.js";
|
||||
|
||||
export function useTimelineModel(d) {
|
||||
const finiteDuration = (value) => {
|
||||
const duration = Number(value);
|
||||
return Number.isFinite(duration) && duration > 0 ? duration : 0;
|
||||
};
|
||||
const selectedVoice = useMemo(
|
||||
() => VOICES.find((voice) => voice.id === d.selectedVoiceId) ?? VOICES[0],
|
||||
[d.selectedVoiceId],
|
||||
@@ -62,7 +66,7 @@ export function useTimelineModel(d) {
|
||||
[d.captionSegments],
|
||||
);
|
||||
const voiceTrackDuration = useMemo(
|
||||
() => getTimedSegmentsEnd(d.audioSegments),
|
||||
() => finiteDuration(getTimedSegmentsEnd(d.audioSegments)),
|
||||
[d.audioSegments],
|
||||
);
|
||||
const captionTargetDuration = voiceTrackDuration;
|
||||
@@ -70,27 +74,27 @@ export function useTimelineModel(d) {
|
||||
() => getCaptionTimeline(d.captionSegments, captionTargetDuration),
|
||||
[d.captionSegments, captionTargetDuration],
|
||||
);
|
||||
const captionDuration = captionTimeline.at(-1)?.end ?? 0;
|
||||
const captionDuration = finiteDuration(captionTimeline.at(-1)?.end);
|
||||
const visualTimeline = useMemo(
|
||||
() => getVisualSegmentTimeline(d.visualSegments),
|
||||
[d.visualSegments],
|
||||
);
|
||||
const stickerDuration = useMemo(
|
||||
() => getTimedSegmentsEnd(d.stickerSegments),
|
||||
() => finiteDuration(getTimedSegmentsEnd(d.stickerSegments)),
|
||||
[d.stickerSegments],
|
||||
);
|
||||
const visualOverlayDuration = useMemo(
|
||||
() => getTimedSegmentsEnd(d.visualOverlaySegments),
|
||||
() => finiteDuration(getTimedSegmentsEnd(d.visualOverlaySegments)),
|
||||
[d.visualOverlaySegments],
|
||||
);
|
||||
const estimatedDuration = useMemo(() => Math.max(
|
||||
voiceTrackDuration,
|
||||
captionDuration,
|
||||
d.sourceAudioBlob ? (d.sourceAudioTimelineEnd ?? d.sourceAudioStart + d.sourceAudioDuration) : 0,
|
||||
d.musicBlob ? d.musicStart + d.musicDuration : 0,
|
||||
d.sourceAudioBlob ? finiteDuration(d.sourceAudioTimelineEnd ?? Number(d.sourceAudioStart) + Number(d.sourceAudioDuration)) : 0,
|
||||
d.musicBlob ? finiteDuration(Number(d.musicStart) + Number(d.musicDuration)) : 0,
|
||||
stickerDuration,
|
||||
visualOverlayDuration,
|
||||
d.imageSrc ? d.imageDuration : 0,
|
||||
d.imageSrc ? finiteDuration(d.imageDuration) : 0,
|
||||
), [
|
||||
voiceTrackDuration, captionDuration, d.imageDuration, d.imageSrc, d.musicBlob,
|
||||
d.musicDuration, d.musicStart, d.sourceAudioBlob, d.sourceAudioDuration,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { decodeWaveform } from "../lib/media.js";
|
||||
import { decodeWaveform, sliceAudioBlob } from "../lib/media.js";
|
||||
import { separateVocals } from "../lib/vocalSeparation.js";
|
||||
|
||||
export function useVocalSeparation({ sourceAudioBlob, sourceAudioName, replaceSourceAudio, replaceMusic, notify, t }) {
|
||||
export function useVocalSeparation({ sourceAudioBlob, sourceAudioName, replaceAudio, replaceSourceAudio, replaceMusic, notify, t }) {
|
||||
const [job, setJob] = useState({ running: false, progress: 0, phase: "" });
|
||||
const run = useCallback(async () => {
|
||||
if (!sourceAudioBlob || job.running) return;
|
||||
@@ -30,5 +30,37 @@ export function useVocalSeparation({ sourceAudioBlob, sourceAudioName, replaceSo
|
||||
notify(`${t("vocalSeparationFailed")}:${reason}`);
|
||||
}
|
||||
}, [job.running, notify, replaceMusic, replaceSourceAudio, sourceAudioBlob, sourceAudioName, t]);
|
||||
return { vocalSeparationJob: job, separateSourceVocals: run };
|
||||
const runClip = useCallback(async ({ blob, name, start = 0, sourceStart = 0, duration, segmentId = "", track }) => {
|
||||
if (!blob || job.running) return;
|
||||
setJob({ running: true, progress: 1, phase: t("vocalSeparationPreparing") });
|
||||
try {
|
||||
const clipBlob = Number.isFinite(duration) ? await sliceAudioBlob(blob, sourceStart, duration) : blob;
|
||||
const result = await separateVocals(clipBlob, (progress, phase) => setJob({
|
||||
running: true,
|
||||
progress,
|
||||
phase: phase.key === "vocalSeparationProcessingChunk"
|
||||
? t(phase.key).replace("{current}", phase.current).replace("{total}", phase.total)
|
||||
: t(phase.key),
|
||||
}));
|
||||
const [voiceMeta, musicMeta] = await Promise.all([decodeWaveform(result.vocals, 96), decodeWaveform(result.accompaniment, 96)]);
|
||||
const base = (name || t("audioClipFile")).replace(/\.[^.]+$/, "");
|
||||
replaceAudio(result.vocals, voiceMeta.duration, voiceMeta.peaks, t("vocalStemPlaced"), {
|
||||
start,
|
||||
name: `${base}-${t("vocalStemFile")}.wav`,
|
||||
replaceSegmentId: track === "audio" ? segmentId : "",
|
||||
});
|
||||
replaceMusic(result.accompaniment, musicMeta.duration, musicMeta.peaks, `${base}-${t("instrumentalStemFile")}.wav`, t("instrumentalStemPlaced"), { start });
|
||||
setJob({ running: false, progress: 100, phase: t("vocalSeparationComplete") });
|
||||
notify(t("vocalSeparationComplete"));
|
||||
} catch (error) {
|
||||
console.error(error); setJob({ running: false, progress: 0, phase: "" });
|
||||
const reason = error.message === "VOCAL_RUNTIME_DOWNLOAD_FAILED"
|
||||
? t("vocalSeparationRuntimeFailed")
|
||||
: error.message === "VOCAL_BACKEND_UNAVAILABLE"
|
||||
? t("vocalSeparationBackendFailed")
|
||||
: t("vocalSeparationModelFailed");
|
||||
notify(`${t("vocalSeparationFailed")}:${reason}`);
|
||||
}
|
||||
}, [job.running, notify, replaceAudio, replaceMusic, t]);
|
||||
return { vocalSeparationJob: job, separateAudioClipVocals: runClip, separateSourceVocals: run };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback } from "react";
|
||||
import { MODEL_ID } from "../config/editor.js";
|
||||
import { predictPiperVoice } from "../lib/piperVoiceRuntime.js";
|
||||
import { predictMmsVoice } from "../lib/mmsVoiceRuntime.js";
|
||||
import { clearPiperCacheIfStorageTight, isPiperSymbolError, isStorageQuotaError, prepareTextForVoice, TtsInputError } from "../lib/ttsText.js";
|
||||
|
||||
export function useVoiceGeneration(d) {
|
||||
@@ -22,7 +23,7 @@ export function useVoiceGeneration(d) {
|
||||
if (await clearPiperCacheIfStorageTight(tts)) d.notify(d.t("ttsNoticePiperCacheCleared"));
|
||||
d.setStatusText(d.selectedVoice.language === "中文"
|
||||
? d.t("ttsStatusLoadingChineseModel")
|
||||
: `Loading ${d.selectedVoice.language} Piper model…`);
|
||||
: d.t("ttsStatusPreparingModel"));
|
||||
const progress = (event) => {
|
||||
if (event?.backend) d.setStatusText(d.t(event.backend === "webgpu" ? "ttsStatusGeneratingWebGpu" : "ttsStatusGeneratingWasm"));
|
||||
if (event?.total) {
|
||||
@@ -38,6 +39,19 @@ export function useVoiceGeneration(d) {
|
||||
if (!isStorageQuotaError(error)) throw error;
|
||||
d.setStatusText(d.t("ttsStatusClearingCache")); await tts.flush?.(); blob = await predictPiperVoice(tts, input, progress);
|
||||
}
|
||||
} else if (d.selectedVoice.engine === "mms") {
|
||||
d.setStatusText(d.t("ttsStatusPreparingModel"));
|
||||
blob = await predictMmsVoice({ text: prepared.text, voiceId: d.selectedVoice.id }, (event) => {
|
||||
if (event?.backend) d.setStatusText(d.t("ttsStatusGeneratingWasm"));
|
||||
if (Number.isFinite(event?.progress)) d.setProgress((current) => Math.max(current, Math.min(86, Math.round(event.progress))));
|
||||
});
|
||||
} else if (d.selectedVoice.engine === "supertonic") {
|
||||
d.setStatusText(d.t("ttsStatusPreparingModel"));
|
||||
const { predictSupertonicVoice } = await import("../lib/supertonicVoiceRuntime.js");
|
||||
blob = await predictSupertonicVoice({ text: prepared.text, speed: d.speed }, (event) => {
|
||||
if (event?.backend) d.setStatusText(d.t("ttsStatusGeneratingWasm"));
|
||||
if (Number.isFinite(event?.progress)) d.setProgress((current) => Math.max(current, Math.min(86, Math.round(event.progress))));
|
||||
});
|
||||
} else {
|
||||
// Kokoro and the editor share the same Transformers runtime. Disable
|
||||
// its second Cache Storage layer before Kokoro starts loading; the
|
||||
|
||||
+79
-11
@@ -53,6 +53,47 @@ const TRANSITION_EDITOR_COPY = {
|
||||
vi: { transitionSettings: "Cài đặt chuyển cảnh", close: "Đóng", duration: "Thời lượng", secondsShort: "giây" },
|
||||
};
|
||||
|
||||
const ASSET_PREVIEW_COPY = {
|
||||
zh: { assetPreview: "素材预览", closeAssetPreview: "关闭预览", audioPreviewLoading: "正在加载音乐预览…", audioPreviewFailed: "音乐预览加载失败,请稍后重试" },
|
||||
en: { assetPreview: "Preview", closeAssetPreview: "Close preview", audioPreviewLoading: "Loading music preview…", audioPreviewFailed: "Music preview failed to load. Try again later." },
|
||||
ja: { assetPreview: "素材プレビュー", closeAssetPreview: "プレビューを閉じる", audioPreviewLoading: "音楽プレビューを読み込み中…", audioPreviewFailed: "音楽プレビューを読み込めませんでした" },
|
||||
ko: { assetPreview: "미디어 미리보기", closeAssetPreview: "미리보기 닫기", audioPreviewLoading: "음악 미리보기 로딩 중…", audioPreviewFailed: "음악 미리보기를 불러오지 못했습니다" },
|
||||
es: { assetPreview: "Vista previa", closeAssetPreview: "Cerrar vista previa", audioPreviewLoading: "Cargando vista previa de música…", audioPreviewFailed: "No se pudo cargar la vista previa" },
|
||||
fr: { assetPreview: "Aperçu", closeAssetPreview: "Fermer l’aperçu", audioPreviewLoading: "Chargement de l’aperçu musical…", audioPreviewFailed: "Impossible de charger l’aperçu musical" },
|
||||
de: { assetPreview: "Vorschau", closeAssetPreview: "Vorschau schließen", audioPreviewLoading: "Musikvorschau wird geladen…", audioPreviewFailed: "Musikvorschau konnte nicht geladen werden" },
|
||||
pt: { assetPreview: "Pré-visualização", closeAssetPreview: "Fechar pré-visualização", audioPreviewLoading: "Carregando prévia da música…", audioPreviewFailed: "Não foi possível carregar a prévia" },
|
||||
th: { assetPreview: "ดูตัวอย่าง", closeAssetPreview: "ปิดตัวอย่าง", audioPreviewLoading: "กำลังโหลดตัวอย่างเพลง…", audioPreviewFailed: "โหลดตัวอย่างเพลงไม่สำเร็จ" },
|
||||
vi: { assetPreview: "Xem trước", closeAssetPreview: "Đóng bản xem trước", audioPreviewLoading: "Đang tải bản nghe thử…", audioPreviewFailed: "Không thể tải bản nghe thử" },
|
||||
};
|
||||
|
||||
const ASSET_DROP_COPY = {
|
||||
zh: { remoteAssetDownloading: "正在下载在线素材…", remoteAssetDownloadFailed: "在线素材下载失败,请稍后重试或打开来源页下载", assetTrackMismatch: "请把素材拖到匹配的轨道", remoteAssetPreparing: "在线素材正在准备", remoteAssetRemovedAfterFailure: "在线素材下载失败,已移除临时片段", audioAssetUnavailable: "当前音频素材不可用,请重新上传", audioDroppedOnVoiceTrack: "音频已拖入配音音频轨" },
|
||||
en: { remoteAssetDownloading: "Downloading online media…", remoteAssetDownloadFailed: "Couldn’t download the online media. Try again later or open the source page.", assetTrackMismatch: "Drop the media onto a compatible track", remoteAssetPreparing: "Preparing online media", remoteAssetRemovedAfterFailure: "Download failed and the temporary clip was removed", audioAssetUnavailable: "This audio item is unavailable. Please upload it again.", audioDroppedOnVoiceTrack: "Audio added to the voiceover track" },
|
||||
ja: { remoteAssetDownloading: "オンライン素材をダウンロード中…", remoteAssetDownloadFailed: "オンライン素材をダウンロードできませんでした。後でもう一度お試しください。", assetTrackMismatch: "対応するトラックに素材をドロップしてください", remoteAssetPreparing: "オンライン素材を準備中", remoteAssetRemovedAfterFailure: "ダウンロードに失敗したため一時クリップを削除しました", audioAssetUnavailable: "この音声素材は利用できません。再アップロードしてください。", audioDroppedOnVoiceTrack: "音声をナレーショントラックに追加しました" },
|
||||
ko: { remoteAssetDownloading: "온라인 미디어 다운로드 중…", remoteAssetDownloadFailed: "온라인 미디어를 다운로드하지 못했습니다. 나중에 다시 시도하세요.", assetTrackMismatch: "호환되는 트랙에 미디어를 놓으세요", remoteAssetPreparing: "온라인 미디어 준비 중", remoteAssetRemovedAfterFailure: "다운로드에 실패하여 임시 클립을 제거했습니다", audioAssetUnavailable: "이 오디오를 사용할 수 없습니다. 다시 업로드하세요.", audioDroppedOnVoiceTrack: "오디오를 보이스오버 트랙에 추가했습니다" },
|
||||
es: { remoteAssetDownloading: "Descargando contenido en línea…", remoteAssetDownloadFailed: "No se pudo descargar. Inténtalo de nuevo más tarde.", assetTrackMismatch: "Suelta el contenido en una pista compatible", remoteAssetPreparing: "Preparando contenido en línea", remoteAssetRemovedAfterFailure: "La descarga falló y se eliminó el clip temporal", audioAssetUnavailable: "Este audio no está disponible. Vuelve a subirlo.", audioDroppedOnVoiceTrack: "Audio añadido a la pista de voz" },
|
||||
fr: { remoteAssetDownloading: "Téléchargement du média en ligne…", remoteAssetDownloadFailed: "Impossible de télécharger le média. Réessayez plus tard.", assetTrackMismatch: "Déposez le média sur une piste compatible", remoteAssetPreparing: "Préparation du média en ligne", remoteAssetRemovedAfterFailure: "Échec du téléchargement, clip temporaire supprimé", audioAssetUnavailable: "Ce média audio est indisponible. Importez-le à nouveau.", audioDroppedOnVoiceTrack: "Audio ajouté à la piste de voix off" },
|
||||
de: { remoteAssetDownloading: "Online-Medium wird heruntergeladen…", remoteAssetDownloadFailed: "Online-Medium konnte nicht heruntergeladen werden. Versuche es später erneut.", assetTrackMismatch: "Medium auf eine kompatible Spur ziehen", remoteAssetPreparing: "Online-Medium wird vorbereitet", remoteAssetRemovedAfterFailure: "Download fehlgeschlagen; temporärer Clip wurde entfernt", audioAssetUnavailable: "Dieses Audio ist nicht verfügbar. Bitte erneut hochladen.", audioDroppedOnVoiceTrack: "Audio zur Voiceover-Spur hinzugefügt" },
|
||||
pt: { remoteAssetDownloading: "Baixando mídia on-line…", remoteAssetDownloadFailed: "Não foi possível baixar a mídia. Tente novamente mais tarde.", assetTrackMismatch: "Solte a mídia em uma faixa compatível", remoteAssetPreparing: "Preparando mídia on-line", remoteAssetRemovedAfterFailure: "O download falhou e o clipe temporário foi removido", audioAssetUnavailable: "Este áudio não está disponível. Envie-o novamente.", audioDroppedOnVoiceTrack: "Áudio adicionado à faixa de narração" },
|
||||
th: { remoteAssetDownloading: "กำลังดาวน์โหลดสื่อออนไลน์…", remoteAssetDownloadFailed: "ดาวน์โหลดสื่อไม่สำเร็จ โปรดลองอีกครั้งภายหลัง", assetTrackMismatch: "วางสื่อลงในแทร็กที่รองรับ", remoteAssetPreparing: "กำลังเตรียมสื่อออนไลน์", remoteAssetRemovedAfterFailure: "ดาวน์โหลดไม่สำเร็จและลบคลิปชั่วคราวแล้ว", audioAssetUnavailable: "ไฟล์เสียงนี้ใช้ไม่ได้ โปรดอัปโหลดใหม่", audioDroppedOnVoiceTrack: "เพิ่มเสียงลงในแทร็กพากย์แล้ว" },
|
||||
vi: { remoteAssetDownloading: "Đang tải nội dung trực tuyến…", remoteAssetDownloadFailed: "Không thể tải nội dung. Hãy thử lại sau.", assetTrackMismatch: "Thả nội dung vào rãnh tương thích", remoteAssetPreparing: "Đang chuẩn bị nội dung trực tuyến", remoteAssetRemovedAfterFailure: "Tải xuống thất bại và clip tạm đã bị xóa", audioAssetUnavailable: "Âm thanh này không khả dụng. Vui lòng tải lên lại.", audioDroppedOnVoiceTrack: "Đã thêm âm thanh vào rãnh lồng tiếng" },
|
||||
ru: { remoteAssetDownloading: "Загрузка онлайн-медиа…", remoteAssetDownloadFailed: "Не удалось загрузить медиа. Повторите попытку позже.", assetTrackMismatch: "Перетащите медиа на совместимую дорожку", remoteAssetPreparing: "Подготовка онлайн-медиа", remoteAssetRemovedAfterFailure: "Загрузка не удалась, временный клип удалён", audioAssetUnavailable: "Это аудио недоступно. Загрузите его снова.", audioDroppedOnVoiceTrack: "Аудио добавлено на дорожку озвучки" },
|
||||
};
|
||||
|
||||
const AUTO_CAPTION_STATUS_COPY = {
|
||||
zh: { asrDownloadingModel: "下载或读取 Whisper small ONNX", asrDetectingLanguage: "识别音频语言", asrInitializingWebGpu: "初始化 WebGPU ONNX", asrInitializingWasm: "初始化 WASM ONNX", asrFallingBackWasm: "WebGPU 初始化失败,切换 WASM", asrTranscribingLanguage: "使用 {language} 转写字幕", asrDecodingAudio: "解码原声音频", asrWorkerFallback: "Worker 不可用,切换主线程自动字幕", asrRetryingWasm: "识别结果异常,切换稳定 WASM 重新识别", asrWritingCaptions: "写入字幕轨道" },
|
||||
en: { asrDownloadingModel: "Downloading or loading Whisper small ONNX", asrDetectingLanguage: "Detecting audio language", asrInitializingWebGpu: "Initializing WebGPU ONNX", asrInitializingWasm: "Initializing WASM ONNX", asrFallingBackWasm: "WebGPU initialization failed; switching to WASM", asrTranscribingLanguage: "Transcribing captions in {language}", asrDecodingAudio: "Decoding source audio", asrWorkerFallback: "Worker unavailable; switching to main-thread captions", asrRetryingWasm: "Unexpected result; retrying with stable WASM", asrWritingCaptions: "Writing caption track" },
|
||||
ja: { asrDownloadingModel: "Whisper small ONNXをダウンロードまたは読み込み中", asrDetectingLanguage: "音声言語を検出中", asrInitializingWebGpu: "WebGPU ONNXを初期化中", asrInitializingWasm: "WASM ONNXを初期化中", asrFallingBackWasm: "WebGPUの初期化に失敗、WASMへ切り替え中", asrTranscribingLanguage: "{language}で字幕を文字起こし中", asrDecodingAudio: "元音声をデコード中", asrWorkerFallback: "Workerを利用できないためメインスレッドへ切り替え中", asrRetryingWasm: "結果が不安定なためWASMで再認識中", asrWritingCaptions: "字幕トラックへ書き込み中" },
|
||||
ko: { asrDownloadingModel: "Whisper small ONNX 다운로드 또는 불러오는 중", asrDetectingLanguage: "오디오 언어 감지 중", asrInitializingWebGpu: "WebGPU ONNX 초기화 중", asrInitializingWasm: "WASM ONNX 초기화 중", asrFallingBackWasm: "WebGPU 초기화 실패, WASM으로 전환 중", asrTranscribingLanguage: "{language} 자막 변환 중", asrDecodingAudio: "원본 오디오 디코딩 중", asrWorkerFallback: "Worker를 사용할 수 없어 메인 스레드로 전환 중", asrRetryingWasm: "결과가 불안정하여 WASM으로 다시 인식 중", asrWritingCaptions: "자막 트랙 작성 중" },
|
||||
es: { asrDownloadingModel: "Descargando o cargando Whisper small ONNX", asrDetectingLanguage: "Detectando idioma del audio", asrInitializingWebGpu: "Inicializando WebGPU ONNX", asrInitializingWasm: "Inicializando WASM ONNX", asrFallingBackWasm: "Falló WebGPU; cambiando a WASM", asrTranscribingLanguage: "Transcribiendo subtítulos en {language}", asrDecodingAudio: "Decodificando audio de origen", asrWorkerFallback: "Worker no disponible; usando el hilo principal", asrRetryingWasm: "Resultado inesperado; reintentando con WASM", asrWritingCaptions: "Escribiendo pista de subtítulos" },
|
||||
fr: { asrDownloadingModel: "Téléchargement ou chargement de Whisper small ONNX", asrDetectingLanguage: "Détection de la langue audio", asrInitializingWebGpu: "Initialisation de WebGPU ONNX", asrInitializingWasm: "Initialisation de WASM ONNX", asrFallingBackWasm: "Échec de WebGPU, passage à WASM", asrTranscribingLanguage: "Transcription des sous-titres en {language}", asrDecodingAudio: "Décodage de l’audio source", asrWorkerFallback: "Worker indisponible, passage au thread principal", asrRetryingWasm: "Résultat inattendu, nouvel essai avec WASM", asrWritingCaptions: "Écriture de la piste de sous-titres" },
|
||||
de: { asrDownloadingModel: "Whisper small ONNX wird geladen", asrDetectingLanguage: "Audiosprache wird erkannt", asrInitializingWebGpu: "WebGPU ONNX wird initialisiert", asrInitializingWasm: "WASM ONNX wird initialisiert", asrFallingBackWasm: "WebGPU fehlgeschlagen; Wechsel zu WASM", asrTranscribingLanguage: "Untertitel werden auf {language} transkribiert", asrDecodingAudio: "Quellaudio wird dekodiert", asrWorkerFallback: "Worker nicht verfügbar; Wechsel zum Hauptthread", asrRetryingWasm: "Unerwartetes Ergebnis; neuer WASM-Versuch", asrWritingCaptions: "Untertitelspur wird geschrieben" },
|
||||
pt: { asrDownloadingModel: "Baixando ou carregando Whisper small ONNX", asrDetectingLanguage: "Detectando idioma do áudio", asrInitializingWebGpu: "Inicializando WebGPU ONNX", asrInitializingWasm: "Inicializando WASM ONNX", asrFallingBackWasm: "Falha no WebGPU; alternando para WASM", asrTranscribingLanguage: "Transcrevendo legendas em {language}", asrDecodingAudio: "Decodificando áudio de origem", asrWorkerFallback: "Worker indisponível; alternando para a thread principal", asrRetryingWasm: "Resultado inesperado; tentando novamente com WASM", asrWritingCaptions: "Gravando faixa de legendas" },
|
||||
th: { asrDownloadingModel: "กำลังดาวน์โหลดหรือโหลด Whisper small ONNX", asrDetectingLanguage: "กำลังตรวจหาภาษาเสียง", asrInitializingWebGpu: "กำลังเริ่ม WebGPU ONNX", asrInitializingWasm: "กำลังเริ่ม WASM ONNX", asrFallingBackWasm: "เริ่ม WebGPU ไม่สำเร็จ กำลังเปลี่ยนเป็น WASM", asrTranscribingLanguage: "กำลังถอดคำบรรยายภาษา {language}", asrDecodingAudio: "กำลังถอดรหัสเสียงต้นฉบับ", asrWorkerFallback: "ใช้ Worker ไม่ได้ กำลังเปลี่ยนไปใช้เธรดหลัก", asrRetryingWasm: "ผลลัพธ์ผิดปกติ กำลังลองใหม่ด้วย WASM", asrWritingCaptions: "กำลังเขียนแทร็กคำบรรยาย" },
|
||||
vi: { asrDownloadingModel: "Đang tải Whisper small ONNX", asrDetectingLanguage: "Đang nhận diện ngôn ngữ âm thanh", asrInitializingWebGpu: "Đang khởi tạo WebGPU ONNX", asrInitializingWasm: "Đang khởi tạo WASM ONNX", asrFallingBackWasm: "WebGPU thất bại; chuyển sang WASM", asrTranscribingLanguage: "Đang chép phụ đề bằng {language}", asrDecodingAudio: "Đang giải mã âm thanh nguồn", asrWorkerFallback: "Worker không khả dụng; chuyển sang luồng chính", asrRetryingWasm: "Kết quả bất thường; thử lại bằng WASM", asrWritingCaptions: "Đang ghi rãnh phụ đề" },
|
||||
ru: { asrDownloadingModel: "Загрузка Whisper small ONNX", asrDetectingLanguage: "Определение языка аудио", asrInitializingWebGpu: "Инициализация WebGPU ONNX", asrInitializingWasm: "Инициализация WASM ONNX", asrFallingBackWasm: "Ошибка WebGPU; переключение на WASM", asrTranscribingLanguage: "Распознавание субтитров на языке {language}", asrDecodingAudio: "Декодирование исходного аудио", asrWorkerFallback: "Worker недоступен; переход в основной поток", asrRetryingWasm: "Неожиданный результат; повтор через WASM", asrWritingCaptions: "Запись дорожки субтитров" },
|
||||
};
|
||||
|
||||
const VISUAL_PANEL_TITLE_COPY = {
|
||||
zh: { visualPanelTitle: "画面" },
|
||||
en: { visualPanelTitle: "Visuals" },
|
||||
@@ -214,16 +255,16 @@ const CONTEXT_PANEL_COPY = {
|
||||
};
|
||||
|
||||
const TIMELINE_AUDIO_MENU_COPY = {
|
||||
zh: { muteClip: "静音", unmuteClip: "取消静音", separateSourceAudio: "分离音频", separatingSourceAudio: "正在分离音频…" },
|
||||
en: { muteClip: "Mute", unmuteClip: "Unmute", separateSourceAudio: "Separate audio", separatingSourceAudio: "Separating audio…" },
|
||||
ja: { muteClip: "ミュート", unmuteClip: "ミュート解除", separateSourceAudio: "音声を分離", separatingSourceAudio: "音声を分離中…" },
|
||||
ko: { muteClip: "음소거", unmuteClip: "음소거 해제", separateSourceAudio: "오디오 분리", separatingSourceAudio: "오디오 분리 중…" },
|
||||
es: { muteClip: "Silenciar", unmuteClip: "Activar sonido", separateSourceAudio: "Separar audio", separatingSourceAudio: "Separando audio…" },
|
||||
fr: { muteClip: "Couper le son", unmuteClip: "Rétablir le son", separateSourceAudio: "Séparer l’audio", separatingSourceAudio: "Séparation audio…" },
|
||||
de: { muteClip: "Stummschalten", unmuteClip: "Ton einschalten", separateSourceAudio: "Audio trennen", separatingSourceAudio: "Audio wird getrennt…" },
|
||||
pt: { muteClip: "Silenciar", unmuteClip: "Ativar som", separateSourceAudio: "Separar áudio", separatingSourceAudio: "Separando áudio…" },
|
||||
th: { muteClip: "ปิดเสียง", unmuteClip: "เปิดเสียง", separateSourceAudio: "แยกเสียง", separatingSourceAudio: "กำลังแยกเสียง…" },
|
||||
vi: { muteClip: "Tắt tiếng", unmuteClip: "Bật tiếng", separateSourceAudio: "Tách âm thanh", separatingSourceAudio: "Đang tách âm thanh…" },
|
||||
zh: { muteClip: "静音", unmuteClip: "取消静音", separateSourceAudio: "分离音频", separatingSourceAudio: "正在分离音频…", separateVocalsFromClip: "AI 人声分离", generateCaptionsFromClip: "从此片段生成字幕", captionTrackLocked: "字幕轨已锁定,无法生成自动字幕", autoCaptionsPreparing: "准备自动字幕模型", autoCaptionsComplete: "已生成 {count} 条自动字幕", autoCaptionsFailed: "自动字幕生成失败", autoCaptionsFailedHint: "自动字幕生成失败,请换一段有清晰人声的音频试试", audioClipFile: "音频片段" },
|
||||
en: { muteClip: "Mute", unmuteClip: "Unmute", separateSourceAudio: "Separate audio", separatingSourceAudio: "Separating audio…", separateVocalsFromClip: "AI vocal separation", generateCaptionsFromClip: "Generate captions from clip", captionTrackLocked: "The caption track is locked", autoCaptionsPreparing: "Preparing the automatic caption model", autoCaptionsComplete: "Generated {count} automatic captions", autoCaptionsFailed: "Automatic caption generation failed", autoCaptionsFailedHint: "Caption generation failed. Try audio with clearer speech.", audioClipFile: "audio-clip" },
|
||||
ja: { muteClip: "ミュート", unmuteClip: "ミュート解除", separateSourceAudio: "音声を分離", separatingSourceAudio: "音声を分離中…", separateVocalsFromClip: "AIボーカル分離", generateCaptionsFromClip: "このクリップから字幕を生成", captionTrackLocked: "字幕トラックがロックされています", autoCaptionsPreparing: "自動字幕モデルを準備中", autoCaptionsComplete: "自動字幕を{count}件生成しました", autoCaptionsFailed: "自動字幕の生成に失敗しました", autoCaptionsFailedHint: "字幕を生成できませんでした。音声が明瞭なクリップをお試しください。", audioClipFile: "音声クリップ" },
|
||||
ko: { muteClip: "음소거", unmuteClip: "음소거 해제", separateSourceAudio: "오디오 분리", separatingSourceAudio: "오디오 분리 중…", separateVocalsFromClip: "AI 보컬 분리", generateCaptionsFromClip: "이 클립에서 자막 생성", captionTrackLocked: "자막 트랙이 잠겨 있습니다", autoCaptionsPreparing: "자동 자막 모델 준비 중", autoCaptionsComplete: "자동 자막 {count}개 생성됨", autoCaptionsFailed: "자동 자막 생성 실패", autoCaptionsFailedHint: "자막 생성에 실패했습니다. 음성이 더 선명한 오디오를 사용해 보세요.", audioClipFile: "오디오 클립" },
|
||||
es: { muteClip: "Silenciar", unmuteClip: "Activar sonido", separateSourceAudio: "Separar audio", separatingSourceAudio: "Separando audio…", separateVocalsFromClip: "Separación vocal con IA", generateCaptionsFromClip: "Generar subtítulos del clip", captionTrackLocked: "La pista de subtítulos está bloqueada", autoCaptionsPreparing: "Preparando el modelo de subtítulos", autoCaptionsComplete: "Se generaron {count} subtítulos", autoCaptionsFailed: "Error al generar subtítulos", autoCaptionsFailedHint: "No se pudieron generar subtítulos. Prueba un audio con voz más clara.", audioClipFile: "clip-de-audio" },
|
||||
fr: { muteClip: "Couper le son", unmuteClip: "Rétablir le son", separateSourceAudio: "Séparer l’audio", separatingSourceAudio: "Séparation audio…", separateVocalsFromClip: "Séparation vocale par IA", generateCaptionsFromClip: "Générer les sous-titres du clip", captionTrackLocked: "La piste de sous-titres est verrouillée", autoCaptionsPreparing: "Préparation du modèle de sous-titres", autoCaptionsComplete: "{count} sous-titres générés", autoCaptionsFailed: "Échec de la génération des sous-titres", autoCaptionsFailedHint: "Échec des sous-titres. Essayez un son avec une voix plus nette.", audioClipFile: "clip-audio" },
|
||||
de: { muteClip: "Stummschalten", unmuteClip: "Ton einschalten", separateSourceAudio: "Audio trennen", separatingSourceAudio: "Audio wird getrennt…", separateVocalsFromClip: "KI-Stimmentrennung", generateCaptionsFromClip: "Untertitel aus Clip erzeugen", captionTrackLocked: "Die Untertitelspur ist gesperrt", autoCaptionsPreparing: "Automatisches Untertitelmodell wird vorbereitet", autoCaptionsComplete: "{count} automatische Untertitel erstellt", autoCaptionsFailed: "Untertitel konnten nicht erstellt werden", autoCaptionsFailedHint: "Untertitel fehlgeschlagen. Versuche Audio mit deutlicherer Sprache.", audioClipFile: "audio-clip" },
|
||||
pt: { muteClip: "Silenciar", unmuteClip: "Ativar som", separateSourceAudio: "Separar áudio", separatingSourceAudio: "Separando áudio…", separateVocalsFromClip: "Separação vocal por IA", generateCaptionsFromClip: "Gerar legendas do clipe", captionTrackLocked: "A faixa de legendas está bloqueada", autoCaptionsPreparing: "Preparando o modelo de legendas", autoCaptionsComplete: "{count} legendas automáticas geradas", autoCaptionsFailed: "Falha ao gerar legendas", autoCaptionsFailedHint: "Falha nas legendas. Tente um áudio com fala mais clara.", audioClipFile: "clipe-de-audio" },
|
||||
th: { muteClip: "ปิดเสียง", unmuteClip: "เปิดเสียง", separateSourceAudio: "แยกเสียง", separatingSourceAudio: "กำลังแยกเสียง…", separateVocalsFromClip: "แยกเสียงร้องด้วย AI", generateCaptionsFromClip: "สร้างคำบรรยายจากคลิป", captionTrackLocked: "แทร็กคำบรรยายถูกล็อก", autoCaptionsPreparing: "กำลังเตรียมโมเดลคำบรรยาย", autoCaptionsComplete: "สร้างคำบรรยายอัตโนมัติ {count} รายการแล้ว", autoCaptionsFailed: "สร้างคำบรรยายไม่สำเร็จ", autoCaptionsFailedHint: "สร้างคำบรรยายไม่สำเร็จ โปรดลองเสียงพูดที่ชัดเจนกว่า", audioClipFile: "คลิปเสียง" },
|
||||
vi: { muteClip: "Tắt tiếng", unmuteClip: "Bật tiếng", separateSourceAudio: "Tách âm thanh", separatingSourceAudio: "Đang tách âm thanh…", separateVocalsFromClip: "Tách giọng hát bằng AI", generateCaptionsFromClip: "Tạo phụ đề từ clip", captionTrackLocked: "Rãnh phụ đề đang bị khóa", autoCaptionsPreparing: "Đang chuẩn bị mô hình phụ đề", autoCaptionsComplete: "Đã tạo {count} phụ đề tự động", autoCaptionsFailed: "Không thể tạo phụ đề", autoCaptionsFailedHint: "Tạo phụ đề thất bại. Hãy thử âm thanh có giọng nói rõ hơn.", audioClipFile: "clip-am-thanh" },
|
||||
};
|
||||
|
||||
Object.entries(TIMELINE_AUDIO_MENU_COPY).forEach(([language, copy]) => {
|
||||
@@ -426,6 +467,18 @@ export const UI_COPY = {
|
||||
loadMoreStickers: "加载更多贴纸",
|
||||
uploadTab: "本地上传",
|
||||
libraryTab: "素材库",
|
||||
libraryMediaType: "素材类型",
|
||||
libraryImage: "图片",
|
||||
libraryVideo: "视频",
|
||||
libraryAudio: "音乐",
|
||||
librarySearchPlaceholder: "搜索开放素材",
|
||||
librarySearchMusicPlaceholder: "搜索开放音乐",
|
||||
libraryProvidedBy: "素材来源:",
|
||||
libraryLoading: "正在加载开放素材…",
|
||||
libraryPreparingAsset: "正在准备素材",
|
||||
libraryAssetReady: "素材已准备,可快速拖入",
|
||||
timelineMediaPreparing: "正在准备素材",
|
||||
libraryEmpty: "没有找到匹配的开放素材,请更换关键词。",
|
||||
mineTab: "我的素材",
|
||||
uploadDropTitle: "点击上传或拖拽图片/视频/音频到此处",
|
||||
uploadSupport: "支持 JPG、PNG、WebP、MP4、WebM、MOV、MP3、WAV、M4A",
|
||||
@@ -810,6 +863,18 @@ export const UI_COPY = {
|
||||
loadMoreStickers: "Load more stickers",
|
||||
uploadTab: "Upload",
|
||||
libraryTab: "Library",
|
||||
libraryMediaType: "Media type",
|
||||
libraryImage: "Images",
|
||||
libraryVideo: "Videos",
|
||||
libraryAudio: "Music",
|
||||
librarySearchPlaceholder: "Search open media",
|
||||
librarySearchMusicPlaceholder: "Search open music",
|
||||
libraryProvidedBy: "Provided by",
|
||||
libraryLoading: "Loading open media…",
|
||||
libraryPreparingAsset: "Preparing media",
|
||||
libraryAssetReady: "Media ready to add",
|
||||
timelineMediaPreparing: "Preparing media",
|
||||
libraryEmpty: "No matching open media. Try another search.",
|
||||
mineTab: "My assets",
|
||||
uploadDropTitle: "Click or drop image, video, or audio here",
|
||||
uploadSupport: "Supports JPG, PNG, WebP, MP4, WebM, MOV, MP3, WAV, M4A",
|
||||
@@ -1740,7 +1805,10 @@ export function createTranslator(languageId) {
|
||||
const copy = UI_COPY[copyLanguage] ?? UI_COPY.en;
|
||||
const fallback = UI_COPY.en;
|
||||
const exportCopy = EXPORT_RENDER_COPY[copyLanguage] ?? EXPORT_RENDER_COPY.en;
|
||||
return (key, fallbackText) => exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
|
||||
const assetPreviewCopy = ASSET_PREVIEW_COPY[copyLanguage] ?? ASSET_PREVIEW_COPY.en;
|
||||
const assetDropCopy = ASSET_DROP_COPY[copyLanguage] ?? ASSET_DROP_COPY.en;
|
||||
const autoCaptionStatusCopy = AUTO_CAPTION_STATUS_COPY[copyLanguage] ?? AUTO_CAPTION_STATUS_COPY.en;
|
||||
return (key, fallbackText) => exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? assetPreviewCopy[key] ?? ASSET_PREVIEW_COPY.en[key] ?? assetDropCopy[key] ?? ASSET_DROP_COPY.en[key] ?? autoCaptionStatusCopy[key] ?? AUTO_CAPTION_STATUS_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
|
||||
}
|
||||
|
||||
export function translateOptionName(languageId, name) {
|
||||
|
||||
@@ -54,6 +54,7 @@ export function createAssetDragControls(deps) {
|
||||
};
|
||||
const handleAssetPointerDown = (event, asset) => {
|
||||
if (event.button !== 0 || (event.target instanceof Element && event.target.closest(".asset-delete"))) return;
|
||||
void deps.prefetchAsset?.(asset);
|
||||
deps.setSelectedLibraryAssetId(asset.id);
|
||||
deps.pointerAssetDragRef.current = { assetId: asset.id, startX: event.clientX, startY: event.clientY, dragging: false };
|
||||
const move = (e) => {
|
||||
|
||||
@@ -1,9 +1,50 @@
|
||||
import { decodeWaveform } from "./media.js";
|
||||
import { decodeWaveform, extractVideoTrackFrames } from "./media.js";
|
||||
import { getRemoteAssetBlob } from "./remoteAssetCache.js";
|
||||
|
||||
export function createAssetDropActions(d) {
|
||||
const tr = (key, fallback) => d.t?.(key, fallback) ?? fallback;
|
||||
async function resolveRemoteAsset(asset, onProgress) {
|
||||
if (!asset?.src || asset.blob || !/^https?:/i.test(asset.src)) return asset;
|
||||
try {
|
||||
d.notify(tr("remoteAssetDownloading", "正在下载在线素材…"));
|
||||
const blob = await getRemoteAssetBlob(asset, (progress) => {
|
||||
d.onRemoteAssetProgress?.(asset.id, progress);
|
||||
onProgress?.(progress);
|
||||
});
|
||||
if (!blob) throw new Error("Missing remote asset");
|
||||
const src = URL.createObjectURL(blob);
|
||||
d.imageUrlRefs?.current?.add(src);
|
||||
return { ...asset, src, blob, remoteSrc: asset.src };
|
||||
} catch {
|
||||
d.notify(tr("remoteAssetDownloadFailed", "在线素材下载失败,请稍后重试或打开来源页下载"));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function applyAssetToTrack(asset, track, options = {}) {
|
||||
if (!d.canDropAssetOnTrack(asset, track)) {
|
||||
d.notify("请把素材拖到匹配的轨道");
|
||||
d.notify(tr("assetTrackMismatch", "请把素材拖到匹配的轨道"));
|
||||
return;
|
||||
}
|
||||
const isRemoteVisual = (track === "image" || track === "overlay") && asset?.src && !asset.blob && /^https?:/i.test(asset.src);
|
||||
const hadVisualBefore = Boolean(d.visualSegments?.length);
|
||||
let pendingSegment = null;
|
||||
let progressBucket = -1;
|
||||
if (isRemoteVisual && track === "image") {
|
||||
pendingSegment = d.appendVisualAssetToTimeline({ ...asset, preparing: true, prepareProgress: 0 }, { message: tr("remoteAssetPreparing", "在线素材正在准备") });
|
||||
d.onFirstVisualDropped?.();
|
||||
}
|
||||
asset = await resolveRemoteAsset(asset, pendingSegment ? (progress) => {
|
||||
const bucket = Math.round(Math.max(0, Math.min(1, progress || 0)) * 20) / 20;
|
||||
if (bucket === progressBucket) return;
|
||||
progressBucket = bucket;
|
||||
d.setVisualSegments((segments) => segments.map((segment) => segment.id === pendingSegment.id ? { ...segment, prepareProgress: bucket } : segment));
|
||||
} : undefined);
|
||||
if (!asset) {
|
||||
if (pendingSegment) {
|
||||
if (hadVisualBefore) d.setVisualSegments((segments) => segments.filter((segment) => segment.id !== pendingSegment.id));
|
||||
else d.clearImageTrack?.(tr("remoteAssetRemovedAfterFailure", "在线素材下载失败,已移除临时片段"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
d.setSelectedLibraryAssetId(asset.id);
|
||||
@@ -12,29 +53,40 @@ export function createAssetDropActions(d) {
|
||||
return;
|
||||
}
|
||||
if (track === "image") {
|
||||
d.appendVisualAssetToTimeline(asset);
|
||||
if (pendingSegment) {
|
||||
d.updateVisualAssetInTimeline(asset.id, { ...asset, preparing: false, prepareProgress: 1 });
|
||||
if (asset.type === "video") {
|
||||
extractVideoTrackFrames(asset.src, { duration: asset.duration, width: asset.width, height: asset.height })
|
||||
.then((trackFrames) => { if (trackFrames.length) d.updateVisualAssetInTimeline(asset.id, { trackFrames }); })
|
||||
.catch((error) => console.warn("Remote video timeline frame extraction failed", error));
|
||||
}
|
||||
} else {
|
||||
d.appendVisualAssetToTimeline(asset);
|
||||
d.onFirstVisualDropped?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (track === "overlay") {
|
||||
d.addVisualOverlay?.(asset, options);
|
||||
d.onFirstVisualDropped?.();
|
||||
return;
|
||||
}
|
||||
if (track === "music") {
|
||||
await d.selectAsset(asset);
|
||||
await d.selectAsset(asset, { focusAudio: false });
|
||||
return;
|
||||
}
|
||||
if (track === "audio") {
|
||||
if (!asset.blob) {
|
||||
d.notify("当前音频素材不可用,请重新上传");
|
||||
d.notify(tr("audioAssetUnavailable", "当前音频素材不可用,请重新上传"));
|
||||
return;
|
||||
}
|
||||
const decoded = asset.peaks?.length
|
||||
? { duration: asset.duration, peaks: asset.peaks }
|
||||
const hasValidDuration = Number.isFinite(Number(asset.duration)) && Number(asset.duration) > 0;
|
||||
const decoded = asset.peaks?.length && hasValidDuration
|
||||
? { duration: Number(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("音频已拖入配音音频轨");
|
||||
d.notify(tr("audioDroppedOnVoiceTrack", "音频已拖入配音音频轨"));
|
||||
return;
|
||||
}
|
||||
if (track === "source") {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createAssetDropActions } from "./assetDropActions.js";
|
||||
|
||||
describe("asset timeline drops", () => {
|
||||
it("keeps the Media workspace when audio is dropped on the voice track", async () => {
|
||||
const asset = {
|
||||
id: "ambient-voice",
|
||||
type: "audio",
|
||||
blob: new Blob(["audio"]),
|
||||
duration: 10,
|
||||
peaks: [0.2, 0.7],
|
||||
};
|
||||
const deps = {
|
||||
canDropAssetOnTrack: vi.fn(() => true),
|
||||
setSelectedLibraryAssetId: vi.fn(),
|
||||
replaceAudio: vi.fn(),
|
||||
setSelectedTrack: vi.fn(),
|
||||
setActiveTool: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
};
|
||||
|
||||
await createAssetDropActions(deps).applyAssetToTrack(asset, "audio");
|
||||
|
||||
expect(deps.replaceAudio).toHaveBeenCalledWith(asset.blob, 10, asset.peaks, "音频已写入配音轨");
|
||||
expect(deps.setSelectedTrack).toHaveBeenCalledWith("audio");
|
||||
expect(deps.setActiveTool).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,21 @@
|
||||
import { decodeWaveform } from "./media.js";
|
||||
|
||||
export function createAssetLibraryActions(deps) {
|
||||
async function selectAsset(asset) {
|
||||
async function selectAsset(asset, options = {}) {
|
||||
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);
|
||||
const hasValidDuration = Number.isFinite(Number(asset.duration)) && Number(asset.duration) > 0;
|
||||
const decoded = asset.peaks?.length && hasValidDuration
|
||||
? { duration: Number(asset.duration), peaks: asset.peaks }
|
||||
: await decodeWaveform(asset.blob, 96);
|
||||
deps.replaceMusic(
|
||||
asset.blob,
|
||||
decoded.duration,
|
||||
decoded.peaks,
|
||||
asset.name,
|
||||
undefined,
|
||||
{ focusAudio: options.focusAudio !== false },
|
||||
);
|
||||
return;
|
||||
}
|
||||
deps.replaceVisualTimeline(asset, deps.getVisualDurationForAsset(asset));
|
||||
|
||||
@@ -2,6 +2,30 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { createAssetLibraryActions } from "./assetLibraryActions.js";
|
||||
|
||||
describe("asset library visual selection", () => {
|
||||
it("preserves the Media workspace when music is placed by timeline drag", async () => {
|
||||
const audio = {
|
||||
id: "music-1",
|
||||
type: "audio",
|
||||
blob: new Blob(["audio"]),
|
||||
name: "ambient.mp3",
|
||||
duration: 12,
|
||||
peaks: [0.2, 0.8],
|
||||
};
|
||||
const deps = { replaceMusic: vi.fn(), notify: vi.fn() };
|
||||
const { selectAsset } = createAssetLibraryActions(deps);
|
||||
|
||||
await selectAsset(audio, { focusAudio: false });
|
||||
|
||||
expect(deps.replaceMusic).toHaveBeenCalledWith(
|
||||
audio.blob,
|
||||
12,
|
||||
audio.peaks,
|
||||
audio.name,
|
||||
undefined,
|
||||
{ focusAudio: false },
|
||||
);
|
||||
});
|
||||
|
||||
it("does not extract video audio until the user requests it from the clip menu", async () => {
|
||||
const video = { id: "video-1", type: "video", src: "blob:video", duration: 8 };
|
||||
const deps = {
|
||||
|
||||
@@ -10,7 +10,11 @@ import {
|
||||
export function createAudioTrackActions(d) {
|
||||
function replaceAudio(blob, duration, nextPeaks, nextStatusText, options = {}) {
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
const nextDuration = duration || estimateDuration(options.script ?? d.script);
|
||||
const decodedDuration = Number(duration);
|
||||
const estimatedFallback = Number(estimateDuration(options.script ?? d.script));
|
||||
const nextDuration = Number.isFinite(decodedDuration) && decodedDuration > 0
|
||||
? decodedDuration
|
||||
: Number.isFinite(estimatedFallback) && estimatedFallback > 0 ? estimatedFallback : 0;
|
||||
const start = Math.max(0, options.start ?? d.currentTimeRef.current ?? 0);
|
||||
const id = crypto.randomUUID();
|
||||
const segment = {
|
||||
@@ -19,7 +23,7 @@ export function createAudioTrackActions(d) {
|
||||
url: nextUrl,
|
||||
start,
|
||||
duration: nextDuration,
|
||||
peaks: nextPeaks,
|
||||
peaks: Array.isArray(nextPeaks) ? nextPeaks : [],
|
||||
volume: 1,
|
||||
fadeIn: 0,
|
||||
fadeOut: 0,
|
||||
@@ -57,18 +61,27 @@ export function createAudioTrackActions(d) {
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
function replaceMusic(blob, duration, nextPeaks, nextName, message = "背景音乐已添加到时间线") {
|
||||
function replaceMusic(blob, duration, nextPeaks, nextName, message = "背景音乐已添加到时间线", options = {}) {
|
||||
// Replacing the source while the timeline is playing can leave React's
|
||||
// playback state active after the old object URL has been revoked. The new
|
||||
// audio element then mounts after the sync effect and never receives play().
|
||||
// Stop the old element first so the next user play starts from a clean state.
|
||||
d.musicRef.current?.pause();
|
||||
d.setIsPlaying(false);
|
||||
if (d.musicUrlRef.current) URL.revokeObjectURL(d.musicUrlRef.current);
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
const nextDuration = Number.isFinite(Number(duration)) && Number(duration) > 0 ? Number(duration) : 0;
|
||||
d.musicUrlRef.current = nextUrl;
|
||||
d.setMusicBlob(blob);
|
||||
d.setMusicUrl(nextUrl);
|
||||
d.setMusicName(nextName);
|
||||
d.setMusicDuration(duration || 0);
|
||||
d.setMusicStart(0);
|
||||
d.setMusicDuration(nextDuration);
|
||||
const nextStart = Math.max(0, Number(options.start) || 0);
|
||||
d.setMusicStart(nextStart);
|
||||
d.setMusicPeaks(nextPeaks);
|
||||
d.setMusicSegments?.([{ id: crypto.randomUUID(), start: nextStart, duration: nextDuration, sourceStart: 0, peaks: nextPeaks }]);
|
||||
d.setSelectedTrack("music");
|
||||
d.setActiveTool("audio");
|
||||
if (options.focusAudio !== false) d.setActiveTool("audio");
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
@@ -143,6 +156,7 @@ export function createAudioTrackActions(d) {
|
||||
d.setMusicDuration(0);
|
||||
d.setMusicStart(0);
|
||||
d.setMusicPeaks([]);
|
||||
d.setMusicSegments?.([]);
|
||||
d.setCurrentTime((time) => Math.min(time, Math.max(
|
||||
d.audioBlob ? d.audioDuration : 0,
|
||||
d.captionDuration,
|
||||
|
||||
@@ -125,3 +125,20 @@ export function revokeVisionObjectUrls(value) {
|
||||
}
|
||||
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; }
|
||||
|
||||
export function requestTimelineMediaPlay(media) {
|
||||
if (!media || media.__timelinePlayPending) return;
|
||||
media.__timelinePlayPending = true;
|
||||
let request;
|
||||
try {
|
||||
request = media.play();
|
||||
} catch {
|
||||
media.__timelinePlayPending = false;
|
||||
return;
|
||||
}
|
||||
if (!request?.then) {
|
||||
media.__timelinePlayPending = false;
|
||||
return;
|
||||
}
|
||||
request.catch(() => {}).finally(() => { media.__timelinePlayPending = false; });
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export const FIRST_VISUAL_GUIDE_STORAGE_KEY = "timeline-studio-first-visual-guide-seen-v1";
|
||||
|
||||
export function hasSeenFirstVisualGuide() {
|
||||
try { return window.localStorage.getItem(FIRST_VISUAL_GUIDE_STORAGE_KEY) === "1"; } catch { return false; }
|
||||
}
|
||||
|
||||
export function markFirstVisualGuideSeen() {
|
||||
try { window.localStorage.setItem(FIRST_VISUAL_GUIDE_STORAGE_KEY, "1"); } catch { /* Keep the guide non-blocking when storage is unavailable. */ }
|
||||
}
|
||||
@@ -209,6 +209,27 @@ function encodeAudioBufferAsWav(buffer) {
|
||||
return new Blob([output], { type: "audio/wav" });
|
||||
}
|
||||
|
||||
export async function sliceAudioBlob(blob, start = 0, duration = Infinity) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) throw new Error("当前浏览器不支持 AudioContext,无法裁剪音频。");
|
||||
const context = new AudioContextClass();
|
||||
try {
|
||||
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
|
||||
const safeStart = Math.max(0, Math.min(decoded.duration, Number(start) || 0));
|
||||
const safeDuration = Math.max(0, Math.min(decoded.duration - safeStart, Number(duration) || decoded.duration));
|
||||
if (safeStart <= 0.001 && safeDuration >= decoded.duration - 0.001) return blob;
|
||||
const startFrame = Math.floor(safeStart * decoded.sampleRate);
|
||||
const frameCount = Math.max(1, Math.floor(safeDuration * decoded.sampleRate));
|
||||
const sliced = context.createBuffer(decoded.numberOfChannels, frameCount, decoded.sampleRate);
|
||||
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
|
||||
sliced.getChannelData(channel).set(decoded.getChannelData(channel).subarray(startFrame, startFrame + frameCount));
|
||||
}
|
||||
return encodeAudioBufferAsWav(sliced);
|
||||
} finally {
|
||||
await context.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function concatenateAudioBlobs(blobs = []) {
|
||||
const sources = blobs.filter((blob) => blob instanceof Blob && blob.size > 0);
|
||||
if (!sources.length) throw new Error("没有可合并的音频");
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
const MMS_MODEL_BY_VOICE = {
|
||||
"ko_KR-mms-medium": "Xenova/mms-tts-kor",
|
||||
"vi_VN-mms-medium": "Xenova/mms-tts-vie",
|
||||
"ru_RU-mms-medium": "Xenova/mms-tts-rus",
|
||||
"th_TH-mms-medium": "siridech/mms-tts-tha-onnx",
|
||||
};
|
||||
|
||||
const runtimePromises = new Map();
|
||||
let thaiVocabPromise;
|
||||
|
||||
function encodeWav(samples, sampleRate) {
|
||||
const buffer = new ArrayBuffer(44 + samples.length * 2);
|
||||
const view = new DataView(buffer);
|
||||
const write = (offset, value) => [...value].forEach((char, index) => view.setUint8(offset + index, char.charCodeAt(0)));
|
||||
write(0, "RIFF"); view.setUint32(4, buffer.byteLength - 8, true); write(8, "WAVE"); write(12, "fmt ");
|
||||
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
|
||||
view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
|
||||
write(36, "data"); view.setUint32(40, samples.length * 2, true);
|
||||
for (let index = 0; index < samples.length; index += 1) view.setInt16(44 + index * 2, Math.max(-1, Math.min(1, samples[index])) * 32767, true);
|
||||
return new Blob([buffer], { type: "audio/wav" });
|
||||
}
|
||||
|
||||
export async function predictMmsVoice(input, onProgress) {
|
||||
const modelId = MMS_MODEL_BY_VOICE[input.voiceId];
|
||||
if (!modelId) throw new Error(`Unsupported MMS voice: ${input.voiceId}`);
|
||||
if (!runtimePromises.has(modelId)) {
|
||||
runtimePromises.set(modelId, (async () => {
|
||||
const { env, pipeline } = await import("@huggingface/transformers");
|
||||
env.useBrowserCache = false;
|
||||
const isRootOnnxModel = modelId === "siridech/mms-tts-tha-onnx";
|
||||
return pipeline("text-to-speech", modelId, {
|
||||
dtype: isRootOnnxModel ? "fp32" : "q8",
|
||||
device: "wasm",
|
||||
...(isRootOnnxModel ? { model_file_name: "../model" } : {}),
|
||||
progress_callback: (event) => onProgress?.(event),
|
||||
});
|
||||
})().catch((error) => { runtimePromises.delete(modelId); throw error; }));
|
||||
}
|
||||
const synthesizer = await runtimePromises.get(modelId);
|
||||
onProgress?.({ backend: "wasm" });
|
||||
let text = input.text.trim();
|
||||
if (input.voiceId === "ko_KR-mms-medium") {
|
||||
const { convert } = await import("hangul-romanization");
|
||||
text = convert(text);
|
||||
}
|
||||
let samples;
|
||||
let sampleRate = 16000;
|
||||
if (input.voiceId === "th_TH-mms-medium") {
|
||||
thaiVocabPromise ??= fetch("https://huggingface.co/siridech/mms-tts-tha-onnx/resolve/main/vocab.json").then((response) => {
|
||||
if (!response.ok) throw new Error(`Thai MMS vocabulary failed to load (${response.status})`);
|
||||
return response.json();
|
||||
});
|
||||
const [vocab, { Tensor }] = await Promise.all([thaiVocabPromise, import("@huggingface/transformers")]);
|
||||
const characterIds = [...text].map((character) => vocab[character]).filter(Number.isInteger);
|
||||
if (!characterIds.length) throw new Error("Thai MMS input contains no supported characters");
|
||||
const ids = [0];
|
||||
characterIds.forEach((id) => ids.push(id, 0));
|
||||
const dims = [1, ids.length];
|
||||
const modelOutput = await synthesizer.model({
|
||||
input_ids: new Tensor("int64", BigInt64Array.from(ids, BigInt), dims),
|
||||
attention_mask: new Tensor("int64", BigInt64Array.from(ids, () => 1n), dims),
|
||||
});
|
||||
samples = modelOutput?.waveform?.data;
|
||||
sampleRate = Number(synthesizer.model.config?.sampling_rate) || sampleRate;
|
||||
} else {
|
||||
const output = await synthesizer(text);
|
||||
samples = output?.audio;
|
||||
sampleRate = Number(output?.sampling_rate) || sampleRate;
|
||||
}
|
||||
if (!(samples instanceof Float32Array) || !samples.length || samples.some((sample) => !Number.isFinite(sample))) {
|
||||
throw new Error("MMS generated invalid audio");
|
||||
}
|
||||
return encodeWav(samples, sampleRate);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack } from "./editorRuntime.js";
|
||||
import { getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack, requestTimelineMediaPlay } from "./editorRuntime.js";
|
||||
import { getVisualSegmentIndexAtTime } from "./timeline.js";
|
||||
import { getLinkedSourceAudioState } from "./sourceAudioSync.js";
|
||||
import { getVisualSourceTime, normalizeVisualPlaybackRate } from "./visualEffects.js";
|
||||
|
||||
export function createPlaybackControls(deps) {
|
||||
const isTrackAudible = (track) => deps.trackVisibility?.[track] !== false;
|
||||
const getSourceState = (timelineTime) => deps.sourceAudioLinked && deps.linkedSourceAudioSegments?.length
|
||||
? getLinkedSourceAudioState(deps.linkedSourceAudioSegments, timelineTime)
|
||||
: {
|
||||
@@ -45,14 +46,14 @@ export function createPlaybackControls(deps) {
|
||||
};
|
||||
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;
|
||||
const voices = isTrackAudible("audio") ? deps.audioSegments.map((segment) => ({ segment, audio: deps.audioSegmentRefs.current.get(segment.id) })).filter(({ audio }) => audio) : [];
|
||||
const source = isTrackAudible("source") ? deps.sourceAudioRef.current : null;
|
||||
const music = isTrackAudible("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();
|
||||
const playIf = (media, ready) => ready ? requestTimelineMediaPlay(media) : media?.pause();
|
||||
voices.forEach(({ segment, audio }) => {
|
||||
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
|
||||
audio.currentTime = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
|
||||
|
||||
@@ -23,6 +23,31 @@ function createDeps(overrides = {}) {
|
||||
}
|
||||
|
||||
describe("timeline playhead seeking", () => {
|
||||
it("starts voice and music together when visibility defaults are absent", async () => {
|
||||
const voice = { currentTime: 0, paused: true, playbackRate: 1, volume: 1, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
const music = { currentTime: 0, paused: true, playbackRate: 1, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
const voiceSegment = { id: "voice-1", start: 0, duration: 8, volume: 1 };
|
||||
const deps = createDeps({
|
||||
isPlaying: false,
|
||||
canPreview: true,
|
||||
estimatedDuration: 8,
|
||||
trackVisibility: {},
|
||||
audioSegments: [voiceSegment],
|
||||
audioSegmentRefs: { current: new Map([[voiceSegment.id, voice]]) },
|
||||
musicRef: { current: music },
|
||||
musicUrl: "blob:music",
|
||||
musicDuration: 8,
|
||||
notify: vi.fn(),
|
||||
previewVisualType: "image",
|
||||
visualSegments: [],
|
||||
visualTimeline: [],
|
||||
});
|
||||
createPlaybackControls(deps).handlePlayToggle();
|
||||
expect(voice.play).toHaveBeenCalledOnce();
|
||||
expect(music.play).toHaveBeenCalledOnce();
|
||||
expect(deps.setIsPlaying).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("pauses playback immediately on pointer-down before any move", () => {
|
||||
const pointerListeners = new Map();
|
||||
vi.stubGlobal("addEventListener", vi.fn((type, listener) => pointerListeners.set(type, listener)));
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
const remoteAssetCache = new Map();
|
||||
|
||||
export function clearRemoteAssetCache() {
|
||||
remoteAssetCache.clear();
|
||||
}
|
||||
|
||||
export async function getRemoteAssetBlob(asset, onProgress) {
|
||||
if (asset?.blob) return asset.blob;
|
||||
if (!asset?.src || !/^https?:/i.test(asset.src)) return null;
|
||||
const key = asset.src;
|
||||
const cached = remoteAssetCache.get(key);
|
||||
if (cached?.blob) { onProgress?.(1); return cached.blob; }
|
||||
if (cached?.promise) { cached.listeners.add(onProgress); return cached.promise; }
|
||||
|
||||
const listeners = new Set(onProgress ? [onProgress] : []);
|
||||
const entry = { blob: null, listeners, promise: null };
|
||||
entry.promise = (async () => {
|
||||
const response = await fetch(key, {
|
||||
mode: "cors",
|
||||
credentials: "omit",
|
||||
referrerPolicy: "no-referrer",
|
||||
});
|
||||
if (!response.ok) throw new Error(String(response.status));
|
||||
const total = Number(response.headers.get("content-length")) || 0;
|
||||
if (!response.body) return response.blob();
|
||||
const reader = response.body.getReader();
|
||||
const chunks = [];
|
||||
let received = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value); received += value.byteLength;
|
||||
const progress = total ? Math.min(0.98, received / total) : 0.45;
|
||||
entry.listeners.forEach((listener) => listener?.(progress));
|
||||
}
|
||||
return new Blob(chunks, { type: response.headers.get("content-type") || "application/octet-stream" });
|
||||
})().then((blob) => {
|
||||
entry.blob = blob; entry.listeners.forEach((listener) => listener?.(1)); return blob;
|
||||
}).catch((error) => { remoteAssetCache.delete(key); throw error; });
|
||||
remoteAssetCache.set(key, entry);
|
||||
return entry.promise;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { loadTextToSpeech, loadVoiceStyle, writeWavFile } from "./supertonicWebRuntime.js";
|
||||
|
||||
const MODEL_BASE = "https://huggingface.co/Supertone/supertonic-3/resolve/main/onnx";
|
||||
const STYLE_URL = "https://huggingface.co/Supertone/supertonic-3/resolve/main/voice_styles/F1.json";
|
||||
let runtimePromise;
|
||||
|
||||
async function loadRuntime(onProgress) {
|
||||
if (!runtimePromise) {
|
||||
runtimePromise = (async () => {
|
||||
const [{ textToSpeech }, style] = await Promise.all([
|
||||
loadTextToSpeech(MODEL_BASE, { executionProviders: ["wasm"], graphOptimizationLevel: "all" }, (modelName, current, total) => {
|
||||
onProgress?.({ progress: (current / total) * 100, file: modelName });
|
||||
}),
|
||||
loadVoiceStyle([STYLE_URL], false),
|
||||
]);
|
||||
return { textToSpeech, style };
|
||||
})().catch((error) => { runtimePromise = undefined; throw error; });
|
||||
}
|
||||
return runtimePromise;
|
||||
}
|
||||
|
||||
export async function predictSupertonicVoice(input, onProgress) {
|
||||
const { textToSpeech, style } = await loadRuntime(onProgress);
|
||||
onProgress?.({ backend: "wasm" });
|
||||
const { wav, duration } = await textToSpeech.call(input.text.trim(), "ja", style, 5, Number(input.speed) || 1.05, 0.3, (step, total) => {
|
||||
onProgress?.({ progress: (step / total) * 100 });
|
||||
});
|
||||
const sampleCount = Math.max(1, Math.floor(textToSpeech.sampleRate * duration[0]));
|
||||
return new Blob([writeWavFile(wav.slice(0, sampleCount), textToSpeech.sampleRate)], { type: "audio/wav" });
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
/* eslint-disable */
|
||||
// Vendored from Supertone's MIT-licensed Supertonic 3 browser reference runtime.
|
||||
import * as ort from 'onnxruntime-web/webgpu';
|
||||
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?url";
|
||||
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
|
||||
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
|
||||
|
||||
// Available languages for multilingual TTS
|
||||
export const AVAILABLE_LANGS = ['en', 'ko', 'ja', 'ar', 'bg', 'cs', 'da', 'de', 'el', 'es', 'et', 'fi', 'fr', 'hi', 'hr', 'hu', 'id', 'it', 'lt', 'lv', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sv', 'tr', 'uk', 'vi', 'na'];
|
||||
|
||||
export function isValidLang(lang) {
|
||||
return AVAILABLE_LANGS.includes(lang);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unicode Text Processor
|
||||
*/
|
||||
export class UnicodeProcessor {
|
||||
constructor(indexer) {
|
||||
this.indexer = indexer;
|
||||
}
|
||||
|
||||
call(textList, langList) {
|
||||
const processedTexts = textList.map((text, i) => this.preprocessText(text, langList[i]));
|
||||
|
||||
const textIdsLengths = processedTexts.map(text => text.length);
|
||||
const maxLen = Math.max(...textIdsLengths);
|
||||
|
||||
const textIds = processedTexts.map(text => {
|
||||
const row = new Array(maxLen).fill(0);
|
||||
for (let j = 0; j < text.length; j++) {
|
||||
const codePoint = text.codePointAt(j);
|
||||
row[j] = (codePoint < this.indexer.length) ? this.indexer[codePoint] : -1;
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
const textMask = this.getTextMask(textIdsLengths);
|
||||
return { textIds, textMask };
|
||||
}
|
||||
|
||||
preprocessText(text, lang) {
|
||||
// TODO: Need advanced normalizer for better performance
|
||||
text = text.normalize('NFKD');
|
||||
|
||||
// Remove emojis (wide Unicode range)
|
||||
const emojiPattern = /[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F1E6}-\u{1F1FF}]+/gu;
|
||||
text = text.replace(emojiPattern, '');
|
||||
|
||||
// Replace various dashes and symbols
|
||||
const replacements = {
|
||||
'–': '-',
|
||||
'‑': '-',
|
||||
'—': '-',
|
||||
'_': ' ',
|
||||
'\u201C': '"', // left double quote "
|
||||
'\u201D': '"', // right double quote "
|
||||
'\u2018': "'", // left single quote '
|
||||
'\u2019': "'", // right single quote '
|
||||
'´': "'",
|
||||
'`': "'",
|
||||
'[': ' ',
|
||||
']': ' ',
|
||||
'|': ' ',
|
||||
'/': ' ',
|
||||
'#': ' ',
|
||||
'→': ' ',
|
||||
'←': ' ',
|
||||
};
|
||||
for (const [k, v] of Object.entries(replacements)) {
|
||||
text = text.replaceAll(k, v);
|
||||
}
|
||||
|
||||
// Remove special symbols
|
||||
text = text.replace(/[♥☆♡©\\]/g, '');
|
||||
|
||||
// Replace known expressions
|
||||
const exprReplacements = {
|
||||
'@': ' at ',
|
||||
'e.g.,': 'for example, ',
|
||||
'i.e.,': 'that is, ',
|
||||
};
|
||||
for (const [k, v] of Object.entries(exprReplacements)) {
|
||||
text = text.replaceAll(k, v);
|
||||
}
|
||||
|
||||
// Fix spacing around punctuation
|
||||
text = text.replace(/ ,/g, ',');
|
||||
text = text.replace(/ \./g, '.');
|
||||
text = text.replace(/ !/g, '!');
|
||||
text = text.replace(/ \?/g, '?');
|
||||
text = text.replace(/ ;/g, ';');
|
||||
text = text.replace(/ :/g, ':');
|
||||
text = text.replace(/ '/g, "'");
|
||||
|
||||
// Remove duplicate quotes
|
||||
while (text.includes('""')) {
|
||||
text = text.replace('""', '"');
|
||||
}
|
||||
while (text.includes("''")) {
|
||||
text = text.replace("''", "'");
|
||||
}
|
||||
while (text.includes('``')) {
|
||||
text = text.replace('``', '`');
|
||||
}
|
||||
|
||||
// Remove extra spaces
|
||||
text = text.replace(/\s+/g, ' ').trim();
|
||||
|
||||
// If text doesn't end with punctuation, quotes, or closing brackets, add a period
|
||||
if (!/[.!?;:,'\"')\]}…。」』】〉》›»]$/.test(text)) {
|
||||
text += '.';
|
||||
}
|
||||
|
||||
// Validate language
|
||||
if (!isValidLang(lang)) {
|
||||
throw new Error(`Invalid language: ${lang}. Available: ${AVAILABLE_LANGS.join(', ')}`);
|
||||
}
|
||||
|
||||
// Wrap text with language tags
|
||||
text = `<${lang}>${text}</${lang}>`;
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
getTextMask(textIdsLengths) {
|
||||
const maxLen = Math.max(...textIdsLengths);
|
||||
return this.lengthToMask(textIdsLengths, maxLen);
|
||||
}
|
||||
|
||||
lengthToMask(lengths, maxLen = null) {
|
||||
const actualMaxLen = maxLen || Math.max(...lengths);
|
||||
return lengths.map(len => {
|
||||
const row = new Array(actualMaxLen).fill(0.0);
|
||||
for (let j = 0; j < Math.min(len, actualMaxLen); j++) {
|
||||
row[j] = 1.0;
|
||||
}
|
||||
return [row];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Style class to hold TTL and DP tensors
|
||||
*/
|
||||
export class Style {
|
||||
constructor(ttlTensor, dpTensor) {
|
||||
this.ttl = ttlTensor;
|
||||
this.dp = dpTensor;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Text-to-Speech class
|
||||
*/
|
||||
export class TextToSpeech {
|
||||
constructor(cfgs, textProcessor, dpOrt, textEncOrt, vectorEstOrt, vocoderOrt) {
|
||||
this.cfgs = cfgs;
|
||||
this.textProcessor = textProcessor;
|
||||
this.dpOrt = dpOrt;
|
||||
this.textEncOrt = textEncOrt;
|
||||
this.vectorEstOrt = vectorEstOrt;
|
||||
this.vocoderOrt = vocoderOrt;
|
||||
this.sampleRate = cfgs.ae.sample_rate;
|
||||
}
|
||||
|
||||
async _infer(textList, langList, style, totalStep, speed = 1.05, progressCallback = null) {
|
||||
const bsz = textList.length;
|
||||
|
||||
// Process text
|
||||
const { textIds, textMask } = this.textProcessor.call(textList, langList);
|
||||
|
||||
const textIdsFlat = new BigInt64Array(textIds.flat().map(x => BigInt(x)));
|
||||
const textIdsShape = [bsz, textIds[0].length];
|
||||
const textIdsTensor = new ort.Tensor('int64', textIdsFlat, textIdsShape);
|
||||
|
||||
const textMaskFlat = new Float32Array(textMask.flat(2));
|
||||
const textMaskShape = [bsz, 1, textMask[0][0].length];
|
||||
const textMaskTensor = new ort.Tensor('float32', textMaskFlat, textMaskShape);
|
||||
|
||||
// Predict duration
|
||||
const dpOutputs = await this.dpOrt.run({
|
||||
text_ids: textIdsTensor,
|
||||
style_dp: style.dp,
|
||||
text_mask: textMaskTensor
|
||||
});
|
||||
const duration = Array.from(dpOutputs.duration.data);
|
||||
|
||||
// Apply speed factor to duration
|
||||
for (let i = 0; i < duration.length; i++) {
|
||||
duration[i] /= speed;
|
||||
}
|
||||
|
||||
// Encode text
|
||||
const textEncOutputs = await this.textEncOrt.run({
|
||||
text_ids: textIdsTensor,
|
||||
style_ttl: style.ttl,
|
||||
text_mask: textMaskTensor
|
||||
});
|
||||
const textEmb = textEncOutputs.text_emb;
|
||||
|
||||
// Sample noisy latent
|
||||
let { xt, latentMask } = this.sampleNoisyLatent(
|
||||
duration,
|
||||
this.sampleRate,
|
||||
this.cfgs.ae.base_chunk_size,
|
||||
this.cfgs.ttl.chunk_compress_factor,
|
||||
this.cfgs.ttl.latent_dim
|
||||
);
|
||||
|
||||
const latentMaskFlat = new Float32Array(latentMask.flat(2));
|
||||
const latentMaskShape = [bsz, 1, latentMask[0][0].length];
|
||||
const latentMaskTensor = new ort.Tensor('float32', latentMaskFlat, latentMaskShape);
|
||||
|
||||
// Prepare constant arrays
|
||||
const totalStepArray = new Float32Array(bsz).fill(totalStep);
|
||||
const totalStepTensor = new ort.Tensor('float32', totalStepArray, [bsz]);
|
||||
|
||||
// Denoising loop
|
||||
for (let step = 0; step < totalStep; step++) {
|
||||
if (progressCallback) {
|
||||
progressCallback(step + 1, totalStep);
|
||||
}
|
||||
|
||||
const currentStepArray = new Float32Array(bsz).fill(step);
|
||||
const currentStepTensor = new ort.Tensor('float32', currentStepArray, [bsz]);
|
||||
|
||||
const xtFlat = new Float32Array(xt.flat(2));
|
||||
const xtShape = [bsz, xt[0].length, xt[0][0].length];
|
||||
const xtTensor = new ort.Tensor('float32', xtFlat, xtShape);
|
||||
|
||||
const vectorEstOutputs = await this.vectorEstOrt.run({
|
||||
noisy_latent: xtTensor,
|
||||
text_emb: textEmb,
|
||||
style_ttl: style.ttl,
|
||||
latent_mask: latentMaskTensor,
|
||||
text_mask: textMaskTensor,
|
||||
current_step: currentStepTensor,
|
||||
total_step: totalStepTensor
|
||||
});
|
||||
|
||||
const denoised = Array.from(vectorEstOutputs.denoised_latent.data);
|
||||
|
||||
// Reshape to 3D
|
||||
const latentDim = xt[0].length;
|
||||
const latentLen = xt[0][0].length;
|
||||
xt = [];
|
||||
let idx = 0;
|
||||
for (let b = 0; b < bsz; b++) {
|
||||
const batch = [];
|
||||
for (let d = 0; d < latentDim; d++) {
|
||||
const row = [];
|
||||
for (let t = 0; t < latentLen; t++) {
|
||||
row.push(denoised[idx++]);
|
||||
}
|
||||
batch.push(row);
|
||||
}
|
||||
xt.push(batch);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate waveform
|
||||
const finalXtFlat = new Float32Array(xt.flat(2));
|
||||
const finalXtShape = [bsz, xt[0].length, xt[0][0].length];
|
||||
const finalXtTensor = new ort.Tensor('float32', finalXtFlat, finalXtShape);
|
||||
|
||||
const vocoderOutputs = await this.vocoderOrt.run({
|
||||
latent: finalXtTensor
|
||||
});
|
||||
|
||||
const wav = Array.from(vocoderOutputs.wav_tts.data);
|
||||
|
||||
return { wav, duration };
|
||||
}
|
||||
|
||||
async call(text, lang, style, totalStep, speed = 1.05, silenceDuration = 0.3, progressCallback = null) {
|
||||
if (style.ttl.dims[0] !== 1) {
|
||||
throw new Error('Single speaker text to speech only supports single style');
|
||||
}
|
||||
const maxLen = (lang === 'ko' || lang === 'ja') ? 120 : 300;
|
||||
const textList = chunkText(text, maxLen);
|
||||
const langList = new Array(textList.length).fill(lang);
|
||||
let wavCat = [];
|
||||
let durCat = 0;
|
||||
|
||||
for (let i = 0; i < textList.length; i++) {
|
||||
const { wav, duration } = await this._infer([textList[i]], [langList[i]], style, totalStep, speed, progressCallback);
|
||||
|
||||
if (wavCat.length === 0) {
|
||||
wavCat = wav;
|
||||
durCat = duration[0];
|
||||
} else {
|
||||
const silenceLen = Math.floor(silenceDuration * this.sampleRate);
|
||||
const silence = new Array(silenceLen).fill(0);
|
||||
wavCat = [...wavCat, ...silence, ...wav];
|
||||
durCat += duration[0] + silenceDuration;
|
||||
}
|
||||
}
|
||||
|
||||
return { wav: wavCat, duration: [durCat] };
|
||||
}
|
||||
|
||||
async batch(textList, langList, style, totalStep, speed = 1.05, progressCallback = null) {
|
||||
return await this._infer(textList, langList, style, totalStep, speed, progressCallback);
|
||||
}
|
||||
|
||||
sampleNoisyLatent(duration, sampleRate, baseChunkSize, chunkCompress, latentDim) {
|
||||
const bsz = duration.length;
|
||||
const maxDur = Math.max(...duration);
|
||||
|
||||
const wavLenMax = Math.floor(maxDur * sampleRate);
|
||||
const wavLengths = duration.map(d => Math.floor(d * sampleRate));
|
||||
|
||||
const chunkSize = baseChunkSize * chunkCompress;
|
||||
const latentLen = Math.floor((wavLenMax + chunkSize - 1) / chunkSize);
|
||||
const latentDimVal = latentDim * chunkCompress;
|
||||
|
||||
const xt = [];
|
||||
for (let b = 0; b < bsz; b++) {
|
||||
const batch = [];
|
||||
for (let d = 0; d < latentDimVal; d++) {
|
||||
const row = [];
|
||||
for (let t = 0; t < latentLen; t++) {
|
||||
// Box-Muller transform
|
||||
const u1 = Math.max(0.0001, Math.random());
|
||||
const u2 = Math.random();
|
||||
const val = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2);
|
||||
row.push(val);
|
||||
}
|
||||
batch.push(row);
|
||||
}
|
||||
xt.push(batch);
|
||||
}
|
||||
|
||||
const latentLengths = wavLengths.map(len => Math.floor((len + chunkSize - 1) / chunkSize));
|
||||
const latentMask = this.lengthToMask(latentLengths, latentLen);
|
||||
|
||||
// Apply mask
|
||||
for (let b = 0; b < bsz; b++) {
|
||||
for (let d = 0; d < latentDimVal; d++) {
|
||||
for (let t = 0; t < latentLen; t++) {
|
||||
xt[b][d][t] *= latentMask[b][0][t];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { xt, latentMask };
|
||||
}
|
||||
|
||||
lengthToMask(lengths, maxLen = null) {
|
||||
const actualMaxLen = maxLen || Math.max(...lengths);
|
||||
return lengths.map(len => {
|
||||
const row = new Array(actualMaxLen).fill(0.0);
|
||||
for (let j = 0; j < Math.min(len, actualMaxLen); j++) {
|
||||
row[j] = 1.0;
|
||||
}
|
||||
return [row];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load voice style from JSON files
|
||||
*/
|
||||
export async function loadVoiceStyle(voiceStylePaths, verbose = false) {
|
||||
const bsz = voiceStylePaths.length;
|
||||
|
||||
// Read first file to get dimensions
|
||||
const firstResponse = await fetch(voiceStylePaths[0]);
|
||||
const firstStyle = await firstResponse.json();
|
||||
|
||||
const ttlDims = firstStyle.style_ttl.dims;
|
||||
const dpDims = firstStyle.style_dp.dims;
|
||||
|
||||
const ttlDim1 = ttlDims[1];
|
||||
const ttlDim2 = ttlDims[2];
|
||||
const dpDim1 = dpDims[1];
|
||||
const dpDim2 = dpDims[2];
|
||||
|
||||
// Pre-allocate arrays with full batch size
|
||||
const ttlSize = bsz * ttlDim1 * ttlDim2;
|
||||
const dpSize = bsz * dpDim1 * dpDim2;
|
||||
const ttlFlat = new Float32Array(ttlSize);
|
||||
const dpFlat = new Float32Array(dpSize);
|
||||
|
||||
// Fill in the data
|
||||
for (let i = 0; i < bsz; i++) {
|
||||
const response = await fetch(voiceStylePaths[i]);
|
||||
const voiceStyle = await response.json();
|
||||
|
||||
// Flatten TTL data
|
||||
const ttlData = voiceStyle.style_ttl.data.flat(Infinity);
|
||||
const ttlOffset = i * ttlDim1 * ttlDim2;
|
||||
ttlFlat.set(ttlData, ttlOffset);
|
||||
|
||||
// Flatten DP data
|
||||
const dpData = voiceStyle.style_dp.data.flat(Infinity);
|
||||
const dpOffset = i * dpDim1 * dpDim2;
|
||||
dpFlat.set(dpData, dpOffset);
|
||||
}
|
||||
|
||||
const ttlShape = [bsz, ttlDim1, ttlDim2];
|
||||
const dpShape = [bsz, dpDim1, dpDim2];
|
||||
|
||||
const ttlTensor = new ort.Tensor('float32', ttlFlat, ttlShape);
|
||||
const dpTensor = new ort.Tensor('float32', dpFlat, dpShape);
|
||||
|
||||
if (verbose) {
|
||||
console.log(`Loaded ${bsz} voice styles`);
|
||||
}
|
||||
|
||||
return new Style(ttlTensor, dpTensor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configuration from JSON
|
||||
*/
|
||||
export async function loadCfgs(onnxDir) {
|
||||
const response = await fetch(`${onnxDir}/tts.json`);
|
||||
const cfgs = await response.json();
|
||||
return cfgs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load text processor
|
||||
*/
|
||||
export async function loadTextProcessor(onnxDir) {
|
||||
const response = await fetch(`${onnxDir}/unicode_indexer.json`);
|
||||
const indexer = await response.json();
|
||||
return new UnicodeProcessor(indexer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load ONNX model
|
||||
*/
|
||||
export async function loadOnnx(onnxPath, options) {
|
||||
const session = await ort.InferenceSession.create(onnxPath, options);
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all TTS components
|
||||
*/
|
||||
export async function loadTextToSpeech(onnxDir, sessionOptions = {}, progressCallback = null) {
|
||||
console.log('Using WebAssembly/WebGPU for inference');
|
||||
|
||||
const cfgs = await loadCfgs(onnxDir);
|
||||
|
||||
const dpPath = `${onnxDir}/duration_predictor.onnx`;
|
||||
const textEncPath = `${onnxDir}/text_encoder.onnx`;
|
||||
const vectorEstPath = `${onnxDir}/vector_estimator.onnx`;
|
||||
const vocoderPath = `${onnxDir}/vocoder.onnx`;
|
||||
|
||||
const modelPaths = [
|
||||
{ name: 'Duration Predictor', path: dpPath },
|
||||
{ name: 'Text Encoder', path: textEncPath },
|
||||
{ name: 'Vector Estimator', path: vectorEstPath },
|
||||
{ name: 'Vocoder', path: vocoderPath }
|
||||
];
|
||||
|
||||
const sessions = [];
|
||||
for (let i = 0; i < modelPaths.length; i++) {
|
||||
if (progressCallback) {
|
||||
progressCallback(modelPaths[i].name, i + 1, modelPaths.length);
|
||||
}
|
||||
const session = await loadOnnx(modelPaths[i].path, sessionOptions);
|
||||
sessions.push(session);
|
||||
}
|
||||
|
||||
const [dpOrt, textEncOrt, vectorEstOrt, vocoderOrt] = sessions;
|
||||
|
||||
const textProcessor = await loadTextProcessor(onnxDir);
|
||||
const textToSpeech = new TextToSpeech(cfgs, textProcessor, dpOrt, textEncOrt, vectorEstOrt, vocoderOrt);
|
||||
|
||||
return { textToSpeech, cfgs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Chunk text into manageable segments
|
||||
*/
|
||||
function chunkText(text, maxLen = 300) {
|
||||
if (typeof text !== 'string') {
|
||||
throw new Error(`chunkText expects a string, got ${typeof text}`);
|
||||
}
|
||||
|
||||
// Split by paragraph (two or more newlines)
|
||||
const paragraphs = text.trim().split(/\n\s*\n+/).filter(p => p.trim());
|
||||
|
||||
const chunks = [];
|
||||
|
||||
for (let paragraph of paragraphs) {
|
||||
paragraph = paragraph.trim();
|
||||
if (!paragraph) continue;
|
||||
|
||||
// Split by sentence boundaries (period, question mark, exclamation mark followed by space)
|
||||
// But exclude common abbreviations like Mr., Mrs., Dr., etc. and single capital letters like F.
|
||||
const sentences = paragraph.split(/(?<!Mr\.|Mrs\.|Ms\.|Dr\.|Prof\.|Sr\.|Jr\.|Ph\.D\.|etc\.|e\.g\.|i\.e\.|vs\.|Inc\.|Ltd\.|Co\.|Corp\.|St\.|Ave\.|Blvd\.)(?<!\b[A-Z]\.)(?<=[.!?])\s+/);
|
||||
|
||||
let currentChunk = "";
|
||||
|
||||
for (let sentence of sentences) {
|
||||
if (currentChunk.length + sentence.length + 1 <= maxLen) {
|
||||
currentChunk += (currentChunk ? " " : "") + sentence;
|
||||
} else {
|
||||
if (currentChunk) {
|
||||
chunks.push(currentChunk.trim());
|
||||
}
|
||||
currentChunk = sentence;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentChunk) {
|
||||
chunks.push(currentChunk.trim());
|
||||
}
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write WAV file to ArrayBuffer
|
||||
*/
|
||||
export function writeWavFile(audioData, sampleRate) {
|
||||
const numChannels = 1;
|
||||
const bitsPerSample = 16;
|
||||
const byteRate = sampleRate * numChannels * bitsPerSample / 8;
|
||||
const blockAlign = numChannels * bitsPerSample / 8;
|
||||
const dataSize = audioData.length * 2;
|
||||
|
||||
// Create ArrayBuffer
|
||||
const buffer = new ArrayBuffer(44 + dataSize);
|
||||
const view = new DataView(buffer);
|
||||
|
||||
// Write WAV header
|
||||
const writeString = (offset, string) => {
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
view.setUint8(offset + i, string.charCodeAt(i));
|
||||
}
|
||||
};
|
||||
|
||||
writeString(0, 'RIFF');
|
||||
view.setUint32(4, 36 + dataSize, true);
|
||||
writeString(8, 'WAVE');
|
||||
writeString(12, 'fmt ');
|
||||
view.setUint32(16, 16, true);
|
||||
view.setUint16(20, 1, true); // PCM
|
||||
view.setUint16(22, numChannels, true);
|
||||
view.setUint32(24, sampleRate, true);
|
||||
view.setUint32(28, byteRate, true);
|
||||
view.setUint16(32, blockAlign, true);
|
||||
view.setUint16(34, bitsPerSample, true);
|
||||
writeString(36, 'data');
|
||||
view.setUint32(40, dataSize, true);
|
||||
|
||||
// Write audio data
|
||||
const int16Data = new Int16Array(audioData.length);
|
||||
for (let i = 0; i < audioData.length; i++) {
|
||||
const clamped = Math.max(-1.0, Math.min(1.0, audioData[i]));
|
||||
int16Data[i] = Math.floor(clamped * 32767);
|
||||
}
|
||||
|
||||
const dataView = new Uint8Array(buffer, 44);
|
||||
dataView.set(new Uint8Array(int16Data.buffer));
|
||||
|
||||
return buffer;
|
||||
}
|
||||
@@ -30,6 +30,8 @@ export function getVisualAssetPayload(asset) {
|
||||
assetId: asset.assetId ?? asset.id ?? "",
|
||||
type: asset.type ?? "image",
|
||||
src: asset.src ?? "",
|
||||
thumbnail: asset.thumbnail ?? "",
|
||||
originalSrc: asset.originalSrc ?? "",
|
||||
name: asset.name ?? "",
|
||||
meta: asset.meta ?? "",
|
||||
blob: asset.blob ?? null,
|
||||
@@ -39,6 +41,8 @@ export function getVisualAssetPayload(asset) {
|
||||
sourceDuration: Math.max(0, Number(asset.sourceDuration ?? asset.duration) || 0),
|
||||
playbackRate: Math.max(0.25, Math.min(4, Number(asset.playbackRate) || 1)),
|
||||
trackFrames: Array.isArray(asset.trackFrames) ? asset.trackFrames : [],
|
||||
preparing: Boolean(asset.preparing),
|
||||
prepareProgress: Math.max(0, Math.min(1, Number(asset.prepareProgress) || 0)),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -83,10 +83,34 @@ export function createTimelineCutActions(d) {
|
||||
d.setSelectedAudioSegmentId(secondId);
|
||||
d.notify("已在播放头位置切开配音片段");
|
||||
};
|
||||
const handleCutMusicSegment = () => {
|
||||
if (d.trackLocks.music) return void d.notify("音乐轨已锁定,无法剪切");
|
||||
if (!d.musicBlob || d.musicDuration <= 0) return void d.notify("请先添加背景音乐");
|
||||
const segments = d.musicSegments?.length ? d.musicSegments : [{
|
||||
id: "music-audio", start: d.musicStart || 0, duration: d.musicDuration,
|
||||
sourceStart: 0, peaks: d.musicPeaks || [],
|
||||
}];
|
||||
const index = segments.findIndex((segment) => d.currentTime > segment.start + 0.05 && d.currentTime < segment.start + segment.duration - 0.05);
|
||||
const source = segments[index];
|
||||
if (!source) return void d.notify("请把播放头放在音乐片段中间再剪切");
|
||||
const firstDuration = d.currentTime - source.start;
|
||||
const secondDuration = source.duration - firstDuration;
|
||||
const peakCount = source.peaks?.length || 0;
|
||||
const peakSplit = peakCount > 1 ? Math.max(1, Math.min(peakCount - 1, Math.round(firstDuration / source.duration * peakCount))) : 0;
|
||||
const first = { ...source, id: makeId("music"), duration: firstDuration, peaks: peakCount ? source.peaks.slice(0, peakSplit) : [] };
|
||||
const second = { ...source, id: makeId("music"), start: d.currentTime, duration: secondDuration,
|
||||
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration,
|
||||
peaks: peakCount ? source.peaks.slice(peakSplit) : [] };
|
||||
const next = [...segments];
|
||||
next.splice(index, 1, first, second);
|
||||
d.setMusicSegments(next);
|
||||
d.notify("已在播放头位置切开音乐片段");
|
||||
};
|
||||
const handleCutTrack = () => {
|
||||
if (d.selectedTrack === "image") return void handleCutVisualSegment();
|
||||
if (d.selectedTrack === "caption") return void handleCutCaption();
|
||||
if (d.selectedTrack === "audio") return void handleCutAudioSegment();
|
||||
if (d.selectedTrack === "music") return void handleCutMusicSegment();
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法剪切");
|
||||
const selected = d.selectedStickerSegmentId && d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId);
|
||||
|
||||
@@ -3,6 +3,30 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { createTimelineCutActions } from "./timelineCutActions.js";
|
||||
|
||||
describe("timeline cut actions", () => {
|
||||
it("cuts music at the playhead and preserves waveform and source offsets", () => {
|
||||
let musicSegments = [];
|
||||
const notify = vi.fn();
|
||||
const actions = createTimelineCutActions({
|
||||
currentTime: 6,
|
||||
musicBlob: new Blob(["music"]),
|
||||
musicDuration: 10,
|
||||
musicPeaks: [0.1, 0.2, 0.3, 0.4],
|
||||
musicSegments,
|
||||
musicStart: 2,
|
||||
notify,
|
||||
selectedTrack: "music",
|
||||
setMusicSegments: (segments) => { musicSegments = segments; },
|
||||
trackLocks: {},
|
||||
});
|
||||
|
||||
actions.handleCutTrack();
|
||||
|
||||
expect(musicSegments).toHaveLength(2);
|
||||
expect(musicSegments[0]).toMatchObject({ start: 2, duration: 4, sourceStart: 0, peaks: [0.1, 0.2] });
|
||||
expect(musicSegments[1]).toMatchObject({ start: 6, duration: 6, sourceStart: 4, peaks: [0.3, 0.4] });
|
||||
expect(notify).toHaveBeenCalledWith("已在播放头位置切开音乐片段");
|
||||
});
|
||||
|
||||
it("cuts a selected voiceover at the playhead and offsets the second source", () => {
|
||||
const source = {
|
||||
id: "voice-original",
|
||||
|
||||
@@ -11,8 +11,9 @@ export function createTimelineMoveControls(d) {
|
||||
if (!(clipDuration > 0) || d.trackLocks[track]) return void d.notify(`${isSource ? "视频原声" : "音乐"}轨已锁定,无法移动`);
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect(); const duration = d.timelineDurationRef.current || 10;
|
||||
if (!rect) return;
|
||||
event.preventDefault(); event.stopPropagation(); d.setSelectedTrack(track); d.setActiveTool("audio");
|
||||
event.preventDefault(); event.stopPropagation(); d.setSelectedTrack(track);
|
||||
const startX = event.clientX; let moved = false; let latest = start;
|
||||
const originalMusicSegments = !isSource && Array.isArray(d.musicSegments) ? d.musicSegments : [];
|
||||
const snapPoints = collectTimelineSnapPoints(d, { track, id: track });
|
||||
const move = (e) => {
|
||||
if (!moved && Math.abs(e.clientX - startX) < 4) return;
|
||||
@@ -22,11 +23,18 @@ export function createTimelineMoveControls(d) {
|
||||
latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - clipDuration, snapped.start));
|
||||
d.setSnapGuide?.(snapped.guide);
|
||||
if (isSource) { d.setSourceAudioLinked(false); d.setSourceAudioStart(latest); }
|
||||
else d.setMusicStart(latest);
|
||||
else {
|
||||
d.setMusicStart(latest);
|
||||
if (originalMusicSegments.length) d.setMusicSegments?.(originalMusicSegments.map((segment) => ({ ...segment, start: segment.start + latest - start })));
|
||||
}
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((latest + clipDuration + 5) / 10) * 10));
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
|
||||
const up = () => { cleanup(); if (moved) { d.seekTo(latest); d.notify(`${isSource ? "视频原声" : "音乐"}片段位置已调整`); } };
|
||||
const up = () => { cleanup(); if (moved) {
|
||||
d.suppressTimelineClipClickRef.current = track;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === track) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
d.seekTo(latest); d.notify(`${isSource ? "视频原声" : "音乐"}片段位置已调整`);
|
||||
} };
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
};
|
||||
const startAudioSegmentMove = (event, id = "") => {
|
||||
@@ -57,7 +65,11 @@ export function createTimelineMoveControls(d) {
|
||||
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); d.setSnapGuide?.(null); };
|
||||
const up = () => { cleanup(); if (moved) { d.seekTo(latest); d.notify(d.t("audioClipMoved")); } };
|
||||
const up = () => { cleanup(); if (moved) {
|
||||
d.suppressTimelineClipClickRef.current = segment.id;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segment.id) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
d.seekTo(latest); d.notify(d.t("audioClipMoved"));
|
||||
} };
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
};
|
||||
const startStickerSegmentMove = (event, id = "") => {
|
||||
|
||||
+29
-16
@@ -125,33 +125,46 @@ export function removeVisualPropertyKeyframe(keyframes = [], time, key) {
|
||||
});
|
||||
}
|
||||
|
||||
export function snapVisualScaleToFrameEdges(transform = {}, frame = {}, thresholdPixels = 8) {
|
||||
export function snapVisualScaleToFrameEdges(transform = {}, frame = {}, thresholdPixels = 8, contentBox = frame) {
|
||||
const width = Math.max(1, Number(frame.width) || 1);
|
||||
const height = Math.max(1, Number(frame.height) || 1);
|
||||
const boxWidth = Math.max(1, Number(contentBox?.width) || width);
|
||||
const boxHeight = Math.max(1, Number(contentBox?.height) || height);
|
||||
const scale = Math.max(0.1, Number(transform.scale) || 1);
|
||||
const centerX = 0.5 + (Number(transform.x) || 0) / 100;
|
||||
const centerY = 0.5 + (Number(transform.y) || 0) / 100;
|
||||
const centerX = width * (0.5 + (Number(transform.x) || 0) / 100);
|
||||
const centerY = height * (0.5 + (Number(transform.y) || 0) / 100);
|
||||
const radians = (Number(transform.rotation) || 0) * Math.PI / 180;
|
||||
const cosine = Math.abs(Math.cos(radians));
|
||||
const sine = Math.abs(Math.sin(radians));
|
||||
const horizontalScaleExtent = 0.5 * (cosine + (height / width) * sine);
|
||||
const verticalScaleExtent = 0.5 * (cosine + (width / height) * sine);
|
||||
const targets = [
|
||||
{ scale: centerX / horizontalScaleExtent, guide: "left", dimension: width },
|
||||
{ scale: (1 - centerX) / horizontalScaleExtent, guide: "right", dimension: width },
|
||||
{ scale: centerY / verticalScaleExtent, guide: "top", dimension: height },
|
||||
{ scale: (1 - centerY) / verticalScaleExtent, guide: "bottom", dimension: height },
|
||||
].filter((target) => Number.isFinite(target.scale) && target.scale >= 0.1 && target.scale <= 4);
|
||||
const horizontalExtent = Math.max(0.5, (cosine * boxWidth + sine * boxHeight) / 2);
|
||||
const verticalExtent = Math.max(0.5, (sine * boxWidth + cosine * boxHeight) / 2);
|
||||
const divisions = [
|
||||
{ ratio: 0, xGuide: "left", yGuide: "top" },
|
||||
{ ratio: 0.25, xGuide: "quarter-x-1", yGuide: "quarter-y-1" },
|
||||
{ ratio: 0.5, xGuide: "center-x", yGuide: "center-y" },
|
||||
{ ratio: 0.75, xGuide: "quarter-x-3", yGuide: "quarter-y-3" },
|
||||
{ ratio: 1, xGuide: "right", yGuide: "bottom" },
|
||||
];
|
||||
const targets = divisions.flatMap(({ ratio, xGuide, yGuide }) => {
|
||||
const guideX = ratio * width;
|
||||
const guideY = ratio * height;
|
||||
return [
|
||||
{ scale: (centerX - guideX) / horizontalExtent, guide: xGuide, extent: horizontalExtent },
|
||||
{ scale: (guideX - centerX) / horizontalExtent, guide: xGuide, extent: horizontalExtent },
|
||||
{ scale: (centerY - guideY) / verticalExtent, guide: yGuide, extent: verticalExtent },
|
||||
{ scale: (guideY - centerY) / verticalExtent, guide: yGuide, extent: verticalExtent },
|
||||
];
|
||||
}).filter((target) => Number.isFinite(target.scale) && target.scale >= 0.1 && target.scale <= 4);
|
||||
const nearest = targets.reduce((best, target) => {
|
||||
const distance = Math.abs(scale - target.scale) * target.dimension * (target.dimension === width ? horizontalScaleExtent : verticalScaleExtent);
|
||||
const distance = Math.abs(scale - target.scale) * target.extent;
|
||||
return distance < best.distance ? { ...target, distance } : best;
|
||||
}, { distance: Infinity });
|
||||
if (nearest.distance > Math.max(1, Number(thresholdPixels) || 8)) return { transform, guides: [] };
|
||||
const snappedScale = nearest.scale;
|
||||
const guides = targets.filter((target) => {
|
||||
const extent = target.dimension === width ? horizontalScaleExtent : verticalScaleExtent;
|
||||
return Math.abs(snappedScale - target.scale) * target.dimension * extent <= 0.75;
|
||||
}).map((target) => target.guide);
|
||||
const guideOrder = ["left", "quarter-x-1", "center-x", "quarter-x-3", "right", "top", "quarter-y-1", "center-y", "quarter-y-3", "bottom"];
|
||||
const guides = [...new Set(targets
|
||||
.filter((target) => Math.abs(snappedScale - target.scale) * target.extent <= 0.75)
|
||||
.map((target) => target.guide))].sort((left, right) => guideOrder.indexOf(left) - guideOrder.indexOf(right));
|
||||
return { transform: { ...transform, scale: snappedScale }, guides };
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,26 @@ describe("visual effects", () => {
|
||||
expect(snapVisualScaleToFrameEdges(transform, { width: 360, height: 640 })).toEqual({ transform, guides: [] });
|
||||
});
|
||||
|
||||
it("snaps intrinsic media bounds to quarter and half-frame guides", () => {
|
||||
const quarter = snapVisualScaleToFrameEdges(
|
||||
{ x: 0, y: 0, scale: 0.49, rotation: 0 },
|
||||
{ width: 400, height: 400 },
|
||||
8,
|
||||
{ width: 400, height: 200 },
|
||||
);
|
||||
expect(quarter.transform.scale).toBeCloseTo(0.5);
|
||||
expect(quarter.guides).toEqual(expect.arrayContaining(["quarter-x-1", "quarter-x-3"]));
|
||||
|
||||
const half = snapVisualScaleToFrameEdges(
|
||||
{ x: -25, y: 0, scale: 0.49, rotation: 0 },
|
||||
{ width: 400, height: 400 },
|
||||
8,
|
||||
{ width: 400, height: 200 },
|
||||
);
|
||||
expect(half.transform.scale).toBeCloseTo(0.5);
|
||||
expect(half.guides).toContain("center-x");
|
||||
});
|
||||
|
||||
it("maps timeline time to source time using the clip playback rate", () => {
|
||||
expect(getVisualSourceTime({ sourceStart: 1.5, playbackRate: 2 }, 2)).toBe(5.5);
|
||||
});
|
||||
|
||||
@@ -88,10 +88,10 @@ export function createVisualTimelineActions(d) {
|
||||
d.setImageClipCount(getImageThumbnailCount(segment.duration));
|
||||
}
|
||||
|
||||
function appendVisualAssetToTimeline(asset) {
|
||||
function appendVisualAssetToTimeline(asset, options = {}) {
|
||||
if (d.trackLocks.image) {
|
||||
d.notify("图片轨已锁定,无法添加素材");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const sourceSegments = d.visualSegments.length
|
||||
? d.visualSegments
|
||||
@@ -102,7 +102,7 @@ export function createVisualTimelineActions(d) {
|
||||
const availableDuration = MAX_TIMELINE_DURATION_SECONDS - totalDuration;
|
||||
if (availableDuration < MIN_VISUAL_SEGMENT_SECONDS) {
|
||||
d.notify("视觉轨道已经达到 30 分钟上限");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const segmentDuration = Math.min(getVisualDurationForAsset(asset), availableDuration);
|
||||
const nextSegment = createVisualSegment(segmentDuration, asset);
|
||||
@@ -110,10 +110,11 @@ export function createVisualTimelineActions(d) {
|
||||
setCurrentVisualAsset(asset);
|
||||
commitVisualSegments(
|
||||
[...sourceSegments, nextSegment],
|
||||
`${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
|
||||
options.message ?? `${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
|
||||
sourceSegments.length,
|
||||
);
|
||||
d.seekTo(totalDuration);
|
||||
return nextSegment;
|
||||
}
|
||||
|
||||
function updateVisualAssetInTimeline(assetId, updates) {
|
||||
@@ -144,6 +145,7 @@ export function createVisualTimelineActions(d) {
|
||||
if (d.previewVisualSegment?.assetId === assetId || d.previewVisualSegment?.src === updates.src) {
|
||||
d.setImageMeta(updates.meta ?? d.imageMeta);
|
||||
if (updates.type) d.setVisualType(updates.type);
|
||||
if (updates.src) d.setImageSrc(updates.src);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+414
-25
@@ -581,6 +581,173 @@ button:disabled {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.first-visual-guide {
|
||||
position: fixed;
|
||||
z-index: 10020;
|
||||
inset: 0;
|
||||
background: rgba(3, 7, 12, .48);
|
||||
backdrop-filter: blur(1.5px);
|
||||
}
|
||||
|
||||
.first-visual-guide-heading {
|
||||
position: fixed;
|
||||
top: 18px;
|
||||
left: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: 44px;
|
||||
border: 1px solid rgba(255, 255, 255, .12);
|
||||
border-radius: 10px;
|
||||
padding: 7px 8px 7px 16px;
|
||||
color: #eef8fa;
|
||||
background: #171d25;
|
||||
box-shadow: 0 16px 50px rgba(0, 0, 0, .42);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.first-visual-guide-heading strong { font-size: 13px; white-space: nowrap; }
|
||||
.first-visual-guide-heading button { min-height: 30px; border: 0; border-radius: 6px; padding: 0 13px; color: #061411; font-size: 12px; font-weight: 750; background: #35ead9; cursor: pointer; }
|
||||
.first-visual-guide-dismiss { position: fixed; top: 18px; right: 18px; display: grid; place-items: center; width: 34px; height: 34px; border: 1px solid rgba(255,255,255,.12); border-radius: 7px; color: #dce7ea; background: #171d25; cursor: pointer; }
|
||||
|
||||
.first-visual-guide-highlight {
|
||||
position: fixed;
|
||||
border: 2px solid #35ead9;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 0 0 3px rgba(53, 234, 217, .18), 0 0 28px rgba(53, 234, 217, .3);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.first-visual-guide-demo {
|
||||
position: fixed;
|
||||
z-index: 2;
|
||||
overflow: visible;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.first-visual-guide-demo.is-transform { container-type: size; }
|
||||
.first-visual-guide-demo-box {
|
||||
position: absolute;
|
||||
top: 28%;
|
||||
left: 24%;
|
||||
width: 48%;
|
||||
height: 44%;
|
||||
border: 1.5px dashed rgba(255, 255, 255, .92);
|
||||
border-radius: 3px;
|
||||
background: rgba(53, 234, 217, .07);
|
||||
transform-origin: center;
|
||||
animation: first-visual-transform-demo 3.8s cubic-bezier(.42, 0, .22, 1) infinite;
|
||||
}
|
||||
|
||||
.first-visual-guide-demo-box i { position: absolute; width: 9px; height: 9px; border: 2px solid #071018; border-radius: 50%; background: #35ead9; box-shadow: 0 0 0 1px rgba(255,255,255,.7); }
|
||||
.first-visual-guide-demo-box i:nth-child(1) { top: -5px; left: -5px; }
|
||||
.first-visual-guide-demo-box i:nth-child(2) { top: -5px; right: -5px; }
|
||||
.first-visual-guide-demo-box i:nth-child(3) { right: -5px; bottom: -5px; }
|
||||
.first-visual-guide-demo-box i:nth-child(4) { bottom: -5px; left: -5px; }
|
||||
.first-visual-guide-demo-cursor {
|
||||
position: absolute;
|
||||
top: 51%;
|
||||
left: 48%;
|
||||
color: #fff;
|
||||
filter: drop-shadow(0 2px 3px rgba(0,0,0,.9));
|
||||
animation: first-visual-drag-cursor 3.8s cubic-bezier(.42, 0, .22, 1) infinite;
|
||||
}
|
||||
|
||||
.first-visual-guide-demo.is-context { display: grid; place-items: center; }
|
||||
.first-visual-guide-demo-mouse {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
color: #fff;
|
||||
filter: drop-shadow(0 2px 3px rgba(0,0,0,.9));
|
||||
animation: first-visual-right-click 3.8s ease-in-out infinite;
|
||||
}
|
||||
.first-visual-guide-click-ring {
|
||||
position: absolute;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border: 2px solid #35ead9;
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
animation: first-visual-click-ring 3.8s ease-out infinite;
|
||||
}
|
||||
.first-visual-guide-mini-menu {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: calc(50% - 60px);
|
||||
left: calc(50% + 18px);
|
||||
width: 94px;
|
||||
border: 1px solid rgba(255,255,255,.16);
|
||||
border-radius: 7px;
|
||||
padding: 7px;
|
||||
opacity: 0;
|
||||
background: #1c232c;
|
||||
box-shadow: 0 12px 28px rgba(0,0,0,.5);
|
||||
transform: translateY(6px) scale(.96);
|
||||
animation: first-visual-menu-demo 3.8s ease-in-out infinite;
|
||||
}
|
||||
.first-visual-guide-mini-menu i { display: block; height: 5px; margin: 6px 3px; border-radius: 3px; background: rgba(225,239,242,.75); }
|
||||
.first-visual-guide-mini-menu i:nth-child(2) { width: 72%; }
|
||||
.first-visual-guide-mini-menu i:nth-child(3) { width: 84%; }
|
||||
|
||||
@keyframes first-visual-transform-demo {
|
||||
0%, 12%, 88%, 100% { transform: translate(0, 0) scale(1); }
|
||||
38%, 50% { transform: translate(10%, -7%) scale(1); }
|
||||
70%, 80% { transform: translate(10%, -7%) scale(1.14); }
|
||||
}
|
||||
@keyframes first-visual-drag-cursor {
|
||||
0%, 10%, 88%, 100% { opacity: 0; transform: translate(-35px, 22px); }
|
||||
16%, 24% { opacity: 1; transform: translate(0, 0) scale(.9); }
|
||||
38%, 50% { opacity: 1; transform: translate(10cqw, -7cqh) scale(.9); }
|
||||
58% { opacity: 0; transform: translate(10cqw, -7cqh); }
|
||||
64% { opacity: 1; transform: translate(calc(24cqw - 4px), calc(22cqh - 4px)); }
|
||||
72%, 80% { opacity: 1; transform: translate(calc(31cqw - 4px), calc(29cqh - 4px)); }
|
||||
}
|
||||
@keyframes first-visual-right-click {
|
||||
0%, 12%, 82%, 100% { opacity: 0; transform: translate(-38px, 12px) scale(1); }
|
||||
20%, 30% { opacity: 1; transform: translate(0, 0) scale(1); }
|
||||
34%, 40% { opacity: 1; transform: translate(0, 0) scale(.84); color: #35ead9; }
|
||||
48%, 72% { opacity: 1; transform: translate(0, 0) scale(1); }
|
||||
}
|
||||
@keyframes first-visual-click-ring {
|
||||
32% { opacity: .9; transform: scale(.45); }
|
||||
48% { opacity: 0; transform: scale(1.8); }
|
||||
}
|
||||
@keyframes first-visual-menu-demo {
|
||||
0%, 38%, 82%, 100% { opacity: 0; transform: translateY(6px) scale(.96); }
|
||||
48%, 72% { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.first-visual-guide-demo * { animation: none !important; }
|
||||
.first-visual-guide-demo-box { transform: translate(8%, -5%) scale(1.08); }
|
||||
.first-visual-guide-demo-cursor, .first-visual-guide-demo-mouse { opacity: 1; }
|
||||
.first-visual-guide-mini-menu { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
.first-visual-guide-card {
|
||||
position: fixed;
|
||||
display: grid;
|
||||
grid-template-columns: 24px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
width: 320px;
|
||||
border: 1px solid rgba(53, 234, 217, .5);
|
||||
border-radius: 9px;
|
||||
padding: 13px 14px;
|
||||
color: #dfeaed;
|
||||
background: #151c24;
|
||||
box-shadow: 0 16px 44px rgba(0, 0, 0, .5);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.first-visual-guide-card svg { color: #35ead9; }
|
||||
.first-visual-guide-card span { font-size: 12px; line-height: 1.55; }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.first-visual-guide-card { left: 16px !important; width: calc(100vw - 32px); }
|
||||
.first-visual-guide-card.is-canvas { top: 76px !important; }
|
||||
.first-visual-guide-card.is-timeline { bottom: 16px !important; }
|
||||
}
|
||||
|
||||
.language-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
@@ -966,6 +1133,31 @@ button:disabled {
|
||||
background: rgba(0, 0, 0, 0.68);
|
||||
}
|
||||
|
||||
.asset-thumb .asset-preview-hover {
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
align-content: center;
|
||||
justify-items: center;
|
||||
gap: 5px;
|
||||
margin: 0;
|
||||
border-radius: 6px;
|
||||
padding: 0;
|
||||
color: #f2fffe;
|
||||
opacity: 0;
|
||||
background: rgba(2, 8, 11, 0.52);
|
||||
backdrop-filter: blur(1.5px);
|
||||
transform: scale(0.98);
|
||||
transition: opacity 140ms ease, transform 140ms ease;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.asset-preview-hover svg { filter: drop-shadow(0 3px 10px rgba(0,0,0,.6)); }
|
||||
.asset-preview-hover em { color: #f2fffe; font-size: 10px; font-style: normal; font-weight: 700; }
|
||||
.asset-row-button:hover .asset-preview-hover,
|
||||
.asset-row-button:focus-visible .asset-preview-hover { opacity: 1; transform: scale(1); }
|
||||
|
||||
.asset-card strong,
|
||||
.voice-card strong {
|
||||
display: block;
|
||||
@@ -1007,6 +1199,69 @@ button:disabled {
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.library-type-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 5px;
|
||||
margin-top: 14px;
|
||||
padding: 3px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.035);
|
||||
}
|
||||
|
||||
.library-type-tabs button {
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
padding: 7px 4px;
|
||||
color: #84919c;
|
||||
font-size: 11px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.library-type-tabs button.is-active { color: #eafffd; background: rgba(53, 234, 217, 0.12); box-shadow: inset 0 0 0 1px rgba(53, 234, 217, 0.28); }
|
||||
.library-search { margin-top: 8px; }
|
||||
.library-search input { width: 100%; border: 1px solid rgba(255,255,255,.09); border-radius: 7px; padding: 9px 10px; color: #e9f2f4; background: rgba(6,10,14,.62); outline: none; }
|
||||
.library-search input:focus { border-color: rgba(53,234,217,.52); }
|
||||
.library-provider { margin-top: 7px; color: #697680; font-size: 10px; }
|
||||
.library-provider strong { color: #9aa9b2; font-weight: 600; }
|
||||
|
||||
.library-loading-grid {
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.library-skeleton-card { min-width: 0; border: 1px solid rgba(255,255,255,.055); border-radius: 9px; padding: 7px; background: rgba(255,255,255,.018); }
|
||||
.library-skeleton-thumb, .asset-media-loading { position: relative; overflow: hidden; border-radius: 6px; background: rgba(121,136,148,.075); }
|
||||
.library-skeleton-thumb { aspect-ratio: 16 / 10; }
|
||||
.library-skeleton-thumb::after, .asset-media-loading::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
transform: translateX(-110%);
|
||||
background: linear-gradient(100deg, transparent 18%, rgba(184,206,211,.06) 36%, rgba(216,235,236,.15) 50%, rgba(184,206,211,.06) 64%, transparent 82%);
|
||||
animation: library-shimmer 1.55s cubic-bezier(.4,0,.2,1) infinite;
|
||||
}
|
||||
.library-skeleton-thumb i, .asset-media-loading i { position: absolute; inset: 28% 34%; border-radius: 999px; background: rgba(171,190,195,.045); filter: blur(9px); animation: library-breathe 1.7s ease-in-out infinite; }
|
||||
.library-skeleton-card > span, .library-skeleton-card > small { display: block; overflow: hidden; border-radius: 4px; background: rgba(151,166,176,.11); }
|
||||
.library-skeleton-card > span { width: 76%; height: 12px; margin-top: 10px; }
|
||||
.library-skeleton-card > small { width: 54%; height: 9px; margin-top: 8px; }
|
||||
.asset-media-loading { position: absolute; z-index: 2; inset: 0; }
|
||||
|
||||
.asset-download-progress { position: absolute; z-index: 4; inset: auto 6px 6px; height: 3px; overflow: hidden; border-radius: 999px; background: rgba(4,9,13,.7); }
|
||||
.asset-download-progress i { display: block; width: var(--asset-progress); height: 100%; border-radius: inherit; background: linear-gradient(90deg, #2ee9d9, #7cf8ed); box-shadow: 0 0 8px rgba(46,233,217,.45); transition: width 120ms ease-out; }
|
||||
.asset-ready-dot { position: absolute; z-index: 4; top: 7px; left: 7px; width: 7px; height: 7px; border: 1px solid rgba(225,255,251,.8); border-radius: 50%; background: #2ee9d9; box-shadow: 0 0 7px rgba(46,233,217,.7); }
|
||||
|
||||
@keyframes library-shimmer { to { transform: translateX(110%); } }
|
||||
@keyframes library-breathe { 0%,100% { opacity: .35; transform: scale(.82); } 50% { opacity: .8; transform: scale(1.12); } }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.library-skeleton-thumb::after, .asset-media-loading::after, .library-skeleton-thumb i, .asset-media-loading i { animation: none; }
|
||||
}
|
||||
|
||||
.asset-list.upload-assets {
|
||||
max-height: min(430px, 50vh);
|
||||
padding-right: 2px;
|
||||
@@ -1070,6 +1325,77 @@ button:disabled {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.asset-preview-backdrop {
|
||||
position: fixed;
|
||||
z-index: 10000;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 28px;
|
||||
background: rgba(2, 6, 9, 0.78);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.asset-preview-dialog {
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
width: min(920px, calc(100vw - 56px));
|
||||
height: min(720px, calc(100vh - 56px));
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(143, 181, 191, 0.24);
|
||||
border-radius: 16px;
|
||||
color: #eaf2f4;
|
||||
background: #0e1419;
|
||||
box-shadow: 0 36px 110px rgba(0, 0, 0, 0.7), inset 0 1px rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.asset-preview-dialog header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
min-width: 0;
|
||||
padding: 15px 17px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.asset-preview-dialog header > div { min-width: 0; }
|
||||
.asset-preview-dialog header span { display: block; color: #77848e; font-size: 11px; }
|
||||
.asset-preview-dialog header strong { display: block; overflow: hidden; margin-top: 3px; font-size: 14px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.asset-preview-dialog header button { display: grid; flex: 0 0 auto; place-items: center; width: 34px; height: 34px; border: 1px solid rgba(255,255,255,.08); border-radius: 8px; padding: 0; color: #b9c5cb; background: rgba(255,255,255,.035); cursor: pointer; }
|
||||
.asset-preview-dialog header button:hover { color: #fff; border-color: rgba(53,234,217,.36); background: rgba(53,234,217,.08); }
|
||||
|
||||
.asset-preview-media {
|
||||
display: grid;
|
||||
min-height: 0;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
padding: 22px;
|
||||
background: radial-gradient(circle at 50% 45%, #182129 0, #080c10 72%);
|
||||
}
|
||||
|
||||
.asset-preview-media img,
|
||||
.asset-preview-media video { display: block; max-width: 100%; max-height: 100%; border-radius: 5px; object-fit: contain; box-shadow: 0 12px 44px rgba(0,0,0,.42); }
|
||||
.asset-preview-media video { width: 100%; height: 100%; background: #000; }
|
||||
.asset-preview-audio { position: relative; display: grid; width: min(580px, 100%); justify-items: center; gap: 18px; padding: 36px; border: 1px solid rgba(117,181,208,.16); border-radius: 14px; color: #8bc5ff; background: linear-gradient(145deg,rgba(31,55,91,.68),rgba(12,21,34,.88)); }
|
||||
.asset-preview-audio strong { max-width: 100%; overflow: hidden; color: #e8f3f8; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.asset-preview-audio audio { width: 100%; transition: opacity 180ms ease, transform 180ms ease; }
|
||||
.asset-preview-audio audio.is-waiting { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }
|
||||
.asset-preview-audio audio.is-ready { opacity: 1; transform: translateY(0); }
|
||||
.asset-preview-audio-loading { display: grid; min-height: 54px; place-items: center; gap: 9px; color: #aac0ca; font-size: 12px; }
|
||||
.asset-preview-audio-loading i { position: relative; display: grid; width: 46px; height: 46px; place-items: center; border-radius: 999px; background: conic-gradient(#54eadc var(--audio-preview-progress, 0%), rgba(117,217,235,.13) 0); box-shadow: 0 0 24px rgba(53,234,217,.12); font-style: normal; transition: background 160ms ease; }
|
||||
.asset-preview-audio-loading i::after { position: absolute; inset: 4px; border-radius: inherit; content: ""; background: #16263a; }
|
||||
.asset-preview-audio-loading b { position: relative; z-index: 1; color: #c9fffa; font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
.asset-preview-audio-loading span { animation: library-breathe 1.7s ease-in-out infinite; }
|
||||
.asset-preview-audio-error { min-height: 54px; display: grid; place-items: center; color: #ffaaa5; font-size: 12px; text-align: center; }
|
||||
.asset-preview-dialog footer { overflow: hidden; padding: 11px 17px; color: #82909a; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; border-top: 1px solid rgba(255,255,255,.06); }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.asset-preview-backdrop { padding: 12px; }
|
||||
.asset-preview-dialog { width: calc(100vw - 24px); height: calc(100vh - 24px); }
|
||||
.asset-preview-media { padding: 10px; }
|
||||
}
|
||||
|
||||
.asset-drag-preview {
|
||||
position: fixed;
|
||||
z-index: 90;
|
||||
@@ -2697,9 +3023,8 @@ button:disabled {
|
||||
.visual-transform-box {
|
||||
position: absolute;
|
||||
z-index: 7;
|
||||
inset: 0;
|
||||
border: 1.5px solid #58a6ff;
|
||||
box-shadow: 0 0 0 1px rgba(5, 10, 18, .82), 0 0 18px rgba(46, 143, 255, .18);
|
||||
border: 1.5px dashed rgba(255, 255, 255, .94);
|
||||
box-shadow: 0 0 0 1px rgba(5, 10, 18, .55), 0 0 20px rgba(53, 234, 217, .13);
|
||||
cursor: move;
|
||||
pointer-events: auto;
|
||||
transform-origin: center;
|
||||
@@ -2714,8 +3039,10 @@ button:disabled {
|
||||
overflow: hidden;
|
||||
padding: 3px 7px;
|
||||
border-radius: 4px;
|
||||
color: #07121e;
|
||||
background: #58a6ff;
|
||||
border: 1px solid rgba(53, 234, 217, .58);
|
||||
color: #e9fbf9;
|
||||
background: rgba(10, 18, 24, .9);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, .32);
|
||||
font-size: 10px;
|
||||
font-weight: 750;
|
||||
line-height: 16px;
|
||||
@@ -2727,24 +3054,24 @@ button:disabled {
|
||||
.visual-transform-rotate {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid #071018;
|
||||
border-radius: 2px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 3px solid #091117;
|
||||
border-radius: 50%;
|
||||
padding: 0;
|
||||
background: #f2f7ff;
|
||||
box-shadow: 0 0 0 1px #58a6ff;
|
||||
background: #35ead9;
|
||||
box-shadow: 0 0 0 1.5px rgba(235, 255, 253, .9), 0 2px 8px rgba(0, 0, 0, .55);
|
||||
}
|
||||
.visual-transform-handle.is-nw { top: -6px; left: -6px; cursor: nwse-resize; }
|
||||
.visual-transform-handle.is-ne { top: -6px; right: -6px; cursor: nesw-resize; }
|
||||
.visual-transform-handle.is-sw { bottom: -6px; left: -6px; cursor: nesw-resize; }
|
||||
.visual-transform-handle.is-se { right: -6px; bottom: -6px; cursor: nwse-resize; }
|
||||
.visual-transform-handle.is-n { top: -6px; left: calc(50% - 6px); cursor: ns-resize; }
|
||||
.visual-transform-handle.is-e { top: calc(50% - 6px); right: -6px; cursor: ew-resize; }
|
||||
.visual-transform-handle.is-s { bottom: -6px; left: calc(50% - 6px); cursor: ns-resize; }
|
||||
.visual-transform-handle.is-w { top: calc(50% - 6px); left: -6px; cursor: ew-resize; }
|
||||
.visual-transform-rotate { top: -34px; left: calc(50% - 6px); border-radius: 50%; background: #58a6ff; cursor: grab; }
|
||||
.visual-transform-rotate::after { position: absolute; top: 10px; left: 4px; width: 2px; height: 22px; background: #58a6ff; content: ""; }
|
||||
.visual-transform-handle.is-nw { top: -7px; left: -7px; cursor: nwse-resize; }
|
||||
.visual-transform-handle.is-ne { top: -7px; right: -7px; cursor: nesw-resize; }
|
||||
.visual-transform-handle.is-sw { bottom: -7px; left: -7px; cursor: nesw-resize; }
|
||||
.visual-transform-handle.is-se { right: -7px; bottom: -7px; cursor: nwse-resize; }
|
||||
.visual-transform-handle.is-n { top: -7px; left: calc(50% - 7px); cursor: ns-resize; }
|
||||
.visual-transform-handle.is-e { top: calc(50% - 7px); right: -7px; cursor: ew-resize; }
|
||||
.visual-transform-handle.is-s { bottom: -7px; left: calc(50% - 7px); cursor: ns-resize; }
|
||||
.visual-transform-handle.is-w { top: calc(50% - 7px); left: -7px; cursor: ew-resize; }
|
||||
.visual-transform-rotate { top: -38px; left: calc(50% - 7px); cursor: grab; }
|
||||
.visual-transform-rotate::after { position: absolute; top: 11px; left: 5px; width: 2px; height: 25px; background: repeating-linear-gradient(to bottom, rgba(255,255,255,.95) 0 3px, transparent 3px 5px); content: ""; }
|
||||
|
||||
.visual-overlay-layer {
|
||||
position: absolute;
|
||||
@@ -2754,16 +3081,20 @@ button:disabled {
|
||||
}
|
||||
.visual-overlay-layer > img,
|
||||
.visual-overlay-layer > video { display: block; width: 100%; height: 100%; object-fit: contain; background: transparent; pointer-events: none; }
|
||||
.visual-overlay-layer.is-selected { border: 1.5px solid #58a6ff; box-shadow: 0 0 0 1px rgba(5,10,18,.82), 0 0 18px rgba(46,143,255,.18); }
|
||||
.visual-overlay-layer.is-selected { border: 1.5px dashed rgba(255,255,255,.94); box-shadow: 0 0 0 1px rgba(5,10,18,.55), 0 0 20px rgba(53,234,217,.15); }
|
||||
.visual-overlay-order-actions { position: absolute; top: -26px; right: 0; display: flex; gap: 3px; }
|
||||
.visual-overlay-order-actions button { display: grid; place-items: center; width: 22px; height: 20px; border: 1px solid rgba(88,166,255,.7); border-radius: 4px; padding: 0; color: #eaf4ff; background: #162536; cursor: pointer; }
|
||||
.visual-overlay-order-actions button { display: grid; place-items: center; width: 22px; height: 20px; border: 1px solid rgba(53,234,217,.58); border-radius: 4px; padding: 0; color: #eafffd; background: #142528; cursor: pointer; }
|
||||
.visual-snap-guide { position: absolute; z-index: 30; pointer-events: none; background: #ff4fa3; box-shadow: 0 0 0 1px rgba(6,10,16,.7); }
|
||||
.visual-snap-guide.is-center-x, .visual-snap-guide.is-left, .visual-snap-guide.is-right { top: 0; bottom: 0; width: 1px; }
|
||||
.visual-snap-guide.is-center-x, .visual-snap-guide.is-quarter-x-1, .visual-snap-guide.is-quarter-x-3, .visual-snap-guide.is-left, .visual-snap-guide.is-right { top: 0; bottom: 0; width: 1px; }
|
||||
.visual-snap-guide.is-center-x { left: 50%; }
|
||||
.visual-snap-guide.is-quarter-x-1 { left: 25%; }
|
||||
.visual-snap-guide.is-quarter-x-3 { left: 75%; }
|
||||
.visual-snap-guide.is-left { left: 0; }
|
||||
.visual-snap-guide.is-right { right: 0; }
|
||||
.visual-snap-guide.is-center-y, .visual-snap-guide.is-top, .visual-snap-guide.is-bottom { right: 0; left: 0; height: 1px; }
|
||||
.visual-snap-guide.is-center-y, .visual-snap-guide.is-quarter-y-1, .visual-snap-guide.is-quarter-y-3, .visual-snap-guide.is-top, .visual-snap-guide.is-bottom { right: 0; left: 0; height: 1px; }
|
||||
.visual-snap-guide.is-center-y { top: 50%; }
|
||||
.visual-snap-guide.is-quarter-y-1 { top: 25%; }
|
||||
.visual-snap-guide.is-quarter-y-3 { top: 75%; }
|
||||
.visual-snap-guide.is-top { top: 0; }
|
||||
.visual-snap-guide.is-bottom { bottom: 0; }
|
||||
|
||||
@@ -4311,6 +4642,64 @@ button:disabled {
|
||||
box-shadow: inset 0 0 0 1px rgba(103, 181, 255, 0.18);
|
||||
}
|
||||
|
||||
.image-clip.is-preparing {
|
||||
border-color: rgba(53, 234, 217, 0.58);
|
||||
background: rgba(8, 24, 27, 0.92);
|
||||
cursor: progress;
|
||||
box-shadow: inset 0 0 0 1px rgba(53, 234, 217, 0.16), 0 0 12px rgba(53, 234, 217, 0.09);
|
||||
}
|
||||
|
||||
.image-clip.is-preparing::before {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
content: "";
|
||||
background: linear-gradient(105deg, transparent 18%, rgba(92, 255, 239, 0.13) 42%, rgba(190, 255, 249, 0.2) 50%, rgba(92, 255, 239, 0.13) 58%, transparent 82%);
|
||||
transform: translateX(-110%);
|
||||
animation: timeline-media-shimmer 1.45s cubic-bezier(.45, 0, .55, 1) infinite;
|
||||
}
|
||||
|
||||
.timeline-media-preparing {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
padding: 0 9px;
|
||||
color: #c9fffa;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.timeline-media-preparing strong {
|
||||
overflow: hidden;
|
||||
font-size: 10px;
|
||||
font-weight: 720;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.timeline-media-preparing em {
|
||||
margin-left: auto;
|
||||
color: rgba(204, 255, 250, 0.72);
|
||||
font-size: 9px;
|
||||
font-style: normal;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.timeline-media-spinner {
|
||||
flex: 0 0 auto;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 1.5px solid rgba(163, 255, 247, 0.24);
|
||||
border-top-color: #55f3e3;
|
||||
border-radius: 999px;
|
||||
animation: timeline-media-spin .72s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes timeline-media-shimmer { to { transform: translateX(110%); } }
|
||||
@keyframes timeline-media-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.image-clip.is-reorder-dragging {
|
||||
z-index: 7;
|
||||
border-style: dashed;
|
||||
|
||||
Reference in new issue
Block a user