Add sticker timeline and offline model caching
This commit is contained in:
1 parent
ddb6f4a5e1
commit
1cc16c8c2f
65 files changed
+4432
-373
No files matched your search
+918
-159
File diff suppressed because it is too large.
Load diff
@@ -25,9 +25,6 @@ export function PreviewStage({
|
||||
selectedFilter,
|
||||
fitMode,
|
||||
setFitMode,
|
||||
audioUrl,
|
||||
setIsPlaying,
|
||||
setCurrentTime,
|
||||
captionsEnabled,
|
||||
currentCaption,
|
||||
captionSize,
|
||||
@@ -43,16 +40,19 @@ export function PreviewStage({
|
||||
seekTo,
|
||||
notify,
|
||||
}) {
|
||||
const hasStickerOverlay = Boolean(selectedSticker?.src || selectedSticker?.text);
|
||||
const hasPreviewContent = Boolean(previewVisualSrc || hasStickerOverlay);
|
||||
|
||||
return (
|
||||
<section className="preview-stage">
|
||||
<div
|
||||
ref={previewShellRef}
|
||||
className={`preview-canvas fit-${fitMode} ${previewVisualSrc ? "" : "is-empty"} ${
|
||||
className={`preview-canvas fit-${fitMode} ${hasPreviewContent ? "" : "is-empty"} ${
|
||||
previewVisualSrc && !trackVisibility.image ? "is-image-hidden" : ""
|
||||
}`}
|
||||
style={{ "--preview-ratio": previewRatio }}
|
||||
>
|
||||
{!previewVisualSrc ? (
|
||||
{!hasPreviewContent ? (
|
||||
<button className="preview-empty" type="button" style={previewFrameStyle} onClick={() => fileInputRef.current?.click()}>
|
||||
<CloudArrowUp size={38} />
|
||||
<strong>{t("previewEmptyTitle")}</strong>
|
||||
@@ -65,7 +65,7 @@ export function PreviewStage({
|
||||
data-hidden-label={t("imageHidden")}
|
||||
style={previewFrameStyle}
|
||||
>
|
||||
{trackVisibility.image && previewVisualType === "image" ? (
|
||||
{previewVisualSrc && trackVisibility.image && previewVisualType === "image" ? (
|
||||
<img
|
||||
src={previewVisualSrc}
|
||||
alt={t("currentMediaAlt")}
|
||||
@@ -75,7 +75,7 @@ export function PreviewStage({
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{trackVisibility.image && previewVisualType === "video" ? (
|
||||
{previewVisualSrc && trackVisibility.image && previewVisualType === "video" ? (
|
||||
<video
|
||||
key={previewVisualSrc}
|
||||
ref={previewVideoRef}
|
||||
@@ -88,25 +88,6 @@ export function PreviewStage({
|
||||
filter: selectedFilter.css,
|
||||
objectFit: fitMode,
|
||||
}}
|
||||
onPlay={() => {
|
||||
if (!audioUrl) {
|
||||
setIsPlaying(true);
|
||||
}
|
||||
}}
|
||||
onPause={() => {
|
||||
if (!audioUrl) {
|
||||
setIsPlaying(false);
|
||||
}
|
||||
}}
|
||||
onEnded={() => {
|
||||
setIsPlaying(false);
|
||||
setCurrentTime(0);
|
||||
}}
|
||||
onTimeUpdate={(event) => {
|
||||
if (!audioUrl) {
|
||||
setCurrentTime(event.currentTarget.currentTime);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{captionsEnabled && trackVisibility.caption && currentCaption ? (
|
||||
@@ -124,7 +105,11 @@ export function PreviewStage({
|
||||
{currentCaption}
|
||||
</button>
|
||||
) : null}
|
||||
{selectedSticker.text ? <div className="sticker-overlay">{selectedSticker.text}</div> : null}
|
||||
{selectedSticker.src ? (
|
||||
<img className="sticker-overlay is-image" src={selectedSticker.src} alt="" draggable={false} />
|
||||
) : selectedSticker.text ? (
|
||||
<div className="sticker-overlay is-label">{selectedSticker.text}</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+394
-58
@@ -1,3 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ArrowClockwise,
|
||||
ArrowCounterClockwise,
|
||||
@@ -22,11 +23,59 @@ import {
|
||||
|
||||
import { IMAGE_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { formatClock, formatTime, getImageThumbnailCount, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import {
|
||||
TIMELINE_MIN_ZOOM,
|
||||
clampTimelineZoom,
|
||||
getTimelineRulerTicks,
|
||||
getTimelineTrackWidthPercent,
|
||||
getTimelineZoomLabel,
|
||||
} from "../lib/timelineScale.js";
|
||||
import { IconButton, WaveformStrip } from "./ui.jsx";
|
||||
|
||||
const MIN_TIMELINE_ZOOM = 0.25;
|
||||
const MAX_TIMELINE_ZOOM = 3;
|
||||
const TIMELINE_WHEEL_ZOOM_RATIO = 1.12;
|
||||
const TIMELINE_WHEEL_ZOOM_SENSITIVITY = 0.00034;
|
||||
const TIMELINE_WHEEL_ZOOM_COMMIT_DELAY = 180;
|
||||
const TIMELINE_BUTTON_ZOOM_RATIO = 1.25;
|
||||
const VIDEO_FRAME_MIN_COUNT = 1;
|
||||
|
||||
function getSampledVideoFrames(frames, count) {
|
||||
if (!Array.isArray(frames) || !frames.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const safeCount = Math.max(VIDEO_FRAME_MIN_COUNT, Math.min(frames.length, count));
|
||||
if (safeCount >= frames.length) {
|
||||
return frames;
|
||||
}
|
||||
|
||||
if (safeCount === 1) {
|
||||
return [frames[Math.floor(frames.length / 2)]];
|
||||
}
|
||||
|
||||
return Array.from({ length: safeCount }, (_, index) => {
|
||||
const frameIndex = Math.round((index / (safeCount - 1)) * (frames.length - 1));
|
||||
return frames[frameIndex];
|
||||
});
|
||||
}
|
||||
|
||||
function getVideoTimelineFrameCount({ duration, timelineDuration, contentWidth, timelineZoom, availableFrames }) {
|
||||
if (!availableFrames || timelineDuration <= 0 || contentWidth <= 0) {
|
||||
return VIDEO_FRAME_MIN_COUNT;
|
||||
}
|
||||
|
||||
const clipPixelWidth = Math.max(68, (Math.max(0, duration || 0) / timelineDuration) * contentWidth);
|
||||
const targetCellWidth =
|
||||
timelineZoom >= 8
|
||||
? 34
|
||||
: timelineZoom >= 3
|
||||
? 42
|
||||
: timelineZoom >= 1
|
||||
? 54
|
||||
: 82;
|
||||
return Math.max(
|
||||
VIDEO_FRAME_MIN_COUNT,
|
||||
Math.min(availableFrames, Math.ceil(clipPixelWidth / targetCellWidth)),
|
||||
);
|
||||
}
|
||||
|
||||
export function Timeline({
|
||||
t,
|
||||
@@ -47,12 +96,12 @@ export function Timeline({
|
||||
setTimelineZoom,
|
||||
selectedTrack,
|
||||
setSelectedTrack,
|
||||
setActiveTool,
|
||||
trackVisibility,
|
||||
toggleTrackVisibility,
|
||||
trackLocks,
|
||||
toggleTrackLock,
|
||||
trackScrollRef,
|
||||
trackWidth,
|
||||
startTimelineSeek,
|
||||
timelineDuration,
|
||||
currentTime,
|
||||
@@ -66,6 +115,11 @@ export function Timeline({
|
||||
handleTrackAssetDragLeave,
|
||||
handleTrackAssetDrop,
|
||||
activeTimelineClipDrag,
|
||||
showStickerTrack,
|
||||
stickerSegments,
|
||||
currentStickerSegment,
|
||||
selectedStickerSegmentId,
|
||||
setSelectedStickerSegmentId,
|
||||
imageSrc,
|
||||
displayedVisualSegments,
|
||||
renderedVisualTimeline,
|
||||
@@ -78,6 +132,7 @@ export function Timeline({
|
||||
suppressTimelineClipClickRef,
|
||||
startTimelineClipDrag,
|
||||
startImageResize,
|
||||
startStickerSegmentMove,
|
||||
displayedCaptionSegments,
|
||||
displayedCaptionTimeline,
|
||||
currentCaptionSegment,
|
||||
@@ -87,6 +142,7 @@ export function Timeline({
|
||||
sourceAudioBlob,
|
||||
sourceAudioPeaks,
|
||||
sourceAudioClipPercent,
|
||||
sourceAudioStartPercent,
|
||||
sourceAudioDuration,
|
||||
audioBlob,
|
||||
peaks,
|
||||
@@ -105,14 +161,168 @@ export function Timeline({
|
||||
activeTimelineClipDrag?.track === "caption"
|
||||
? displayedCaptionSegments.find((segment) => segment.id === activeTimelineClipDrag.segmentId)
|
||||
: null;
|
||||
const adjustTimelineZoom = (nextZoomOrUpdater) => {
|
||||
setTimelineZoom((currentZoom) => {
|
||||
const rawNextZoom =
|
||||
typeof nextZoomOrUpdater === "function"
|
||||
? nextZoomOrUpdater(currentZoom)
|
||||
: nextZoomOrUpdater;
|
||||
return Math.max(MIN_TIMELINE_ZOOM, Math.min(MAX_TIMELINE_ZOOM, rawNextZoom));
|
||||
});
|
||||
const timelineTrackRows = showStickerTrack
|
||||
? "28px 46px 46px 46px 58px 58px 58px"
|
||||
: "28px 46px 46px 58px 58px 58px";
|
||||
const timelineLabelRows = showStickerTrack
|
||||
? "46px 46px 46px 58px 58px 58px"
|
||||
: "46px 46px 58px 58px 58px";
|
||||
const timelineTrackLabels = [
|
||||
["image", t("imageTrack")],
|
||||
...(showStickerTrack ? [["sticker", t("stickerTrack")]] : []),
|
||||
["caption", t("caption")],
|
||||
["source", t("sourceTrack")],
|
||||
["audio", t("voiceTrack")],
|
||||
["music", t("musicTrack")],
|
||||
];
|
||||
const [rulerViewport, setRulerViewport] = useState({
|
||||
scrollLeft: 0,
|
||||
viewportWidth: 0,
|
||||
contentWidth: 0,
|
||||
});
|
||||
const [localTimelineZoom, setLocalTimelineZoom] = useState(() => clampTimelineZoom(timelineZoom));
|
||||
const timelineZoomRef = useRef(timelineZoom);
|
||||
const wheelZoomFrameRef = useRef(0);
|
||||
const commitZoomTimerRef = useRef(0);
|
||||
const rulerViewportFrameRef = useRef(0);
|
||||
const pendingWheelDeltaRef = useRef(0);
|
||||
const pendingWheelAnchorRef = useRef(null);
|
||||
const timelineWheelHandlerRef = useRef(null);
|
||||
useEffect(() => {
|
||||
const trackElement = trackScrollRef.current;
|
||||
const scrollElement = trackElement?.parentElement;
|
||||
if (!trackElement || !scrollElement) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const applyRulerViewportUpdate = () => {
|
||||
rulerViewportFrameRef.current = 0;
|
||||
const nextViewport = {
|
||||
scrollLeft: scrollElement.scrollLeft,
|
||||
viewportWidth: scrollElement.clientWidth,
|
||||
contentWidth: trackElement.clientWidth,
|
||||
};
|
||||
setRulerViewport((viewport) =>
|
||||
Math.abs(viewport.scrollLeft - nextViewport.scrollLeft) < 0.5 &&
|
||||
Math.abs(viewport.viewportWidth - nextViewport.viewportWidth) < 0.5 &&
|
||||
Math.abs(viewport.contentWidth - nextViewport.contentWidth) < 0.5
|
||||
? viewport
|
||||
: nextViewport,
|
||||
);
|
||||
};
|
||||
const scheduleRulerViewportUpdate = () => {
|
||||
if (rulerViewportFrameRef.current) {
|
||||
return;
|
||||
}
|
||||
rulerViewportFrameRef.current = window.requestAnimationFrame(applyRulerViewportUpdate);
|
||||
};
|
||||
const resizeObserver =
|
||||
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(scheduleRulerViewportUpdate);
|
||||
|
||||
applyRulerViewportUpdate();
|
||||
scrollElement.addEventListener("scroll", scheduleRulerViewportUpdate, { passive: true });
|
||||
resizeObserver?.observe(scrollElement);
|
||||
resizeObserver?.observe(trackElement);
|
||||
|
||||
return () => {
|
||||
scrollElement.removeEventListener("scroll", scheduleRulerViewportUpdate);
|
||||
if (rulerViewportFrameRef.current) {
|
||||
window.cancelAnimationFrame(rulerViewportFrameRef.current);
|
||||
rulerViewportFrameRef.current = 0;
|
||||
}
|
||||
resizeObserver?.disconnect();
|
||||
};
|
||||
}, [trackScrollRef]);
|
||||
useEffect(() => {
|
||||
const nextZoom = clampTimelineZoom(timelineZoom);
|
||||
if (Math.abs(nextZoom - timelineZoomRef.current) < 0.0008) {
|
||||
return;
|
||||
}
|
||||
timelineZoomRef.current = nextZoom;
|
||||
setLocalTimelineZoom(nextZoom);
|
||||
}, [timelineZoom]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (wheelZoomFrameRef.current) {
|
||||
window.cancelAnimationFrame(wheelZoomFrameRef.current);
|
||||
}
|
||||
window.clearTimeout(commitZoomTimerRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const secondsPerPixel =
|
||||
timelineDuration > 0 && rulerViewport.contentWidth > 0
|
||||
? timelineDuration / rulerViewport.contentWidth
|
||||
: 0;
|
||||
const rulerVisibleStart = Math.max(0, rulerViewport.scrollLeft * secondsPerPixel);
|
||||
const rulerVisibleEnd = Math.min(
|
||||
timelineDuration,
|
||||
(rulerViewport.scrollLeft + rulerViewport.viewportWidth) * secondsPerPixel,
|
||||
);
|
||||
const rulerTicks = useMemo(
|
||||
() => getTimelineRulerTicks(timelineDuration, localTimelineZoom, rulerVisibleStart, rulerVisibleEnd),
|
||||
[timelineDuration, localTimelineZoom, rulerVisibleEnd, rulerVisibleStart],
|
||||
);
|
||||
const zoomReadout = getTimelineZoomLabel(localTimelineZoom);
|
||||
const localTrackWidth = `${getTimelineTrackWidthPercent(timelineDuration, localTimelineZoom)}%`;
|
||||
const commitTimelineZoom = (nextZoom, delay = 0) => {
|
||||
window.clearTimeout(commitZoomTimerRef.current);
|
||||
if (delay <= 0) {
|
||||
setTimelineZoom(nextZoom);
|
||||
return;
|
||||
}
|
||||
commitZoomTimerRef.current = window.setTimeout(() => {
|
||||
setTimelineZoom(nextZoom);
|
||||
}, delay);
|
||||
};
|
||||
const adjustTimelineZoom = (nextZoomOrUpdater, { commitDelay = 0 } = {}) => {
|
||||
const currentZoom = clampTimelineZoom(timelineZoomRef.current);
|
||||
const rawNextZoom =
|
||||
typeof nextZoomOrUpdater === "function"
|
||||
? nextZoomOrUpdater(currentZoom)
|
||||
: nextZoomOrUpdater;
|
||||
const nextZoom = clampTimelineZoom(rawNextZoom);
|
||||
if (Math.abs(nextZoom - currentZoom) < 0.0008) {
|
||||
return;
|
||||
}
|
||||
|
||||
timelineZoomRef.current = nextZoom;
|
||||
setLocalTimelineZoom(nextZoom);
|
||||
commitTimelineZoom(nextZoom, commitDelay);
|
||||
};
|
||||
const flushWheelZoom = () => {
|
||||
wheelZoomFrameRef.current = 0;
|
||||
|
||||
const anchor = pendingWheelAnchorRef.current;
|
||||
const wheelDelta = Math.max(-640, Math.min(640, pendingWheelDeltaRef.current));
|
||||
pendingWheelDeltaRef.current = 0;
|
||||
if (!anchor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentZoom = clampTimelineZoom(timelineZoomRef.current);
|
||||
const nextZoom = clampTimelineZoom(
|
||||
currentZoom * Math.exp(-wheelDelta * TIMELINE_WHEEL_ZOOM_SENSITIVITY),
|
||||
);
|
||||
|
||||
if (Math.abs(nextZoom - currentZoom) < 0.0008) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, currentZoom);
|
||||
const nextTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, nextZoom);
|
||||
const nextTrackWidth =
|
||||
anchor.trackWidth * (nextTrackWidthPercent / Math.max(currentTrackWidthPercent, 0.001));
|
||||
const nextScrollLeft =
|
||||
anchor.trackContentStart +
|
||||
anchor.pointerTrackRatio * nextTrackWidth -
|
||||
anchor.pointerViewportX;
|
||||
const syncScrollAnchor = () => {
|
||||
anchor.scrollElement.scrollLeft = Math.max(0, nextScrollLeft);
|
||||
};
|
||||
|
||||
adjustTimelineZoom(nextZoom, { commitDelay: TIMELINE_WHEEL_ZOOM_COMMIT_DELAY });
|
||||
window.requestAnimationFrame(syncScrollAnchor);
|
||||
};
|
||||
const handleTimelineWheel = (event) => {
|
||||
if (event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
|
||||
@@ -126,17 +336,6 @@ export function Timeline({
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
const currentZoom = Math.max(MIN_TIMELINE_ZOOM, Math.min(MAX_TIMELINE_ZOOM, timelineZoom));
|
||||
const zoomDirection = event.deltaY < 0 ? 1 : -1;
|
||||
const nextZoom =
|
||||
zoomDirection > 0
|
||||
? Math.min(MAX_TIMELINE_ZOOM, currentZoom * TIMELINE_WHEEL_ZOOM_RATIO)
|
||||
: Math.max(MIN_TIMELINE_ZOOM, currentZoom / TIMELINE_WHEEL_ZOOM_RATIO);
|
||||
|
||||
if (Math.abs(nextZoom - currentZoom) < 0.001) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trackRect = trackElement.getBoundingClientRect();
|
||||
const scrollRect = scrollElement.getBoundingClientRect();
|
||||
const trackContentStart = trackRect.left - scrollRect.left + scrollElement.scrollLeft;
|
||||
@@ -144,17 +343,40 @@ export function Timeline({
|
||||
0,
|
||||
Math.min(1, (event.clientX - trackRect.left) / Math.max(trackRect.width, 1)),
|
||||
);
|
||||
const nextTrackWidth = (trackRect.width / currentZoom) * nextZoom;
|
||||
const nextScrollLeft =
|
||||
trackContentStart + pointerTrackRatio * nextTrackWidth - (event.clientX - scrollRect.left);
|
||||
const syncScrollAnchor = () => {
|
||||
scrollElement.scrollLeft = Math.max(0, nextScrollLeft);
|
||||
const deltaModeMultiplier =
|
||||
event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scrollElement.clientHeight : 1;
|
||||
const normalizedDelta = Math.max(
|
||||
-280,
|
||||
Math.min(280, event.deltaY * deltaModeMultiplier),
|
||||
);
|
||||
|
||||
pendingWheelDeltaRef.current = Math.max(
|
||||
-720,
|
||||
Math.min(720, pendingWheelDeltaRef.current + normalizedDelta),
|
||||
);
|
||||
pendingWheelAnchorRef.current = {
|
||||
pointerTrackRatio,
|
||||
pointerViewportX: event.clientX - scrollRect.left,
|
||||
scrollElement,
|
||||
trackContentStart,
|
||||
trackWidth: trackRect.width,
|
||||
};
|
||||
|
||||
adjustTimelineZoom(nextZoom);
|
||||
window.requestAnimationFrame(syncScrollAnchor);
|
||||
window.setTimeout(syncScrollAnchor, 180);
|
||||
if (!wheelZoomFrameRef.current) {
|
||||
wheelZoomFrameRef.current = window.requestAnimationFrame(flushWheelZoom);
|
||||
}
|
||||
};
|
||||
timelineWheelHandlerRef.current = handleTimelineWheel;
|
||||
useEffect(() => {
|
||||
const scrollElement = trackScrollRef.current?.parentElement;
|
||||
if (!scrollElement) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const handleWheel = (event) => timelineWheelHandlerRef.current?.(event);
|
||||
scrollElement.addEventListener("wheel", handleWheel, { passive: false });
|
||||
return () => scrollElement.removeEventListener("wheel", handleWheel);
|
||||
}, [trackScrollRef]);
|
||||
const renderAssetDropSlot = (track) =>
|
||||
assetDropTargetTrack === track ? (
|
||||
<div
|
||||
@@ -180,10 +402,72 @@ export function Timeline({
|
||||
? t("assetAudio")
|
||||
: assetDragPreview?.type === "video"
|
||||
? t("assetVideo")
|
||||
: assetDragPreview?.type === "sticker"
|
||||
? t("assetSticker")
|
||||
: t("assetImage")}
|
||||
</strong>
|
||||
</div>
|
||||
) : null;
|
||||
const renderStickerTrack = () =>
|
||||
showStickerTrack ? (
|
||||
<div
|
||||
className={`sticker-track ${selectedTrack === "sticker" ? "is-selected" : ""} ${
|
||||
assetDropTargetTrack === "sticker" ? "is-drop-target" : ""
|
||||
} ${assetDropPulseTrack === "sticker" ? "is-drop-landing" : ""}`}
|
||||
onClick={() => {
|
||||
setSelectedTrack("sticker");
|
||||
setActiveTool("stickers");
|
||||
}}
|
||||
onDragOver={(event) => handleTrackAssetDragOver(event, "sticker")}
|
||||
onDragLeave={(event) => handleTrackAssetDragLeave(event, "sticker")}
|
||||
onDrop={(event) => handleTrackAssetDrop(event, "sticker")}
|
||||
data-asset-drop-track="sticker"
|
||||
>
|
||||
{assetDropTargetTrack === "sticker" ? (
|
||||
<div className="track-drop-hint">{t("dropStickerHere")}</div>
|
||||
) : null}
|
||||
{trackVisibility.sticker
|
||||
? stickerSegments.map((segment) => {
|
||||
const segmentLeft =
|
||||
timelineDuration > 0
|
||||
? Math.max(0, Math.min(100, ((segment.start || 0) / timelineDuration) * 100))
|
||||
: 0;
|
||||
const segmentWidth =
|
||||
timelineDuration > 0
|
||||
? Math.max(0.4, Math.min(100 - segmentLeft, ((segment.duration || 0) / timelineDuration) * 100))
|
||||
: 0;
|
||||
return (
|
||||
<button
|
||||
className={`sticker-segment ${
|
||||
segment.id === currentStickerSegment?.id ? "is-current" : ""
|
||||
} ${segment.id === selectedStickerSegmentId ? "is-selected-segment" : ""}`}
|
||||
type="button"
|
||||
key={segment.id}
|
||||
style={{
|
||||
"--sticker-left": `${segmentLeft}%`,
|
||||
"--sticker-width": `${segmentWidth}%`,
|
||||
}}
|
||||
onPointerDown={(event) => startStickerSegmentMove(event, segment.id)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === segment.id) {
|
||||
return;
|
||||
}
|
||||
setSelectedTrack("sticker");
|
||||
setActiveTool("stickers");
|
||||
setSelectedStickerSegmentId(segment.id);
|
||||
seekTo(segment.start || 0);
|
||||
}}
|
||||
>
|
||||
<img src={segment.src} alt="" draggable={false} />
|
||||
<span>{segment.name}</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
: null}
|
||||
{renderAssetDropSlot("sticker")}
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<section className="timeline">
|
||||
@@ -233,28 +517,26 @@ export function Timeline({
|
||||
</IconButton>
|
||||
</div>
|
||||
<div className="timeline-icon-group">
|
||||
<IconButton label={t("zoomOut")} onClick={() => adjustTimelineZoom((zoom) => zoom - 0.25)}>
|
||||
<IconButton label={t("zoomOut")} onClick={() => adjustTimelineZoom((zoom) => zoom / TIMELINE_BUTTON_ZOOM_RATIO)}>
|
||||
<MagnifyingGlassMinus size={17} />
|
||||
</IconButton>
|
||||
<span className="zoom-readout">{Math.round(timelineZoom * 100)}%</span>
|
||||
<IconButton label={t("fitTimeline")} active={timelineZoom === 1} onClick={() => setTimelineZoom(1)}>
|
||||
<span className="zoom-readout">{zoomReadout}</span>
|
||||
<IconButton
|
||||
label={t("fitTimeline")}
|
||||
active={Math.abs(localTimelineZoom - TIMELINE_MIN_ZOOM) < 0.001}
|
||||
onClick={() => adjustTimelineZoom(TIMELINE_MIN_ZOOM)}
|
||||
>
|
||||
<MonitorPlay size={17} />
|
||||
</IconButton>
|
||||
<IconButton label={t("zoomIn")} onClick={() => adjustTimelineZoom((zoom) => zoom + 0.25)}>
|
||||
<IconButton label={t("zoomIn")} onClick={() => adjustTimelineZoom((zoom) => zoom * TIMELINE_BUTTON_ZOOM_RATIO)}>
|
||||
<MagnifyingGlassPlus size={17} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="timeline-board">
|
||||
<div className="track-labels">
|
||||
{[
|
||||
["image", t("imageTrack")],
|
||||
["caption", t("caption")],
|
||||
["source", t("sourceTrack")],
|
||||
["audio", t("voiceTrack")],
|
||||
["music", t("musicTrack")],
|
||||
].map(([track, label]) => (
|
||||
<div className="track-labels" style={{ gridTemplateRows: timelineLabelRows }}>
|
||||
{timelineTrackLabels.map(([track, label]) => (
|
||||
<div className={selectedTrack === track ? "is-selected" : ""} key={track}>
|
||||
<button
|
||||
type="button"
|
||||
@@ -283,15 +565,15 @@ export function Timeline({
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="tracks" onWheel={handleTimelineWheel}>
|
||||
<div className="tracks">
|
||||
<div
|
||||
ref={trackScrollRef}
|
||||
className="track-scroll"
|
||||
style={{ width: trackWidth, "--timeline-zoom": timelineZoom }}
|
||||
style={{ width: localTrackWidth, "--timeline-zoom": localTimelineZoom, gridTemplateRows: timelineTrackRows }}
|
||||
onPointerDown={(event) => {
|
||||
if (
|
||||
event.target.closest(
|
||||
"button, .image-clip, .caption-segment, .audio-track, .waveform-strip",
|
||||
"button, .image-clip, .caption-segment, .sticker-track, .sticker-segment, .audio-track, .waveform-strip",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
@@ -300,8 +582,14 @@ export function Timeline({
|
||||
}}
|
||||
>
|
||||
<div className="ruler" onPointerDown={startTimelineSeek}>
|
||||
{Array.from({ length: 11 }, (_, index) => (
|
||||
<span key={index}>{formatClock((timelineDuration / 10) * index)}</span>
|
||||
{rulerTicks.map((tick) => (
|
||||
<span
|
||||
className={`ruler-tick ${tick.isMajor ? "is-major" : "is-minor"}`}
|
||||
key={tick.id}
|
||||
style={{ left: `${tick.left}%` }}
|
||||
>
|
||||
{tick.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
@@ -346,7 +634,7 @@ export function Timeline({
|
||||
const segmentType = segment.type || visualType;
|
||||
const segmentWidth =
|
||||
timelineDuration > 0
|
||||
? Math.max(0.8, Math.min(100, (segment.duration / timelineDuration) * 100))
|
||||
? Math.max(0.01, Math.min(100, (segment.duration / timelineDuration) * 100))
|
||||
: 0;
|
||||
const segmentRange = renderedVisualTimeline[index];
|
||||
const isCurrentVisualSegment =
|
||||
@@ -362,6 +650,21 @@ export function Timeline({
|
||||
activeTimelineClipDrag?.track === "image" &&
|
||||
activeTimelineClipDrag.overIndex === index &&
|
||||
!isDraggingVisualSegment;
|
||||
const videoTrackFrames = Array.isArray(segment.trackFrames) ? segment.trackFrames : [];
|
||||
const visibleVideoFrames =
|
||||
segmentType === "video" && videoTrackFrames.length
|
||||
? getSampledVideoFrames(
|
||||
videoTrackFrames,
|
||||
getVideoTimelineFrameCount({
|
||||
duration: segment.duration,
|
||||
timelineDuration,
|
||||
contentWidth: rulerViewport.contentWidth,
|
||||
timelineZoom: localTimelineZoom,
|
||||
availableFrames: videoTrackFrames.length,
|
||||
}),
|
||||
)
|
||||
: [];
|
||||
const isPortraitVideo = segmentType === "video" && (segment.height || 0) > (segment.width || 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -397,9 +700,24 @@ export function Timeline({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""}`}>
|
||||
<div
|
||||
className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${
|
||||
isPortraitVideo ? "is-portrait-video" : ""
|
||||
}`}
|
||||
>
|
||||
{segmentType === "video" ? (
|
||||
<video src={segmentSrc} muted playsInline preload="metadata" draggable={false} />
|
||||
visibleVideoFrames.length ? (
|
||||
visibleVideoFrames.map((frameSrc, frameIndex) => (
|
||||
<img
|
||||
src={frameSrc}
|
||||
alt=""
|
||||
draggable={false}
|
||||
key={`${segment.id}-frame-${frameIndex}`}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<video src={segmentSrc} muted playsInline preload="metadata" draggable={false} />
|
||||
)
|
||||
) : (
|
||||
Array.from(
|
||||
{
|
||||
@@ -429,19 +747,28 @@ export function Timeline({
|
||||
: null}
|
||||
{renderAssetDropSlot("image")}
|
||||
</div>
|
||||
{renderStickerTrack()}
|
||||
<div
|
||||
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
|
||||
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
|
||||
}`}
|
||||
onClick={() => setSelectedTrack("caption")}
|
||||
onClick={() => {
|
||||
setSelectedTrack("caption");
|
||||
setActiveTool("caption");
|
||||
}}
|
||||
data-timeline-reorder-track="caption"
|
||||
>
|
||||
{trackVisibility.caption
|
||||
? displayedCaptionSegments.map((segment, index) => {
|
||||
const segmentRange = displayedCaptionTimeline[index];
|
||||
const segmentDuration = displayedCaptionTimeline[index]?.duration ?? 0;
|
||||
const segmentLeft =
|
||||
segmentRange && timelineDuration > 0
|
||||
? Math.max(0, Math.min(100, (segmentRange.start / timelineDuration) * 100))
|
||||
: 0;
|
||||
const segmentWidth =
|
||||
timelineDuration > 0
|
||||
? Math.max(0.6, Math.min(100, (segmentDuration / timelineDuration) * 100))
|
||||
? Math.max(0.01, Math.min(100, (segmentDuration / timelineDuration) * 100))
|
||||
: 0;
|
||||
const isDraggingCaptionSegment =
|
||||
activeTimelineClipDrag?.track === "caption" &&
|
||||
@@ -450,9 +777,9 @@ export function Timeline({
|
||||
activeTimelineClipDrag?.track === "caption" &&
|
||||
activeTimelineClipDrag.overIndex === index &&
|
||||
!isDraggingCaptionSegment;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={segment.id}
|
||||
type="button"
|
||||
className={`caption-segment ${
|
||||
segment.id === currentCaptionSegment?.id ? "is-current" : ""
|
||||
@@ -461,12 +788,14 @@ export function Timeline({
|
||||
} ${isDraggingCaptionSegment ? "is-reorder-dragging" : ""} ${
|
||||
isReorderTarget ? "is-reorder-target" : ""
|
||||
}`}
|
||||
key={segment.id}
|
||||
data-timeline-segment-track="caption"
|
||||
data-timeline-segment-index={index}
|
||||
data-timeline-segment-id={segment.id}
|
||||
data-placeholder={t("dropSlot", "放置位置")}
|
||||
style={{ "--caption-width": `${segmentWidth}%` }}
|
||||
style={{
|
||||
"--caption-left": `${segmentLeft}%`,
|
||||
"--caption-width": `${segmentWidth}%`,
|
||||
}}
|
||||
onPointerDown={(event) => startTimelineClipDrag(event, "caption", segment.id, index)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -474,8 +803,9 @@ export function Timeline({
|
||||
return;
|
||||
}
|
||||
setSelectedTrack("caption");
|
||||
setActiveTool("caption");
|
||||
setSelectedSegmentId(segment.id);
|
||||
seekTo(getSegmentStartTime(displayedCaptionSegments, index, captionTargetDuration));
|
||||
seekTo(segmentRange?.start ?? getSegmentStartTime(displayedCaptionSegments, index, captionTargetDuration));
|
||||
}}
|
||||
>
|
||||
{segment.text}
|
||||
@@ -500,7 +830,13 @@ export function Timeline({
|
||||
) : null}
|
||||
{renderAssetDropSlot("source")}
|
||||
{trackVisibility.source && sourceAudioBlob ? (
|
||||
<div className="audio-clip is-source" style={{ width: `${sourceAudioClipPercent}%` }}>
|
||||
<div
|
||||
className="audio-clip is-source"
|
||||
style={{
|
||||
width: `${sourceAudioClipPercent}%`,
|
||||
marginLeft: `${sourceAudioStartPercent}%`,
|
||||
}}
|
||||
>
|
||||
<WaveformStrip peaks={sourceAudioPeaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(sourceAudioDuration)}</span>
|
||||
</div>
|
||||
|
||||
+203
-87
@@ -1,7 +1,141 @@
|
||||
import {
|
||||
ClosedCaptioning,
|
||||
Eye,
|
||||
EyeSlash,
|
||||
ListBullets,
|
||||
Trash,
|
||||
} from "@phosphor-icons/react";
|
||||
|
||||
import { formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { HistoryPanel, MyVoicesPanel, VoiceSynthesisPanel } from "./panels.jsx";
|
||||
|
||||
function CaptionContextPanel({
|
||||
t,
|
||||
captionSegments,
|
||||
selectedCaptionSegment,
|
||||
selectedSegmentId,
|
||||
setSelectedSegmentId,
|
||||
currentSegmentIndex,
|
||||
captionTargetDuration,
|
||||
updateCaptionSegmentText,
|
||||
toggleCaptionSegmentHidden,
|
||||
deleteCaptionSegment,
|
||||
seekTo,
|
||||
sourceAudioBlob,
|
||||
generateCaptionsFromSourceAudio,
|
||||
isGeneratingCaptions,
|
||||
automaticCaptionProgress,
|
||||
}) {
|
||||
const selectedIndex = Math.max(
|
||||
0,
|
||||
captionSegments.findIndex((segment) => segment.id === selectedCaptionSegment?.id),
|
||||
);
|
||||
const selectedStart = captionSegments.length
|
||||
? getSegmentStartTime(captionSegments, selectedIndex, captionTargetDuration)
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div className="caption-context-panel">
|
||||
<label className="field-label" htmlFor="caption-context-input">
|
||||
{t("captionScriptLabel", "字幕文案")}
|
||||
</label>
|
||||
{selectedCaptionSegment ? (
|
||||
<div className="script-box caption-sync-box">
|
||||
<textarea
|
||||
id="caption-context-input"
|
||||
value={selectedCaptionSegment.text}
|
||||
onChange={(event) => updateCaptionSegmentText(selectedCaptionSegment.id, event.target.value)}
|
||||
/>
|
||||
<div className="script-meta">
|
||||
<button type="button" onClick={() => seekTo(selectedStart)}>
|
||||
<ClosedCaptioning size={14} />
|
||||
{formatTime(selectedStart)}
|
||||
</button>
|
||||
<span>{selectedCaptionSegment.text.length} / 500</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="caption-context-empty">
|
||||
<ClosedCaptioning size={28} weight="duotone" />
|
||||
<strong>{t("noCaptionSegments")}</strong>
|
||||
<span>{t("captionEmptyHint", "选择时间线字幕片段后,这里会同步编辑。")}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="caption-context-actions">
|
||||
<button
|
||||
className="panel-secondary"
|
||||
type="button"
|
||||
disabled={!selectedCaptionSegment}
|
||||
onClick={() => selectedCaptionSegment && toggleCaptionSegmentHidden(selectedCaptionSegment.id)}
|
||||
>
|
||||
{selectedCaptionSegment?.hidden ? <Eye size={15} /> : <EyeSlash size={15} />}
|
||||
{selectedCaptionSegment?.hidden ? t("showCurrentCaption") : t("hideCurrentCaption", "隐藏当前字幕")}
|
||||
</button>
|
||||
<button
|
||||
className="panel-danger"
|
||||
type="button"
|
||||
disabled={!selectedCaptionSegment}
|
||||
onClick={() => selectedCaptionSegment && deleteCaptionSegment(selectedCaptionSegment.id)}
|
||||
>
|
||||
<Trash size={15} />
|
||||
{t("deleteCurrentCaption")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!captionSegments.length ? (
|
||||
<button
|
||||
className="audio-entry-card caption-entry-card"
|
||||
type="button"
|
||||
disabled={!sourceAudioBlob || isGeneratingCaptions}
|
||||
onClick={generateCaptionsFromSourceAudio}
|
||||
>
|
||||
<ClosedCaptioning size={24} weight="duotone" />
|
||||
<span>
|
||||
<strong>{isGeneratingCaptions ? t("autoCaptionsRunning") : t("autoCaptionsTitle")}</strong>
|
||||
<em>{sourceAudioBlob ? t("autoCaptionsDesc") : t("autoCaptionsNeedsSource")}</em>
|
||||
</span>
|
||||
{isGeneratingCaptions ? (
|
||||
<span className="inline-progress" aria-hidden="true">
|
||||
<span style={{ width: `${automaticCaptionProgress}%` }} />
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<div className="caption-context-heading">
|
||||
<ListBullets size={16} />
|
||||
<span>{t("captionList", "字幕列表")}</span>
|
||||
</div>
|
||||
<div className="caption-context-list">
|
||||
{captionSegments.length ? (
|
||||
captionSegments.map((segment, index) => (
|
||||
<button
|
||||
type="button"
|
||||
className={`${index === currentSegmentIndex ? "is-current" : ""} ${
|
||||
segment.id === selectedSegmentId ? "is-selected" : ""
|
||||
} ${segment.hidden ? "is-hidden" : ""}`}
|
||||
key={segment.id}
|
||||
onClick={() => {
|
||||
setSelectedSegmentId(segment.id);
|
||||
seekTo(getSegmentStartTime(captionSegments, index, captionTargetDuration));
|
||||
}}
|
||||
>
|
||||
<span>{segment.text}</span>
|
||||
<em>{formatTime(getSegmentStartTime(captionSegments, index, captionTargetDuration))}</em>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<div className="empty-state">{t("noCaptionSegments")}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VoicePanel({
|
||||
t,
|
||||
activeTool,
|
||||
status,
|
||||
statusText,
|
||||
voiceTab,
|
||||
@@ -38,43 +172,85 @@ export function VoicePanel({
|
||||
notify,
|
||||
audioUrl,
|
||||
audioRef,
|
||||
setIsPlaying,
|
||||
sourceAudioRef,
|
||||
musicRef,
|
||||
previewVideoRef,
|
||||
sourceAudioUrl,
|
||||
trackVisibility,
|
||||
musicUrl,
|
||||
setCurrentTime,
|
||||
captionSegments,
|
||||
selectedCaptionSegment,
|
||||
selectedSegmentId,
|
||||
setSelectedSegmentId,
|
||||
currentSegmentIndex,
|
||||
captionTargetDuration,
|
||||
updateCaptionSegmentText,
|
||||
toggleCaptionSegmentHidden,
|
||||
deleteCaptionSegment,
|
||||
seekTo,
|
||||
sourceAudioBlob,
|
||||
generateCaptionsFromSourceAudio,
|
||||
isGeneratingCaptions,
|
||||
automaticCaptionProgress,
|
||||
}) {
|
||||
const isCaptionContext = activeTool === "caption";
|
||||
const title = isCaptionContext ? t("caption") : t("aiVoice");
|
||||
const panelStatusText = isCaptionContext
|
||||
? captionSegments.length
|
||||
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
|
||||
: t("noCaptionSegments")
|
||||
: statusText === "模型待命"
|
||||
? t("modelReady")
|
||||
: statusText;
|
||||
|
||||
return (
|
||||
<aside className="voice-panel">
|
||||
<aside className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""}`}>
|
||||
<div className="panel-title-row">
|
||||
<h1>{t("aiVoice")}</h1>
|
||||
<span className={`status-pill ${status}`}>
|
||||
{statusText === "模型待命" ? t("modelReady") : statusText}
|
||||
<h1>{title}</h1>
|
||||
<span className={`status-pill ${isCaptionContext ? "done" : status}`}>
|
||||
{panelStatusText}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="tabs compact">
|
||||
{[
|
||||
["synthesis", t("voiceSynthesis")],
|
||||
["mine", t("myVoices")],
|
||||
["history", t("history")],
|
||||
].map(([id, label]) => (
|
||||
<button
|
||||
className={voiceTab === id ? "is-active" : ""}
|
||||
type="button"
|
||||
key={id}
|
||||
onClick={() => setVoiceTab(id)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{!isCaptionContext ? (
|
||||
<div className="tabs compact">
|
||||
{[
|
||||
["synthesis", t("voiceSynthesis")],
|
||||
["mine", t("myVoices")],
|
||||
["history", t("history")],
|
||||
].map(([id, label]) => (
|
||||
<button
|
||||
className={voiceTab === id ? "is-active" : ""}
|
||||
type="button"
|
||||
key={id}
|
||||
onClick={() => setVoiceTab(id)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="voice-tab-body">
|
||||
{voiceTab === "synthesis" ? (
|
||||
{isCaptionContext ? (
|
||||
<CaptionContextPanel
|
||||
t={t}
|
||||
captionSegments={captionSegments}
|
||||
selectedCaptionSegment={selectedCaptionSegment}
|
||||
selectedSegmentId={selectedSegmentId}
|
||||
setSelectedSegmentId={setSelectedSegmentId}
|
||||
currentSegmentIndex={currentSegmentIndex}
|
||||
captionTargetDuration={captionTargetDuration}
|
||||
updateCaptionSegmentText={updateCaptionSegmentText}
|
||||
toggleCaptionSegmentHidden={toggleCaptionSegmentHidden}
|
||||
deleteCaptionSegment={deleteCaptionSegment}
|
||||
seekTo={seekTo}
|
||||
sourceAudioBlob={sourceAudioBlob}
|
||||
generateCaptionsFromSourceAudio={generateCaptionsFromSourceAudio}
|
||||
isGeneratingCaptions={isGeneratingCaptions}
|
||||
automaticCaptionProgress={automaticCaptionProgress}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!isCaptionContext && voiceTab === "synthesis" ? (
|
||||
<VoiceSynthesisPanel
|
||||
script={script}
|
||||
updateScript={updateScript}
|
||||
@@ -101,7 +277,7 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{voiceTab === "mine" ? (
|
||||
{!isCaptionContext && voiceTab === "mine" ? (
|
||||
<MyVoicesPanel
|
||||
favoriteVoiceIds={favoriteVoiceIds}
|
||||
setFavoriteVoiceIds={setFavoriteVoiceIds}
|
||||
@@ -119,7 +295,7 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{voiceTab === "history" ? (
|
||||
{!isCaptionContext && voiceTab === "history" ? (
|
||||
<HistoryPanel
|
||||
historyItems={historyItems}
|
||||
useHistoryItem={useHistoryItem}
|
||||
@@ -134,78 +310,18 @@ export function VoicePanel({
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src={audioUrl}
|
||||
onPlay={() => setIsPlaying(true)}
|
||||
onPause={() => {
|
||||
setIsPlaying(false);
|
||||
sourceAudioRef.current?.pause();
|
||||
musicRef.current?.pause();
|
||||
previewVideoRef.current?.pause();
|
||||
}}
|
||||
onEnded={() => {
|
||||
setIsPlaying(false);
|
||||
sourceAudioRef.current?.pause();
|
||||
musicRef.current?.pause();
|
||||
previewVideoRef.current?.pause();
|
||||
}}
|
||||
onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
|
||||
/>
|
||||
) : null}
|
||||
{sourceAudioUrl ? (
|
||||
<audio
|
||||
ref={sourceAudioRef}
|
||||
src={sourceAudioUrl}
|
||||
onPlay={() => {
|
||||
if (!audioUrl || !trackVisibility.audio) {
|
||||
setIsPlaying(true);
|
||||
}
|
||||
}}
|
||||
onPause={() => {
|
||||
if (!audioUrl || !trackVisibility.audio) {
|
||||
setIsPlaying(false);
|
||||
musicRef.current?.pause();
|
||||
previewVideoRef.current?.pause();
|
||||
}
|
||||
}}
|
||||
onEnded={() => {
|
||||
if (!audioUrl || !trackVisibility.audio) {
|
||||
setIsPlaying(false);
|
||||
musicRef.current?.pause();
|
||||
previewVideoRef.current?.pause();
|
||||
}
|
||||
}}
|
||||
onTimeUpdate={(event) => {
|
||||
if (!audioUrl || !trackVisibility.audio) {
|
||||
setCurrentTime(event.currentTarget.currentTime);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{musicUrl ? (
|
||||
<audio
|
||||
ref={musicRef}
|
||||
src={musicUrl}
|
||||
onPlay={() => {
|
||||
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
|
||||
setIsPlaying(true);
|
||||
}
|
||||
}}
|
||||
onPause={() => {
|
||||
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
|
||||
setIsPlaying(false);
|
||||
previewVideoRef.current?.pause();
|
||||
}
|
||||
}}
|
||||
onEnded={() => {
|
||||
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
|
||||
setIsPlaying(false);
|
||||
previewVideoRef.current?.pause();
|
||||
}
|
||||
}}
|
||||
onTimeUpdate={(event) => {
|
||||
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
|
||||
setCurrentTime(event.currentTarget.currentTime);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</aside>
|
||||
|
||||
+168
-6
@@ -1,7 +1,10 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
CaretDown,
|
||||
Check,
|
||||
CloudArrowUp,
|
||||
ClosedCaptioning,
|
||||
DownloadSimple,
|
||||
MicrophoneStage,
|
||||
MusicNote,
|
||||
@@ -10,7 +13,16 @@ import {
|
||||
Waveform,
|
||||
} from "@phosphor-icons/react";
|
||||
|
||||
import { EFFECT_OPTIONS, FILTER_OPTIONS, SAMPLE_IMAGE, STICKERS, TRANSITIONS, VOICES } from "../config/editor.js";
|
||||
import {
|
||||
EFFECT_OPTIONS,
|
||||
FILTER_OPTIONS,
|
||||
SAMPLE_IMAGE,
|
||||
STICKERS,
|
||||
STICKER_CATEGORIES,
|
||||
STICKER_PAGE_SIZE,
|
||||
TRANSITIONS,
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import { APP_LANGUAGES } from "../i18n.js";
|
||||
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { Popover } from "./ui.jsx";
|
||||
@@ -216,6 +228,8 @@ export function ToolPanel(props) {
|
||||
setSelectedTransitionId,
|
||||
selectedStickerId,
|
||||
setSelectedStickerId,
|
||||
handleStickerPointerDown,
|
||||
handleStickerClick,
|
||||
audioBlob,
|
||||
audioDuration,
|
||||
sourceAudioBlob,
|
||||
@@ -224,6 +238,9 @@ export function ToolPanel(props) {
|
||||
sourceAudioVolume,
|
||||
setSourceAudioVolume,
|
||||
clearSourceAudioTrack,
|
||||
generateCaptionsFromSourceAudio,
|
||||
isGeneratingCaptions,
|
||||
automaticCaptionProgress,
|
||||
musicBlob,
|
||||
musicName,
|
||||
musicDuration,
|
||||
@@ -264,7 +281,7 @@ export function ToolPanel(props) {
|
||||
|
||||
if (activeTool === "caption") {
|
||||
return (
|
||||
<div className="tool-panel">
|
||||
<div className="tool-panel caption-tool-panel">
|
||||
<h2>{t("caption")}</h2>
|
||||
<label className="switch-row">
|
||||
<input type="checkbox" checked={captionsEnabled} onChange={(event) => setCaptionsEnabled(event.target.checked)} />
|
||||
@@ -290,7 +307,7 @@ export function ToolPanel(props) {
|
||||
<input
|
||||
id="caption-size"
|
||||
type="range"
|
||||
min="20"
|
||||
min="12"
|
||||
max="42"
|
||||
step="1"
|
||||
value={captionSize}
|
||||
@@ -366,6 +383,23 @@ export function ToolPanel(props) {
|
||||
<em>{t("aiVoiceEntryDesc")}</em>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
className="audio-entry-card caption-entry-card"
|
||||
type="button"
|
||||
disabled={!sourceAudioBlob || isGeneratingCaptions}
|
||||
onClick={generateCaptionsFromSourceAudio}
|
||||
>
|
||||
<ClosedCaptioning size={24} weight="duotone" />
|
||||
<span>
|
||||
<strong>{isGeneratingCaptions ? t("autoCaptionsRunning") : t("autoCaptionsTitle")}</strong>
|
||||
<em>{sourceAudioBlob ? t("autoCaptionsDesc") : t("autoCaptionsNeedsSource")}</em>
|
||||
</span>
|
||||
{isGeneratingCaptions ? (
|
||||
<span className="inline-progress" aria-hidden="true">
|
||||
<span style={{ width: `${automaticCaptionProgress}%` }} />
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
<div className="metric-list">
|
||||
<div>
|
||||
<span>{t("currentVoice")}</span>
|
||||
@@ -493,11 +527,14 @@ export function ToolPanel(props) {
|
||||
|
||||
if (activeTool === "stickers") {
|
||||
return (
|
||||
<ChoicePanel
|
||||
<StickerPanel
|
||||
title={t("stickers")}
|
||||
options={STICKERS}
|
||||
selectedId={selectedStickerId}
|
||||
trOption={trOption}
|
||||
t={t}
|
||||
onStickerPointerDown={handleStickerPointerDown}
|
||||
onStickerClick={handleStickerClick}
|
||||
onSelect={(id) => {
|
||||
setSelectedStickerId(id);
|
||||
notify(t("stickerApplied"));
|
||||
@@ -541,7 +578,7 @@ function VisualChoicePanel({ title, kind, options, selectedId, trOption = (name)
|
||||
>
|
||||
<span className="visual-choice-thumb" aria-hidden="true" />
|
||||
<span className="visual-choice-label">
|
||||
<span>{trOption(option.name)}</span>
|
||||
<span>{trOption(option.name, option)}</span>
|
||||
{selectedId === option.id ? <Check size={14} weight="bold" /> : null}
|
||||
</span>
|
||||
</button>
|
||||
@@ -558,7 +595,7 @@ function ChoicePanel({ title, options, selectedId, trOption = (name) => name, on
|
||||
<div className="choice-list">
|
||||
{options.map((option) => (
|
||||
<button className={selectedId === option.id ? "is-selected" : ""} type="button" key={option.id} onClick={() => onSelect(option.id)}>
|
||||
<span>{trOption(option.name)}</span>
|
||||
<span>{trOption(option.name, option)}</span>
|
||||
{selectedId === option.id ? <Check size={16} /> : null}
|
||||
</button>
|
||||
))}
|
||||
@@ -567,6 +604,131 @@ function ChoicePanel({ title, options, selectedId, trOption = (name) => name, on
|
||||
);
|
||||
}
|
||||
|
||||
function StickerPanel({
|
||||
title,
|
||||
options,
|
||||
selectedId,
|
||||
trOption = (name) => name,
|
||||
onSelect,
|
||||
t,
|
||||
onStickerPointerDown,
|
||||
onStickerClick,
|
||||
}) {
|
||||
const [activeCategory, setActiveCategory] = useState("all");
|
||||
const [visibleCount, setVisibleCount] = useState(STICKER_PAGE_SIZE);
|
||||
const loadMoreRef = useRef(null);
|
||||
const emptySticker = options.find((option) => option.id === "none") ?? { id: "none", name: "无贴纸" };
|
||||
const stickerOptions = useMemo(() => options.filter((option) => option.id !== "none"), [options]);
|
||||
const filteredStickers = useMemo(
|
||||
() =>
|
||||
activeCategory === "all"
|
||||
? stickerOptions
|
||||
: stickerOptions.filter((option) => option.category === activeCategory),
|
||||
[activeCategory, stickerOptions],
|
||||
);
|
||||
const visibleStickers = filteredStickers.slice(0, visibleCount);
|
||||
const hasMore = visibleCount < filteredStickers.length;
|
||||
|
||||
useEffect(() => {
|
||||
setVisibleCount(STICKER_PAGE_SIZE);
|
||||
}, [activeCategory]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasMore || !loadMoreRef.current) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (!entries.some((entry) => entry.isIntersecting)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setVisibleCount((count) => Math.min(count + STICKER_PAGE_SIZE, filteredStickers.length));
|
||||
},
|
||||
{ root: null, rootMargin: "120px 0px" },
|
||||
);
|
||||
observer.observe(loadMoreRef.current);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [filteredStickers.length, hasMore]);
|
||||
|
||||
const loadMore = () => {
|
||||
setVisibleCount((count) => Math.min(count + STICKER_PAGE_SIZE, filteredStickers.length));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="tool-panel sticker-panel">
|
||||
<h2>{title}</h2>
|
||||
<button
|
||||
className={`sticker-none-button ${selectedId === emptySticker.id ? "is-selected" : ""}`}
|
||||
type="button"
|
||||
onClick={() => onSelect(emptySticker.id)}
|
||||
>
|
||||
<span>{trOption(emptySticker.name, emptySticker)}</span>
|
||||
{selectedId === emptySticker.id ? <Check size={15} weight="bold" /> : null}
|
||||
</button>
|
||||
<div className="sticker-category-row" role="tablist" aria-label={t("stickerCategories")}>
|
||||
{STICKER_CATEGORIES.map((category) => (
|
||||
<button
|
||||
className={activeCategory === category.id ? "is-active" : ""}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeCategory === category.id}
|
||||
key={category.id}
|
||||
onClick={() => setActiveCategory(category.id)}
|
||||
>
|
||||
{trOption(category.name, category)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="sticker-grid" aria-live="polite">
|
||||
{visibleStickers.map((option) => {
|
||||
const dragAsset = {
|
||||
...option,
|
||||
type: "sticker",
|
||||
meta: "贴纸",
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
className={`sticker-tile ${selectedId === option.id ? "is-selected" : ""}`}
|
||||
type="button"
|
||||
key={option.id}
|
||||
onPointerDown={(event) => onStickerPointerDown?.(event, dragAsset)}
|
||||
onClick={(event) => {
|
||||
if (onStickerClick) {
|
||||
onStickerClick(event, option);
|
||||
return;
|
||||
}
|
||||
onSelect(option.id);
|
||||
}}
|
||||
>
|
||||
<span className="sticker-tile-thumb" aria-hidden="true">
|
||||
<img src={option.src} alt="" loading="lazy" draggable={false} />
|
||||
</span>
|
||||
<span className="sticker-tile-label">
|
||||
<span>{trOption(option.name, option)}</span>
|
||||
{selectedId === option.id ? <Check size={13} weight="bold" /> : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{hasMore ? (
|
||||
<button className="sticker-load-more" type="button" ref={loadMoreRef} onClick={loadMore}>
|
||||
<span>{t("loadMoreStickers")}</span>
|
||||
<span>
|
||||
{visibleStickers.length}/{filteredStickers.length}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<span className="sticker-load-sentinel" ref={loadMoreRef} aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VoiceSynthesisPanel({
|
||||
script,
|
||||
updateScript,
|
||||
|
||||
+53
-4
@@ -9,8 +9,9 @@ import {
|
||||
TextT,
|
||||
} from "@phosphor-icons/react";
|
||||
|
||||
export { MODEL_ID, AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "./models.js";
|
||||
|
||||
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
|
||||
export const MODEL_ID = "onnx-community/Kokoro-82M-v1.0-ONNX";
|
||||
export const FFMPEG_CLASS_WORKER_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/ffmpeg@0.12.15/dist/esm/worker.js";
|
||||
export const FFMPEG_CORE_BASE_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.10/dist/esm";
|
||||
export const MAX_TIMELINE_DURATION_SECONDS = 30 * 60;
|
||||
@@ -156,9 +157,57 @@ export const TRANSITIONS = [
|
||||
{ id: "glitch", name: "故障闪" },
|
||||
];
|
||||
|
||||
export const STICKER_PAGE_SIZE = 9;
|
||||
export const DEFAULT_STICKER_SEGMENT_SECONDS = 3;
|
||||
|
||||
export const STICKER_CATEGORIES = [
|
||||
{ id: "all", name: "全部", nameEn: "All", kind: "stickerCategory" },
|
||||
{ id: "trending", name: "热门", nameEn: "Hot", kind: "stickerCategory" },
|
||||
{ id: "voice", name: "旁白", nameEn: "Voiceover", kind: "stickerCategory" },
|
||||
{ id: "reaction", name: "互动", nameEn: "Reactions", kind: "stickerCategory" },
|
||||
{ id: "commerce", name: "带货", nameEn: "Shop", kind: "stickerCategory" },
|
||||
];
|
||||
|
||||
export const STICKER_LIBRARY = [
|
||||
{ id: "trend-flame", name: "热度火焰", nameEn: "Hot Flame", category: "trending", src: "/assets/stickers/trend-flame.png" },
|
||||
{ id: "trend-spark", name: "闪光爆点", nameEn: "Spark Burst", category: "trending", src: "/assets/stickers/trend-spark.png" },
|
||||
{ id: "trend-bolt", name: "闪电强调", nameEn: "Lightning", category: "trending", src: "/assets/stickers/trend-bolt.png" },
|
||||
{ id: "trend-starburst", name: "爆点星芒", nameEn: "Starburst", category: "trending", src: "/assets/stickers/trend-starburst.png" },
|
||||
{ id: "trend-crown", name: "精选皇冠", nameEn: "Crown", category: "trending", src: "/assets/stickers/trend-crown.png" },
|
||||
{ id: "trend-megaphone", name: "扩音提醒", nameEn: "Megaphone", category: "trending", src: "/assets/stickers/trend-megaphone.png" },
|
||||
{ id: "trend-rocket", name: "起飞火箭", nameEn: "Rocket", category: "trending", src: "/assets/stickers/trend-rocket.png" },
|
||||
{ id: "trend-confetti", name: "彩带庆祝", nameEn: "Confetti", category: "trending", src: "/assets/stickers/trend-confetti.png" },
|
||||
{ id: "trend-verified", name: "认证勾选", nameEn: "Verified Check", category: "trending", src: "/assets/stickers/trend-verified.png" },
|
||||
{ id: "voice-mic", name: "录音麦克风", nameEn: "Studio Mic", category: "voice", src: "/assets/stickers/voice-mic.png" },
|
||||
{ id: "voice-waveform", name: "音频波形", nameEn: "Waveform", category: "voice", src: "/assets/stickers/voice-waveform.png" },
|
||||
{ id: "voice-headphones", name: "监听耳机", nameEn: "Headphones", category: "voice", src: "/assets/stickers/voice-headphones.png" },
|
||||
{ id: "voice-sound-ring", name: "声波圆环", nameEn: "Sound Ring", category: "voice", src: "/assets/stickers/voice-sound-ring.png" },
|
||||
{ id: "voice-caption-card", name: "字幕卡片", nameEn: "Caption Card", category: "voice", src: "/assets/stickers/voice-caption-card.png" },
|
||||
{ id: "voice-music-note", name: "音乐音符", nameEn: "Music Note", category: "voice", src: "/assets/stickers/voice-music-note.png" },
|
||||
{ id: "voice-speaker", name: "扬声器", nameEn: "Speaker", category: "voice", src: "/assets/stickers/voice-speaker.png" },
|
||||
{ id: "voice-magic-wand", name: "魔法增强", nameEn: "Magic Wand", category: "voice", src: "/assets/stickers/voice-magic-wand.png" },
|
||||
{ id: "voice-timeline-marker", name: "时间线标记", nameEn: "Timeline Marker", category: "voice", src: "/assets/stickers/voice-timeline-marker.png" },
|
||||
{ id: "react-heart", name: "爱心", nameEn: "Heart", category: "reaction", src: "/assets/stickers/react-heart.png" },
|
||||
{ id: "react-like", name: "点赞", nameEn: "Like", category: "reaction", src: "/assets/stickers/react-like.png" },
|
||||
{ id: "react-smile", name: "微笑", nameEn: "Smile", category: "reaction", src: "/assets/stickers/react-smile.png" },
|
||||
{ id: "react-surprise", name: "惊讶", nameEn: "Surprise", category: "reaction", src: "/assets/stickers/react-surprise.png" },
|
||||
{ id: "react-eyes", name: "亮眼", nameEn: "Bright Eyes", category: "reaction", src: "/assets/stickers/react-eyes.png" },
|
||||
{ id: "react-applause", name: "鼓掌", nameEn: "Applause", category: "reaction", src: "/assets/stickers/react-applause.png" },
|
||||
{ id: "react-chat", name: "评论气泡", nameEn: "Chat Bubble", category: "reaction", src: "/assets/stickers/react-chat.png" },
|
||||
{ id: "react-dots", name: "互动点点", nameEn: "Dot Bubble", category: "reaction", src: "/assets/stickers/react-dots.png" },
|
||||
{ id: "react-alert", name: "重点提醒", nameEn: "Alert Burst", category: "reaction", src: "/assets/stickers/react-alert.png" },
|
||||
{ id: "shop-gift", name: "礼盒", nameEn: "Gift", category: "commerce", src: "/assets/stickers/shop-gift.png" },
|
||||
{ id: "shop-bag", name: "购物袋", nameEn: "Shopping Bag", category: "commerce", src: "/assets/stickers/shop-bag.png" },
|
||||
{ id: "shop-tag", name: "价格标签", nameEn: "Blank Tag", category: "commerce", src: "/assets/stickers/shop-tag.png" },
|
||||
{ id: "shop-coins", name: "金币", nameEn: "Coins", category: "commerce", src: "/assets/stickers/shop-coins.png" },
|
||||
{ id: "shop-box", name: "产品盒", nameEn: "Product Box", category: "commerce", src: "/assets/stickers/shop-box.png" },
|
||||
{ id: "shop-cart", name: "购物车", nameEn: "Cart", category: "commerce", src: "/assets/stickers/shop-cart.png" },
|
||||
{ id: "shop-camera", name: "相机", nameEn: "Camera", category: "commerce", src: "/assets/stickers/shop-camera.png" },
|
||||
{ id: "shop-idea", name: "灵感灯泡", nameEn: "Idea Bulb", category: "commerce", src: "/assets/stickers/shop-idea.png" },
|
||||
{ id: "shop-calendar", name: "日历", nameEn: "Calendar", category: "commerce", src: "/assets/stickers/shop-calendar.png" },
|
||||
];
|
||||
|
||||
export const STICKERS = [
|
||||
{ id: "none", name: "无贴纸", text: "" },
|
||||
{ id: "new", name: "新品感", text: "NEW" },
|
||||
{ id: "hot", name: "热点", text: "HOT" },
|
||||
{ id: "note", name: "旁白", text: "AI VOICE" },
|
||||
...STICKER_LIBRARY,
|
||||
];
|
||||
@@ -0,0 +1,3 @@
|
||||
export const MODEL_ID = "onnx-community/Kokoro-82M-v1.0-ONNX";
|
||||
export const AUTOMATIC_CAPTION_MODEL_ID = "onnx-community/whisper-small";
|
||||
export const AUTOMATIC_CAPTION_MODEL_LABEL = "Whisper small";
|
||||
+28
@@ -46,6 +46,8 @@ export const UI_COPY = {
|
||||
effects: "效果",
|
||||
stickers: "贴纸",
|
||||
filters: "滤镜",
|
||||
stickerCategories: "贴纸分类",
|
||||
loadMoreStickers: "加载更多贴纸",
|
||||
uploadTab: "本地上传",
|
||||
libraryTab: "素材库",
|
||||
mineTab: "我的素材",
|
||||
@@ -72,6 +74,7 @@ export const UI_COPY = {
|
||||
fitTimeline: "缩放适配",
|
||||
zoomIn: "放大时间线",
|
||||
imageTrack: "图片",
|
||||
stickerTrack: "贴纸",
|
||||
sourceTrack: "视频原声",
|
||||
voiceTrack: "配音音频",
|
||||
musicTrack: "背景音乐",
|
||||
@@ -110,7 +113,12 @@ export const UI_COPY = {
|
||||
bottom: "底部",
|
||||
fontSize: "字号",
|
||||
currentCaption: "当前字幕",
|
||||
captionScriptLabel: "字幕文案",
|
||||
captionList: "字幕列表",
|
||||
captionSegmentsUnit: "条字幕",
|
||||
captionEmptyHint: "选择时间线字幕片段后,这里会同步编辑。",
|
||||
showCurrentCaption: "显示当前字幕",
|
||||
hideCurrentCaption: "隐藏当前字幕",
|
||||
deleteCurrentCaption: "删除当前字幕",
|
||||
noCaptionSegments: "当前没有字幕片段。",
|
||||
openingHook: "开场强调",
|
||||
@@ -120,6 +128,10 @@ export const UI_COPY = {
|
||||
audioPanel: "音频",
|
||||
aiVoiceEntryTitle: "AI 配音",
|
||||
aiVoiceEntryDesc: "输入文案、选择声音并生成语音",
|
||||
autoCaptionsTitle: "从原声生成字幕",
|
||||
autoCaptionsDesc: "本地加载 Whisper small,识别后写入字幕轨",
|
||||
autoCaptionsNeedsSource: "先上传视频或把音频拖到原声轨",
|
||||
autoCaptionsRunning: "正在生成自动字幕",
|
||||
currentVoice: "当前声音",
|
||||
voiceDuration: "配音时长",
|
||||
sourceAudio: "视频原声",
|
||||
@@ -151,9 +163,11 @@ export const UI_COPY = {
|
||||
assetAudio: "音频",
|
||||
assetVideo: "视频",
|
||||
assetImage: "图片",
|
||||
assetSticker: "贴纸",
|
||||
deleteAsset: "删除素材",
|
||||
imageHidden: "图片轨已隐藏",
|
||||
dropVisualHere: "释放到图片轨",
|
||||
dropStickerHere: "释放到贴纸轨",
|
||||
dropVoiceHere: "释放到配音音频轨",
|
||||
dropSourceHere: "释放后分离视频原声",
|
||||
dropMusicHere: "释放到背景音乐轨",
|
||||
@@ -190,6 +204,8 @@ export const UI_COPY = {
|
||||
effects: "Effects",
|
||||
stickers: "Stickers",
|
||||
filters: "Filters",
|
||||
stickerCategories: "Sticker categories",
|
||||
loadMoreStickers: "Load more stickers",
|
||||
uploadTab: "Upload",
|
||||
libraryTab: "Library",
|
||||
mineTab: "My assets",
|
||||
@@ -216,6 +232,7 @@ export const UI_COPY = {
|
||||
fitTimeline: "Fit timeline",
|
||||
zoomIn: "Zoom in",
|
||||
imageTrack: "Image",
|
||||
stickerTrack: "Stickers",
|
||||
sourceTrack: "Source audio",
|
||||
voiceTrack: "Voiceover",
|
||||
musicTrack: "Music",
|
||||
@@ -254,7 +271,12 @@ export const UI_COPY = {
|
||||
bottom: "Bottom",
|
||||
fontSize: "Font size",
|
||||
currentCaption: "Current caption",
|
||||
captionScriptLabel: "Caption text",
|
||||
captionList: "Caption list",
|
||||
captionSegmentsUnit: "caption segment(s)",
|
||||
captionEmptyHint: "Select a caption segment on the timeline to edit it here.",
|
||||
showCurrentCaption: "Show current caption",
|
||||
hideCurrentCaption: "Hide current caption",
|
||||
deleteCurrentCaption: "Delete current caption",
|
||||
noCaptionSegments: "No caption segments.",
|
||||
openingHook: "Opening hook",
|
||||
@@ -264,6 +286,10 @@ export const UI_COPY = {
|
||||
audioPanel: "Audio",
|
||||
aiVoiceEntryTitle: "AI Voiceover",
|
||||
aiVoiceEntryDesc: "Write script, choose a voice, generate audio",
|
||||
autoCaptionsTitle: "Generate captions from source",
|
||||
autoCaptionsDesc: "Loads Whisper small locally, then writes a caption track",
|
||||
autoCaptionsNeedsSource: "Upload video or drop audio on the source track first",
|
||||
autoCaptionsRunning: "Generating captions",
|
||||
currentVoice: "Current voice",
|
||||
voiceDuration: "Voice duration",
|
||||
sourceAudio: "Source audio",
|
||||
@@ -295,9 +321,11 @@ export const UI_COPY = {
|
||||
assetAudio: "Audio",
|
||||
assetVideo: "Video",
|
||||
assetImage: "Image",
|
||||
assetSticker: "Sticker",
|
||||
deleteAsset: "Delete asset",
|
||||
imageHidden: "Image track hidden",
|
||||
dropVisualHere: "Drop on visual track",
|
||||
dropStickerHere: "Drop on sticker track",
|
||||
dropVoiceHere: "Drop on voiceover track",
|
||||
dropSourceHere: "Drop to extract source audio",
|
||||
dropMusicHere: "Drop on music track",
|
||||
|
||||
+797
@@ -0,0 +1,797 @@
|
||||
import { AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "../config/models.js";
|
||||
import { makeId } from "./timeline.js";
|
||||
|
||||
const ASR_SAMPLE_RATE = 16000;
|
||||
const MIN_CAPTION_DURATION = 0.45;
|
||||
const FALLBACK_CAPTION_SECONDS = 3.2;
|
||||
const LANGUAGE_DETECTION_SECONDS = 20;
|
||||
const CHINESE_VISIBLE_CHAR_THRESHOLD = 8;
|
||||
const ENERGY_FRAME_SECONDS = 0.05;
|
||||
const ENERGY_MERGE_GAP_SECONDS = 0.35;
|
||||
const ENERGY_MIN_INTERVAL_SECONDS = 0.1;
|
||||
const ENERGY_SEQUENCE_MIN_INTERVAL_SECONDS = 0.48;
|
||||
const ENERGY_SEQUENCE_REALIGN_LEAD_SECONDS = 1;
|
||||
const ENERGY_SEQUENCE_FIRST_START_SECONDS = 0.75;
|
||||
const ENERGY_SKIPPED_INTERVAL_RATIO = 0.95;
|
||||
const ENERGY_BOUNDARY_PADDING_SECONDS = 0.12;
|
||||
const ENERGY_MAX_EXTENSION_SECONDS = 0.45;
|
||||
const CHINESE_CAPTION_CHARS_PER_SECOND = 5;
|
||||
const MAX_SEQUENCE_CAPTION_SECONDS = 4.5;
|
||||
const CJK_PATTERN = /[\u3400-\u9fff]/;
|
||||
|
||||
const CHINESE_ASR_CONTEXT_REPLACEMENTS = [
|
||||
[/侯[父付负](?=主[母姆幕]|夫人|公子|小姐|世子|嫡|庶|门|中|里|内|上下)/g, "侯府"],
|
||||
[/候府(?=主[母姆幕]|夫人|公子|小姐|世子|嫡|庶|门|中|里|内|上下)/g, "侯府"],
|
||||
[/(侯府)主[姆幕](?=$|[,。!?!?、\s])/g, "$1主母"],
|
||||
];
|
||||
|
||||
const UI_LANGUAGE_TO_WHISPER_LANGUAGE = {
|
||||
zh: "zh",
|
||||
en: "en",
|
||||
ja: "ja",
|
||||
ko: "ko",
|
||||
es: "es",
|
||||
fr: "fr",
|
||||
de: "de",
|
||||
pt: "pt",
|
||||
th: "th",
|
||||
vi: "vi",
|
||||
};
|
||||
|
||||
const WHISPER_LANGUAGE_NAMES = {
|
||||
zh: "中文",
|
||||
en: "English",
|
||||
ja: "日本語",
|
||||
ko: "한국어",
|
||||
es: "Español",
|
||||
fr: "Français",
|
||||
de: "Deutsch",
|
||||
pt: "Português",
|
||||
th: "ไทย",
|
||||
vi: "Tiếng Việt",
|
||||
};
|
||||
|
||||
let transcriberState = null;
|
||||
let asrWorker = null;
|
||||
let shouldSkipAsrWorker = false;
|
||||
const workerRequests = new Map();
|
||||
|
||||
function getAudioContext(sampleRate = ASR_SAMPLE_RATE) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
throw new Error("当前浏览器不支持 AudioContext,无法识别音频。");
|
||||
}
|
||||
|
||||
return new AudioContextClass({ sampleRate });
|
||||
}
|
||||
|
||||
function downmixToMono(decoded) {
|
||||
if (decoded.numberOfChannels <= 1) {
|
||||
return new Float32Array(decoded.getChannelData(0));
|
||||
}
|
||||
|
||||
const left = decoded.getChannelData(0);
|
||||
const right = decoded.getChannelData(1);
|
||||
const mono = new Float32Array(decoded.length);
|
||||
const scale = Math.SQRT2 / 2;
|
||||
for (let index = 0; index < decoded.length; index += 1) {
|
||||
mono[index] = (left[index] + right[index]) * scale;
|
||||
}
|
||||
return mono;
|
||||
}
|
||||
|
||||
async function decodeAudioForAsr(blob) {
|
||||
const audioContext = getAudioContext();
|
||||
try {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const decoded = await audioContext.decodeAudioData(buffer.slice(0));
|
||||
return {
|
||||
audio: downmixToMono(decoded),
|
||||
duration: decoded.duration,
|
||||
};
|
||||
} finally {
|
||||
await audioContext.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTimestampValue(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeTimestamp(timestamp, fallbackStart, fallbackEnd, timelineOffset = 0) {
|
||||
if (!Array.isArray(timestamp)) {
|
||||
return [fallbackStart + timelineOffset, fallbackEnd + timelineOffset];
|
||||
}
|
||||
|
||||
const [rawStart, rawEnd] = timestamp;
|
||||
const timestampStart = normalizeTimestampValue(rawStart);
|
||||
const timestampEnd = normalizeTimestampValue(rawEnd);
|
||||
const start = (timestampStart ?? fallbackStart) + timelineOffset;
|
||||
const end = (timestampEnd ?? fallbackEnd) + timelineOffset;
|
||||
return [Math.max(0, start), Math.max(start + MIN_CAPTION_DURATION, end)];
|
||||
}
|
||||
|
||||
function normalizeAsrWhitespace(text, language) {
|
||||
const normalized = String(text ?? "").replace(/\s+/g, " ").trim();
|
||||
if (language !== "zh") {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return normalized.replace(/([\u3400-\u9fff])\s+([\u3400-\u9fff])/g, "$1$2");
|
||||
}
|
||||
|
||||
function normalizeChineseAsrText(text) {
|
||||
if (!CJK_PATTERN.test(text)) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return CHINESE_ASR_CONTEXT_REPLACEMENTS.reduce(
|
||||
(currentText, [pattern, replacement]) => currentText.replace(pattern, replacement),
|
||||
text,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeAsrText(text, language) {
|
||||
const normalized = normalizeAsrWhitespace(text, language);
|
||||
return language === "zh" ? normalizeChineseAsrText(normalized) : normalized;
|
||||
}
|
||||
|
||||
function outputToCaptionSegments(output, duration, timelineOffset = 0, language = "zh") {
|
||||
const chunks = Array.isArray(output?.chunks) ? output.chunks : [];
|
||||
let previousEnd = timelineOffset;
|
||||
const segments = chunks
|
||||
.map((chunk, index) => {
|
||||
const rawText = normalizeAsrWhitespace(chunk.text, language);
|
||||
const text = normalizeAsrText(rawText, language);
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fallbackStart = Math.max(
|
||||
0,
|
||||
Math.min(duration, index === 0 ? 0 : previousEnd - timelineOffset),
|
||||
);
|
||||
const fallbackEnd = Math.min(duration, fallbackStart + FALLBACK_CAPTION_SECONDS);
|
||||
const [start, end] = normalizeTimestamp(
|
||||
chunk.timestamp,
|
||||
fallbackStart,
|
||||
fallbackEnd,
|
||||
timelineOffset,
|
||||
);
|
||||
const clampedStart = Math.min(
|
||||
duration + timelineOffset,
|
||||
Math.max(timelineOffset, start < previousEnd - 0.05 ? previousEnd : start),
|
||||
);
|
||||
const clampedEnd = Math.min(
|
||||
duration + timelineOffset,
|
||||
Math.max(clampedStart + MIN_CAPTION_DURATION, end),
|
||||
);
|
||||
previousEnd = clampedEnd;
|
||||
|
||||
return {
|
||||
id: makeId("caption"),
|
||||
text,
|
||||
rawText: rawText !== text ? rawText : undefined,
|
||||
start: clampedStart,
|
||||
end: clampedEnd,
|
||||
hidden: false,
|
||||
source: "asr",
|
||||
};
|
||||
})
|
||||
.filter(Boolean)
|
||||
.filter((segment) => segment.end > segment.start)
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
if (segments.length) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
const rawText = normalizeAsrWhitespace(output?.text, language);
|
||||
const text = normalizeAsrText(rawText, language);
|
||||
return text
|
||||
? [
|
||||
{
|
||||
id: makeId("caption"),
|
||||
text,
|
||||
rawText: rawText !== text ? rawText : undefined,
|
||||
start: timelineOffset,
|
||||
end: timelineOffset + Math.max(MIN_CAPTION_DURATION, duration || FALLBACK_CAPTION_SECONDS),
|
||||
hidden: false,
|
||||
source: "asr",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}
|
||||
|
||||
function getQuantile(sortedValues, quantile) {
|
||||
if (!sortedValues.length) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const index = Math.max(0, Math.min(sortedValues.length - 1, Math.floor(sortedValues.length * quantile)));
|
||||
return sortedValues[index];
|
||||
}
|
||||
|
||||
function getAudioEnergyFrames(audio) {
|
||||
const frameLength = Math.max(1, Math.round(ASR_SAMPLE_RATE * ENERGY_FRAME_SECONDS));
|
||||
const frames = [];
|
||||
for (let index = 0; index < audio.length; index += frameLength) {
|
||||
let sum = 0;
|
||||
const end = Math.min(audio.length, index + frameLength);
|
||||
for (let sampleIndex = index; sampleIndex < end; sampleIndex += 1) {
|
||||
sum += audio[sampleIndex] * audio[sampleIndex];
|
||||
}
|
||||
|
||||
frames.push({
|
||||
start: index / ASR_SAMPLE_RATE,
|
||||
end: end / ASR_SAMPLE_RATE,
|
||||
rms: Math.sqrt(sum / Math.max(1, end - index)),
|
||||
});
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
function getActiveAudioIntervals(audio) {
|
||||
const frames = getAudioEnergyFrames(audio);
|
||||
if (!frames.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rmsValues = frames.map((frame) => frame.rms).sort((a, b) => a - b);
|
||||
const median = getQuantile(rmsValues, 0.5);
|
||||
const upperMid = getQuantile(rmsValues, 0.75);
|
||||
const loud = getQuantile(rmsValues, 0.9);
|
||||
const threshold = Math.max(0.008, median * 1.8, upperMid * 1.12, loud * 0.45);
|
||||
const rawIntervals = [];
|
||||
let currentStart = null;
|
||||
let currentEnd = null;
|
||||
|
||||
frames.forEach((frame) => {
|
||||
if (frame.rms >= threshold) {
|
||||
currentStart ??= frame.start;
|
||||
currentEnd = frame.end;
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentStart !== null && currentEnd - currentStart >= ENERGY_MIN_INTERVAL_SECONDS) {
|
||||
rawIntervals.push({ start: currentStart, end: currentEnd });
|
||||
}
|
||||
currentStart = null;
|
||||
currentEnd = null;
|
||||
});
|
||||
|
||||
if (currentStart !== null && currentEnd - currentStart >= ENERGY_MIN_INTERVAL_SECONDS) {
|
||||
rawIntervals.push({ start: currentStart, end: currentEnd });
|
||||
}
|
||||
|
||||
return rawIntervals.reduce((merged, interval) => {
|
||||
const previous = merged.at(-1);
|
||||
if (previous && interval.start - previous.end <= ENERGY_MERGE_GAP_SECONDS) {
|
||||
previous.end = Math.max(previous.end, interval.end);
|
||||
return merged;
|
||||
}
|
||||
|
||||
merged.push({ ...interval });
|
||||
return merged;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function scoreActiveInterval(interval, segmentStart, segmentEnd) {
|
||||
const duration = interval.end - interval.start;
|
||||
const endDistance = Math.abs(interval.end - segmentEnd);
|
||||
const centerDistance = Math.abs((interval.start + interval.end - segmentStart - segmentEnd) / 2);
|
||||
return duration * 1.8 - endDistance * 0.35 - centerDistance * 0.05;
|
||||
}
|
||||
|
||||
function findBestActiveInterval(intervals, searchStart, searchEnd, segmentStart, segmentEnd) {
|
||||
return intervals
|
||||
.map((interval) => ({
|
||||
start: Math.max(searchStart, interval.start),
|
||||
end: Math.min(searchEnd, interval.end),
|
||||
}))
|
||||
.filter((interval) => interval.end - interval.start >= ENERGY_MIN_INTERVAL_SECONDS)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
scoreActiveInterval(right, segmentStart, segmentEnd) -
|
||||
scoreActiveInterval(left, segmentStart, segmentEnd),
|
||||
)[0] ?? null;
|
||||
}
|
||||
|
||||
function getIntervalDuration(interval) {
|
||||
return Math.max(0, interval.end - interval.start);
|
||||
}
|
||||
|
||||
function getRealignedEnergySequence(intervals, segments, timelineOffset = 0) {
|
||||
if (segments.length < 2 || intervals.length <= segments.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const firstSegmentStart = Math.max(0, segments[0].start - timelineOffset);
|
||||
if (firstSegmentStart > ENERGY_SEQUENCE_FIRST_START_SECONDS) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meaningfulIntervals = intervals.filter(
|
||||
(interval) => getIntervalDuration(interval) >= ENERGY_SEQUENCE_MIN_INTERVAL_SECONDS,
|
||||
);
|
||||
if (meaningfulIntervals.length <= segments.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const candidateIntervals = meaningfulIntervals.slice(-segments.length);
|
||||
const skippedIntervals = meaningfulIntervals.slice(0, -segments.length);
|
||||
const firstCandidateDuration = getIntervalDuration(candidateIntervals[0]);
|
||||
const skippedMaxDuration = skippedIntervals.reduce(
|
||||
(maxDuration, interval) => Math.max(maxDuration, getIntervalDuration(interval)),
|
||||
0,
|
||||
);
|
||||
const hasClearLeadIn = candidateIntervals[0].start - firstSegmentStart >= ENERGY_SEQUENCE_REALIGN_LEAD_SECONDS;
|
||||
const skippedLooksLikeNoise = skippedMaxDuration <= firstCandidateDuration * ENERGY_SKIPPED_INTERVAL_RATIO;
|
||||
|
||||
return hasClearLeadIn && skippedLooksLikeNoise ? candidateIntervals : null;
|
||||
}
|
||||
|
||||
function getEstimatedCaptionSpeechSeconds(text) {
|
||||
const compactText = String(text ?? "").replace(/\s/g, "");
|
||||
const cjkCount = compactText.match(/[\u3400-\u9fff]/g)?.length ?? 0;
|
||||
if (cjkCount) {
|
||||
return Math.max(
|
||||
MIN_CAPTION_DURATION,
|
||||
Math.min(MAX_SEQUENCE_CAPTION_SECONDS, cjkCount / CHINESE_CAPTION_CHARS_PER_SECOND + 0.6),
|
||||
);
|
||||
}
|
||||
|
||||
const wordCount = compactText ? Math.max(1, compactText.split(/\s+/).length) : 1;
|
||||
return Math.max(MIN_CAPTION_DURATION, Math.min(MAX_SEQUENCE_CAPTION_SECONDS, wordCount / 2.8 + 0.8));
|
||||
}
|
||||
|
||||
function refineCaptionSegmentsWithAudioEnergy(segments, audio, duration, timelineOffset = 0) {
|
||||
if (!segments.length || !audio.length || duration <= 0) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
const intervals = getActiveAudioIntervals(audio);
|
||||
if (!intervals.length) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let previousEnd = timelineOffset;
|
||||
const realignedSequence = getRealignedEnergySequence(intervals, segments, timelineOffset);
|
||||
return segments.map((segment, index) => {
|
||||
const localStart = Math.max(0, segment.start - timelineOffset);
|
||||
const localEnd = Math.max(localStart + MIN_CAPTION_DURATION, segment.end - timelineOffset);
|
||||
const hasNextSegment = Number.isFinite(segments[index + 1]?.start);
|
||||
const nextLocalStart = hasNextSegment
|
||||
? Math.max(0, segments[index + 1].start - timelineOffset)
|
||||
: duration;
|
||||
const searchStart = Math.max(0, localStart - 0.35);
|
||||
const searchEnd = Math.min(
|
||||
duration,
|
||||
hasNextSegment ? nextLocalStart - 0.05 : duration,
|
||||
localEnd + ENERGY_MAX_EXTENSION_SECONDS,
|
||||
);
|
||||
const sequenceInterval = realignedSequence?.[index] ?? null;
|
||||
const activeInterval =
|
||||
sequenceInterval ??
|
||||
findBestActiveInterval(
|
||||
intervals,
|
||||
searchStart,
|
||||
searchEnd,
|
||||
localStart,
|
||||
localEnd,
|
||||
);
|
||||
|
||||
if (!activeInterval) {
|
||||
previousEnd = segment.end;
|
||||
return segment;
|
||||
}
|
||||
|
||||
const sequenceEndBound =
|
||||
sequenceInterval && localEnd >= activeInterval.start
|
||||
? timelineOffset + localEnd + ENERGY_MAX_EXTENSION_SECONDS
|
||||
: timelineOffset + duration;
|
||||
const nextSequenceStart = realignedSequence?.[index + 1]?.start;
|
||||
const refinedStart = Math.max(
|
||||
timelineOffset,
|
||||
previousEnd + 0.01,
|
||||
timelineOffset + activeInterval.start - ENERGY_BOUNDARY_PADDING_SECONDS,
|
||||
);
|
||||
const sequenceDurationBound = sequenceInterval
|
||||
? refinedStart + getEstimatedCaptionSpeechSeconds(segment.text)
|
||||
: timelineOffset + duration;
|
||||
const refinedEnd = Math.min(
|
||||
timelineOffset + duration,
|
||||
sequenceInterval
|
||||
? timelineOffset + (Number.isFinite(nextSequenceStart) ? nextSequenceStart - 0.05 : duration)
|
||||
: timelineOffset + localEnd + ENERGY_MAX_EXTENSION_SECONDS,
|
||||
sequenceEndBound,
|
||||
sequenceDurationBound,
|
||||
sequenceInterval ? timelineOffset + duration : timelineOffset + nextLocalStart - 0.05,
|
||||
Math.max(refinedStart + MIN_CAPTION_DURATION, timelineOffset + activeInterval.end + 0.16),
|
||||
);
|
||||
|
||||
if (refinedEnd - refinedStart < MIN_CAPTION_DURATION) {
|
||||
previousEnd = segment.end;
|
||||
return segment;
|
||||
}
|
||||
|
||||
previousEnd = refinedEnd;
|
||||
return {
|
||||
...segment,
|
||||
start: refinedStart,
|
||||
end: refinedEnd,
|
||||
rawStart: segment.rawStart ?? segment.start,
|
||||
rawEnd: segment.rawEnd ?? segment.end,
|
||||
timingSource: "asr-energy",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTokenId(value) {
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
function getGeneratedTokenIds(output) {
|
||||
const tensorLike = output?.sequences ?? output;
|
||||
const rawTokens =
|
||||
tensorLike?.[0] && typeof tensorLike[0].tolist === "function"
|
||||
? tensorLike[0].tolist()
|
||||
: typeof tensorLike?.tolist === "function"
|
||||
? tensorLike.tolist()
|
||||
: tensorLike;
|
||||
const firstSequence = Array.isArray(rawTokens?.[0]) ? rawTokens[0] : rawTokens;
|
||||
return Array.isArray(firstSequence)
|
||||
? firstSequence.map(normalizeTokenId).filter((token) => token !== null)
|
||||
: [];
|
||||
}
|
||||
|
||||
function getWhisperLanguageIdMap(transcriber) {
|
||||
const langToId = transcriber?.model?.generation_config?.lang_to_id;
|
||||
if (!langToId) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
return new Map(
|
||||
Object.entries(langToId)
|
||||
.map(([token, id]) => {
|
||||
const language = normalizeWhisperLanguageToken(token);
|
||||
return [normalizeTokenId(id), language];
|
||||
})
|
||||
.filter(([id, language]) => id !== null && language),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeWhisperLanguageToken(token) {
|
||||
const normalized = String(token ?? "").match(/^<\|?([a-z_]+)\|?>$/i)?.[1];
|
||||
return normalized || String(token ?? "").replace(/[<|>]/g, "");
|
||||
}
|
||||
|
||||
function getPreferredWhisperLanguage(preferredLanguage) {
|
||||
return UI_LANGUAGE_TO_WHISPER_LANGUAGE[preferredLanguage] ?? "zh";
|
||||
}
|
||||
|
||||
function getLanguageDetectionSample(audio) {
|
||||
const sampleLength = Math.min(audio.length, ASR_SAMPLE_RATE * LANGUAGE_DETECTION_SECONDS);
|
||||
return audio.subarray(0, sampleLength);
|
||||
}
|
||||
|
||||
function isMultilingualWhisper(transcriber) {
|
||||
return Boolean(transcriber?.model?.generation_config?.is_multilingual);
|
||||
}
|
||||
|
||||
function createModelLoadProgressCallback(onProgress) {
|
||||
const progressByFile = new Map();
|
||||
let reportedProgress = 8;
|
||||
|
||||
return (event) => {
|
||||
const rawProgress = Number(event?.progress);
|
||||
if (!Number.isFinite(rawProgress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fileKey = event.file ?? event.name ?? event.url ?? "__model__";
|
||||
progressByFile.set(fileKey, Math.max(0, Math.min(100, rawProgress)));
|
||||
const totalProgress = Array.from(progressByFile.values()).reduce((sum, value) => sum + value, 0);
|
||||
const averageProgress = totalProgress / progressByFile.size;
|
||||
const nextProgress = Math.min(70, Math.max(8, Math.round(8 + averageProgress * 0.62)));
|
||||
if (nextProgress <= reportedProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
reportedProgress = nextProgress;
|
||||
onProgress?.({
|
||||
progress: nextProgress,
|
||||
phase: `下载或读取 ${AUTOMATIC_CAPTION_MODEL_LABEL} ONNX`,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function detectWhisperLanguage(transcriber, audio, preferredLanguage, onProgress) {
|
||||
const generationConfig = transcriber?.model?.generation_config;
|
||||
const fallbackLanguage = getPreferredWhisperLanguage(preferredLanguage);
|
||||
if (!isMultilingualWhisper(transcriber)) {
|
||||
return { language: "en", detected: false };
|
||||
}
|
||||
|
||||
const languageIdMap = getWhisperLanguageIdMap(transcriber);
|
||||
if (!languageIdMap.size) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
const decoderStartTokenId = normalizeTokenId(generationConfig.decoder_start_token_id);
|
||||
if (decoderStartTokenId === null) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
try {
|
||||
onProgress?.({ progress: 70, phase: "识别音频语言" });
|
||||
const sample = getLanguageDetectionSample(audio);
|
||||
const features = await transcriber.processor(sample);
|
||||
const output = await transcriber.model.generate({
|
||||
inputs: features.input_features,
|
||||
decoder_input_ids: [decoderStartTokenId],
|
||||
max_new_tokens: 1,
|
||||
return_timestamps: false,
|
||||
});
|
||||
const tokenIds = getGeneratedTokenIds(output);
|
||||
const languageTokenId = tokenIds.find((token) => token !== decoderStartTokenId && languageIdMap.has(token));
|
||||
const language = languageTokenId === undefined ? null : languageIdMap.get(languageTokenId);
|
||||
|
||||
return {
|
||||
language: language || fallbackLanguage,
|
||||
detected: Boolean(language),
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("Whisper language detection failed, falling back to preferred language.", error);
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
}
|
||||
|
||||
async function getTranscriber(onProgress) {
|
||||
if (!transcriberState || transcriberState.modelId !== AUTOMATIC_CAPTION_MODEL_ID) {
|
||||
const modelId = AUTOMATIC_CAPTION_MODEL_ID;
|
||||
transcriberState = {
|
||||
modelId,
|
||||
promise: (async () => {
|
||||
const { pipeline } = await import("@huggingface/transformers");
|
||||
const reportModelLoadProgress = createModelLoadProgressCallback(onProgress);
|
||||
return pipeline("automatic-speech-recognition", modelId, {
|
||||
dtype: "q8",
|
||||
device: "wasm",
|
||||
progress_callback: reportModelLoadProgress,
|
||||
});
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
return transcriberState.promise;
|
||||
}
|
||||
|
||||
function rejectWorkerRequests(error) {
|
||||
workerRequests.forEach((request) => {
|
||||
request.reject(error);
|
||||
});
|
||||
workerRequests.clear();
|
||||
}
|
||||
|
||||
function getAsrWorker() {
|
||||
if (typeof Worker === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (asrWorker) {
|
||||
return asrWorker;
|
||||
}
|
||||
|
||||
asrWorker = new Worker(new URL("../workers/asr.worker.js", import.meta.url), {
|
||||
type: "module",
|
||||
});
|
||||
|
||||
asrWorker.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
const request = workerRequests.get(message?.requestId);
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "progress") {
|
||||
request.onProgress?.({
|
||||
progress: message.progress,
|
||||
phase: message.phase,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
workerRequests.delete(message.requestId);
|
||||
if (message.type === "result") {
|
||||
request.resolve({
|
||||
output: message.output,
|
||||
language: message.language,
|
||||
languageDetected: Boolean(message.languageDetected),
|
||||
modelId: message.modelId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "error") {
|
||||
request.reject(new Error(message.error || "自动字幕生成失败"));
|
||||
}
|
||||
});
|
||||
|
||||
asrWorker.addEventListener("error", (event) => {
|
||||
const error = new Error(event.message || "自动字幕 Worker 运行失败");
|
||||
asrWorker?.terminate();
|
||||
asrWorker = null;
|
||||
rejectWorkerRequests(error);
|
||||
});
|
||||
|
||||
return asrWorker;
|
||||
}
|
||||
|
||||
function transcribeAudioInWorker(audio, { onProgress, preferredLanguage }) {
|
||||
if (shouldSkipAsrWorker) {
|
||||
return Promise.reject(new Error("本轮已停用自动字幕 Worker。"));
|
||||
}
|
||||
|
||||
const worker = getAsrWorker();
|
||||
if (!worker) {
|
||||
return Promise.reject(new Error("当前浏览器不支持 Worker 自动字幕。"));
|
||||
}
|
||||
|
||||
const requestId = makeId("asr");
|
||||
const transferableAudio = audio.slice();
|
||||
return new Promise((resolve, reject) => {
|
||||
workerRequests.set(requestId, {
|
||||
resolve,
|
||||
reject,
|
||||
onProgress,
|
||||
});
|
||||
|
||||
worker.postMessage(
|
||||
{
|
||||
type: "transcribe",
|
||||
requestId,
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
audioBuffer: transferableAudio.buffer,
|
||||
preferredLanguage,
|
||||
},
|
||||
[transferableAudio.buffer],
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage }) {
|
||||
const transcriber = await getTranscriber(onProgress);
|
||||
const languageResult = await detectWhisperLanguage(transcriber, audio, preferredLanguage, onProgress);
|
||||
const languageLabel = WHISPER_LANGUAGE_NAMES[languageResult.language] ?? languageResult.language.toUpperCase();
|
||||
onProgress?.({
|
||||
progress: 74,
|
||||
phase: `${languageResult.detected ? "检测为" : "按"} ${languageLabel} 转写字幕`,
|
||||
});
|
||||
const transcriptionOptions = {
|
||||
chunk_length_s: 30,
|
||||
max_new_tokens: 224,
|
||||
no_repeat_ngram_size: 3,
|
||||
repetition_penalty: 1.15,
|
||||
stride_length_s: 5,
|
||||
return_timestamps: true,
|
||||
};
|
||||
if (isMultilingualWhisper(transcriber)) {
|
||||
transcriptionOptions.language = languageResult.language;
|
||||
transcriptionOptions.task = "transcribe";
|
||||
}
|
||||
const output = await transcriber(audio, transcriptionOptions);
|
||||
|
||||
return {
|
||||
output,
|
||||
language: languageResult.language,
|
||||
languageDetected: languageResult.detected,
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
source: "main",
|
||||
};
|
||||
}
|
||||
|
||||
function getTranscriptText(output) {
|
||||
const chunkText = Array.isArray(output?.chunks)
|
||||
? output.chunks.map((chunk) => chunk?.text ?? "").join("")
|
||||
: "";
|
||||
return String(chunkText || output?.text || "").replace(/\s+/g, "");
|
||||
}
|
||||
|
||||
function countPattern(text, pattern) {
|
||||
return text.match(pattern)?.length ?? 0;
|
||||
}
|
||||
|
||||
function isSuspiciousChineseTranscript(output) {
|
||||
const text = getTranscriptText(output);
|
||||
const visibleCount = countPattern(text, /[^\s]/g);
|
||||
if (visibleCount < CHINESE_VISIBLE_CHAR_THRESHOLD) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cjkCount = countPattern(text, /[\u3400-\u9fff]/g);
|
||||
const latinCount = countPattern(text, /[A-Za-zÀ-ÖØ-öø-ÿ]/g);
|
||||
const latinRatio = latinCount / visibleCount;
|
||||
const cjkRatio = cjkCount / visibleCount;
|
||||
const hasLongLatinRun = /[A-Za-zÀ-ÖØ-öø-ÿ]{12,}/.test(text);
|
||||
|
||||
return cjkCount === 0 || (latinRatio > 0.45 && cjkRatio < 0.2) || hasLongLatinRun;
|
||||
}
|
||||
|
||||
function isSuspiciousTranscript(output, language, preferredLanguage) {
|
||||
const expectedLanguage = language || getPreferredWhisperLanguage(preferredLanguage);
|
||||
return expectedLanguage === "zh" && isSuspiciousChineseTranscript(output);
|
||||
}
|
||||
|
||||
function resetAsrWorker() {
|
||||
asrWorker?.terminate();
|
||||
asrWorker = null;
|
||||
workerRequests.clear();
|
||||
}
|
||||
|
||||
export async function transcribeAudioToCaptionSegments(
|
||||
blob,
|
||||
{ onProgress, preferredLanguage = "zh", timelineOffset = 0 } = {},
|
||||
) {
|
||||
onProgress?.({ progress: 5, phase: "解码原声音频" });
|
||||
const { audio, duration } = await decodeAudioForAsr(blob);
|
||||
if (!audio.length || !duration) {
|
||||
throw new Error("没有检测到可识别的音频。");
|
||||
}
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await transcribeAudioInWorker(audio, { onProgress, preferredLanguage });
|
||||
result.source = "worker";
|
||||
} catch (error) {
|
||||
console.warn("ASR worker failed, falling back to main thread.", error);
|
||||
onProgress?.({ progress: 8, phase: "Worker 不可用,切换主线程自动字幕" });
|
||||
result = await transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage });
|
||||
}
|
||||
|
||||
if (result.source === "worker" && isSuspiciousTranscript(result.output, result.language, preferredLanguage)) {
|
||||
console.warn("ASR worker returned a suspicious transcript, retrying on the WASM main thread.", result.output);
|
||||
shouldSkipAsrWorker = true;
|
||||
resetAsrWorker();
|
||||
onProgress?.({ progress: 78, phase: "Worker 结果异常,切换稳定 WASM 重新识别" });
|
||||
result = await transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage });
|
||||
}
|
||||
|
||||
if (isSuspiciousTranscript(result.output, result.language, preferredLanguage)) {
|
||||
throw new Error("自动字幕结果像是识别错语言了,请刷新后重新生成一次。");
|
||||
}
|
||||
|
||||
const rawSegments = outputToCaptionSegments(
|
||||
result.output,
|
||||
duration,
|
||||
Math.max(0, timelineOffset || 0),
|
||||
result.language,
|
||||
);
|
||||
const segments = refineCaptionSegmentsWithAudioEnergy(
|
||||
rawSegments,
|
||||
audio,
|
||||
duration,
|
||||
Math.max(0, timelineOffset || 0),
|
||||
);
|
||||
if (!segments.length) {
|
||||
throw new Error("没有识别到可用字幕。");
|
||||
}
|
||||
|
||||
onProgress?.({ progress: 96, phase: "写入字幕轨道" });
|
||||
return {
|
||||
segments,
|
||||
text: segments.map((segment) => segment.text).join("\n"),
|
||||
duration,
|
||||
language: result.language,
|
||||
languageDetected: result.languageDetected,
|
||||
};
|
||||
}
|
||||
+145
-10
@@ -28,6 +28,95 @@ export function getAudioRecordingFormat() {
|
||||
let ffmpegLoadPromise = null;
|
||||
let ffmpegTaskQueue = Promise.resolve();
|
||||
|
||||
const VIDEO_TRACK_FRAME_MAX = 72;
|
||||
const VIDEO_TRACK_FRAME_HEIGHT = 90;
|
||||
|
||||
function getVideoTrackSampleCount(duration, maxFrames = VIDEO_TRACK_FRAME_MAX) {
|
||||
const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);
|
||||
if (!safeDuration) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const targetStep =
|
||||
safeDuration <= 20
|
||||
? 0.5
|
||||
: safeDuration <= 120
|
||||
? 1.25
|
||||
: safeDuration <= 600
|
||||
? 3
|
||||
: 10;
|
||||
|
||||
return Math.max(1, Math.min(maxFrames, Math.ceil(safeDuration / targetStep)));
|
||||
}
|
||||
|
||||
function seekVideoFrame(video, time) {
|
||||
const safeTime = Math.max(0, Math.min(time, Math.max(0, (video.duration || time) - 0.04)));
|
||||
if (video.readyState >= 2 && Math.abs(video.currentTime - safeTime) < 0.015) {
|
||||
return new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
video.removeEventListener("seeked", handleSeeked);
|
||||
video.removeEventListener("error", handleError);
|
||||
};
|
||||
const handleSeeked = () => {
|
||||
cleanup();
|
||||
window.requestAnimationFrame(resolve);
|
||||
};
|
||||
const handleError = () => {
|
||||
cleanup();
|
||||
reject(new Error("Video frame seek failed"));
|
||||
};
|
||||
|
||||
video.addEventListener("seeked", handleSeeked, { once: true });
|
||||
video.addEventListener("error", handleError, { once: true });
|
||||
video.currentTime = safeTime;
|
||||
});
|
||||
}
|
||||
|
||||
export async function extractVideoTrackFrames(src, options = {}) {
|
||||
const {
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
maxFrames = VIDEO_TRACK_FRAME_MAX,
|
||||
quality = 0.72,
|
||||
} = options;
|
||||
const video = await loadVideo(src);
|
||||
const safeDuration = Math.max(0, duration || video.duration || 0);
|
||||
const frameCount = getVideoTrackSampleCount(safeDuration, maxFrames);
|
||||
if (!frameCount) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const naturalWidth = Math.max(1, width || video.videoWidth || 16);
|
||||
const naturalHeight = Math.max(1, height || video.videoHeight || 9);
|
||||
const aspectRatio = naturalWidth / naturalHeight;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.height = VIDEO_TRACK_FRAME_HEIGHT;
|
||||
canvas.width = Math.max(36, Math.min(180, Math.round(canvas.height * aspectRatio)));
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const frames = [];
|
||||
video.pause();
|
||||
for (let index = 0; index < frameCount; index += 1) {
|
||||
const time = ((index + 0.5) / frameCount) * safeDuration;
|
||||
await seekVideoFrame(video, time);
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
frames.push(canvas.toDataURL("image/jpeg", quality));
|
||||
}
|
||||
return frames;
|
||||
} finally {
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
}
|
||||
}
|
||||
|
||||
export async function decodeWaveform(blob, barCount = 118) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
@@ -142,8 +231,9 @@ function drawPreviewFrame(context, visual, canvas, options) {
|
||||
captionsEnabled = true,
|
||||
captionPosition = "bottom",
|
||||
captionPlacement = null,
|
||||
captionSize = 34,
|
||||
captionSize = 12,
|
||||
sticker = null,
|
||||
stickerImage = null,
|
||||
transitionId = "none",
|
||||
} = options;
|
||||
|
||||
@@ -175,7 +265,15 @@ function drawPreviewFrame(context, visual, canvas, options) {
|
||||
context.fillText(subtitle.slice(0, 34), overlayX + overlayWidth / 2, overlayY + overlayHeight * 0.62);
|
||||
}
|
||||
|
||||
if (sticker?.text) {
|
||||
if (sticker?.src && stickerImage) {
|
||||
const stickerRatio =
|
||||
(stickerImage.naturalWidth || stickerImage.width || 1) /
|
||||
(stickerImage.naturalHeight || stickerImage.height || 1);
|
||||
const maxStickerSize = Math.min(width, height) * 0.22;
|
||||
const stickerWidth = stickerRatio >= 1 ? maxStickerSize : maxStickerSize * stickerRatio;
|
||||
const stickerHeight = stickerRatio >= 1 ? maxStickerSize / stickerRatio : maxStickerSize;
|
||||
context.drawImage(stickerImage, width - stickerWidth - width * 0.1, height * 0.1, stickerWidth, stickerHeight);
|
||||
} else if (sticker?.text) {
|
||||
context.fillStyle = "rgba(53, 240, 221, 0.92)";
|
||||
context.fillRect(width - 246, 54, 172, 54);
|
||||
context.fillStyle = "#061515";
|
||||
@@ -256,6 +354,7 @@ export async function exportBrowserVideo({
|
||||
voiceVolume = 1,
|
||||
sourceAudioBlob,
|
||||
sourceAudioVolume = 1,
|
||||
sourceAudioStart = 0,
|
||||
musicBlob,
|
||||
musicVolume = 0.35,
|
||||
text,
|
||||
@@ -269,6 +368,7 @@ export async function exportBrowserVideo({
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
stickerSegments = [],
|
||||
transitionId,
|
||||
onProgress,
|
||||
}) {
|
||||
@@ -287,6 +387,16 @@ export async function exportBrowserVideo({
|
||||
visual: segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src),
|
||||
})),
|
||||
);
|
||||
const stickerSources = Array.from(
|
||||
new Set([
|
||||
...(sticker?.src ? [sticker.src] : []),
|
||||
...stickerSegments.map((segment) => segment.src).filter(Boolean),
|
||||
]),
|
||||
);
|
||||
const stickerImageEntries = await Promise.all(
|
||||
stickerSources.map(async (src) => [src, await loadImage(src).catch(() => null)]),
|
||||
);
|
||||
const stickerImageMap = new Map(stickerImageEntries.filter(([, image]) => image));
|
||||
onProgress?.({ progress: 8, phase: "准备画布与轨道" });
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = ratio.width;
|
||||
@@ -300,9 +410,11 @@ export async function exportBrowserVideo({
|
||||
const sources = [];
|
||||
let destination = null;
|
||||
const audioInputs = [
|
||||
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice" } : null,
|
||||
sourceAudioBlob ? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source" } : null,
|
||||
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music" } : null,
|
||||
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice", start: 0 } : null,
|
||||
sourceAudioBlob
|
||||
? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source", start: Math.max(0, sourceAudioStart || 0) }
|
||||
: null,
|
||||
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music", start: 0 } : null,
|
||||
].filter(Boolean);
|
||||
|
||||
if (audioInputs.length) {
|
||||
@@ -330,7 +442,10 @@ export async function exportBrowserVideo({
|
||||
gain.gain.value = input.volume;
|
||||
source.connect(gain);
|
||||
gain.connect(destination);
|
||||
sources.push(source);
|
||||
sources.push({
|
||||
node: source,
|
||||
start: input.start,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -345,7 +460,7 @@ export async function exportBrowserVideo({
|
||||
const totalDuration = Math.max(
|
||||
duration,
|
||||
decodedDuration,
|
||||
...sources.map((source) => source.buffer?.duration ?? 0),
|
||||
...sources.map(({ node, start }) => start + (node.buffer?.duration ?? 0)),
|
||||
1,
|
||||
);
|
||||
const captionTargetDuration = decodedDuration || 0;
|
||||
@@ -381,6 +496,22 @@ export async function exportBrowserVideo({
|
||||
range: exportVisualTimeline[Math.max(0, visualIndex)] ?? exportVisualTimeline[0],
|
||||
};
|
||||
};
|
||||
const getStickerAtTime = (elapsed) => {
|
||||
if (!stickerSegments.length) {
|
||||
return sticker;
|
||||
}
|
||||
|
||||
for (let index = stickerSegments.length - 1; index >= 0; index -= 1) {
|
||||
const segment = stickerSegments[index];
|
||||
const start = Math.max(0, segment.start || 0);
|
||||
const end = start + Math.max(0, segment.duration || 0);
|
||||
if (elapsed >= start && elapsed < end) {
|
||||
return segment;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
const draw = () => {
|
||||
const elapsed = Math.min(totalDuration, (performance.now() - startTime) / 1000);
|
||||
const segmentIndex = getSegmentIndexAtTime(exportSegments, elapsed, captionTargetDuration);
|
||||
@@ -394,6 +525,7 @@ export async function exportBrowserVideo({
|
||||
visualItem.visual.currentTime = nextVideoTime;
|
||||
}
|
||||
}
|
||||
const exportSticker = getStickerAtTime(elapsed);
|
||||
drawPreviewFrame(context, visualItem.visual, canvas, {
|
||||
subtitle: exportCaption,
|
||||
progress: elapsed / totalDuration,
|
||||
@@ -403,7 +535,8 @@ export async function exportBrowserVideo({
|
||||
captionPosition,
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
sticker: exportSticker,
|
||||
stickerImage: exportSticker?.src ? stickerImageMap.get(exportSticker.src) : null,
|
||||
transitionId,
|
||||
});
|
||||
|
||||
@@ -421,7 +554,7 @@ export async function exportBrowserVideo({
|
||||
};
|
||||
|
||||
draw();
|
||||
sources.forEach((source) => source.start());
|
||||
sources.forEach(({ node, start }) => node.start(start));
|
||||
await new Promise((resolve) => {
|
||||
window.setTimeout(resolve, totalDuration * 1000);
|
||||
});
|
||||
@@ -433,6 +566,7 @@ export async function exportBrowserVideo({
|
||||
});
|
||||
const finalSegmentIndex = getSegmentIndexAtTime(exportSegments, totalDuration, captionTargetDuration);
|
||||
const { item: finalVisualItem } = getVisualItemAtTime(totalDuration);
|
||||
const finalSticker = getStickerAtTime(totalDuration);
|
||||
drawPreviewFrame(context, finalVisualItem.visual, canvas, {
|
||||
subtitle:
|
||||
finalSegmentIndex >= 0 && !exportSegments[finalSegmentIndex]?.hidden
|
||||
@@ -445,7 +579,8 @@ export async function exportBrowserVideo({
|
||||
captionPosition,
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
sticker: finalSticker,
|
||||
stickerImage: finalSticker?.src ? stickerImageMap.get(finalSticker.src) : null,
|
||||
transitionId,
|
||||
});
|
||||
recorder.stop();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
const MODEL_CACHE_WORKER_URL = "/model-cache-sw.js";
|
||||
|
||||
export function registerModelCacheServiceWorker() {
|
||||
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.serviceWorker
|
||||
.register(MODEL_CACHE_WORKER_URL)
|
||||
.then((registration) => registration.update().catch(() => {}))
|
||||
.catch((error) => {
|
||||
console.warn("Model cache service worker registration failed.", error);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
MAX_CAPTION_SEGMENT_SECONDS,
|
||||
MAX_IMAGE_THUMBNAILS,
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
@@ -7,6 +8,8 @@ import {
|
||||
IMAGE_SEGMENT_SECONDS,
|
||||
} from "../config/editor.js";
|
||||
|
||||
const MIN_TIMED_CAPTION_SECONDS = 0.2;
|
||||
|
||||
export function makeId(prefix) {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
@@ -30,6 +33,9 @@ export function getVisualAssetPayload(asset) {
|
||||
name: asset.name ?? "",
|
||||
meta: asset.meta ?? "",
|
||||
blob: asset.blob ?? null,
|
||||
width: asset.width ?? asset.naturalWidth ?? 0,
|
||||
height: asset.height ?? asset.naturalHeight ?? 0,
|
||||
trackFrames: Array.isArray(asset.trackFrames) ? asset.trackFrames : [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +47,45 @@ export function createVisualSegment(duration = 4, asset = null) {
|
||||
};
|
||||
}
|
||||
|
||||
export function createStickerSegment(sticker, start = 0, duration = DEFAULT_STICKER_SEGMENT_SECONDS) {
|
||||
const safeDuration = Math.max(
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, duration || DEFAULT_STICKER_SEGMENT_SECONDS),
|
||||
);
|
||||
|
||||
return {
|
||||
id: makeId("sticker"),
|
||||
stickerId: sticker?.stickerId ?? sticker?.id ?? "",
|
||||
name: sticker?.name ?? "",
|
||||
nameEn: sticker?.nameEn ?? "",
|
||||
category: sticker?.category ?? "",
|
||||
src: sticker?.src ?? "",
|
||||
start: Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - safeDuration, start || 0)),
|
||||
duration: safeDuration,
|
||||
};
|
||||
}
|
||||
|
||||
export function getTimedSegmentsEnd(segments) {
|
||||
return segments.reduce(
|
||||
(end, segment) => Math.max(end, Math.max(0, segment.start || 0) + Math.max(0, segment.duration || 0)),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
export function getTimedSegmentIndexAtTime(segments, time) {
|
||||
const safeTime = Math.max(0, Number.isFinite(time) ? time : 0);
|
||||
for (let index = segments.length - 1; index >= 0; index -= 1) {
|
||||
const segment = segments[index];
|
||||
const start = Math.max(0, segment.start || 0);
|
||||
const end = start + Math.max(0, segment.duration || 0);
|
||||
if (safeTime >= start && safeTime < end) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function getVisualSegmentsTotal(segments) {
|
||||
return segments.reduce((sum, segment) => sum + Math.max(0, segment.duration || 0), 0);
|
||||
}
|
||||
@@ -107,13 +152,39 @@ export function getCaptionBaseDuration(text) {
|
||||
}
|
||||
|
||||
export function getCaptionSegmentDuration(segment) {
|
||||
if (hasExplicitCaptionTiming(segment)) {
|
||||
return Math.max(MIN_TIMED_CAPTION_SECONDS, segment.end - segment.start);
|
||||
}
|
||||
|
||||
const defaultWeight = getCaptionDefaultWeight(segment.text);
|
||||
const weight = Number.isFinite(segment.weight) ? segment.weight : defaultWeight;
|
||||
const weightScale = Math.max(0.35, weight / defaultWeight);
|
||||
return getCaptionBaseDuration(segment.text) * weightScale;
|
||||
}
|
||||
|
||||
export function hasExplicitCaptionTiming(segment) {
|
||||
return Number.isFinite(segment?.start) && Number.isFinite(segment?.end) && segment.end > segment.start;
|
||||
}
|
||||
|
||||
export function getCaptionTimeline(captionSegments, targetDuration = 0) {
|
||||
if (captionSegments.some(hasExplicitCaptionTiming)) {
|
||||
let cursor = 0;
|
||||
return captionSegments.map((segment) => {
|
||||
const hasTiming = hasExplicitCaptionTiming(segment);
|
||||
const start = hasTiming ? Math.max(0, segment.start) : cursor;
|
||||
const duration = hasTiming
|
||||
? Math.max(MIN_TIMED_CAPTION_SECONDS, segment.end - segment.start)
|
||||
: getCaptionSegmentDuration(segment);
|
||||
const timelineItem = {
|
||||
start,
|
||||
end: start + duration,
|
||||
duration,
|
||||
};
|
||||
cursor = timelineItem.end;
|
||||
return timelineItem;
|
||||
});
|
||||
}
|
||||
|
||||
const naturalDurations = captionSegments.map((segment) => getCaptionSegmentDuration(segment));
|
||||
const naturalTotal = naturalDurations.reduce((sum, duration) => sum + duration, 0);
|
||||
const shouldAlignToTarget = targetDuration > 0 && naturalTotal > 0;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
|
||||
export const TIMELINE_MIN_ZOOM = 0.25;
|
||||
export const TIMELINE_MAX_ZOOM = 16;
|
||||
export const TIMELINE_DEFAULT_VISIBLE_SECONDS = 10;
|
||||
export const TIMELINE_MIN_VISIBLE_SECONDS = 0.5;
|
||||
export const TIMELINE_FRAME_RATE = 30;
|
||||
|
||||
const ZOOM_IN_CURVE = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS / TIMELINE_MIN_VISIBLE_SECONDS) /
|
||||
Math.log(TIMELINE_MAX_ZOOM);
|
||||
|
||||
export function clampTimelineZoom(zoom) {
|
||||
return Math.max(TIMELINE_MIN_ZOOM, Math.min(TIMELINE_MAX_ZOOM, zoom));
|
||||
}
|
||||
|
||||
export function getTimelineVisibleDuration(zoom) {
|
||||
const clampedZoom = clampTimelineZoom(zoom);
|
||||
|
||||
if (clampedZoom <= 1) {
|
||||
const progress = (clampedZoom - TIMELINE_MIN_ZOOM) / (1 - TIMELINE_MIN_ZOOM);
|
||||
const maxLog = Math.log(MAX_TIMELINE_DURATION_SECONDS);
|
||||
const defaultLog = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS);
|
||||
return Math.exp(maxLog + (defaultLog - maxLog) * progress);
|
||||
}
|
||||
|
||||
return Math.max(
|
||||
TIMELINE_MIN_VISIBLE_SECONDS,
|
||||
TIMELINE_DEFAULT_VISIBLE_SECONDS / Math.pow(clampedZoom, ZOOM_IN_CURVE),
|
||||
);
|
||||
}
|
||||
|
||||
export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
|
||||
if (timelineDuration <= 0) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
return Math.max(100, (timelineDuration / visibleDuration) * 100);
|
||||
}
|
||||
|
||||
export function getTimelineRulerScale(visibleDuration) {
|
||||
if (visibleDuration <= 0.75) {
|
||||
return { minorStep: 1 / TIMELINE_FRAME_RATE, majorStep: 0.5, labelMode: "frames" };
|
||||
}
|
||||
if (visibleDuration <= 2) {
|
||||
return { minorStep: 0.1, majorStep: 0.5, labelMode: "subseconds" };
|
||||
}
|
||||
if (visibleDuration <= 6) {
|
||||
return { minorStep: 0.25, majorStep: 0.5, labelMode: "subseconds" };
|
||||
}
|
||||
if (visibleDuration <= 16) {
|
||||
return { minorStep: 0.5, majorStep: 1, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 45) {
|
||||
return { minorStep: 1, majorStep: 5, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 120) {
|
||||
return { minorStep: 5, majorStep: 15, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 420) {
|
||||
return { minorStep: 15, majorStep: 60, labelMode: "minutes" };
|
||||
}
|
||||
if (visibleDuration <= 900) {
|
||||
return { minorStep: 60, majorStep: 300, labelMode: "minutes" };
|
||||
}
|
||||
return { minorStep: 300, majorStep: 600, labelMode: "minutes" };
|
||||
}
|
||||
|
||||
export function getTimelineRulerTicks(timelineDuration, zoom, visibleStart = 0, visibleEnd = timelineDuration) {
|
||||
if (timelineDuration <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
const { minorStep, majorStep, labelMode } = getTimelineRulerScale(visibleDuration);
|
||||
const rangePadding = Math.max(visibleDuration * 0.35, majorStep);
|
||||
const rangeStart = Math.max(0, visibleStart - rangePadding);
|
||||
const rangeEnd = Math.min(timelineDuration, visibleEnd + rangePadding);
|
||||
const startIndex = Math.max(0, Math.floor(rangeStart / minorStep));
|
||||
const endIndex = Math.max(startIndex, Math.ceil(rangeEnd / minorStep));
|
||||
|
||||
return Array.from({ length: endIndex - startIndex + 1 }, (_, offset) => {
|
||||
const index = startIndex + offset;
|
||||
const time = Math.min(timelineDuration, index * minorStep);
|
||||
const isMajor = Math.abs(time / majorStep - Math.round(time / majorStep)) < 0.001;
|
||||
return {
|
||||
id: `${minorStep}-${index}`,
|
||||
time,
|
||||
left: (time / timelineDuration) * 100,
|
||||
isMajor,
|
||||
label: isMajor ? formatTimelineRulerLabel(time, labelMode) : "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function getTimelineZoomLabel(zoom) {
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
|
||||
if (visibleDuration <= 0.75) {
|
||||
return "15f";
|
||||
}
|
||||
|
||||
if (visibleDuration < 2) {
|
||||
return `${visibleDuration.toFixed(1)}s`;
|
||||
}
|
||||
|
||||
if (visibleDuration < 60) {
|
||||
return `${Math.round(visibleDuration)}s`;
|
||||
}
|
||||
|
||||
return `${Math.round(visibleDuration / 60)}m`;
|
||||
}
|
||||
|
||||
export function formatTimelineRulerLabel(value, mode = "seconds") {
|
||||
const safeSeconds = Math.max(0, Number.isFinite(value) ? value : 0);
|
||||
const minutes = Math.floor(safeSeconds / 60);
|
||||
const seconds = Math.floor(safeSeconds % 60);
|
||||
const frame = Math.round((safeSeconds - Math.floor(safeSeconds)) * TIMELINE_FRAME_RATE);
|
||||
const centiseconds = Math.round((safeSeconds - Math.floor(safeSeconds)) * 100);
|
||||
const clock = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
|
||||
|
||||
if (mode === "frames" && frame > 0) {
|
||||
return `${clock}:${String(frame).padStart(2, "0")}f`;
|
||||
}
|
||||
|
||||
if (mode === "subseconds" && centiseconds > 0) {
|
||||
return `${clock}.${String(centiseconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
return clock;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
const CHINESE_SPOKEN_DIGITS = {
|
||||
0: "零",
|
||||
1: "一",
|
||||
2: "二",
|
||||
3: "三",
|
||||
4: "四",
|
||||
5: "五",
|
||||
6: "六",
|
||||
7: "七",
|
||||
8: "八",
|
||||
9: "九",
|
||||
};
|
||||
|
||||
const CHINESE_SPOKEN_LETTERS = {
|
||||
A: "诶",
|
||||
B: "比",
|
||||
C: "西",
|
||||
D: "迪",
|
||||
E: "伊",
|
||||
F: "艾弗",
|
||||
G: "吉",
|
||||
H: "艾尺",
|
||||
I: "艾",
|
||||
J: "杰",
|
||||
K: "开",
|
||||
L: "艾勒",
|
||||
M: "艾姆",
|
||||
N: "恩",
|
||||
O: "欧",
|
||||
P: "皮",
|
||||
Q: "丘",
|
||||
R: "阿尔",
|
||||
S: "艾斯",
|
||||
T: "提",
|
||||
U: "优",
|
||||
V: "维",
|
||||
W: "达不溜",
|
||||
X: "艾克斯",
|
||||
Y: "歪",
|
||||
Z: "泽德",
|
||||
};
|
||||
|
||||
const ASCII_PUNCTUATION_MAP = new Map([
|
||||
[",", ","],
|
||||
[".", "。"],
|
||||
["?", "?"],
|
||||
["!", "!"],
|
||||
[";", ";"],
|
||||
[":", ":"],
|
||||
]);
|
||||
|
||||
export class TtsInputError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "TtsInputError";
|
||||
}
|
||||
}
|
||||
|
||||
function countMatches(text, pattern) {
|
||||
return text.match(pattern)?.join("").length ?? 0;
|
||||
}
|
||||
|
||||
function normalizeBaseText(text) {
|
||||
return text
|
||||
.normalize("NFKC")
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, "")
|
||||
.replace(/[“”"']/g, "")
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function speakShortLatinTokenInChinese(token) {
|
||||
return [...token.toUpperCase()]
|
||||
.map((char) => CHINESE_SPOKEN_DIGITS[char] ?? CHINESE_SPOKEN_LETTERS[char] ?? "")
|
||||
.join("");
|
||||
}
|
||||
|
||||
function prepareChinesePiperText(rawText) {
|
||||
const normalized = normalizeBaseText(rawText);
|
||||
const latinCount = countMatches(normalized, /[A-Za-z]/g);
|
||||
const hanCount = countMatches(normalized, /\p{Script=Han}/gu);
|
||||
|
||||
if (latinCount > Math.max(14, hanCount * 0.8)) {
|
||||
throw new TtsInputError("当前中文语音不适合大量英文文案,请切换 English 声音后再生成。");
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
let text = normalized
|
||||
.replace(/[A-Za-z0-9]+/g, (token) => {
|
||||
changed = true;
|
||||
return token.length <= 8 ? speakShortLatinTokenInChinese(token) : ",";
|
||||
})
|
||||
.replace(/[()()\[\]{}【】<>《》]/g, () => {
|
||||
changed = true;
|
||||
return ",";
|
||||
})
|
||||
.replace(/[-_/\\|~`^+=*@#$%&]/g, () => {
|
||||
changed = true;
|
||||
return ",";
|
||||
})
|
||||
.replace(/[,.?!;:]/g, (mark) => {
|
||||
changed = true;
|
||||
return ASCII_PUNCTUATION_MAP.get(mark) ?? ",";
|
||||
})
|
||||
.replace(/\s+/g, ",")
|
||||
.replace(/[^\p{Script=Han}零一二三四五六七八九十百千万亿两,。!?;:、\n]/gu, () => {
|
||||
changed = true;
|
||||
return "";
|
||||
})
|
||||
.replace(/[,、]{2,}/g, ",")
|
||||
.replace(/[。!?;:]{2,}/g, (marks) => marks[0])
|
||||
.replace(/^[,。!?;:、]+|[,。!?;:、]+$/g, "")
|
||||
.trim();
|
||||
|
||||
if (!text) {
|
||||
throw new TtsInputError("当前中文语音没有可朗读的中文内容,请输入中文或切换英文声音。");
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
warning: changed ? "已自动清理中文语音不支持的符号,避免本地 ONNX 运行失败。" : "",
|
||||
};
|
||||
}
|
||||
|
||||
function prepareKokoroText(rawText) {
|
||||
const normalized = normalizeBaseText(rawText).replace(/\s+/g, " ");
|
||||
const hanCount = countMatches(normalized, /\p{Script=Han}/gu);
|
||||
const latinCount = countMatches(normalized, /[A-Za-z]/g);
|
||||
|
||||
if (hanCount > Math.max(4, latinCount * 0.5)) {
|
||||
throw new TtsInputError("当前英文语音不适合中文文案,请切换中文声音后再生成。");
|
||||
}
|
||||
|
||||
const text = normalized.replace(/[^\p{Script=Latin}0-9\s.,!?;:'"()\-]/gu, "").trim();
|
||||
if (!text) {
|
||||
throw new TtsInputError("当前英文语音没有可朗读的英文内容,请输入英文或切换中文声音。");
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
warning: text !== normalized ? "已自动清理英文语音不支持的字符。" : "",
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareTextForVoice(rawText, voice) {
|
||||
if (voice?.engine === "piper" && voice.language === "中文") {
|
||||
return prepareChinesePiperText(rawText);
|
||||
}
|
||||
|
||||
if (voice?.engine === "kokoro") {
|
||||
return prepareKokoroText(rawText);
|
||||
}
|
||||
|
||||
const text = normalizeBaseText(rawText);
|
||||
if (!text) {
|
||||
throw new TtsInputError("请输入要生成的文案。");
|
||||
}
|
||||
return { text, warning: "" };
|
||||
}
|
||||
|
||||
export function isPiperSymbolError(error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return /Gather|indices element out of data bounds|OrtRun|emb\/Gather/i.test(message);
|
||||
}
|
||||
|
||||
export function isStorageQuotaError(error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return /QuotaExceededError|storage quota|exceed.*quota/i.test(message);
|
||||
}
|
||||
|
||||
export async function clearPiperCacheIfStorageTight(tts) {
|
||||
if (!navigator.storage?.estimate || typeof tts?.flush !== "function") {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
const usage = estimate.usage ?? 0;
|
||||
const quota = estimate.quota ?? 0;
|
||||
const remaining = quota > usage ? quota - usage : 0;
|
||||
if (quota > 0 && (usage / quota > 0.9 || remaining < 120 * 1024 * 1024)) {
|
||||
await tts.flush();
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App.jsx";
|
||||
import { registerModelCacheServiceWorker } from "./lib/serviceWorker.js";
|
||||
import "./styles.css";
|
||||
|
||||
registerModelCacheServiceWorker();
|
||||
|
||||
createRoot(document.getElementById("root")).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
|
||||
+521
-18
@@ -1060,6 +1060,167 @@ button:disabled {
|
||||
opacity: 0.52;
|
||||
}
|
||||
|
||||
.sticker-panel {
|
||||
gap: 0;
|
||||
padding-bottom: 4px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.sticker-panel::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sticker-none-button,
|
||||
.sticker-load-more {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex: 0 0 auto;
|
||||
min-height: 42px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.075);
|
||||
border-radius: 7px;
|
||||
padding: 0 12px;
|
||||
color: #dbe6ec;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
background: rgba(255, 255, 255, 0.045);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sticker-none-button:hover,
|
||||
.sticker-none-button.is-selected,
|
||||
.sticker-load-more:hover {
|
||||
border-color: rgba(46, 234, 216, 0.8);
|
||||
color: #effffd;
|
||||
background: rgba(46, 234, 216, 0.09);
|
||||
}
|
||||
|
||||
.sticker-none-button svg {
|
||||
color: #35ead9;
|
||||
}
|
||||
|
||||
.sticker-category-row {
|
||||
display: flex;
|
||||
gap: 7px;
|
||||
flex: 0 0 auto;
|
||||
margin: 12px 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.sticker-category-row::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sticker-category-row button {
|
||||
flex: 0 0 auto;
|
||||
min-height: 30px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 999px;
|
||||
padding: 0 11px;
|
||||
color: #9aa6b0;
|
||||
font-size: 12px;
|
||||
font-weight: 750;
|
||||
background: rgba(255, 255, 255, 0.042);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sticker-category-row button:hover,
|
||||
.sticker-category-row button.is-active {
|
||||
border-color: rgba(53, 234, 217, 0.72);
|
||||
color: #effffd;
|
||||
background: rgba(53, 234, 217, 0.1);
|
||||
}
|
||||
|
||||
.sticker-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.sticker-tile {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
aspect-ratio: 1 / 1.12;
|
||||
border: 1px solid rgba(255, 255, 255, 0.075);
|
||||
border-radius: 8px;
|
||||
padding: 7px 7px 8px;
|
||||
color: #dce7ec;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sticker-tile:hover,
|
||||
.sticker-tile.is-selected {
|
||||
border-color: rgba(53, 234, 217, 0.8);
|
||||
background: rgba(53, 234, 217, 0.08);
|
||||
}
|
||||
|
||||
.sticker-tile-thumb {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 0;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 7px;
|
||||
background:
|
||||
linear-gradient(135deg, rgba(53, 234, 217, 0.08), rgba(103, 181, 255, 0.055)),
|
||||
rgba(255, 255, 255, 0.055);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.045);
|
||||
}
|
||||
|
||||
.sticker-tile-thumb img {
|
||||
display: block;
|
||||
width: 82%;
|
||||
height: 82%;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 8px 14px rgba(0, 0, 0, 0.28));
|
||||
}
|
||||
|
||||
.sticker-tile-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
margin-top: 6px;
|
||||
color: #cdd8de;
|
||||
font-size: 11px;
|
||||
font-weight: 740;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.sticker-tile-label span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sticker-tile-label svg {
|
||||
flex: 0 0 auto;
|
||||
color: #35ead9;
|
||||
}
|
||||
|
||||
.sticker-load-more {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.sticker-load-more span:last-child {
|
||||
color: #82909b;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.sticker-load-sentinel {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.switch-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1095,7 +1256,10 @@ button:disabled {
|
||||
}
|
||||
|
||||
.segment-list {
|
||||
overflow: auto;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.segment-list button {
|
||||
@@ -1104,6 +1268,39 @@ button:disabled {
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.caption-tool-panel {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.caption-tool-panel > h2,
|
||||
.caption-tool-panel > .switch-row,
|
||||
.caption-tool-panel > .segmented,
|
||||
.caption-tool-panel > .compact-slider,
|
||||
.caption-tool-panel > .caption-editor {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.caption-tool-panel .segment-list {
|
||||
flex: 1 1 96px;
|
||||
min-height: 0;
|
||||
margin-top: 2px;
|
||||
padding: 1px 3px 10px 0;
|
||||
}
|
||||
|
||||
.caption-tool-panel .segment-list::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.caption-tool-panel .segment-list::-webkit-scrollbar-thumb {
|
||||
border: 2px solid rgba(17, 21, 27, 0.96);
|
||||
border-radius: 999px;
|
||||
background: rgba(143, 157, 169, 0.52);
|
||||
}
|
||||
|
||||
.caption-tool-panel .segment-list::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.caption-editor {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
@@ -1194,6 +1391,7 @@ button:disabled {
|
||||
}
|
||||
|
||||
.audio-entry-card {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 42px minmax(0, 1fr);
|
||||
align-items: center;
|
||||
@@ -1212,6 +1410,12 @@ button:disabled {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.audio-entry-card:disabled {
|
||||
opacity: 0.52;
|
||||
cursor: not-allowed;
|
||||
filter: saturate(0.7);
|
||||
}
|
||||
|
||||
.audio-entry-card svg {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
@@ -1246,6 +1450,43 @@ button:disabled {
|
||||
rgba(255, 255, 255, 0.055);
|
||||
}
|
||||
|
||||
.audio-entry-card:disabled:hover {
|
||||
border-color: rgba(53, 234, 217, 0.3);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(53, 234, 217, 0.12), rgba(120, 163, 255, 0.08)),
|
||||
rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.caption-entry-card {
|
||||
border-color: rgba(103, 181, 255, 0.28);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(103, 181, 255, 0.12), rgba(53, 234, 217, 0.07)),
|
||||
rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.caption-entry-card svg {
|
||||
background: #78a3ff;
|
||||
}
|
||||
|
||||
.inline-progress {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
right: 12px;
|
||||
bottom: 7px;
|
||||
height: 4px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.inline-progress span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(90deg, #78a3ff, #33ebd7);
|
||||
transition: width 180ms ease;
|
||||
}
|
||||
|
||||
.visual-choice-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
@@ -1422,9 +1663,11 @@ button:disabled {
|
||||
}
|
||||
|
||||
.preview-empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
gap: 9px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 14px;
|
||||
width: min(420px, 78%);
|
||||
aspect-ratio: var(--preview-ratio, 16 / 9);
|
||||
border: 1px dashed rgba(173, 184, 196, 0.22);
|
||||
@@ -1437,11 +1680,13 @@ button:disabled {
|
||||
.preview-empty strong {
|
||||
color: #e3edf2;
|
||||
font-size: 14px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.preview-empty span {
|
||||
color: #77838e;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.preview-frame {
|
||||
@@ -1462,6 +1707,7 @@ button:disabled {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
object-position: center center;
|
||||
background: #080a0e;
|
||||
}
|
||||
|
||||
@@ -1525,6 +1771,18 @@ button:disabled {
|
||||
top: 12%;
|
||||
right: 12%;
|
||||
z-index: 3;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sticker-overlay.is-image {
|
||||
width: clamp(76px, 18%, 142px);
|
||||
height: auto;
|
||||
object-fit: contain;
|
||||
background: transparent;
|
||||
filter: drop-shadow(0 12px 18px rgba(0, 0, 0, 0.3));
|
||||
}
|
||||
|
||||
.sticker-overlay.is-label {
|
||||
border-radius: 7px;
|
||||
padding: 9px 15px;
|
||||
color: #061515;
|
||||
@@ -1691,6 +1949,119 @@ button:disabled {
|
||||
color: #9faab4;
|
||||
}
|
||||
|
||||
.caption-context-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.caption-context-panel .field-label {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.caption-sync-box textarea {
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
.caption-context-empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
gap: 8px;
|
||||
min-height: 156px;
|
||||
border: 1px dashed rgba(173, 184, 196, 0.18);
|
||||
border-radius: 8px;
|
||||
padding: 18px;
|
||||
color: #88959f;
|
||||
text-align: center;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
|
||||
.caption-context-empty svg {
|
||||
color: #5eece0;
|
||||
}
|
||||
|
||||
.caption-context-empty strong {
|
||||
color: #dce8ec;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.caption-context-empty span {
|
||||
max-width: 260px;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.caption-context-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.caption-context-actions button {
|
||||
min-height: 38px;
|
||||
}
|
||||
|
||||
.caption-context-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
color: #dce7eb;
|
||||
font-size: 13px;
|
||||
font-weight: 760;
|
||||
}
|
||||
|
||||
.caption-context-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.caption-context-list button {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 42px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.07);
|
||||
border-radius: 7px;
|
||||
padding: 0 10px;
|
||||
color: #dfe9ed;
|
||||
text-align: left;
|
||||
background: rgba(255, 255, 255, 0.045);
|
||||
}
|
||||
|
||||
.caption-context-list button:hover,
|
||||
.caption-context-list button.is-current {
|
||||
border-color: rgba(53, 234, 217, 0.38);
|
||||
background: rgba(53, 234, 217, 0.08);
|
||||
}
|
||||
|
||||
.caption-context-list button.is-selected {
|
||||
border-color: rgba(94, 236, 224, 0.74);
|
||||
background: rgba(53, 234, 217, 0.13);
|
||||
}
|
||||
|
||||
.caption-context-list button.is-hidden {
|
||||
opacity: 0.56;
|
||||
}
|
||||
|
||||
.caption-context-list span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.caption-context-list em {
|
||||
color: #8d9aa5;
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.voice-header {
|
||||
justify-content: space-between;
|
||||
margin-top: 10px;
|
||||
@@ -2135,13 +2506,12 @@ button:disabled {
|
||||
display: grid;
|
||||
grid-template-rows: 28px 46px 46px 58px 58px 58px;
|
||||
min-width: 25%;
|
||||
transition: width 160ms ease;
|
||||
transition: width 140ms cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.ruler {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(11, 1fr);
|
||||
align-items: center;
|
||||
position: relative;
|
||||
display: block;
|
||||
color: #7e8995;
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
@@ -2149,9 +2519,40 @@ button:disabled {
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.ruler span {
|
||||
.ruler::after {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 1px;
|
||||
background: rgba(255, 255, 255, 0.035);
|
||||
content: "";
|
||||
}
|
||||
|
||||
.ruler-tick {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 1px;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.06);
|
||||
padding-left: 8px;
|
||||
padding-left: 7px;
|
||||
color: #838f9b;
|
||||
line-height: 24px;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ruler-tick.is-major {
|
||||
border-left-color: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.ruler-tick.is-minor {
|
||||
top: 15px;
|
||||
bottom: auto;
|
||||
height: 8px;
|
||||
padding-left: 0;
|
||||
color: transparent;
|
||||
border-left-color: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.playhead {
|
||||
@@ -2205,6 +2606,7 @@ button:disabled {
|
||||
|
||||
.image-track,
|
||||
.caption-track,
|
||||
.sticker-track,
|
||||
.audio-track {
|
||||
position: relative;
|
||||
display: flex;
|
||||
@@ -2292,6 +2694,24 @@ button:disabled {
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.image-thumbnails.is-video {
|
||||
gap: 1px;
|
||||
background: #05070a;
|
||||
}
|
||||
|
||||
.image-thumbnails.is-video img {
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
flex: 1 1 0;
|
||||
object-fit: cover;
|
||||
background: #05070a;
|
||||
}
|
||||
|
||||
.image-thumbnails.is-video.is-portrait-video img {
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.image-clip.is-video {
|
||||
border-color: rgba(103, 181, 255, 0.52);
|
||||
box-shadow: inset 0 0 0 1px rgba(103, 181, 255, 0.18);
|
||||
@@ -2400,18 +2820,22 @@ button:disabled {
|
||||
background: rgba(53, 234, 217, 0.34);
|
||||
}
|
||||
|
||||
.caption-track {
|
||||
gap: 2px;
|
||||
.caption-track,
|
||||
.sticker-track {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.caption-segment {
|
||||
position: relative;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: var(--caption-left, 0%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 max(56px, var(--caption-width, 12%));
|
||||
min-width: 56px;
|
||||
max-width: 100%;
|
||||
width: var(--caption-width, 12%);
|
||||
min-width: 0;
|
||||
max-width: calc(100% - var(--caption-left, 0%));
|
||||
height: 34px;
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
@@ -2432,6 +2856,7 @@ button:disabled {
|
||||
opacity 160ms ease,
|
||||
filter 160ms ease,
|
||||
background 160ms ease;
|
||||
transform: translateY(-50%);
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
@@ -2450,6 +2875,75 @@ button:disabled {
|
||||
0 0 0 1px rgba(103, 181, 255, 0.4);
|
||||
}
|
||||
|
||||
.sticker-track {
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.sticker-segment {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: var(--sticker-left, 0%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
width: var(--sticker-width, 8%);
|
||||
min-width: 76px;
|
||||
max-width: calc(100% - var(--sticker-left, 0%));
|
||||
height: 36px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||
border-radius: 5px;
|
||||
padding: 3px 8px 3px 4px;
|
||||
color: #e9f8fa;
|
||||
font-size: 11px;
|
||||
font-weight: 760;
|
||||
text-align: left;
|
||||
background:
|
||||
linear-gradient(135deg, rgba(53, 234, 217, 0.16), rgba(103, 181, 255, 0.12)),
|
||||
rgba(11, 18, 24, 0.92);
|
||||
cursor: grab;
|
||||
transform: translateY(-50%);
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.sticker-segment:hover {
|
||||
border-color: rgba(53, 234, 217, 0.72);
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
|
||||
.sticker-segment:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.sticker-segment.is-current {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.48);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.sticker-segment.is-selected-segment {
|
||||
border-color: rgba(103, 181, 255, 0.9);
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(103, 181, 255, 0.36),
|
||||
0 0 0 1px rgba(103, 181, 255, 0.28);
|
||||
}
|
||||
|
||||
.sticker-segment img {
|
||||
flex: 0 0 auto;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 4px 7px rgba(0, 0, 0, 0.25));
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.sticker-segment span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.caption-segment.is-hidden {
|
||||
color: #8a98a5;
|
||||
opacity: 0.48;
|
||||
@@ -2462,7 +2956,7 @@ button:disabled {
|
||||
color: transparent;
|
||||
opacity: 1;
|
||||
filter: none;
|
||||
transform: translateY(0);
|
||||
transform: translateY(-50%);
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
-45deg,
|
||||
@@ -2491,7 +2985,7 @@ button:disabled {
|
||||
|
||||
.caption-segment.is-reorder-target:not(.is-reorder-dragging) {
|
||||
filter: brightness(1.08);
|
||||
transform: translateY(3px);
|
||||
transform: translateY(calc(-50% + 3px));
|
||||
box-shadow:
|
||||
inset 0 0 0 2px rgba(53, 234, 217, 0.66),
|
||||
0 0 0 1px rgba(53, 234, 217, 0.24);
|
||||
@@ -2603,11 +3097,13 @@ button:disabled {
|
||||
|
||||
.image-track.is-selected,
|
||||
.caption-track.is-selected,
|
||||
.sticker-track.is-selected,
|
||||
.audio-track.is-selected {
|
||||
background: rgba(46, 234, 216, 0.035);
|
||||
}
|
||||
|
||||
.image-track.is-drop-target,
|
||||
.sticker-track.is-drop-target,
|
||||
.audio-track.is-drop-target {
|
||||
background:
|
||||
linear-gradient(90deg, rgba(46, 234, 216, 0.14), rgba(46, 234, 216, 0.035)),
|
||||
@@ -2618,6 +3114,7 @@ button:disabled {
|
||||
}
|
||||
|
||||
.image-track.is-drop-landing,
|
||||
.sticker-track.is-drop-landing,
|
||||
.audio-track.is-drop-landing {
|
||||
animation: track-drop-land 560ms ease;
|
||||
}
|
||||
@@ -2690,6 +3187,12 @@ button:disabled {
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.asset-drop-slot.type-sticker .asset-drop-slot-thumb img,
|
||||
.asset-drag-preview.type-sticker .asset-drag-thumb img {
|
||||
object-fit: contain;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.asset-drop-slot span,
|
||||
.asset-drop-slot strong {
|
||||
position: relative;
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
import { AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "../config/models.js";
|
||||
|
||||
const ASR_SAMPLE_RATE = 16000;
|
||||
const LANGUAGE_DETECTION_SECONDS = 20;
|
||||
|
||||
const UI_LANGUAGE_TO_WHISPER_LANGUAGE = {
|
||||
zh: "zh",
|
||||
en: "en",
|
||||
ja: "ja",
|
||||
ko: "ko",
|
||||
es: "es",
|
||||
fr: "fr",
|
||||
de: "de",
|
||||
pt: "pt",
|
||||
th: "th",
|
||||
vi: "vi",
|
||||
};
|
||||
|
||||
const WHISPER_LANGUAGE_NAMES = {
|
||||
zh: "中文",
|
||||
en: "English",
|
||||
ja: "日本語",
|
||||
ko: "한국어",
|
||||
es: "Español",
|
||||
fr: "Français",
|
||||
de: "Deutsch",
|
||||
pt: "Português",
|
||||
th: "ไทย",
|
||||
vi: "Tiếng Việt",
|
||||
};
|
||||
|
||||
let transcriberState = null;
|
||||
|
||||
function postProgress(requestId, progress, phase) {
|
||||
self.postMessage({
|
||||
type: "progress",
|
||||
requestId,
|
||||
progress,
|
||||
phase,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTokenId(value) {
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
function getGeneratedTokenIds(output) {
|
||||
const tensorLike = output?.sequences ?? output;
|
||||
const rawTokens =
|
||||
tensorLike?.[0] && typeof tensorLike[0].tolist === "function"
|
||||
? tensorLike[0].tolist()
|
||||
: typeof tensorLike?.tolist === "function"
|
||||
? tensorLike.tolist()
|
||||
: tensorLike;
|
||||
const firstSequence = Array.isArray(rawTokens?.[0]) ? rawTokens[0] : rawTokens;
|
||||
return Array.isArray(firstSequence)
|
||||
? firstSequence.map(normalizeTokenId).filter((token) => token !== null)
|
||||
: [];
|
||||
}
|
||||
|
||||
function getWhisperLanguageIdMap(transcriber) {
|
||||
const langToId = transcriber?.model?.generation_config?.lang_to_id;
|
||||
if (!langToId) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
return new Map(
|
||||
Object.entries(langToId)
|
||||
.map(([token, id]) => {
|
||||
const language = normalizeWhisperLanguageToken(token);
|
||||
return [normalizeTokenId(id), language];
|
||||
})
|
||||
.filter(([id, language]) => id !== null && language),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeWhisperLanguageToken(token) {
|
||||
const normalized = String(token ?? "").match(/^<\|?([a-z_]+)\|?>$/i)?.[1];
|
||||
return normalized || String(token ?? "").replace(/[<|>]/g, "");
|
||||
}
|
||||
|
||||
function getPreferredWhisperLanguage(preferredLanguage) {
|
||||
return UI_LANGUAGE_TO_WHISPER_LANGUAGE[preferredLanguage] ?? "zh";
|
||||
}
|
||||
|
||||
function getLanguageDetectionSample(audio) {
|
||||
const sampleLength = Math.min(audio.length, ASR_SAMPLE_RATE * LANGUAGE_DETECTION_SECONDS);
|
||||
return audio.subarray(0, sampleLength);
|
||||
}
|
||||
|
||||
function isMultilingualWhisper(transcriber) {
|
||||
return Boolean(transcriber?.model?.generation_config?.is_multilingual);
|
||||
}
|
||||
|
||||
function createModelLoadProgressCallback(requestId) {
|
||||
const progressByFile = new Map();
|
||||
let reportedProgress = 8;
|
||||
|
||||
return (event) => {
|
||||
const rawProgress = Number(event?.progress);
|
||||
if (!Number.isFinite(rawProgress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fileKey = event.file ?? event.name ?? event.url ?? "__model__";
|
||||
progressByFile.set(fileKey, Math.max(0, Math.min(100, rawProgress)));
|
||||
const totalProgress = Array.from(progressByFile.values()).reduce((sum, value) => sum + value, 0);
|
||||
const averageProgress = totalProgress / progressByFile.size;
|
||||
const nextProgress = Math.min(70, Math.max(8, Math.round(8 + averageProgress * 0.62)));
|
||||
if (nextProgress <= reportedProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
reportedProgress = nextProgress;
|
||||
postProgress(requestId, nextProgress, `下载或读取 ${AUTOMATIC_CAPTION_MODEL_LABEL} ONNX`);
|
||||
};
|
||||
}
|
||||
|
||||
function getPreferredInferenceDevice() {
|
||||
return "wasm";
|
||||
}
|
||||
|
||||
async function createTranscriber(requestId, device) {
|
||||
const { pipeline } = await import("@huggingface/transformers");
|
||||
return pipeline("automatic-speech-recognition", AUTOMATIC_CAPTION_MODEL_ID, {
|
||||
dtype: "q8",
|
||||
device,
|
||||
progress_callback: createModelLoadProgressCallback(requestId),
|
||||
});
|
||||
}
|
||||
|
||||
async function getTranscriber(requestId) {
|
||||
if (!transcriberState || transcriberState.modelId !== AUTOMATIC_CAPTION_MODEL_ID) {
|
||||
transcriberState = {
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
promise: (async () => {
|
||||
const preferredDevice = getPreferredInferenceDevice();
|
||||
try {
|
||||
postProgress(
|
||||
requestId,
|
||||
7,
|
||||
preferredDevice === "webgpu" ? "在 Worker 中初始化 WebGPU ONNX" : "在 Worker 中初始化 WASM ONNX",
|
||||
);
|
||||
return await createTranscriber(requestId, preferredDevice);
|
||||
} catch (error) {
|
||||
if (preferredDevice !== "webgpu") {
|
||||
throw error;
|
||||
}
|
||||
console.warn("Whisper WebGPU initialization failed, falling back to WASM.", error);
|
||||
postProgress(requestId, 7, "WebGPU 初始化失败,切换 WASM Worker");
|
||||
return createTranscriber(requestId, "wasm");
|
||||
}
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
return transcriberState.promise;
|
||||
}
|
||||
|
||||
async function detectWhisperLanguage(transcriber, audio, preferredLanguage, requestId) {
|
||||
const generationConfig = transcriber?.model?.generation_config;
|
||||
const fallbackLanguage = getPreferredWhisperLanguage(preferredLanguage);
|
||||
if (!isMultilingualWhisper(transcriber)) {
|
||||
return { language: "en", detected: false };
|
||||
}
|
||||
|
||||
const languageIdMap = getWhisperLanguageIdMap(transcriber);
|
||||
if (!languageIdMap.size) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
const decoderStartTokenId = normalizeTokenId(generationConfig.decoder_start_token_id);
|
||||
if (decoderStartTokenId === null) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
try {
|
||||
postProgress(requestId, 70, "识别音频语言");
|
||||
const sample = getLanguageDetectionSample(audio);
|
||||
const features = await transcriber.processor(sample);
|
||||
const output = await transcriber.model.generate({
|
||||
inputs: features.input_features,
|
||||
decoder_input_ids: [decoderStartTokenId],
|
||||
max_new_tokens: 1,
|
||||
return_timestamps: false,
|
||||
});
|
||||
const tokenIds = getGeneratedTokenIds(output);
|
||||
const languageTokenId = tokenIds.find((token) => token !== decoderStartTokenId && languageIdMap.has(token));
|
||||
const language = languageTokenId === undefined ? null : languageIdMap.get(languageTokenId);
|
||||
|
||||
return {
|
||||
language: language || fallbackLanguage,
|
||||
detected: Boolean(language),
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("Whisper language detection failed, falling back to preferred language.", error);
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
}
|
||||
|
||||
function serializeTimestamp(timestamp) {
|
||||
if (!Array.isArray(timestamp)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return timestamp.map((value) => {
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
});
|
||||
}
|
||||
|
||||
function serializeOutput(output) {
|
||||
return {
|
||||
text: String(output?.text ?? ""),
|
||||
chunks: Array.isArray(output?.chunks)
|
||||
? output.chunks.map((chunk) => ({
|
||||
text: String(chunk?.text ?? ""),
|
||||
timestamp: serializeTimestamp(chunk?.timestamp),
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
async function transcribe({ requestId, audioBuffer, preferredLanguage, modelId }) {
|
||||
if (modelId && modelId !== AUTOMATIC_CAPTION_MODEL_ID) {
|
||||
throw new Error("自动字幕模型版本已更新,请刷新后重新生成。");
|
||||
}
|
||||
|
||||
const audio = new Float32Array(audioBuffer);
|
||||
if (!audio.length) {
|
||||
throw new Error("没有检测到可识别的音频。");
|
||||
}
|
||||
|
||||
const transcriber = await getTranscriber(requestId);
|
||||
const languageResult = await detectWhisperLanguage(transcriber, audio, preferredLanguage, requestId);
|
||||
const languageLabel = WHISPER_LANGUAGE_NAMES[languageResult.language] ?? languageResult.language.toUpperCase();
|
||||
postProgress(
|
||||
requestId,
|
||||
74,
|
||||
`${languageResult.detected ? "检测为" : "按"} ${languageLabel} 转写字幕`,
|
||||
);
|
||||
|
||||
const transcriptionOptions = {
|
||||
chunk_length_s: 30,
|
||||
max_new_tokens: 224,
|
||||
no_repeat_ngram_size: 3,
|
||||
repetition_penalty: 1.15,
|
||||
stride_length_s: 5,
|
||||
return_timestamps: true,
|
||||
};
|
||||
if (isMultilingualWhisper(transcriber)) {
|
||||
transcriptionOptions.language = languageResult.language;
|
||||
transcriptionOptions.task = "transcribe";
|
||||
}
|
||||
|
||||
const output = await transcriber(audio, transcriptionOptions);
|
||||
self.postMessage({
|
||||
type: "result",
|
||||
requestId,
|
||||
output: serializeOutput(output),
|
||||
language: languageResult.language,
|
||||
languageDetected: languageResult.detected,
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
});
|
||||
}
|
||||
|
||||
self.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (message?.type !== "transcribe") {
|
||||
return;
|
||||
}
|
||||
|
||||
transcribe(message).catch((error) => {
|
||||
self.postMessage({
|
||||
type: "error",
|
||||
requestId: message.requestId,
|
||||
error: error instanceof Error ? error.message : "自动字幕生成失败",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user