Improve editor timeline and caption voice workflows (#13)

* fix editor media caption and audio workflows

* improve editor timeline and caption voice workflows

---------

Co-authored-by: haixin.yang <haixin.yang@weimob.com>
This commit is contained in:
Martin Delophyandhaixin.yang authored and GitHub committed 2026-07-17 12:48:37 +08:00
1 parent 42ea7685e4
commit a6b7a9e51b
40 files changed
+794 -365

No files matched your search

+31 -175
View File
@@ -1,11 +1,11 @@
import { useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { LanguageIntro } from "./components/panels.jsx";
import { PreviewStage } from "./components/PreviewStage.jsx";
import { VoicePanel } from "./components/VoicePanel.jsx";
import { Timeline } from "./components/Timeline.jsx";
import { Topbar } from "./components/Topbar.jsx";
import { AssetDragPreview, ExportProgressOverlay, RemasterProgressOverlay } from "./components/EditorOverlays.jsx";
import { AssetDragPreview, ExportProgressOverlay } from "./components/EditorOverlays.jsx";
import { EditorSidebar } from "./components/EditorSidebar.jsx";
import { useExportElapsed } from "./hooks/useExportElapsed.js";
import { usePreviewFrameSize } from "./hooks/usePreviewFrameSize.js";
@@ -56,8 +56,7 @@ import { decodeWaveform, downloadBlob } from "./lib/media.js";
import { getImageThumbnailCount, getVisualSegmentsTotal } from "./lib/timeline.js";
import { removeVisualPropertyKeyframe, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./lib/visualEffects.js";
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments } from "./lib/sourceAudioSync.js";
import { captureRemasterSource, enhanceRemasterFrame } from "./lib/remasterEnhancement.js";
import { enhanceRemasterClip } from "./lib/remasterClipEnhancement.js";
import { getTimelineInitialContentZoom } from "./lib/timelineScale.js";
function getExportDimensions(ratio, longEdge) {
const sourceLongEdge = Math.max(ratio.width, ratio.height);
@@ -76,9 +75,9 @@ export function App() {
const [uiLanguage, setUiLanguage] = useState(() => getStoredLanguage());
const [showExportMenu, setShowExportMenu] = useState(false);
const [exportSettings, setExportSettings] = useState({ resolution: "1080", frameRate: 30, codec: "h264", quality: "high" });
const [remasterQuality, setRemasterQuality] = useState("fast");
const [captionVoiceFocusRequest, setCaptionVoiceFocusRequest] = useState(0);
const timelineImportRestoreRef = useRef(false);
const [introClosing, setIntroClosing] = useState(false);
const [remasterJob, setRemasterJob] = useState({ running: false, mode: "", segmentId: "", progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0, backend: "" });
const {
captionPlacement, captionPosition, captionSegments, captionSize, captionStyle,
captionsEnabled, script, selectedSegmentId, setCaptionPlacement,
@@ -145,7 +144,7 @@ export function App() {
avatarMotionCacheRef, avatarMotionWorkerRef, avatarRenderWorkerRef,
avatarTestAudioImportedRef, avatarTestImportedRef, currentTimeRef, draggedAssetIdRef,
exportStartRef, fileInputRef, imageUrlRefs, musicRef, musicUrlRef, pointerAssetDragRef,
previewCanvasRef, previewShellRef, previewVideoRef, projectFileInputRef, remasterAbortControllerRef, sourceAudioRef,
previewCanvasRef, previewShellRef, previewVideoRef, projectFileInputRef, sourceAudioRef,
sourceAudioUrlRef, suppressAssetClickRef, suppressTimelineClipClickRef,
timelineClipDragRef, timelineDurationRef, trackScrollRef, visionAbortControllerRef,
visionJobGenerationRef, visionObjectUrlsRef, visualPlaybackFrameRef,
@@ -216,6 +215,26 @@ export function App() {
sourceAudioStart, sourceAudioUrl, stickerSegments, timelineDurationRef, timelineHorizon,
trackVisibility, visionRecords, visualSegments, visualType,
});
const previousTimelineContentDurationRef = useRef(estimatedDuration);
useEffect(() => {
const previousDuration = previousTimelineContentDurationRef.current;
const becameNonEmpty = previousDuration <= 0 && estimatedDuration > 0;
const becameEmpty = previousDuration > 0 && estimatedDuration <= 0;
if (becameNonEmpty) {
if (timelineImportRestoreRef.current) timelineImportRestoreRef.current = false;
else setTimelineZoom(getTimelineInitialContentZoom(estimatedDuration));
if (trackScrollRef.current) trackScrollRef.current.scrollLeft = 0;
} else if (becameEmpty) {
timelineImportRestoreRef.current = false;
setTimelineHorizon(10);
setTimelineZoom(getTimelineInitialContentZoom(0));
setCurrentTime(0);
if (trackScrollRef.current) trackScrollRef.current.scrollLeft = 0;
}
previousTimelineContentDurationRef.current = estimatedDuration;
}, [estimatedDuration, setCurrentTime, setTimelineHorizon, setTimelineZoom, trackScrollRef]);
const previewFrameSize = usePreviewFrameSize(previewShellRef, ratio, compactRail);
const selectedVisualSegment = visualSegments[selectedVisualSegmentIndex] ?? previewVisualSegment ?? null;
const selectedVisualRange = visualTimeline[selectedVisualSegmentIndex] ?? previewVisualRange;
@@ -272,155 +291,6 @@ export function App() {
return nextItems;
});
};
const clearSelectedVisualEnhancement = () => {
if (!selectedVisualSegment?.id) return;
remasterAbortControllerRef.current?.abort();
setVisualSegments((items) => items.map((item) => {
if (item.id !== selectedVisualSegment.id) return item;
if (item.enhancement?.mode !== "remaster-drunet-full" || !item.enhancement.original?.src) return { ...item, enhancement: null };
const original = item.enhancement.original;
return {
...item,
src: original.src,
blob: original.blob,
width: original.width,
height: original.height,
sourceStart: original.sourceStart,
sourceDuration: original.sourceDuration,
trackFrames: original.trackFrames ?? [],
enhancement: null,
};
}));
setRemasterJob({ running: false, mode: "", segmentId: "", progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0 });
};
const enhanceSelectedVisualFrame = async () => {
if (!selectedVisualSegment?.id || !selectedVisualSegment.src) return notify(t("remasterSelectClip"));
if (remasterJob.running) return;
const controller = new AbortController();
remasterAbortControllerRef.current = controller;
setIsPlaying(false);
previewVideoRef.current?.pause();
setRemasterJob({ running: true, mode: "frame", segmentId: selectedVisualSegment.id, progress: 1, phaseKey: "remasterPreparing", frameIndex: 0, totalFrames: 1, startedAt: Date.now() });
try {
const bitmap = await captureRemasterSource({
type: selectedVisualSegment.type,
src: selectedVisualSegment.src,
video: previewVideoRef.current,
});
const result = await enhanceRemasterFrame({
bitmap,
maxLongEdge: remasterQuality === "quality" ? 960 : 640,
signal: controller.signal,
onProgress: ({ progress, phaseKey, phaseParams }) => setRemasterJob((job) => ({ ...job, running: true, progress, phaseKey, phaseParams })),
});
if (controller.signal.aborted) return;
const previewUrl = URL.createObjectURL(result.blob);
imageUrlRefs.current.add(previewUrl);
setVisualSegments((items) => items.map((item) => {
if (item.id !== selectedVisualSegment.id) return item;
return { ...item, enhancement: {
enabled: true,
mode: "remaster-drunet-frame-preview",
previewUrl,
previewBlob: result.blob,
localTime: visualLocalTime,
sourceTime: previewVisualSourceTime,
width: result.width,
height: result.height,
inferenceMs: result.inferenceMs,
} };
}));
setRemasterJob({ running: false, mode: "frame", segmentId: selectedVisualSegment.id, progress: 100, phase: t("remasterReady"), frameIndex: 1, totalFrames: 1, startedAt: 0 });
notify(t("remasterReady"));
} catch (error) {
if (error?.name !== "AbortError") notify(error instanceof Error ? error.message : t("remasterFailed"));
setRemasterJob({ running: false, mode: "frame", segmentId: selectedVisualSegment.id, progress: 0, phase: "", frameIndex: 0, totalFrames: 1, startedAt: 0 });
} finally {
if (remasterAbortControllerRef.current === controller) remasterAbortControllerRef.current = null;
}
};
const cancelRemasterEnhancement = () => {
if (!remasterJob.running) return;
setRemasterJob((job) => ({ ...job, phase: "", phaseKey: "remasterCanceling", phaseParams: {} }));
remasterAbortControllerRef.current?.abort();
};
const enhanceSelectedVisualClip = async () => {
if (!selectedVisualSegment?.id || !selectedVisualSegment.src) return notify(t("remasterSelectClip"));
if (selectedVisualSegment.type !== "video") return notify(t("remasterClipOnlyVideo"));
if (remasterJob.running) return;
const existingOriginal = selectedVisualSegment.enhancement?.mode === "remaster-drunet-full"
? selectedVisualSegment.enhancement.original
: null;
const original = existingOriginal ?? {
src: selectedVisualSegment.src,
blob: selectedVisualSegment.blob,
width: selectedVisualSegment.width,
height: selectedVisualSegment.height,
sourceStart: selectedVisualSegment.sourceStart ?? 0,
sourceDuration: selectedVisualSegment.sourceDuration,
trackFrames: selectedVisualSegment.trackFrames ?? [],
};
const inputSegment = { ...selectedVisualSegment, ...original, type: "video" };
const controller = new AbortController();
remasterAbortControllerRef.current = controller;
setIsPlaying(false);
previewVideoRef.current?.pause();
setRemasterJob({ running: true, mode: "clip", segmentId: selectedVisualSegment.id, progress: 1, phaseKey: "remasterClipPreparing", frameIndex: 0, totalFrames: 0, startedAt: Date.now() });
try {
const result = await enhanceRemasterClip({
segment: inputSegment,
videoElement: previewVideoRef.current,
frameRate: exportSettings.frameRate,
maxLongEdge: 960,
signal: controller.signal,
onProgress: ({ progress, phaseKey, phaseParams, frameIndex = 0, totalFrames = 0, backend = "" }) => setRemasterJob((job) => ({
...job,
running: true,
progress,
phase: "",
phaseKey,
phaseParams,
frameIndex,
totalFrames,
backend: backend || job.backend,
})),
});
if (controller.signal.aborted) return;
const processedUrl = URL.createObjectURL(result.blob);
imageUrlRefs.current.add(processedUrl);
const processed = {
src: processedUrl,
blob: result.blob,
width: result.width,
height: result.height,
sourceStart: 0,
sourceDuration: result.sourceDuration,
trackFrames: [],
};
setVisualSegments((items) => items.map((item) => item.id === selectedVisualSegment.id ? {
...item,
...processed,
enhancement: {
enabled: true,
mode: "remaster-drunet-full",
original,
processed,
frameRate: result.frameRate,
totalFrames: result.totalFrames,
backend: result.backend,
quality: remasterQuality,
},
} : item));
setRemasterJob({ running: false, mode: "clip", segmentId: selectedVisualSegment.id, progress: 100, phase: t("remasterClipReady"), frameIndex: result.totalFrames, totalFrames: result.totalFrames, startedAt: 0 });
notify(t("remasterClipReady"));
} catch (error) {
if (error?.name === "AbortError") notify(t("remasterCanceled"));
else notify(error instanceof Error ? error.message : t("remasterFailed"));
setRemasterJob({ running: false, mode: "clip", segmentId: selectedVisualSegment.id, progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0 });
} finally {
if (remasterAbortControllerRef.current === controller) remasterAbortControllerRef.current = null;
}
};
const exportElapsedSeconds = useExportElapsed(exporting, exportStartRef);
const {
effectiveCaptionPlacement, previewSmartCropRect, previewVisionAnalysis,
@@ -476,15 +346,6 @@ export function App() {
setScript, setSelectedSegmentId, setSelectedTrack,
setVisionRecords, trackLocks,
});
const createCaptionFromPreview = (text, placement) => {
const start = Math.max(0, currentTime);
const segment = { id: crypto.randomUUID(), text, hidden: false, weight: 1, start, end: start + 2.5 };
commitCaptionSegments([...captionSegments, segment].sort((a, b) => (a.start ?? 0) - (b.start ?? 0)), "字幕已加入时间线", 0);
setSelectedSegmentId(segment.id);
setCaptionPlacement({ x: placement.x, y: placement.y });
setCaptionPosition("custom");
};
const {
clearAudioTrack, clearMusicTrack, clearSourceAudioTrack, commitAudio,
replaceAudio, replaceMusic, replaceSourceAudio,
@@ -605,7 +466,7 @@ export function App() {
selectedStickerSegmentId, selectedTrack, selectedVisualSegmentId, setCurrentVisualAsset,
setFitMode, setRatioId, setSelectedSegmentId, setSelectedVisualSegmentId,
setUserAssets, sourceAudioBlob, sourceAudioUrlRef, stickerSegments,
remasterAbortControllerRef, visionAbortControllerRef, visionObjectUrlsRef, visualSegments,
visionAbortControllerRef, visionObjectUrlsRef, visualSegments,
voiceRecorderStreamRef, voiceRecorderTimerRef,
});
@@ -706,7 +567,9 @@ export function App() {
setRatioId, setScript, setSelectedFilterId, setSelectedSegmentId, setSelectedStickerId,
setSelectedStickerSegmentId, setSelectedTransitionId, setSelectedVoiceId, setShowFileMenu,
setSourceAudioAssetId, setSourceAudioLinked, setSourceAudioVolume, setSpeed, setStickerSegments, setTimelineZoom, setTrackVisibility,
setTimelineHorizon,
setVisualSegments, setVolume, setCurrentVisualAsset, sourceAudioBlob, sourceAudioDuration,
markTimelineViewRestored: (hasContent) => { timelineImportRestoreRef.current = hasContent; },
sourceAudioAssetId, sourceAudioLinked, sourceAudioName, sourceAudioStart, sourceAudioVolume, speed, stickerSegments,
timelineZoom, trackVisibility, visualSegments, volume,
});
@@ -877,15 +740,14 @@ export function App() {
currentTime={currentTime}
seekTo={seekTo}
notify={notify}
activeTool={activeTool}
getDraggedAsset={getDraggedAsset}
applyAssetToTrack={applyAssetToTrack}
onCreateCaptionAt={createCaptionFromPreview}
/>
<VoicePanel
t={t}
activeTool={activeTool}
captionVoiceFocusRequest={captionVoiceFocusRequest}
status={status}
statusText={statusText}
voiceTab={voiceTab}
@@ -958,12 +820,6 @@ export function App() {
visualLocalTime={visualLocalTime}
visualTimelineStart={selectedVisualRange?.start ?? 0}
updateSelectedVisualEffects={updateSelectedVisualEffects}
remasterJob={remasterJob}
remasterQuality={remasterQuality}
setRemasterQuality={setRemasterQuality}
enhanceSelectedVisualFrame={enhanceSelectedVisualFrame}
enhanceSelectedVisualClip={enhanceSelectedVisualClip}
clearSelectedVisualEnhancement={clearSelectedVisualEnhancement}
selectedFilterId={selectedFilterId}
setSelectedFilterId={setSelectedFilterId}
trOption={trOption}
@@ -990,6 +846,7 @@ export function App() {
selectedTrack={selectedTrack}
setSelectedTrack={setSelectedTrack}
setActiveTool={setActiveTool}
requestCaptionVoiceFocus={() => setCaptionVoiceFocusRequest((request) => request + 1)}
trackVisibility={trackVisibility}
toggleTrackVisibility={toggleTrackVisibility}
trackLocks={trackLocks}
@@ -1060,7 +917,6 @@ export function App() {
<AssetDragPreview preview={assetDragPreview} t={t} />
<ExportProgressOverlay exporting={exporting} percent={exportPercent} phase={exportPhase} elapsedSeconds={exportElapsedSeconds} t={t} />
<RemasterProgressOverlay job={remasterJob} onCancel={cancelRemasterEnhancement} t={t} />
{shouldShowLanguageIntro ? (
<LanguageIntro t={t} closing={introClosing} onChoose={chooseInterfaceLanguage} />
) : null}
+1 -19
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect } from "react";
import {
CaretDown,
CloudArrowUp,
@@ -58,17 +58,9 @@ export function PreviewStage({
visualLocalTime = 0,
visualMaskEditable = false,
onUpdateVisualMask,
activeTool,
getDraggedAsset,
applyAssetToTrack,
onCreateCaptionAt,
}) {
const [captionDraft, setCaptionDraft] = useState(null);
const commitCaptionDraft = () => {
const text = captionDraft?.text.trim();
if (text) onCreateCaptionAt?.(text, captionDraft);
setCaptionDraft(null);
};
const hasStickerOverlay = Boolean(selectedSticker?.src || selectedSticker?.text);
const hasPreviewContent = Boolean(previewVisualSrc || hasStickerOverlay);
const renderedVisualSrc = previewVisualRenderSrc || previewVisualSrc;
@@ -191,11 +183,6 @@ export function PreviewStage({
} ${smartCropActive ? "has-smart-crop" : ""}`}
data-hidden-label={t("imageHidden")}
style={previewFrameStyle}
onClick={(event) => {
if (activeTool !== "caption" || event.target.closest(".caption-overlay, .visual-mask-editor, .inline-caption-editor")) return;
const rect = event.currentTarget.getBoundingClientRect();
setCaptionDraft({ x: Math.max(8, Math.min(92, ((event.clientX - rect.left) / rect.width) * 100)), y: Math.max(8, Math.min(92, ((event.clientY - rect.top) / rect.height) * 100)), text: "" });
}}
>
{renderedVisualSrc && trackVisibility.image ? (
<div className="visual-media-layer" style={visualMaskStyle}>
@@ -276,11 +263,6 @@ export function PreviewStage({
onDoubleClick={() => setActiveTool("caption")}
/>
) : null}
{captionDraft ? (
<form className="inline-caption-editor" style={{ left: `${captionDraft.x}%`, top: `${captionDraft.y}%` }} onSubmit={(event) => { event.preventDefault(); commitCaptionDraft(); }}>
<input autoFocus value={captionDraft.text} placeholder={t("typeCaptionHere", "在此输入字幕…")} onChange={(event) => setCaptionDraft((draft) => ({ ...draft, text: event.target.value }))} onKeyDown={(event) => { if (event.key === "Escape") setCaptionDraft(null); if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); commitCaptionDraft(); } }} onBlur={() => { if (!captionDraft.text.trim()) setCaptionDraft(null); }} />
</form>
) : null}
{selectedSticker.src ? (
<img className="sticker-overlay is-image" src={selectedSticker.src} alt="" draggable={false} />
) : selectedSticker.text ? (
+68 -22
View File
@@ -22,24 +22,28 @@ import {
Scissors,
SlidersHorizontal,
Trash,
Waveform,
} from "@phosphor-icons/react";
import { IMAGE_SEGMENT_SECONDS } from "../config/editor.js";
import { formatClock, formatTime, getImageThumbnailCount, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { formatClock, formatTime, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js";
import {
TIMELINE_MIN_ZOOM,
clampTimelineZoom,
getTimelineRulerTicks,
getTimelineAutoFitZoom,
getTimelineTrackWidthPercent,
getTimelineZoomLabel,
} from "../lib/timelineScale.js";
import { IconButton, WaveformStrip } from "./ui.jsx";
const TIMELINE_WHEEL_ZOOM_SENSITIVITY = 0.00034;
const TIMELINE_WHEEL_ZOOM_SENSITIVITY = 0.00056;
const TIMELINE_WHEEL_ZOOM_COMMIT_DELAY = 180;
const TIMELINE_BUTTON_ZOOM_RATIO = 1.25;
const TIMELINE_TRACK_ROW_HEIGHT = "48px";
const VIDEO_FRAME_MIN_COUNT = 1;
const IMAGE_THUMBNAIL_TARGET_WIDTH = 84;
const IMAGE_THUMBNAIL_MAX_COUNT = 240;
const TIMELINE_WHEEL_ZOOM_CONTENT_SELECTOR = [
".image-clip",
".caption-segment",
@@ -103,6 +107,15 @@ function getVideoTimelineFrameCount({ duration, timelineDuration, contentWidth,
);
}
function getImageTimelineThumbnailCount({ duration, timelineDuration, contentWidth }) {
if (timelineDuration <= 0 || contentWidth <= 0) {
return 1;
}
const clipPixelWidth = Math.max(0, (Math.max(0, duration || 0) / timelineDuration) * contentWidth);
return Math.max(1, Math.min(IMAGE_THUMBNAIL_MAX_COUNT, Math.ceil(clipPixelWidth / IMAGE_THUMBNAIL_TARGET_WIDTH)));
}
export function Timeline({
t,
undo,
@@ -123,6 +136,7 @@ export function Timeline({
selectedTrack,
setSelectedTrack,
setActiveTool,
requestCaptionVoiceFocus,
trackVisibility,
toggleTrackVisibility,
trackLocks,
@@ -204,7 +218,14 @@ export function Timeline({
() => packCaptionSegmentsIntoLanes(displayedCaptionSegments, displayedCaptionTimeline),
[displayedCaptionSegments, displayedCaptionTimeline],
);
const contentRows = ["46px", ...(showStickerTrack ? stickerLanes.map(() => "46px") : []), ...captionLanes.map(() => "46px"), "58px", ...audioLanes.map(() => "58px"), "58px"];
const contentRows = [
TIMELINE_TRACK_ROW_HEIGHT,
...(showStickerTrack ? stickerLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT) : []),
...captionLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT),
TIMELINE_TRACK_ROW_HEIGHT,
...audioLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT),
TIMELINE_TRACK_ROW_HEIGHT,
];
const timelineTrackRows = ["28px", ...contentRows].join(" ");
const timelineLabelRows = contentRows.join(" ");
const timelineTrackLabels = [
@@ -238,10 +259,14 @@ export function Timeline({
const showTrackContextMenu = (event, track, segmentId = "") => {
event.preventDefault(); event.stopPropagation();
selectContextTarget(track, segmentId);
const trackRect = trackScrollRef.current?.getBoundingClientRect();
const targetTime = trackRect && timelineDuration > 0
? Math.max(0, Math.min(timelineDuration, ((event.clientX - trackRect.left) / trackRect.width) * timelineDuration))
: currentTime;
setContextMenu({
x: Math.max(10, Math.min(window.innerWidth - 234, event.clientX)),
y: Math.max(10, Math.min(window.innerHeight - 258, event.clientY)),
track, segmentId, kind: segmentId ? "clip" : "track",
track, segmentId, targetTime, kind: segmentId ? "clip" : "track",
});
};
const runContextAction = (action) => {
@@ -251,12 +276,16 @@ export function Timeline({
useEffect(() => {
if (!contextMenu) return undefined;
const close = () => setContextMenu(null);
const closeOnOutsidePointer = (event) => {
if (event.target?.closest?.(".timeline-context-menu")) return;
close();
};
const closeOnKey = (event) => event.key === "Escape" && close();
window.addEventListener("pointerdown", close);
window.addEventListener("pointerdown", closeOnOutsidePointer, true);
window.addEventListener("keydown", closeOnKey);
window.addEventListener("blur", close);
return () => {
window.removeEventListener("pointerdown", close);
window.removeEventListener("pointerdown", closeOnOutsidePointer, true);
window.removeEventListener("keydown", closeOnKey);
window.removeEventListener("blur", close);
};
@@ -337,10 +366,11 @@ export function Timeline({
if (wheelZoomFrameRef.current) {
window.cancelAnimationFrame(wheelZoomFrameRef.current);
}
trackScrollRef.current?.classList.remove("is-wheel-zooming");
wheelZoomActiveRef.current = false;
window.clearTimeout(commitZoomTimerRef.current);
},
[],
[trackScrollRef],
);
const secondsPerPixel =
timelineDuration > 0 && rulerViewport.contentWidth > 0
@@ -356,6 +386,7 @@ export function Timeline({
[timelineDuration, localTimelineZoom, rulerVisibleEnd, rulerVisibleStart],
);
const zoomReadout = getTimelineZoomLabel(localTimelineZoom);
const fitTimelineZoom = getTimelineAutoFitZoom(timelineDuration, 0.9);
const localTrackWidth = `${getTimelineTrackWidthPercent(timelineDuration, localTimelineZoom)}%`;
const commitTimelineZoom = (nextZoom, delay = 0) => {
window.clearTimeout(commitZoomTimerRef.current);
@@ -415,6 +446,7 @@ export function Timeline({
wheelZoomActiveRef.current = true;
timelineZoomRef.current = nextZoom;
anchor.trackElement.classList.add("is-wheel-zooming");
anchor.trackElement.style.width = `${nextTrackWidthPercent}%`;
anchor.trackElement.style.setProperty("--timeline-zoom", String(nextZoom));
anchor.scrollElement.scrollLeft = Math.max(0, nextScrollLeft);
@@ -427,7 +459,10 @@ export function Timeline({
wheelZoomActiveRef.current = false;
setLocalTimelineZoom(nextZoom);
setTimelineZoom(nextZoom);
window.requestAnimationFrame(() => rulerViewportSyncRef.current?.());
window.requestAnimationFrame(() => {
anchor.trackElement.classList.remove("is-wheel-zooming");
rulerViewportSyncRef.current?.();
});
}, TIMELINE_WHEEL_ZOOM_COMMIT_DELAY);
};
const handleTimelineWheel = (event) => {
@@ -447,7 +482,7 @@ export function Timeline({
return;
}
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
if (!hasZoomModifier && Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
return;
}
@@ -660,8 +695,8 @@ export function Timeline({
<span ref={zoomReadoutRef} className="zoom-readout" data-testid="timeline-zoom-readout">{zoomReadout}</span>
<IconButton
label={t("fitTimeline")}
active={Math.abs(localTimelineZoom - TIMELINE_MIN_ZOOM) < 0.001}
onClick={() => adjustTimelineZoom(TIMELINE_MIN_ZOOM)}
active={Math.abs(localTimelineZoom - fitTimelineZoom) < 0.001}
onClick={() => adjustTimelineZoom(fitTimelineZoom)}
>
<MonitorPlay size={17} />
</IconButton>
@@ -852,6 +887,7 @@ export function Timeline({
className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${
isPortraitVideo ? "is-portrait-video" : ""
}`}
style={{ "--thumbnail-cell-width": `${IMAGE_THUMBNAIL_TARGET_WIDTH}px` }}
>
{segmentType === "video" ? (
visibleVideoFrames.length ? (
@@ -871,7 +907,11 @@ export function Timeline({
{
length: Math.max(
1,
getImageThumbnailCount(segment.duration || IMAGE_SEGMENT_SECONDS),
getImageTimelineThumbnailCount({
duration: segment.duration || IMAGE_SEGMENT_SECONDS,
timelineDuration,
contentWidth: rulerViewport.contentWidth,
}),
),
},
(_, thumbnailIndex) => (
@@ -1110,21 +1150,27 @@ export function Timeline({
</div>
) : null}
{contextMenu ? (
<div className="timeline-context-menu" role="menu" aria-label="时间线右键菜单" style={{ left: contextMenu.x, top: contextMenu.y }} onPointerDown={(event) => event.stopPropagation()}>
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? "片段操作" : "轨道操作"}<span>{contextMenu.track}</span></div>
<button type="button" role="menuitem" onClick={() => runContextAction(() => openTrackPanel(contextMenu.track))}><SlidersHorizontal size={16} />打开对应面板</button>
<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", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", voice: "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" ? (
<>
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />在播放头处分割</button>
<button type="button" role="menuitem" onClick={() => runContextAction(handleDuplicateTrack)}><CopySimple size={16} />复制片段</button>
{contextMenu.track === "caption" ? (
<button type="button" role="menuitem" onClick={() => runContextAction(() => {
openTrackPanel("caption");
requestCaptionVoiceFocus?.();
})}><Waveform size={16} />{t("aiVoice")}</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" />
<button className="is-danger" type="button" role="menuitem" onClick={() => runContextAction(handleDeleteTrack)}><Trash size={16} />删除片段</button>
<button className="is-danger" type="button" role="menuitem" onClick={() => runContextAction(handleDeleteTrack)}><Trash size={16} />{t("deleteClip")}</button>
</>
) : (
<>
{["image", "caption"].includes(contextMenu.track) ? <button type="button" role="menuitem" onClick={() => runContextAction(handleAddSegment)}><PlusCircle size={16} />新增片段</button> : null}
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.track))}>{trackVisibility[contextMenu.track] ? <EyeSlash size={16} /> : <Eye size={16} />}{trackVisibility[contextMenu.track] ? "隐藏轨道" : "显示轨道"}</button>
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackLock(contextMenu.track))}>{trackLocks[contextMenu.track] ? <LockKeyOpen size={16} /> : <LockKey size={16} />}{trackLocks[contextMenu.track] ? "解锁轨道" : "锁定轨道"}</button>
{["image", "caption"].includes(contextMenu.track) ? <button type="button" role="menuitem" onClick={() => runContextAction(() => handleAddSegment(contextMenu.targetTime))}><PlusCircle size={16} />{t("addClip")}</button> : null}
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.track))}>{trackVisibility[contextMenu.track] ? <EyeSlash size={16} /> : <Eye size={16} />}{t(trackVisibility[contextMenu.track] ? "hideTrack" : "showTrack")}</button>
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackLock(contextMenu.track))}>{trackLocks[contextMenu.track] ? <LockKeyOpen size={16} /> : <LockKey size={16} />}{t(trackLocks[contextMenu.track] ? "unlockTrack" : "lockTrack")}</button>
</>
)}
</div>
+93 -21
View File
@@ -3,16 +3,18 @@ import {
ClosedCaptioning,
Eye,
EyeSlash,
ImageSquare,
ListBullets,
PersonSimpleRun,
Trash,
Waveform,
} from "@phosphor-icons/react";
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import { formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js";
import { getCaptionVoiceSegment } from "../lib/captionVoice.js";
import { normalizeVisualKeyframes } from "../lib/visualEffects.js";
import { HistoryPanel, MyVoicesPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx";
@@ -65,7 +67,7 @@ function CaptionContextPanel({
<div className="caption-context-empty">
<ClosedCaptioning size={28} weight="duotone" />
<strong>{t("noCaptionSegments")}</strong>
<span>{t("captionEmptyHint", "选择时间线字幕片段后,这里会同步编辑。")}</span>
<span>{t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}</span>
</div>
)}
@@ -248,6 +250,7 @@ function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration
export function VoicePanel({
t,
activeTool,
captionVoiceFocusRequest = 0,
status,
statusText,
voiceTab,
@@ -320,37 +323,47 @@ export function VoicePanel({
visualLocalTime,
visualTimelineStart = 0,
updateSelectedVisualEffects,
remasterJob,
remasterQuality,
setRemasterQuality,
enhanceSelectedVisualFrame,
enhanceSelectedVisualClip,
clearSelectedVisualEnhancement,
selectedFilterId,
setSelectedFilterId,
trOption,
}) {
const [captionPanelTab, setCaptionPanelTab] = useState("caption");
const panelRef = useRef(null);
const isCaptionContext = activeTool === "caption";
const isAvatarContext = activeTool === "smart" && avatarPanelOpen;
const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment);
const isVisualContext = selectedTrack === "image" && Boolean(selectedVisualSegment);
const title = isVisualContext ? t("imageTrack") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const isVisualContext = selectedTrack === "image";
const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment);
const title = isVisualContext ? t("visualPanelTitle") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const panelStatusText = isCaptionContext
? captionSegments.length
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
: t("noCaptionSegments")
: isVisualContext
? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}`
? selectedVisualSegment
? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}`
: t("visualSelectClip")
: isAvatarContext
? t("avatarPortingStatus")
: isAudioClipContext
? `${formatTime(selectedAudioSegment.duration)} · ${selectedAudioSegment.start.toFixed(1)}s`
: statusText === "模型待命"
? t("modelReady")
: statusText;
: statusText;
useEffect(() => {
if (!captionVoiceFocusRequest || !isCaptionContext) return;
setCaptionPanelTab("voice");
const frame = requestAnimationFrame(() => {
requestAnimationFrame(() => {
panelRef.current?.querySelector(".voice-header")?.scrollIntoView({ block: "start", behavior: "smooth" });
});
});
return () => cancelAnimationFrame(frame);
}, [captionVoiceFocusRequest, isCaptionContext]);
return (
<aside className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
<aside ref={panelRef} className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
<div className="panel-title-row">
<h1>{title}</h1>
<span className={`status-pill ${isCaptionContext ? "done" : status}`}>
@@ -377,8 +390,31 @@ export function VoicePanel({
</div>
) : null}
{isCaptionContext ? (
<div className="tabs compact caption-context-tabs" role="tablist" aria-label={t("captionTools", "字幕工具")}>
<button
className={captionPanelTab === "caption" ? "is-active" : ""}
type="button"
role="tab"
aria-selected={captionPanelTab === "caption"}
onClick={() => setCaptionPanelTab("caption")}
>
{t("caption", "字幕")}
</button>
<button
className={captionPanelTab === "voice" ? "is-active" : ""}
type="button"
role="tab"
aria-selected={captionPanelTab === "voice"}
onClick={() => setCaptionPanelTab("voice")}
>
{t("aiVoice", "AI 配音")}
</button>
</div>
) : null}
<div className="voice-tab-body">
{isVisualContext ? (
{isVisualContext && selectedVisualSegment ? (
<VisualEffectsPanel
contextMode
t={t}
@@ -390,15 +426,16 @@ export function VoicePanel({
trOption={trOption}
onSelectFilter={(id) => { setSelectedFilterId(id); notify(t("effectApplied")); }}
sourceAudioLinked={sourceAudioLinked}
enhancementJob={remasterJob}
enhancementQuality={remasterQuality}
onEnhancementQualityChange={setRemasterQuality}
onEnhance={enhanceSelectedVisualFrame}
onEnhanceClip={enhanceSelectedVisualClip}
onClearEnhancement={clearSelectedVisualEnhancement}
/>
) : null}
{isCaptionContext ? (
{isVisualContext && !selectedVisualSegment ? (
<div className="visual-context-empty">
<ImageSquare size={30} weight="duotone" />
<strong>{t("visualSelectClip")}</strong>
<span>{t("previewEmptyTitle")}</span>
</div>
) : null}
{isCaptionContext && captionPanelTab === "caption" ? (
<CaptionContextPanel
t={t}
captionSegments={captionSegments}
@@ -418,6 +455,41 @@ export function VoicePanel({
/>
) : null}
{isCaptionContext && captionPanelTab === "voice" ? (
<div className="caption-voice-panel">
<p className="caption-voice-hint">
{selectedCaptionSegment
? t("captionVoiceHint", "仅为当前选中的字幕片段生成配音,并自动对齐到片段起点。")
: t("captionVoiceEmptyHint", "请先在时间线中选择一个字幕片段。")}
</p>
<VoiceSynthesisPanel
script={selectedCaptionSegment?.text ?? ""}
updateScript={(text) => selectedCaptionSegment && updateCaptionSegmentText(selectedCaptionSegment.id, text)}
selectedVoiceId={selectedVoiceId}
setSelectedVoiceId={setSelectedVoiceId}
selectedVoice={selectedVoice}
filteredVoices={filteredVoices}
voiceFilter={voiceFilter}
setVoiceFilter={setVoiceFilter}
showVoiceFilter={showVoiceFilter}
setShowVoiceFilter={setShowVoiceFilter}
speed={speed}
setSpeed={setSpeed}
volume={volume}
setVolume={setVolume}
status={status}
progressPercent={progressPercent}
audioBlob={selectedCaptionAudioSegment?.blob ?? null}
audioUrl={selectedCaptionAudioSegment?.url ?? ""}
generateVoiceover={() => selectedCaptionSegment && generateVoiceover(selectedCaptionSegment)}
downloadBlob={downloadBlob}
favoriteVoiceIds={favoriteVoiceIds}
setFavoriteVoiceIds={setFavoriteVoiceIds}
t={t}
/>
</div>
) : null}
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
+49 -28
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import {
BoundingBox,
@@ -31,7 +32,6 @@ import {
VOICES,
} from "../config/editor.js";
import { APP_LANGUAGES } from "../i18n.js";
import { translateRemasterPhase } from "../lib/remasterProgress.js";
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js";
import { Popover } from "./ui.jsx";
@@ -325,8 +325,8 @@ export function ToolPanel(props) {
<div className="caption-style-heading"><strong>{t("captionStyle")}</strong><span>{t("captionStyleHint")}</span></div>
<div className="caption-style-presets">
<button type="button" className={captionStyle.backgroundOpacity === 0 && captionStyle.borderWidth === 0 ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect: "normal", backgroundOpacity: 0, borderWidth: 0, shadowOpacity: 0 }))}>{t("captionPresetNone")}</button>
{[['normal', t('captionPresetClassic')], ['neon', t('captionPresetNeon')], ['bubble', t('captionPresetBubble')]].map(([effect, label]) => (
<button key={effect} type="button" className={captionStyle.effect === effect ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect, ...(effect === 'neon' ? { backgroundOpacity: 0.18, borderWidth: 1, borderColor: '#35f0dd' } : effect === 'bubble' ? { backgroundOpacity: 0.88, borderWidth: 0, radius: 18 } : {}) }))}>{label}</button>
{[['normal', t('captionPresetClassic')], ['neon', t('captionPresetNeon')]].map(([effect, label]) => (
<button key={effect} type="button" className={captionStyle.effect === effect ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect, ...(effect === 'neon' ? { backgroundOpacity: 0.18, borderWidth: 1, borderColor: '#35f0dd' } : {}) }))}>{label}</button>
))}
</div>
<div className="caption-color-row">
@@ -568,7 +568,7 @@ export function ToolPanel(props) {
);
}
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false, enhancementJob = null, enhancementQuality = "fast", onEnhancementQualityChange, onEnhance, onEnhanceClip, onClearEnhancement }) {
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false }) {
const [activeTab, setActiveTab] = useState("transform");
const keyframes = normalizeVisualKeyframes(segment?.keyframes ?? []);
const transform = resolveVisualTransform(keyframes, localTime);
@@ -578,18 +578,12 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
const isVideo = segment?.type === "video";
const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1));
const sourceDuration = Math.max(0, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0) * playbackRate);
const enhancement = segment?.enhancement ?? null;
const fullClipEnhanced = enhancement?.mode === "remaster-drunet-full";
const hasEnhancement = Boolean(fullClipEnhanced || enhancement?.previewUrl);
const enhancementRunning = Boolean(enhancementJob?.running && enhancementJob.segmentId === segment?.id);
const enhancementBackend = enhancementRunning ? enhancementJob?.backend : enhancement?.backend;
const updateTransform = (key, value) => onChange?.({ propertyKeyframe: { time: localTime, key, value } });
const tabs = [
["transform", t("visualTabTransform")],
["mask", t("visualTabMask")],
["speed", t("visualTabSpeed")],
["effects", t("visualTabEffects")],
["ai", t("visualTabAi")],
];
return (
<div className={`tool-panel visual-effects-panel ${contextMode ? "is-context-mode" : ""}`}>
@@ -630,19 +624,6 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
</> : <div className="empty-state visual-speed-empty">{t("visualSpeedImageHint")}</div>}
</section> : null}
{activeTab === "effects" ? <VisualChoicePanel title={t("visualEffects")} kind="effect" options={EFFECT_OPTIONS} selectedId={selectedFilterId} trOption={trOption} onSelect={onSelectFilter} /> : null}
{activeTab === "ai" ?
<section className="visual-editor-card remaster-card">
<div className="visual-editor-heading"><strong>{t("remasterTitle")}</strong><em>{t("remasterExperimental")}</em></div>
<div className="remaster-model-row"><span><strong>Remaster DRUNet</strong><em>{t("remasterModelMeta")}</em></span><i className={hasEnhancement ? "is-ready" : ""}>{fullClipEnhanced ? t("remasterFullReadyBadge") : enhancement?.previewUrl ? t("remasterReadyBadge") : t("remasterNotRun")}</i></div>
{isVideo ? <div className="remaster-performance-row"><div className="visual-speed-presets" aria-label={t("remasterPerformanceMode")}><button type="button" className={enhancementQuality === "fast" ? "is-active" : ""} disabled={enhancementRunning} onClick={() => onEnhancementQualityChange?.("fast")}>{t("remasterFastMode")}</button><button type="button" className={enhancementQuality === "quality" ? "is-active" : ""} disabled={enhancementRunning} onClick={() => onEnhancementQualityChange?.("quality")}>{t("remasterQualityMode")}</button></div><span className={`remaster-backend ${enhancementBackend === "webgpu" ? "is-gpu" : enhancementBackend ? "is-cpu" : ""}`}>{enhancementBackend === "webgpu" ? t("remasterGpuActive") : enhancementBackend === "wasm" ? t("remasterCpuFallback") : t("remasterGpuAuto")}</span></div> : null}
{hasEnhancement ? <label className="switch-row remaster-preview-toggle"><input type="checkbox" checked={enhancement.enabled !== false} onChange={(event) => onChange?.({ enhancementEnabled: event.target.checked })} />{fullClipEnhanced ? t("remasterUseEnhanced") : t("remasterShowResult")}</label> : null}
{enhancementRunning ? <div className="remaster-progress" role="status" aria-live="polite"><span><i style={{ width: `${Math.max(2, enhancementJob.progress || 0)}%` }} /></span><small>{translateRemasterPhase(enhancementJob, t)} · {Math.round(enhancementJob.progress || 0)}%</small></div> : null}
{isVideo ? <button className="panel-primary" type="button" disabled={enhancementRunning || !onEnhanceClip} onClick={onEnhanceClip}>{enhancementRunning && enhancementJob?.mode === "clip" ? t("remasterProcessing") : fullClipEnhanced ? t("remasterRerunClip") : t("remasterEnhanceClip")}</button> : null}
<button className={isVideo ? "panel-secondary" : "panel-primary"} type="button" disabled={enhancementRunning || !onEnhance || fullClipEnhanced} onClick={onEnhance}>{enhancementRunning && enhancementJob?.mode === "frame" ? t("remasterProcessing") : t("remasterFramePreview")}</button>
{hasEnhancement ? <div className="remaster-result-meta"><span>{fullClipEnhanced ? `${enhancement.totalFrames} ${t("remasterFramesShort")}` : `${enhancement.width}×${enhancement.height}`}</span><span>{fullClipEnhanced ? `${enhancement.frameRate} fps` : `${Math.max(0, enhancement.inferenceMs || 0)} ms`}</span><button type="button" onClick={onClearEnhancement}>{t("remasterClear")}</button></div> : null}
<p className="visual-speed-hint">{segment?.type === "video" ? t("remasterVideoHint") : t("remasterImageHint")}</p>
</section>
: null}
</>}
</div>
);
@@ -1089,6 +1070,31 @@ export function VoiceSynthesisPanel({
t,
}) {
const voiceLanguages = useMemo(() => [...new Set(VOICES.map((voice) => voice.language))], []);
const voiceSampleRef = useRef(null);
const previousVoiceSampleIdRef = useRef(selectedVoiceId);
const selectAndPlayVoiceSample = (voice) => {
previousVoiceSampleIdRef.current = voice.id;
flushSync(() => setSelectedVoiceId(voice.id));
const player = voiceSampleRef.current;
if (!player) return;
player.pause();
player.load();
delete player.dataset.autoplayStarted;
delete player.dataset.autoplayError;
player.play()
.then(() => { player.dataset.autoplayStarted = "true"; })
.catch((error) => { player.dataset.autoplayError = error.name || "PlaybackError"; });
};
useEffect(() => {
const player = voiceSampleRef.current;
if (!player) return;
if (previousVoiceSampleIdRef.current === selectedVoiceId) return;
previousVoiceSampleIdRef.current = selectedVoiceId;
player.pause();
player.load();
}, [selectedVoiceId]);
return (
<>
@@ -1124,7 +1130,7 @@ export function VoiceSynthesisPanel({
setVoiceFilter(filter);
if (filter !== "all") {
const firstVoiceForLanguage = VOICES.find((voice) => voice.language === filter);
if (firstVoiceForLanguage) setSelectedVoiceId(firstVoiceForLanguage.id);
if (firstVoiceForLanguage) selectAndPlayVoiceSample(firstVoiceForLanguage);
}
setShowVoiceFilter(false);
}}
@@ -1144,7 +1150,7 @@ export function VoiceSynthesisPanel({
className={`voice-card ${voice.id === selectedVoiceId ? "is-selected" : ""}`}
type="button"
key={voice.id}
onClick={() => setSelectedVoiceId(voice.id)}
onClick={() => selectAndPlayVoiceSample(voice)}
>
<span className="avatar">
<MicrophoneStage size={17} weight="fill" />
@@ -1161,7 +1167,7 @@ export function VoiceSynthesisPanel({
</div>
<div className="model-row">
<span>{selectedVoice.detail}</span>
<span title={selectedVoice.detail}>{selectedVoice.detail}</span>
<button
type="button"
onClick={() =>
@@ -1170,10 +1176,25 @@ export function VoiceSynthesisPanel({
)
}
>
{favoriteVoiceIds.includes(selectedVoiceId) ? t("saved") : t("favoriteVoice")}
{favoriteVoiceIds.includes(selectedVoiceId) ? t("saved") : t("favorite")}
</button>
</div>
<div className="voice-sample-preview">
<div>
<strong>{t("voiceSampleTitle", "音色样音")}</strong>
<span>{selectedVoice.name} · {t("voiceSampleHint", "切换音色后试听对应的预生成样音")}</span>
</div>
<audio
ref={voiceSampleRef}
data-testid="voice-sample-player"
data-voice-id={selectedVoice.id}
controls
preload="metadata"
src={selectedVoice.sampleUrl}
/>
</div>
<div className="slider-field">
<div>
<label htmlFor="speed">{t("speed")}</label>
@@ -1207,7 +1228,7 @@ export function VoiceSynthesisPanel({
</div>
{audioBlob && audioUrl ? (
<div className="generated-voice-result" aria-live="polite">
<div><Check size={18} weight="bold" /><span><strong>{t("voiceAddedToTimeline", "已加入配音时间线")}</strong><em>{t("voicePreviewHint", "可立即试听,时间线片段可继续调整")}</em></span></div>
<div><Check size={18} weight="bold" /><span><strong>{t("voiceAddedToTimeline", "已加入配音时间线")}</strong><em>{t("voicePreviewHint", "试听本次已生成的时间线配音")}</em></span></div>
<audio controls preload="metadata" src={audioUrl} />
</div>
) : null}
+10 -1
View File
@@ -11,7 +11,7 @@ import {
export { MODEL_ID, AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "./models.js";
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
export const DEFAULT_TIMELINE_DURATION_SECONDS = 30 * 60;
export const DEFAULT_TIMELINE_DURATION_SECONDS = 10;
export const MAX_TIMELINE_DURATION_SECONDS = 24 * 60 * 60;
export const IMAGE_SEGMENT_SECONDS = 2;
export const MIN_VISUAL_SEGMENT_SECONDS = 0.5;
@@ -74,6 +74,7 @@ export const VOICES = [
gender: "自然女声",
engine: "piper",
badge: "推荐",
sampleUrl: "/assets/voice-samples/zh_CN-xiao_ya-medium.mp3",
},
{
id: "zh_CN-chaowen-medium",
@@ -83,6 +84,7 @@ export const VOICES = [
gender: "自然人声",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/zh_CN-chaowen-medium.mp3",
},
{
id: "af_heart",
@@ -92,6 +94,7 @@ export const VOICES = [
gender: "Warm female",
engine: "kokoro",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/af_heart.mp3",
},
{
id: "am_fenrir",
@@ -101,6 +104,7 @@ export const VOICES = [
gender: "Steady male",
engine: "kokoro",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/am_fenrir.mp3",
},
{
id: "de_DE-thorsten-medium",
@@ -110,6 +114,7 @@ export const VOICES = [
gender: "Natural male",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/de_DE-thorsten-medium.mp3",
},
{
id: "es_ES-davefx-medium",
@@ -119,6 +124,7 @@ export const VOICES = [
gender: "Natural male",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/es_ES-davefx-medium.mp3",
},
{
id: "fr_FR-siwis-medium",
@@ -128,6 +134,7 @@ export const VOICES = [
gender: "Natural voice",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/fr_FR-siwis-medium.mp3",
},
{
id: "it_IT-riccardo-x_low",
@@ -137,6 +144,7 @@ export const VOICES = [
gender: "Natural male",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/it_IT-riccardo-x_low.mp3",
},
{
id: "pt_BR-faber-medium",
@@ -146,6 +154,7 @@ export const VOICES = [
gender: "Natural male",
engine: "piper",
badge: "ONNX",
sampleUrl: "/assets/voice-samples/pt_BR-faber-medium.mp3",
},
];
-3
View File
@@ -4,7 +4,6 @@ import { RATIO_OPTIONS } from "../config/editor.js";
import { decodeWaveform } from "../lib/media.js";
import { disposeVisionWorker } from "../lib/vision.js";
import { disposeVocalSeparationWorker } from "../lib/vocalSeparation.js";
import { disposeRemasterWorker } from "../lib/remasterEnhancement.js";
import {
getNearestRatioIdForSize,
revokeVisionObjectUrls,
@@ -157,11 +156,9 @@ export function useEditorLifecycle(d) {
d.imageUrlRefs.current.forEach((url) => URL.revokeObjectURL(url));
d.imageUrlRefs.current.clear();
d.visionAbortControllerRef.current?.abort();
d.remasterAbortControllerRef.current?.abort();
d.visionObjectUrlsRef.current.forEach((urls) => revokeVisionObjectUrls(urls));
d.visionObjectUrlsRef.current.clear();
disposeVisionWorker();
disposeRemasterWorker();
disposeVocalSeparationWorker();
d.voiceRecorderStreamRef.current?.getTracks().forEach((track) => track.stop());
window.clearInterval(d.voiceRecorderTimerRef.current);
-1
View File
@@ -23,7 +23,6 @@ export function useEditorRefs() {
previewCanvasRef: useRef(null),
previewShellRef: useRef(null),
previewVideoRef: useRef(null),
remasterAbortControllerRef: useRef(null),
projectFileInputRef: useRef(null),
sourceAudioRef: useRef(null),
sourceAudioUrlRef: useRef(""),
+1 -1
View File
@@ -35,7 +35,7 @@ export function useEditorUiState() {
const [showFileMenu, setShowFileMenu] = useState(false);
const [compactRail, setCompactRail] = useState(false);
const [selectedTrack, setSelectedTrack] = useState("image");
const [timelineZoom, setTimelineZoom] = useState(0.25);
const [timelineZoom, setTimelineZoom] = useState(1);
const [trackVisibility, setTrackVisibility] = useState(DEFAULT_TRACK_VISIBILITY);
const [trackLocks, setTrackLocks] = useState(DEFAULT_TRACK_LOCKS);
const [timelineClipDrag, setTimelineClipDrag] = useState(null);
+5 -2
View File
@@ -1,5 +1,5 @@
import { useCallback } from "react";
import { DEFAULT_SCRIPT, RATIO_OPTIONS, VOICES } from "../config/editor.js";
import { DEFAULT_SCRIPT, DEFAULT_TIMELINE_DURATION_SECONDS, RATIO_OPTIONS, VOICES } from "../config/editor.js";
import { decodeWaveform, downloadBlob } from "../lib/media.js";
import { createProjectArchive, readProjectArchive, readProjectFileAsText } from "../lib/projectArchive.js";
import { createCaptionSegments, getImageThumbnailCount, getVisualSegmentsTotal } from "../lib/timeline.js";
@@ -44,6 +44,7 @@ export function useProjectFiles(deps) {
deps.setSelectedSegmentId(""); deps.clearImageTrack(""); deps.clearAudioTrack("");
deps.clearSourceAudioTrack(""); deps.clearMusicTrack(""); deps.setStickerSegments([]);
deps.setSelectedStickerSegmentId(""); deps.clearAllVisionState(); deps.setCurrentTime(0);
deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS); deps.setTimelineZoom(1);
deps.setShowFileMenu(false); deps.notify("已新建空白工程");
}, [deps]);
@@ -59,8 +60,10 @@ export function useProjectFiles(deps) {
}
const { payload, visualMedia, audio, sourceAudio, music } = archive;
const data = payload.project;
deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS);
deps.setScript(typeof data.script === "string" ? data.script : DEFAULT_SCRIPT);
const captions = Array.isArray(data.captionSegments) ? data.captionSegments : createCaptionSegments(data.script || DEFAULT_SCRIPT);
deps.markTimelineViewRestored?.(Boolean(captions.length || data.visualSegments?.length || audio || sourceAudio || music));
deps.setCaptionSegments(captions); deps.setSelectedSegmentId(captions[0]?.id ?? "");
deps.setSelectedVoiceId(data.selectedVoiceId || VOICES[0].id); deps.setSpeed(Number(data.speed) || 1);
deps.setVolume(Number(data.volume) || 1); deps.setRatioId(RATIO_OPTIONS.some((option) => option.id === data.ratioId) ? data.ratioId : "16:9");
@@ -78,7 +81,7 @@ export function useProjectFiles(deps) {
deps.setVisualSegments(visuals); deps.setImageDuration(getVisualSegmentsTotal(visuals));
deps.setImageClipCount(getImageThumbnailCount(getVisualSegmentsTotal(visuals))); deps.setCurrentVisualAsset(visuals[0] || null);
if (audio) { const decoded = await decodeWaveform(audio); deps.replaceAudio(audio, Number(data.audioDuration) || decoded.duration, decoded.peaks, "已恢复工程配音"); } else deps.clearAudioTrack("");
if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0, data.sourceAudioAssetId || ""); } else deps.clearSourceAudioTrack("");
if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0, data.sourceAudioAssetId || "", { focusAudio: false }); } else deps.clearSourceAudioTrack("");
if (music) { const decoded = await decodeWaveform(music); deps.replaceMusic(music, Number(data.musicDuration) || decoded.duration, decoded.peaks, data.musicName || "background-music", ""); deps.setMusicStart(Math.max(0, Number(data.musicStart) || 0)); } else deps.clearMusicTrack("");
deps.setMusicVolume(Number(data.musicVolume) || 0.35); deps.setSourceAudioVolume(Number(data.sourceAudioVolume) || 1);
deps.setSourceAudioAssetId(data.sourceAudioAssetId || ""); deps.setSourceAudioLinked(data.sourceAudioLinked !== false);
+1 -1
View File
@@ -8,7 +8,7 @@ export function useSourceAudioExtraction(d) {
try {
const blob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
const decoded = await decodeWaveform(blob, 96); if (!decoded.duration) throw new Error("视频没有可识别的音频轨");
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart, asset.id);
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart, asset.id, { focusAudio: false });
} catch (error) {
console.warn(error); d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
d.setProgress(0); d.notify("视频画面已添加,但没有可分离的原声音轨");
+8 -11
View File
@@ -11,7 +11,6 @@ import {
VOICES,
} from "../config/editor.js";
import {
estimateDuration,
getCaptionTimeline,
getSegmentIndexAtTime,
getTimedSegmentIndexAtTime,
@@ -21,6 +20,7 @@ import {
} from "../lib/timeline.js";
import { getVisionKey } from "../lib/vision.js";
import { getVisualSourceTime } from "../lib/visualEffects.js";
import { getTimelineProjectDuration } from "../lib/timelineScale.js";
export function useTimelineModel(d) {
const selectedVoice = useMemo(
@@ -83,21 +83,18 @@ export function useTimelineModel(d) {
d.sourceAudioBlob ? (d.sourceAudioTimelineEnd ?? d.sourceAudioStart + d.sourceAudioDuration) : 0,
d.musicBlob ? d.musicStart + d.musicDuration : 0,
stickerDuration,
estimateDuration(d.script),
d.imageSrc ? d.imageDuration : 0,
), [
voiceTrackDuration, captionDuration, d.imageDuration, d.imageSrc, d.musicBlob,
d.musicDuration, d.musicStart, d.script, d.sourceAudioBlob, d.sourceAudioDuration,
d.musicDuration, d.musicStart, d.sourceAudioBlob, d.sourceAudioDuration,
d.sourceAudioStart, d.sourceAudioTimelineEnd, stickerDuration,
]);
const timelineDuration = useMemo(() => Math.min(
MAX_TIMELINE_DURATION_SECONDS,
Math.max(
d.timelineHorizon,
DEFAULT_TIMELINE_DURATION_SECONDS,
Math.ceil((estimatedDuration + 1) / 10) * 10,
),
), [estimatedDuration, d.timelineHorizon]);
const timelineDuration = useMemo(() => estimatedDuration <= 0
? DEFAULT_TIMELINE_DURATION_SECONDS
: Math.min(
MAX_TIMELINE_DURATION_SECONDS,
Math.max(d.timelineHorizon, getTimelineProjectDuration(estimatedDuration)),
), [estimatedDuration, d.timelineHorizon]);
d.timelineDurationRef.current = timelineDuration;
const currentSegmentIndex = getSegmentIndexAtTime(
+34 -8
View File
@@ -4,8 +4,8 @@ import { predictPiperVoice } from "../lib/piperVoiceRuntime.js";
import { clearPiperCacheIfStorageTight, isPiperSymbolError, isStorageQuotaError, prepareTextForVoice, TtsInputError } from "../lib/ttsText.js";
export function useVoiceGeneration(d) {
return useCallback(async () => {
const rawText = d.script.trim();
return useCallback(async (captionSegment = null) => {
const rawText = (captionSegment?.text ?? d.script).trim();
if (!rawText || d.status === "generating" || d.status === "captioning") return;
let prepared;
try { prepared = prepareTextForVoice(rawText, d.selectedVoice); }
@@ -23,7 +23,15 @@ export function useVoiceGeneration(d) {
d.setStatusText(d.selectedVoice.language === "中文"
? d.t("ttsStatusLoadingChineseModel")
: `Loading ${d.selectedVoice.language} Piper model…`);
const progress = (event) => { if (event?.total) d.setProgress((current) => Math.max(current, Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))))); };
const progress = (event) => {
if (event?.backend) d.setStatusText(d.t(event.backend === "webgpu" ? "ttsStatusGeneratingWebGpu" : "ttsStatusGeneratingWasm"));
if (event?.total) {
d.setProgress((current) => Math.max(
current,
Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))),
));
}
};
const input = { text: prepared.text, voiceId: d.selectedVoice.id };
try { blob = await predictPiperVoice(tts, input, progress); }
catch (error) {
@@ -32,13 +40,31 @@ export function useVoiceGeneration(d) {
}
} else {
const { KokoroTTS } = await import("kokoro-js"); d.setStatusText(d.t("ttsStatusLoadingKokoro"));
const tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "q8", device: "wasm",
progress_callback: (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); } });
d.setStatusText(d.t("ttsStatusGeneratingEnglish"));
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
const progressCallback = (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); };
let tts;
if (globalThis.navigator?.gpu) {
try {
d.setStatusText(d.t("ttsStatusLoadingWebGpu"));
tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "fp32", device: "webgpu", progress_callback: progressCallback });
d.setStatusText(d.t("ttsStatusGeneratingWebGpu"));
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
} catch (error) {
console.warn("Kokoro WebGPU failed; retrying with WASM.", error);
d.setStatusText(d.t("ttsStatusFallingBackWasm"));
}
}
if (!blob) {
tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "q8", device: "wasm", progress_callback: progressCallback });
d.setStatusText(d.t("ttsStatusGeneratingWasm"));
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
}
}
d.setStatusText(d.t("ttsStatusDecodingWaveform"));
await d.commitAudio(blob, `${d.selectedVoice.name} · ${d.t("ttsGenerated")}`); d.notify(d.t("ttsNoticeGenerated"));
await d.commitAudio(blob, `${d.selectedVoice.name} · ${d.t("ttsGenerated")}`, {
captionSegment,
script: rawText,
});
d.notify(d.t("ttsNoticeGenerated"));
} catch (error) {
console.error(error);
const message = error instanceof TtsInputError ? d.t(error.code)
+73 -2
View File
@@ -26,6 +26,19 @@ const VISUAL_EDITOR_COPY = {
vi: { visualSelectClip: "Chọn một clip trên rãnh Visuals", visualKeyframes: "Khung hình chính", visualFrames: "khung", visualScale: "Tỷ lệ", visualPositionX: "Vị trí ngang", visualPositionY: "Vị trí dọc", visualRotation: "Xoay", visualOpacity: "Độ mờ", visualDeleteKeyframe: "Xóa khung hình chính hiện tại", visualMask: "Mặt nạ", visualMaskResize: "Đổi kích thước mặt nạ", visualClipScoped: "Clip", visualMaskNone: "Không", visualMaskRectangle: "Chữ nhật", visualMaskRounded: "Bo góc", visualMaskCircle: "Tròn", visualFeather: "Làm mềm", visualHorizontal: "Ngang", visualVertical: "Dọc", visualWidth: "Rộng", visualHeight: "Cao", visualInvertMask: "Đảo mặt nạ", visualEffects: "Hiệu ứng hình ảnh" },
};
const VISUAL_PANEL_TITLE_COPY = {
zh: { visualPanelTitle: "画面" },
en: { visualPanelTitle: "Visuals" },
ja: { visualPanelTitle: "映像" },
ko: { visualPanelTitle: "화면" },
es: { visualPanelTitle: "Visuales" },
fr: { visualPanelTitle: "Visuels" },
de: { visualPanelTitle: "Bildmaterial" },
pt: { visualPanelTitle: "Visuais" },
th: { visualPanelTitle: "ภาพ" },
vi: { visualPanelTitle: "Hình ảnh" },
};
const VISUAL_MASK_SHAPE_COPY = {
zh: { visualDiameter: "直径", visualCornerRadius: "圆角半径", visualMaskNoneHint: "选择一种蒙版后显示对应参数" },
en: { visualDiameter: "Diameter", visualCornerRadius: "Corner radius", visualMaskNoneHint: "Choose a mask to show its parameters" },
@@ -160,9 +173,36 @@ const REMASTER_PHASE_COPY = {
vi: { remasterPhasePrepareFrame: "Đang chuẩn bị khung hiện tại", remasterPhaseReadClip: "Đang đọc clip video", remasterPhaseReuseVideo: "Đang đọc video từ trình phát", remasterPhaseDownloadModel: "Đang tải {model}", remasterPhaseInitModel: "Đang khởi tạo mô hình tăng cường", remasterPhaseGpuReady: "Đã bật WebGPU", remasterPhaseCpuFallback: "Không dùng được WebGPU; đang dùng CPU", remasterPhaseGpuFrame: "Đang tăng cường khung bằng GPU", remasterPhaseCpuFrame: "Đang tăng cường khung bằng CPU", remasterPhaseGeneratePreview: "Đang tạo khung đã tăng cường", remasterPhaseEnhancingFrame: "Đang tăng cường khung {current} / {total}", remasterPhaseFrameEnhanced: "Đã tăng cường {current} / {total} khung", remasterPhaseLoadEncoder: "Đang tải bộ mã hóa video", remasterPhaseEncodeVideo: "Đang mã hóa video tăng cường", remasterPhaseCreateAsset: "Đang tạo nội dung tăng cường" },
};
const CONTEXT_PANEL_COPY = {
zh: { timelineContextMenu: "时间线右键菜单", clipActions: "片段操作", trackActions: "轨道操作", openTrackPanel: "打开对应面板", splitAtPlayhead: "在播放头处分割", duplicateClip: "复制片段", deleteClip: "删除片段", addClip: "新增片段", hideTrack: "隐藏轨道", showTrack: "显示轨道", unlockTrack: "解锁轨道", lockTrack: "锁定轨道", voiceSampleTitle: "音色样音", voiceSampleHint: "切换音色后试听对应的预生成样音", voiceAddedToTimeline: "已加入配音时间线", voicePreviewHint: "试听本次已生成的时间线配音", captionTools: "字幕工具", captionVoiceHint: "仅为当前选中的字幕片段生成配音,并自动对齐到片段起点。", captionVoiceEmptyHint: "请先在时间线中选择一个字幕片段。" },
en: { timelineContextMenu: "Timeline context menu", clipActions: "Clip actions", trackActions: "Track actions", openTrackPanel: "Open panel", splitAtPlayhead: "Split at playhead", duplicateClip: "Duplicate clip", deleteClip: "Delete clip", addClip: "Add clip", hideTrack: "Hide track", showTrack: "Show track", unlockTrack: "Unlock track", lockTrack: "Lock track", voiceSampleTitle: "Voice sample", voiceSampleHint: "Switch voices to hear its pre-generated sample", voiceAddedToTimeline: "Added to voiceover timeline", voicePreviewHint: "Preview this generated timeline voiceover", captionTools: "Caption tools", captionVoiceHint: "Generate voice for the selected caption only and align it to the caption start.", captionVoiceEmptyHint: "Select a caption clip on the timeline first." },
ja: { timelineContextMenu: "タイムラインのコンテキストメニュー", clipActions: "クリップ操作", trackActions: "トラック操作", openTrackPanel: "パネルを開く", splitAtPlayhead: "再生ヘッドで分割", duplicateClip: "クリップを複製", deleteClip: "クリップを削除", addClip: "クリップを追加", hideTrack: "トラックを非表示", showTrack: "トラックを表示", unlockTrack: "トラックのロックを解除", lockTrack: "トラックをロック", voiceAddedToTimeline: "ボイスオーバーのタイムラインに追加しました", voicePreviewHint: "すぐに試聴でき、タイムライン上で引き続き調整できます", captionTools: "字幕ツール", captionVoiceHint: "選択中の字幕だけに音声を生成し、字幕の開始位置に合わせます。", captionVoiceEmptyHint: "先にタイムラインで字幕クリップを選択してください。" },
ko: { timelineContextMenu: "타임라인 컨텍스트 메뉴", clipActions: "클립 작업", trackActions: "트랙 작업", openTrackPanel: "패널 열기", splitAtPlayhead: "재생 헤드에서 분할", duplicateClip: "클립 복제", deleteClip: "클립 삭제", addClip: "클립 추가", hideTrack: "트랙 숨기기", showTrack: "트랙 표시", unlockTrack: "트랙 잠금 해제", lockTrack: "트랙 잠금", voiceAddedToTimeline: "보이스오버 타임라인에 추가됨", voicePreviewHint: "바로 미리 듣고 타임라인에서 계속 조정할 수 있습니다" },
es: { timelineContextMenu: "Menú contextual de la línea de tiempo", clipActions: "Acciones del clip", trackActions: "Acciones de la pista", openTrackPanel: "Abrir panel", splitAtPlayhead: "Dividir en el cabezal", duplicateClip: "Duplicar clip", deleteClip: "Eliminar clip", addClip: "Añadir clip", hideTrack: "Ocultar pista", showTrack: "Mostrar pista", unlockTrack: "Desbloquear pista", lockTrack: "Bloquear pista", voiceAddedToTimeline: "Añadido a la pista de voz", voicePreviewHint: "Listo para escuchar y seguir ajustando en la línea de tiempo" },
fr: { timelineContextMenu: "Menu contextuel de la timeline", clipActions: "Actions du clip", trackActions: "Actions de la piste", openTrackPanel: "Ouvrir le panneau", splitAtPlayhead: "Scinder à la tête de lecture", duplicateClip: "Dupliquer le clip", deleteClip: "Supprimer le clip", addClip: "Ajouter un clip", hideTrack: "Masquer la piste", showTrack: "Afficher la piste", unlockTrack: "Déverrouiller la piste", lockTrack: "Verrouiller la piste", voiceAddedToTimeline: "Ajouté à la piste voix off", voicePreviewHint: "Prêt à écouter et à ajuster dans la timeline" },
de: { timelineContextMenu: "Timeline-Kontextmenü", clipActions: "Clip-Aktionen", trackActions: "Spur-Aktionen", openTrackPanel: "Bereich öffnen", splitAtPlayhead: "Am Abspielkopf teilen", duplicateClip: "Clip duplizieren", deleteClip: "Clip löschen", addClip: "Clip hinzufügen", hideTrack: "Spur ausblenden", showTrack: "Spur einblenden", unlockTrack: "Spur entsperren", lockTrack: "Spur sperren", voiceAddedToTimeline: "Zur Voiceover-Spur hinzugefügt", voicePreviewHint: "Bereit zum Anhören und weiteren Bearbeiten in der Timeline" },
pt: { timelineContextMenu: "Menu de contexto da linha do tempo", clipActions: "Ações do clipe", trackActions: "Ações da faixa", openTrackPanel: "Abrir painel", splitAtPlayhead: "Dividir no cursor", duplicateClip: "Duplicar clipe", deleteClip: "Excluir clipe", addClip: "Adicionar clipe", hideTrack: "Ocultar faixa", showTrack: "Mostrar faixa", unlockTrack: "Desbloquear faixa", lockTrack: "Bloquear faixa", voiceAddedToTimeline: "Adicionado à faixa de narração", voicePreviewHint: "Pronto para ouvir e continuar ajustando na linha do tempo" },
th: { timelineContextMenu: "เมนูบริบทไทม์ไลน์", clipActions: "การทำงานกับคลิป", trackActions: "การทำงานกับแทร็ก", openTrackPanel: "เปิดแผง", splitAtPlayhead: "แยกที่หัวเล่น", duplicateClip: "ทำสำเนาคลิป", deleteClip: "ลบคลิป", addClip: "เพิ่มคลิป", hideTrack: "ซ่อนแทร็ก", showTrack: "แสดงแทร็ก", unlockTrack: "ปลดล็อกแทร็ก", lockTrack: "ล็อกแทร็ก", voiceAddedToTimeline: "เพิ่มลงในไทม์ไลน์เสียงพากย์แล้ว", voicePreviewHint: "พร้อมฟังตัวอย่างและปรับต่อบนไทม์ไลน์" },
vi: { timelineContextMenu: "Trình đơn ngữ cảnh dòng thời gian", clipActions: "Thao tác clip", trackActions: "Thao tác rãnh", openTrackPanel: "Mở bảng", splitAtPlayhead: "Tách tại đầu phát", duplicateClip: "Nhân đôi clip", deleteClip: "Xóa clip", addClip: "Thêm clip", hideTrack: "Ẩn rãnh", showTrack: "Hiện rãnh", unlockTrack: "Mở khóa rãnh", lockTrack: "Khóa rãnh", voiceAddedToTimeline: "Đã thêm vào rãnh lồng tiếng", voicePreviewHint: "Sẵn sàng nghe thử và tiếp tục chỉnh trên dòng thời gian" },
};
const TTS_BACKEND_COPY = {
zh: { ttsStatusLoadingWebGpu: "正在加载 WebGPU 配音模型", ttsStatusGeneratingWebGpu: "正在使用 WebGPU 生成配音", ttsStatusFallingBackWasm: "WebGPU 不可用,正在切换到 WASM", ttsStatusGeneratingWasm: "正在使用 WASM 生成配音" },
en: { ttsStatusLoadingWebGpu: "Loading WebGPU voice model", ttsStatusGeneratingWebGpu: "Generating voice with WebGPU", ttsStatusFallingBackWasm: "WebGPU unavailable; switching to WASM", ttsStatusGeneratingWasm: "Generating voice with WASM" },
ja: { ttsStatusLoadingWebGpu: "WebGPU音声モデルを読み込み中", ttsStatusGeneratingWebGpu: "WebGPUで音声を生成中", ttsStatusFallingBackWasm: "WebGPUを利用できないためWASMに切り替え中", ttsStatusGeneratingWasm: "WASMで音声を生成中" },
ko: { ttsStatusLoadingWebGpu: "WebGPU 음성 모델 로드 중", ttsStatusGeneratingWebGpu: "WebGPU로 음성 생성 중", ttsStatusFallingBackWasm: "WebGPU를 사용할 수 없어 WASM으로 전환 중", ttsStatusGeneratingWasm: "WASM으로 음성 생성 중" },
es: { ttsStatusLoadingWebGpu: "Cargando modelo de voz WebGPU", ttsStatusGeneratingWebGpu: "Generando voz con WebGPU", ttsStatusFallingBackWasm: "WebGPU no disponible; cambiando a WASM", ttsStatusGeneratingWasm: "Generando voz con WASM" },
fr: { ttsStatusLoadingWebGpu: "Chargement du modèle vocal WebGPU", ttsStatusGeneratingWebGpu: "Génération vocale avec WebGPU", ttsStatusFallingBackWasm: "WebGPU indisponible ; passage à WASM", ttsStatusGeneratingWasm: "Génération vocale avec WASM" },
de: { ttsStatusLoadingWebGpu: "WebGPU-Sprachmodell wird geladen", ttsStatusGeneratingWebGpu: "Stimme wird mit WebGPU erzeugt", ttsStatusFallingBackWasm: "WebGPU nicht verfügbar; Wechsel zu WASM", ttsStatusGeneratingWasm: "Stimme wird mit WASM erzeugt" },
pt: { ttsStatusLoadingWebGpu: "Carregando modelo de voz WebGPU", ttsStatusGeneratingWebGpu: "Gerando voz com WebGPU", ttsStatusFallingBackWasm: "WebGPU indisponível; mudando para WASM", ttsStatusGeneratingWasm: "Gerando voz com WASM" },
th: { ttsStatusLoadingWebGpu: "กำลังโหลดโมเดลเสียง WebGPU", ttsStatusGeneratingWebGpu: "กำลังสร้างเสียงด้วย WebGPU", ttsStatusFallingBackWasm: "ใช้ WebGPU ไม่ได้ กำลังเปลี่ยนเป็น WASM", ttsStatusGeneratingWasm: "กำลังสร้างเสียงด้วย WASM" },
vi: { ttsStatusLoadingWebGpu: "Đang tải mô hình giọng nói WebGPU", ttsStatusGeneratingWebGpu: "Đang tạo giọng nói bằng WebGPU", ttsStatusFallingBackWasm: "Không dùng được WebGPU; đang chuyển sang WASM", ttsStatusGeneratingWasm: "Đang tạo giọng nói bằng WASM" },
};
export const UI_COPY = {
zh: {
...VISUAL_EDITOR_COPY.zh,
...VISUAL_PANEL_TITLE_COPY.zh,
...VISUAL_MASK_SHAPE_COPY.zh,
...VISUAL_KEYFRAME_ACTION_COPY.zh,
...VISUAL_TAB_COPY.zh,
@@ -172,6 +212,8 @@ export const UI_COPY = {
...REMASTER_GPU_COPY.zh,
...REMASTER_PHASE_COPY.zh,
...SOURCE_AUDIO_SYNC_COPY.zh,
...CONTEXT_PANEL_COPY.zh,
...TTS_BACKEND_COPY.zh,
...CAPTION_WORKSPACE_COPY.zh,
...RESOURCE_LINK_COPY.zh,
languageKicker: "AI Voice Studio",
@@ -452,7 +494,7 @@ export const UI_COPY = {
captionScriptLabel: "字幕文案",
captionList: "字幕列表",
captionSegmentsUnit: "条字幕",
captionEmptyHint: "选择时间线字幕片段后,这里会同步编辑。",
captionEmptyHint: "字幕片段可拖动到字幕轨道,并在这里同步编辑。",
showCurrentCaption: "显示当前字幕",
hideCurrentCaption: "隐藏当前字幕",
deleteCurrentCaption: "删除当前字幕",
@@ -528,6 +570,7 @@ export const UI_COPY = {
},
en: {
...VISUAL_EDITOR_COPY.en,
...VISUAL_PANEL_TITLE_COPY.en,
...VISUAL_MASK_SHAPE_COPY.en,
...VISUAL_KEYFRAME_ACTION_COPY.en,
...VISUAL_TAB_COPY.en,
@@ -537,6 +580,8 @@ export const UI_COPY = {
...REMASTER_GPU_COPY.en,
...REMASTER_PHASE_COPY.en,
...SOURCE_AUDIO_SYNC_COPY.en,
...CONTEXT_PANEL_COPY.en,
...TTS_BACKEND_COPY.en,
...CAPTION_WORKSPACE_COPY.en,
...RESOURCE_LINK_COPY.en,
languageKicker: "AI Voice Studio",
@@ -817,7 +862,7 @@ export const UI_COPY = {
captionScriptLabel: "Caption text",
captionList: "Caption list",
captionSegmentsUnit: "caption segment(s)",
captionEmptyHint: "Select a caption segment on the timeline to edit it here.",
captionEmptyHint: "Drag caption clips onto the caption track and edit them here in sync.",
showCurrentCaption: "Show caption",
hideCurrentCaption: "Hide caption",
deleteCurrentCaption: "Delete caption",
@@ -893,6 +938,7 @@ export const UI_COPY = {
},
ja: {
...VISUAL_EDITOR_COPY.ja,
...VISUAL_PANEL_TITLE_COPY.ja,
...VISUAL_MASK_SHAPE_COPY.ja,
...VISUAL_KEYFRAME_ACTION_COPY.ja,
...VISUAL_TAB_COPY.ja,
@@ -902,6 +948,8 @@ export const UI_COPY = {
...REMASTER_GPU_COPY.ja,
...REMASTER_PHASE_COPY.ja,
...SOURCE_AUDIO_SYNC_COPY.ja,
...CONTEXT_PANEL_COPY.ja,
...TTS_BACKEND_COPY.ja,
...CAPTION_WORKSPACE_COPY.ja,
...RESOURCE_LINK_COPY.ja,
languageTitle: "表示言語を選択",
@@ -967,6 +1015,7 @@ export const UI_COPY = {
Object.assign(UI_COPY, {
ko: {
...VISUAL_EDITOR_COPY.ko,
...VISUAL_PANEL_TITLE_COPY.ko,
...VISUAL_MASK_SHAPE_COPY.ko,
...VISUAL_KEYFRAME_ACTION_COPY.ko,
...VISUAL_TAB_COPY.ko,
@@ -976,7 +1025,11 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.ko,
...REMASTER_PHASE_COPY.ko,
...SOURCE_AUDIO_SYNC_COPY.ko,
...CONTEXT_PANEL_COPY.ko,
...TTS_BACKEND_COPY.ko,
...UI_COPY.en,
...CONTEXT_PANEL_COPY.ko,
...TTS_BACKEND_COPY.ko,
...CAPTION_WORKSPACE_COPY.ko,
...RESOURCE_LINK_COPY.ko,
languageTitle: "인터페이스 언어 선택",
@@ -1021,6 +1074,7 @@ Object.assign(UI_COPY, {
es: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.es,
...VISUAL_PANEL_TITLE_COPY.es,
...VISUAL_MASK_SHAPE_COPY.es,
...VISUAL_KEYFRAME_ACTION_COPY.es,
...VISUAL_TAB_COPY.es,
@@ -1030,6 +1084,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.es,
...REMASTER_PHASE_COPY.es,
...SOURCE_AUDIO_SYNC_COPY.es,
...CONTEXT_PANEL_COPY.es,
...TTS_BACKEND_COPY.es,
...CAPTION_WORKSPACE_COPY.es,
...RESOURCE_LINK_COPY.es,
languageTitle: "Elige el idioma",
@@ -1074,6 +1130,7 @@ Object.assign(UI_COPY, {
fr: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.fr,
...VISUAL_PANEL_TITLE_COPY.fr,
...VISUAL_MASK_SHAPE_COPY.fr,
...VISUAL_KEYFRAME_ACTION_COPY.fr,
...VISUAL_TAB_COPY.fr,
@@ -1083,6 +1140,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.fr,
...REMASTER_PHASE_COPY.fr,
...SOURCE_AUDIO_SYNC_COPY.fr,
...CONTEXT_PANEL_COPY.fr,
...TTS_BACKEND_COPY.fr,
...CAPTION_WORKSPACE_COPY.fr,
...RESOURCE_LINK_COPY.fr,
languageTitle: "Choisir la langue",
@@ -1127,6 +1186,7 @@ Object.assign(UI_COPY, {
de: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.de,
...VISUAL_PANEL_TITLE_COPY.de,
...VISUAL_MASK_SHAPE_COPY.de,
...VISUAL_KEYFRAME_ACTION_COPY.de,
...VISUAL_TAB_COPY.de,
@@ -1136,6 +1196,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.de,
...REMASTER_PHASE_COPY.de,
...SOURCE_AUDIO_SYNC_COPY.de,
...CONTEXT_PANEL_COPY.de,
...TTS_BACKEND_COPY.de,
...CAPTION_WORKSPACE_COPY.de,
...RESOURCE_LINK_COPY.de,
languageTitle: "Sprache wählen",
@@ -1180,6 +1242,7 @@ Object.assign(UI_COPY, {
pt: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.pt,
...VISUAL_PANEL_TITLE_COPY.pt,
...VISUAL_MASK_SHAPE_COPY.pt,
...VISUAL_KEYFRAME_ACTION_COPY.pt,
...VISUAL_TAB_COPY.pt,
@@ -1189,6 +1252,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.pt,
...REMASTER_PHASE_COPY.pt,
...SOURCE_AUDIO_SYNC_COPY.pt,
...CONTEXT_PANEL_COPY.pt,
...TTS_BACKEND_COPY.pt,
...CAPTION_WORKSPACE_COPY.pt,
...RESOURCE_LINK_COPY.pt,
languageTitle: "Escolha o idioma",
@@ -1233,6 +1298,7 @@ Object.assign(UI_COPY, {
th: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.th,
...VISUAL_PANEL_TITLE_COPY.th,
...VISUAL_MASK_SHAPE_COPY.th,
...VISUAL_KEYFRAME_ACTION_COPY.th,
...VISUAL_TAB_COPY.th,
@@ -1242,6 +1308,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.th,
...REMASTER_PHASE_COPY.th,
...SOURCE_AUDIO_SYNC_COPY.th,
...CONTEXT_PANEL_COPY.th,
...TTS_BACKEND_COPY.th,
...CAPTION_WORKSPACE_COPY.th,
...RESOURCE_LINK_COPY.th,
languageTitle: "เลือกภาษาอินเทอร์เฟซ",
@@ -1286,6 +1354,7 @@ Object.assign(UI_COPY, {
vi: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.vi,
...VISUAL_PANEL_TITLE_COPY.vi,
...VISUAL_MASK_SHAPE_COPY.vi,
...VISUAL_KEYFRAME_ACTION_COPY.vi,
...VISUAL_TAB_COPY.vi,
@@ -1295,6 +1364,8 @@ Object.assign(UI_COPY, {
...REMASTER_GPU_COPY.vi,
...REMASTER_PHASE_COPY.vi,
...SOURCE_AUDIO_SYNC_COPY.vi,
...CONTEXT_PANEL_COPY.vi,
...TTS_BACKEND_COPY.vi,
...CAPTION_WORKSPACE_COPY.vi,
...RESOURCE_LINK_COPY.vi,
languageTitle: "Chọn ngôn ngữ giao diện",
+47 -9
View File
@@ -8,10 +8,10 @@ import {
} from "./timeline.js";
export function createAudioTrackActions(d) {
function replaceAudio(blob, duration, nextPeaks, nextStatusText) {
function replaceAudio(blob, duration, nextPeaks, nextStatusText, options = {}) {
const nextUrl = URL.createObjectURL(blob);
const nextDuration = duration || estimateDuration(d.script);
const start = Math.max(0, d.currentTimeRef.current || 0);
const nextDuration = duration || estimateDuration(options.script ?? d.script);
const start = Math.max(0, options.start ?? d.currentTimeRef.current ?? 0);
const id = crypto.randomUUID();
const segment = {
id,
@@ -24,9 +24,17 @@ export function createAudioTrackActions(d) {
fadeIn: 0,
fadeOut: 0,
reversed: false,
name: d.selectedVoice?.name || d.t("voiceTrack"),
name: options.name || d.selectedVoice?.name || d.t("voiceTrack"),
};
d.setAudioSegments((segments) => [...segments, segment]);
if (options.replaceSegmentId) {
const replaced = d.audioSegments.find((item) => item.id === options.replaceSegmentId);
d.audioSegmentRefs.current.get?.(options.replaceSegmentId)?.pause?.();
if (replaced?.url) URL.revokeObjectURL(replaced.url);
}
d.setAudioSegments((segments) => [
...segments.filter((item) => item.id !== options.replaceSegmentId),
segment,
]);
d.setSelectedAudioSegmentId(id);
d.setSelectedTrack("audio");
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((start + nextDuration + 5) / 10) * 10));
@@ -72,6 +80,7 @@ export function createAudioTrackActions(d) {
message = "视频原声已分离到时间线",
timelineStart = 0,
assetId = d.sourceAudioAssetId,
options = {},
) {
if (d.sourceAudioUrlRef.current) URL.revokeObjectURL(d.sourceAudioUrlRef.current);
const nextUrl = URL.createObjectURL(blob);
@@ -86,8 +95,10 @@ export function createAudioTrackActions(d) {
d.setSourceAudioStart(nextStart);
d.setSourceAudioAssetId(assetId || "");
d.setSourceAudioLinked(true);
d.setSelectedTrack("source");
d.setActiveTool("audio");
if (options.focusAudio !== false) {
d.setSelectedTrack("source");
d.setActiveTool("audio");
}
d.setStatus("done");
d.setStatusText("视频原声已分离");
d.setProgress(100);
@@ -144,9 +155,36 @@ export function createAudioTrackActions(d) {
d.notify(message);
}
async function commitAudio(blob, nextStatusText) {
async function commitAudio(blob, nextStatusText, options = {}) {
const decoded = await decodeWaveform(blob);
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText);
const captionSegment = options.captionSegment;
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText, captionSegment ? {
start: captionSegment.start || 0,
script: options.script || captionSegment.text,
replaceSegmentId: captionSegment.audioSegmentId || "",
} : options);
if (captionSegment) {
d.setCaptionSegments((segments) => segments.map((segment) => segment.id === captionSegment.id ? {
...segment,
audioSegmentId: audioSegment.id,
start: audioSegment.start,
end: audioSegment.start + audioSegment.duration,
} : segment).sort((a, b) => (a.start || 0) - (b.start || 0)));
d.setSelectedSegmentId(captionSegment.id);
d.setHistoryItems((items) => [{
id: crypto.randomUUID(),
blob,
voiceId: d.selectedVoiceId,
voiceName: d.selectedVoice.name,
script: options.script || captionSegment.text,
duration: decoded.duration || estimateDuration(options.script || captionSegment.text),
peaks: decoded.peaks,
createdAt: formatSavedTime(),
}, ...items.slice(0, 8)]);
return;
}
const generatedCaptions = createCaptionSegments(d.script);
const generatedTimeline = getCaptionTimeline(generatedCaptions, audioSegment.duration);
const boundCaptions = generatedCaptions.map((segment, index) => ({
+4
View File
@@ -0,0 +1,4 @@
export function getCaptionVoiceSegment(audioSegments, captionSegment) {
if (!captionSegment?.audioSegmentId) return null;
return audioSegments.find((segment) => segment.id === captionSegment.audioSegmentId) ?? null;
}
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { getCaptionVoiceSegment } from "./captionVoice.js";
describe("getCaptionVoiceSegment", () => {
const oldVoice = { id: "voice-old", url: "blob:old", blob: { size: 10 } };
const newVoice = { id: "voice-new", url: "blob:new", blob: { size: 20 } };
const audioSegments = [oldVoice, newVoice];
it("returns only the voice linked to the selected caption", () => {
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-old", audioSegmentId: "voice-old" })).toBe(oldVoice);
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-new", audioSegmentId: "voice-new" })).toBe(newVoice);
});
it("does not leak the previously selected caption voice into an unvoiced caption", () => {
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-fresh" })).toBeNull();
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-missing", audioSegmentId: "removed-voice" })).toBeNull();
});
});
+1
View File
@@ -20,6 +20,7 @@ export function createEditorCommandActions(d) {
d.setSelectedTrack("audio");
d.setVoiceTab("synthesis");
}
if (toolId === "media") d.setSelectedTrack("image");
if (toolId === "caption") d.setSelectedTrack("caption");
}
+45 -15
View File
@@ -6,6 +6,7 @@ import { pinyin } from "pinyin-pro";
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
ort.env.webgpu.powerPreference = "high-performance";
const PINYIN_VOICES = {
"zh_CN-xiao_ya-medium": "zh/zh_CN/xiao_ya/medium",
@@ -96,8 +97,35 @@ async function loadPinyinVoice(voiceId, onProgress) {
if (!configResponse.ok) throw new Error(`${voiceName}配置下载失败 (${configResponse.status})`);
const config = await configResponse.json();
const model = await fetchArrayBufferWithProgress(`${voiceBase}/${voiceId}.onnx`, onProgress, voiceName);
const session = await ort.InferenceSession.create(model, { executionProviders: ["wasm"] });
return { config, session };
if (globalThis.navigator?.gpu) {
try {
const session = await ort.InferenceSession.create(model, {
executionProviders: [{ name: "webgpu", preferredLayout: "NHWC" }],
graphOptimizationLevel: "all",
});
onProgress?.({ backend: "webgpu" });
return { backend: "webgpu", config, model, session };
} catch (error) {
console.warn("Piper WebGPU initialization failed; using WASM.", error);
onProgress?.({ backend: "wasm", fallbackReason: error instanceof Error ? error.message : String(error) });
}
}
const session = await ort.InferenceSession.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
onProgress?.({ backend: "wasm" });
return { backend: "wasm", config, model, session };
}
function createPinyinFeeds(input, config) {
const ids = phonemizeXiaoYa(input.text.trim(), config.phoneme_id_map);
return {
input: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, ids.length]),
input_lengths: new ort.Tensor("int64", BigInt64Array.from([ids.length], BigInt), [1]),
scales: new ort.Tensor("float32", Float32Array.from([
config.inference.noise_scale,
config.inference.length_scale,
config.inference.noise_w,
]), [3]),
};
}
async function predictPinyinVoice(input, onProgress) {
@@ -110,23 +138,25 @@ async function predictPinyinVoice(input, onProgress) {
}),
);
}
const { config, session } = await pinyinRuntimePromises.get(input.voiceId);
const ids = phonemizeXiaoYa(input.text.trim(), config.phoneme_id_map);
const feeds = {
input: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, ids.length]),
input_lengths: new ort.Tensor("int64", BigInt64Array.from([ids.length], BigInt), [1]),
scales: new ort.Tensor("float32", Float32Array.from([
config.inference.noise_scale,
config.inference.length_scale,
config.inference.noise_w,
]), [3]),
};
const result = await session.run(feeds);
let runtime = await pinyinRuntimePromises.get(input.voiceId);
const feeds = createPinyinFeeds(input, runtime.config);
let result;
try {
result = await runtime.session.run(feeds);
} catch (error) {
if (runtime.backend !== "webgpu") throw error;
console.warn("Piper WebGPU inference failed; retrying with WASM.", error);
onProgress?.({ backend: "wasm", fallbackReason: error instanceof Error ? error.message : String(error) });
const session = await ort.InferenceSession.create(runtime.model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
runtime = { ...runtime, backend: "wasm", session };
pinyinRuntimePromises.set(input.voiceId, Promise.resolve(runtime));
result = await session.run(feeds);
}
const samples = result.output.data;
if (!(samples instanceof Float32Array) || !samples.length || samples.some((sample) => !Number.isFinite(sample))) {
throw new Error("小雅生成了无效音频");
}
return encodeWav(samples, config.audio.sample_rate);
return encodeWav(samples, runtime.config.audio.sample_rate);
}
export async function predictPiperVoice(tts, input, onProgress) {
+18 -1
View File
@@ -16,6 +16,8 @@ import {
} from "./timeline.js";
import {
getTimelineAutoFitZoom,
getTimelineInitialContentZoom,
getTimelineProjectDuration,
getTimelineVisibleDuration,
getTimelineZoomForVisibleDuration,
} from "./timelineScale.js";
@@ -29,10 +31,25 @@ describe("timeline primitives", () => {
});
it("clamps automatic timeline fitting to supported zoom limits", () => {
expect(getTimelineVisibleDuration(getTimelineZoomForVisibleDuration(10_000))).toBeCloseTo(1800, 2);
expect(getTimelineVisibleDuration(getTimelineZoomForVisibleDuration(100_000))).toBeCloseTo(86_400, 2);
expect(getTimelineVisibleDuration(getTimelineAutoFitZoom(0.5))).toBeCloseTo(5, 2);
});
it("uses an approachable empty and first-content timeline window", () => {
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(0))).toBeCloseTo(10, 2);
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(1.8))).toBeCloseTo(5, 2);
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(15))).toBeCloseTo(15 / 0.82, 2);
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(90))).toBeCloseTo(30, 2);
});
it("grows the project horizon from real content with bounded tail room", () => {
expect(getTimelineProjectDuration(0)).toBe(10);
expect(getTimelineProjectDuration(1.8)).toBe(10);
expect(getTimelineProjectDuration(12)).toBe(17);
expect(getTimelineProjectDuration(100)).toBe(105);
expect(getTimelineProjectDuration(1_000)).toBe(1_030);
});
it("reorders without mutating the source array", () => {
const source = [{ id: "a" }, { id: "b" }, { id: "c" }];
const result = reorderTimelineItems(source, 0, 2);
+27 -3
View File
@@ -1,4 +1,4 @@
import { DEFAULT_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
import { DEFAULT_TIMELINE_DURATION_SECONDS, MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
export const TIMELINE_MIN_ZOOM = 0.25;
export const TIMELINE_MAX_ZOOM = 16;
@@ -18,7 +18,7 @@ export function getTimelineVisibleDuration(zoom) {
if (clampedZoom <= 1) {
const progress = (clampedZoom - TIMELINE_MIN_ZOOM) / (1 - TIMELINE_MIN_ZOOM);
const maxLog = Math.log(DEFAULT_TIMELINE_DURATION_SECONDS);
const maxLog = Math.log(MAX_TIMELINE_DURATION_SECONDS);
const defaultLog = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS);
return Math.exp(maxLog + (defaultLog - maxLog) * progress);
}
@@ -32,7 +32,7 @@ export function getTimelineVisibleDuration(zoom) {
export function getTimelineZoomForVisibleDuration(visibleDuration) {
const target = Math.max(
TIMELINE_MIN_VISIBLE_SECONDS,
Math.min(DEFAULT_TIMELINE_DURATION_SECONDS, Number(visibleDuration) || TIMELINE_DEFAULT_VISIBLE_SECONDS),
Math.min(MAX_TIMELINE_DURATION_SECONDS, Number(visibleDuration) || TIMELINE_DEFAULT_VISIBLE_SECONDS),
);
let low = TIMELINE_MIN_ZOOM;
let high = TIMELINE_MAX_ZOOM;
@@ -53,6 +53,30 @@ export function getTimelineAutoFitZoom(contentDuration, fillRatio = 0.82) {
return getTimelineZoomForVisibleDuration(paddedVisibleDuration);
}
export function getTimelineInitialContentZoom(contentDuration) {
const safeDuration = Math.max(0, Number(contentDuration) || 0);
if (safeDuration <= 0) return getTimelineZoomForVisibleDuration(TIMELINE_DEFAULT_VISIBLE_SECONDS);
if (safeDuration > 60) return getTimelineZoomForVisibleDuration(30);
return getTimelineAutoFitZoom(safeDuration);
}
export function getTimelineTailPadding(contentDuration) {
const safeDuration = Math.max(0, Number(contentDuration) || 0);
if (safeDuration <= 0) return 0;
if (safeDuration < 10) return 2;
if (safeDuration <= 60) return 5;
return Math.min(30, safeDuration * 0.05);
}
export function getTimelineProjectDuration(contentDuration) {
const safeDuration = Math.max(0, Number(contentDuration) || 0);
if (safeDuration <= 0) return DEFAULT_TIMELINE_DURATION_SECONDS;
return Math.min(
MAX_TIMELINE_DURATION_SECONDS,
Math.max(DEFAULT_TIMELINE_DURATION_SECONDS, Math.ceil((safeDuration + getTimelineTailPadding(safeDuration)) * 2) / 2),
);
}
export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
if (timelineDuration <= 0) {
return 100;
+14 -1
View File
@@ -11,7 +11,7 @@ export function createTimelineSegmentCountActions(d) {
const index = stickerIndex(); const next = d.stickerSegments.filter((_, position) => position !== index);
d.commitStickerSegments(next, next.length ? "已删除当前贴纸片段" : "已删除最后一个贴纸片段", next[Math.max(0, index - 1)]?.id ?? "");
};
const handleAddSegment = () => {
const handleAddSegment = (requestedStart = null) => {
if (d.selectedTrack === "sticker") {
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法新增贴纸片段");
const source = d.stickerSegments[stickerIndex()] ?? d.getStickerDragAsset(d.selectedSticker);
@@ -30,6 +30,19 @@ export function createTimelineSegmentCountActions(d) {
return void d.commitVisualSegments([...source, segment], "已新增一个视觉片段", source.length);
}
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐暂不支持切片,请删除后重新上传" : d.selectedTrack === "source" ? "视频原声暂不支持切片,可删除后重新上传视频" : "音频片段由生成结果决定,请重新生成或复制 WAV");
if (Number.isFinite(requestedStart)) {
const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, requestedStart));
const segment = {
id: makeId("caption"),
text: "新的字幕片段",
weight: 1,
hidden: false,
start,
end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8),
};
const next = [...d.captionSegments, segment].sort((a, b) => (a.start || 0) - (b.start || 0));
return void d.commitCaptionSegments(next, "已在点击位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
}
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
const previous = d.captionSegments[index]; const nextCaption = d.captionSegments[index + 1];
const start = hasExplicitCaptionTiming(previous) ? previous.end : null;
-12
View File
@@ -8,14 +8,8 @@ import {
getImageThumbnailCount,
getVisualSegmentsTotal,
} from "./timeline.js";
import { getTimelineAutoFitZoom } from "./timelineScale.js";
export function createVisualTimelineActions(d) {
function fitTimelineToVideo(duration) {
if (typeof d.setTimelineZoom !== "function") return;
d.setTimelineZoom(getTimelineAutoFitZoom(duration));
}
function getVisualDurationForAsset(asset, fallbackDuration = 4) {
if (asset?.type === "video" && asset.duration) {
return Math.min(
@@ -92,7 +86,6 @@ export function createVisualTimelineActions(d) {
d.setSelectedVisualSegmentId(segment.id);
d.setImageDuration(segment.duration);
d.setImageClipCount(getImageThumbnailCount(segment.duration));
if (asset?.type === "video") fitTimelineToVideo(segment.duration);
}
function appendVisualAssetToTimeline(asset) {
@@ -120,7 +113,6 @@ export function createVisualTimelineActions(d) {
`${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
sourceSegments.length,
);
if (asset.type === "video") fitTimelineToVideo(totalDuration + segmentDuration);
d.seekTo(totalDuration);
if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration);
}
@@ -128,7 +120,6 @@ export function createVisualTimelineActions(d) {
function updateVisualAssetInTimeline(assetId, updates) {
if (!assetId) return;
d.setVisualSegments((segments) => {
const matchingSegment = segments.find((segment) => segment.assetId === assetId);
const nextSegments = segments.map((segment) =>
segment.assetId === assetId
? {
@@ -149,9 +140,6 @@ export function createVisualTimelineActions(d) {
const nextDuration = getVisualSegmentsTotal(nextSegments);
d.setImageDuration(nextDuration);
d.setImageClipCount(getImageThumbnailCount(nextDuration));
if (matchingSegment?.type === "video" && updates.duration) {
fitTimelineToVideo(nextDuration);
}
return nextSegments;
});
if (d.previewVisualSegment?.assetId === assetId || d.previewVisualSegment?.src === updates.src) {
+202 -29
View File
@@ -1841,6 +1841,13 @@ button:disabled {
.caption-tool-panel::-webkit-scrollbar { display: none; width: 0; height: 0; }
.caption-tool-panel > .segmented button {
min-height: 32px;
padding: 5px 8px;
font-size: 12px;
line-height: 1;
}
.caption-tool-panel > h2,
.caption-tool-panel > .switch-row,
.caption-tool-panel > .segmented,
@@ -1877,9 +1884,8 @@ button:disabled {
}
.caption-style-panel { display: grid; gap: 10px; padding: 11px; border: 1px solid rgba(255,255,255,.07); border-radius: 9px; background: rgba(255,255,255,.025); }
.caption-style-panel .compact-slider { margin: 2px 0; }
.tool-helper-copy { margin: 0; color: #8fa0ab; font-size: 12px; line-height: 1.5; }
.inline-caption-editor { position: absolute; z-index: 12; transform: translate(-50%, -50%); margin: 0; }
.inline-caption-editor input { width: min(260px, 45vw); padding: 9px 11px; border: 1px solid #37e8d8; border-radius: 7px; outline: none; color: #f5ffff; background: rgba(7,14,18,.92); box-shadow: 0 8px 30px rgba(0,0,0,.35); }
.generated-voice-result { display: grid; gap: 9px; padding: 11px; border: 1px solid rgba(55,232,216,.28); border-radius: 9px; background: rgba(55,232,216,.07); }
.generated-voice-result > div { display: flex; gap: 8px; color: #37e8d8; }
.generated-voice-result span { display: grid; gap: 2px; }
@@ -1889,9 +1895,9 @@ button:disabled {
.caption-style-heading { display: grid; gap: 2px; }
.caption-style-heading strong { font-size: 13px; color: #eaf7f7; }
.caption-style-heading span { font-size: 11px; color: #82909c; }
.caption-style-presets { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; }
.caption-style-presets { display: grid; grid-template-columns: minmax(0, 1.35fr) repeat(2, minmax(0, 1fr)); gap: 8px; }
.caption-color-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.caption-style-presets button { min-width: 0; min-height: 38px; padding: 7px 9px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; color: #b8c5cd; font-size: 12px; line-height: 1.2; white-space: normal; overflow-wrap: anywhere; background: rgba(255,255,255,.04); cursor:pointer; }
.caption-style-presets button { min-width: 0; min-height: 36px; padding: 6px 4px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; color: #b8c5cd; font-size: 10px; line-height: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background: rgba(255,255,255,.04); cursor:pointer; }
.caption-style-presets button.is-active { color: #061515; border-color: #37e8d8; background: #37e8d8; }
.caption-color-row label { display:grid; gap:4px; color:#93a0aa; font-size:11px; }
.caption-color-row input { width:100%; height:28px; padding:2px; border:1px solid rgba(255,255,255,.1); border-radius:5px; background:#0c1015; }
@@ -2149,7 +2155,7 @@ button:disabled {
.visual-effects-panel { gap: 12px; }
.visual-effects-panel > .tool-panel { padding: 0; }
.visual-effects-panel > .tool-panel > h2 { font-size: 13px; color: #9ba9b2; }
.visual-context-tabs { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
.visual-context-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
.visual-context-tabs button { min-width: 0; border: 0; border-radius: 6px; padding: 8px 3px; color: #82919b; background: transparent; font-size: 11px; cursor: pointer; }
.visual-context-tabs button:hover { color: #c8d8de; background: rgba(255,255,255,.04); }
.visual-context-tabs button.is-active { color: #dffffb; background: rgba(53,234,217,.13); box-shadow: inset 0 0 0 1px rgba(53,234,217,.38); }
@@ -2810,6 +2816,33 @@ button:disabled {
gap: 12px;
}
.caption-context-tabs {
margin-top: 12px;
}
.caption-context-tabs button {
flex: 1;
}
.caption-voice-panel {
min-width: 0;
}
.caption-voice-hint {
margin: 2px 0 12px;
border: 1px solid rgba(53, 234, 217, 0.16);
border-radius: 7px;
padding: 10px 12px;
color: #9eabb4;
font-size: 12px;
line-height: 1.55;
background: rgba(53, 234, 217, 0.055);
}
.caption-voice-panel .field-label:first-of-type {
margin-top: 0;
}
.caption-context-panel .field-label {
margin-top: 2px;
}
@@ -2846,6 +2879,34 @@ button:disabled {
line-height: 1.55;
}
.visual-context-empty {
display: grid;
place-items: center;
gap: 8px;
min-height: 210px;
border: 1px dashed rgba(173, 184, 196, 0.18);
border-radius: 8px;
padding: 24px 18px;
color: #88959f;
text-align: center;
background: rgba(255, 255, 255, 0.025);
}
.visual-context-empty svg {
color: #5eece0;
}
.visual-context-empty strong {
color: #dce8ec;
font-size: 13px;
}
.visual-context-empty span {
max-width: 250px;
font-size: 12px;
line-height: 1.55;
}
.caption-context-actions {
display: grid;
grid-template-columns: 1fr 1fr;
@@ -2995,29 +3056,74 @@ button:disabled {
.model-row {
justify-content: space-between;
gap: 10px;
gap: 12px;
margin-top: 10px;
padding: 9px 10px;
border-radius: 7px;
min-height: 42px;
padding: 7px 8px 7px 12px;
border: 1px solid rgba(255, 255, 255, 0.045);
border-radius: 8px;
color: #8b98a4;
font-size: 12px;
background: rgba(255, 255, 255, 0.045);
background: rgba(255, 255, 255, 0.035);
}
.voice-sample-preview {
display: grid;
gap: 8px;
margin-top: 10px;
padding: 10px;
border: 1px solid rgba(136, 184, 255, 0.18);
border-radius: 8px;
background: rgba(136, 184, 255, 0.06);
}
.voice-sample-preview > div {
display: grid;
gap: 2px;
}
.voice-sample-preview strong {
color: #dce8ef;
font-size: 12px;
}
.voice-sample-preview span {
color: #8b9aa5;
font-size: 11px;
}
.voice-sample-preview audio {
width: 100%;
height: 34px;
}
.model-row span:first-child {
min-width: 0;
overflow: hidden;
color: #cbd5dc;
text-overflow: ellipsis;
white-space: nowrap;
}
.model-row button {
flex: 0 0 auto;
border: 0;
border-radius: 6px;
padding: 5px 8px;
border-radius: 999px;
min-width: 70px;
padding: 6px 11px;
color: #83eee5;
font-size: 12px;
font-size: 11px;
font-weight: 700;
line-height: 1;
white-space: nowrap;
background: rgba(46, 234, 216, 0.08);
cursor: pointer;
}
.model-row button:hover {
background: rgba(46, 234, 216, 0.14);
}
.slider-field {
margin-top: 14px;
}
@@ -3314,7 +3420,7 @@ button:disabled {
.timeline-board {
display: grid;
grid-template-columns: 128px 1fr;
grid-template-columns: 164px minmax(0, 1fr);
min-height: 0;
max-height: min(430px, 48vh);
overflow-y: auto;
@@ -3328,7 +3434,7 @@ button:disabled {
.track-labels {
display: grid;
grid-template-rows: 46px 46px 58px 58px 58px;
grid-template-rows: repeat(5, 48px);
padding-top: 28px;
border-right: 1px solid rgba(255, 255, 255, 0.07);
}
@@ -3336,8 +3442,8 @@ button:disabled {
.track-labels div {
display: flex;
align-items: center;
gap: 7px;
padding: 0 12px;
gap: 6px;
padding: 0 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.045);
color: #c8d3db;
font-size: 13px;
@@ -3386,11 +3492,14 @@ button:disabled {
width: auto;
min-width: 0;
flex: 1;
overflow: hidden;
padding: 0 0 0 2px;
color: inherit;
font-size: 13px;
font-weight: 650;
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
background: transparent;
}
@@ -3410,11 +3519,15 @@ button:disabled {
.track-scroll {
position: relative;
display: grid;
grid-template-rows: 28px 46px 46px 58px 58px 58px;
grid-template-rows: 28px repeat(5, 48px);
min-width: 25%;
transition: width 140ms cubic-bezier(0.16, 1, 0.3, 1);
}
.track-scroll.is-wheel-zooming {
transition: none;
}
.ruler {
position: relative;
display: block;
@@ -3596,17 +3709,21 @@ button:disabled {
}
.image-thumbnails {
display: flex;
display: grid;
grid-auto-flow: column;
grid-auto-columns: var(--thumbnail-cell-width, 84px);
align-items: stretch;
justify-content: start;
width: 100%;
min-width: 0;
overflow: hidden;
}
.image-thumbnails img {
width: auto;
min-width: 42px;
display: block;
width: 100%;
min-width: 0;
height: 36px;
flex: 1 1 max(42px, calc(106px * var(--timeline-zoom, 1)));
object-fit: cover;
user-select: none;
-webkit-user-drag: none;
@@ -3626,10 +3743,9 @@ button:disabled {
}
.image-thumbnails.is-video img {
width: 0;
width: 100%;
min-width: 0;
height: 36px;
flex: 1 1 0;
object-fit: cover;
background: #05070a;
}
@@ -4014,14 +4130,14 @@ button:disabled {
.audio-track {
overflow: hidden;
padding: 7px 0;
padding: 4px 0;
}
.audio-clip {
position: relative;
min-width: 0;
max-width: 100%;
height: 44px;
height: 40px;
container-type: inline-size;
}
@@ -4033,7 +4149,7 @@ button:disabled {
.audio-track:not(.source-track):not(.music-track) .audio-clip {
position: absolute;
top: 7px;
top: 4px;
cursor: grab;
}
@@ -4053,7 +4169,7 @@ button:disabled {
.audio-clip.is-source.is-linked {
position: absolute;
top: 7px;
top: 4px;
}
.audio-clip.is-source .waveform-strip span {
@@ -4241,7 +4357,7 @@ button:disabled {
align-items: center;
gap: 1px;
width: 100%;
height: 54px;
height: 40px;
overflow: hidden;
border: 1px solid rgba(41, 225, 204, 0.52);
border-radius: 6px;
@@ -4251,7 +4367,7 @@ button:disabled {
.waveform-strip span {
width: auto;
height: calc(7px + var(--bar) * 37px);
height: calc(4px + var(--bar) * 22px);
flex: 1 1 0;
min-width: 0;
border-radius: 999px;
@@ -4259,6 +4375,63 @@ button:disabled {
background: #20d2bf;
}
@container (max-width: 160px) {
.waveform-strip {
padding-inline: 6px;
}
.waveform-strip span {
display: none;
}
.waveform-strip span:nth-child(2n + 1) {
display: block;
}
}
@container (max-width: 96px) {
.waveform-strip {
padding-inline: 4px;
}
.waveform-strip span:nth-child(2n + 1) {
display: none;
}
.waveform-strip span:nth-child(4n + 1) {
display: block;
}
}
@container (max-width: 52px) {
.waveform-strip {
padding-inline: 3px;
}
.waveform-strip span:nth-child(4n + 1) {
display: none;
}
.waveform-strip span:nth-child(8n + 1) {
display: block;
}
}
@container (max-width: 28px) {
.waveform-strip {
gap: 0.5px;
padding-inline: 2px;
}
.waveform-strip span:nth-child(8n + 1) {
display: none;
}
.waveform-strip span:nth-child(16n + 1) {
display: block;
}
}
.audio-clip-duration {
position: absolute;
right: 8px;