Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
captions: run Whisper in a Web Worker, move auto-captions button to timeline
Siddharthe5462f1ac81e
diff --git a/package-lock.json b/package-lock.jsonindex 4862a12a5..d4abbfbbe 100644--- a/package-lock.json+++ b/package-lock.json@@ -7,7 +7,6 @@"": {"name": "openscreen","version": "1.4.0",- "hasInstallScript": true,"dependencies": {"@fix-webm-duration/fix": "^1.0.1","@pixi/filter-drop-shadow": "^5.2.0",diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsxindex ec46d8582..dda653274 100644--- a/src/components/video-editor/VideoEditor.tsx+++ b/src/components/video-editor/VideoEditor.tsx@@ -1,7 +1,6 @@import type { Span } from "dnd-timeline";import { FolderOpen, Languages, Save, Video } from "lucide-react";import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";-import { MdClosedCaption } from "react-icons/md";import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -2404,28 +2403,6 @@ export default function VideoEditor() {<Save size={14} />{ts("project.save")}</button>- <Button- type="button"- variant="ghost"- size="sm"- disabled={isAutoCaptioning || !videoPath}- onClick={() => {- if (!videoPath) {- toast.error(t("errors.noVideoLoaded"));- return;- }- if (isAutoCaptioningRef.current) {- toast.error(t("autoCaptions.busy"));- return;- }- setShowAutoCaptionsDialog(true);- }}- className="h-7 px-2 text-white/50 hover:text-white/90 hover:bg-white/10 text-[11px] font-medium gap-1"- style={{ WebkitAppRegion: "no-drag" } as CSSProperties}- >- <MdClosedCaption className="size-3.5 shrink-0" aria-hidden />- {t("autoCaptions.button")}- </Button></div></div>@@ -2781,6 +2758,19 @@ export default function VideoEditor() {}videoUrl={videoPath ?? undefined}showTrimWaveform={showTrimWaveform}+ captionsLabel={t("autoCaptions.button")}+ isGeneratingCaptions={isAutoCaptioning}+ onGenerateCaptions={() => {+ if (!videoPath) {+ toast.error(t("errors.noVideoLoaded"));+ return;+ }+ if (isAutoCaptioningRef.current) {+ toast.error(t("autoCaptions.busy"));+ return;+ }+ setShowAutoCaptionsDialog(true);+ }}/></div></Panel>diff --git a/src/components/video-editor/timeline/TimelineEditor.tsx b/src/components/video-editor/timeline/TimelineEditor.tsxindex f84d038a9..65ebd8bdb 100644--- a/src/components/video-editor/timeline/TimelineEditor.tsx+++ b/src/components/video-editor/timeline/TimelineEditor.tsx@@ -1,6 +1,7 @@import type { Range, Span } from "dnd-timeline";import { useTimelineContext } from "dnd-timeline";import {+ Captions,Check,ChevronDown,Gauge,@@ -92,6 +93,11 @@ interface TimelineEditorProps {onAspectRatioChange: (aspectRatio: AspectRatio) => void;videoUrl?: string;showTrimWaveform?: boolean;+ /** Opens the auto-captions flow. When omitted, the captions button is hidden. */+ onGenerateCaptions?: () => void;+ isGeneratingCaptions?: boolean;+ /** Localized label for the auto-captions button (lives in the `editor` namespace). */+ captionsLabel?: string;}interface TimelineScaleConfig {@@ -924,6 +930,9 @@ export default function TimelineEditor({onAspectRatioChange,videoUrl,showTrimWaveform = false,+ onGenerateCaptions,+ isGeneratingCaptions = false,+ captionsLabel,}: TimelineEditorProps) {const t = useScopedT("timeline");const totalMs = useMemo(() => Math.max(0, Math.round(videoDuration * 1000)), [videoDuration]);@@ -1659,6 +1668,18 @@ export default function TimelineEditor({><Gauge className="w-4 h-4" /></Button>+ {onGenerateCaptions && (+ <Button+ onClick={onGenerateCaptions}+ disabled={isGeneratingCaptions || !videoUrl}+ variant="ghost"+ size="icon"+ className="h-7 w-7 rounded-lg text-slate-400 hover:text-[#a78bfa] hover:bg-[#a78bfa]/10 transition-all"+ title={captionsLabel}+ >+ <Captions className="w-4 h-4" />+ </Button>+ )}</div><div className="flex items-center gap-1.5 min-w-0"><DropdownMenu>diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 336d3e6ba..0e94b9a9f 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -42,5 +42,24 @@"cameraNotFound": "Fotocamera non trovata.","permissionDenied": "Autorizzazione di registrazione negata. Consenti la registrazione dello schermo.","accessibilityAllowAndRetry": "Consenti l'accesso all'accessibilità per OpenScreen, poi premi di nuovo registra per avviare il conto alla rovescia."+ },+ "autoCaptions": {+ "button": "Sottotitoli automatici",+ "dialogTitle": "Sottotitoli automatici",+ "dialogDescription": "Scegli all'incirca quante parole mostrare per ogni sottotitolo. La temporizzazione viene distribuita tra le parole della frase.",+ "minWords": "Numero minimo di parole per sottotitolo",+ "maxWords": "Numero massimo di parole per sottotitolo",+ "wordsCount": "{{count}} parole",+ "generate": "Genera",+ "dialogCancel": "Annulla",+ "generating": "Generazione dei sottotitoli dall'audio…",+ "loadingModel": "Caricamento del modello vocale (al primo utilizzo vengono scaricati ~75 MB)…",+ "transcribing": "Trascrizione del parlato…",+ "busy": "La generazione dei sottotitoli è già in corso.",+ "done": "Aggiunti {{count}} sottotitoli.",+ "noneHeard": "Nessun parlato rilevato.",+ "noAudio": "Questo video non contiene audio utilizzabile per la trascrizione.",+ "failed": "Impossibile generare i sottotitoli.",+ "truncated": "Sono stati trascritti solo i primi {{minutes}} minuti."}}diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 7e3f69531..b0e9ab8c9 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -41,5 +41,24 @@"cameraDisconnected": "Webcam desconectada.","cameraNotFound": "Câmera não encontrada.","permissionDenied": "Permissão de gravação negada. Por favor, permita a gravação de tela."+ },+ "autoCaptions": {+ "button": "Legendas automáticas",+ "dialogTitle": "Legendas automáticas",+ "dialogDescription": "Escolha aproximadamente quantas palavras cada legenda mostra de cada vez. O tempo é distribuído entre as palavras da frase.",+ "minWords": "Mínimo de palavras por legenda",+ "maxWords": "Máximo de palavras por legenda",+ "wordsCount": "{{count}} palavras",+ "generate": "Gerar",+ "dialogCancel": "Cancelar",+ "generating": "Gerando legendas a partir do áudio…",+ "loadingModel": "Carregando o modelo de fala (o primeiro uso baixa ~75 MB)…",+ "transcribing": "Transcrevendo a fala…",+ "busy": "A geração de legendas já está em andamento.",+ "done": "{{count}} legendas adicionadas.",+ "noneHeard": "Nenhuma fala foi detectada.",+ "noAudio": "Este vídeo não tem áudio utilizável para transcrição.",+ "failed": "Não foi possível gerar as legendas.",+ "truncated": "Apenas os primeiros {{minutes}} minutos foram transcritos."}}diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex ff0c80b8b..78fa129a1 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -44,6 +44,25 @@"permissionDenied": "Разрешение на запись запрещено. Пожалуйста, разрешите запись экрана.","accessibilityAllowAndRetry": "Разрешите OpenScreen доступ к Универсальному доступу, затем снова нажмите запись, чтобы начать обратный отсчет."},+ "autoCaptions": {+ "button": "Автосубтитры",+ "dialogTitle": "Автосубтитры",+ "dialogDescription": "Выберите, сколько примерно слов показывать в одном субтитре. Время распределяется между словами фразы.",+ "minWords": "Минимум слов в субтитре",+ "maxWords": "Максимум слов в субтитре",+ "wordsCount": "{{count}} слов",+ "generate": "Создать",+ "dialogCancel": "Отмена",+ "generating": "Создание субтитров из звука…",+ "loadingModel": "Загрузка речевой модели (при первом запуске скачивается ~75 МБ)…",+ "transcribing": "Распознавание речи…",+ "busy": "Создание субтитров уже выполняется.",+ "done": "Добавлено субтитров: {{count}}.",+ "noneHeard": "Речь не обнаружена.",+ "noAudio": "В этом видео нет звука, пригодного для расшифровки.",+ "failed": "Не удалось создать субтитры.",+ "truncated": "Расшифрованы только первые {{minutes}} мин."+ },"emptyState": {"title": "Нет открытых проектов","description": "Импортируйте видео для начала редактирования или загрузите существующий проект OpenScreen.",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 1875bb559..90004091e 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -44,6 +44,25 @@"permissionDenied": "Quyền ghi hình bị từ chối. Vui lòng cho phép ghi màn hình.","accessibilityAllowAndRetry": "Cho phép OpenScreen truy cập Trợ năng, sau đó nhấn ghi lại để bắt đầu đếm ngược."},+ "autoCaptions": {+ "button": "Phụ đề tự động",+ "dialogTitle": "Phụ đề tự động",+ "dialogDescription": "Chọn khoảng bao nhiêu từ mỗi phụ đề hiển thị cùng lúc. Thời gian được phân bổ cho các từ trong cụm từ đó.",+ "minWords": "Số từ tối thiểu mỗi phụ đề",+ "maxWords": "Số từ tối đa mỗi phụ đề",+ "wordsCount": "{{count}} từ",+ "generate": "Tạo",+ "dialogCancel": "Hủy",+ "generating": "Đang tạo phụ đề từ âm thanh…",+ "loadingModel": "Đang tải mô hình giọng nói (lần đầu sử dụng sẽ tải ~75 MB)…",+ "transcribing": "Đang chuyển lời nói thành văn bản…",+ "busy": "Việc tạo phụ đề đang được tiến hành.",+ "done": "Đã thêm {{count}} phụ đề.",+ "noneHeard": "Không phát hiện thấy lời nói.",+ "noAudio": "Video này không có âm thanh dùng được để chuyển thành văn bản.",+ "failed": "Không thể tạo phụ đề.",+ "truncated": "Chỉ {{minutes}} phút đầu tiên được chuyển thành văn bản."+ },"emptyState": {"title": "Không có dự án nào được mở","description": "Nhập video để bắt đầu chỉnh sửa hoặc tải một dự án OpenScreen hiện có.",diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.tsindex e85f15157..91f1d91f0 100644--- a/src/lib/captioning/transcribe.ts+++ b/src/lib/captioning/transcribe.ts@@ -14,209 +14,27 @@ export interface TranscribeMono16kResult {granularity: CaptionTimestampGranularity;}-function segmentOverlapsTrim(startMs: number, endMs: number, trims: TrimRegion[]): boolean {- return trims.some((t) => startMs < t.endMs && endMs > t.startMs);+/** Request payload posted from the renderer to the transcription worker. */+export interface TranscribeWorkerRequest {+ samples: Float32Array;+ trimRegions: TrimRegion[];}-/** Same trim-out rule as {@link segmentsFromTranscriberChunks}; for retry passes that used empty trims. */-function dropSegmentsOverlappingTrimRegions(- segments: CaptionSegment[],- trimRegions: TrimRegion[],-): CaptionSegment[] {- if (trimRegions.length === 0) return segments;- return segments.filter((s) => {- const startMs = Math.round(s.startSec * 1000);- const endMs = Math.round(s.endSec * 1000);- return !segmentOverlapsTrim(startMs, endMs, trimRegions);- });-}--/** Lets the browser paint toast / in-app status before Whisper blocks the main thread (WASM may not yield). */-async function yieldForUiPaint(): Promise<void> {- await new Promise<void>((resolve) => setTimeout(resolve, 0));- await new Promise<void>((resolve) => {- requestAnimationFrame(() => {- requestAnimationFrame(() => resolve());- });- });- // macrotask after rAF so React/Sonner state can commit under load.- await new Promise<void>((resolve) => setTimeout(resolve, 0));-}+/** Messages the transcription worker posts back to the renderer. */+export type TranscribeWorkerResponse =+ | { type: "status"; phase: "model" | "transcribe" }+ | { type: "result"; segments: CaptionSegment[]; granularity: CaptionTimestampGranularity }+ | { type: "error"; message: string };/**- * ONNX Runtime's wasm bundle treats `process.versions.node` (present in Electron's- * renderer) as Node and tries `require("fs")`, which Vite does not support. Mask it- * only while Transformers / ORT run.+ * Transcribes mono 16 kHz audio into timed caption segments using in-browser Whisper.+ *+ * The model load and inference run inside a dedicated Web Worker so the editor's+ * main thread stays responsive (WASM inference does not yield). The first run+ * downloads model weights. Aborting (via `options.signal`) terminates the worker+ * immediately, since model load / inference cannot be cooperatively cancelled.*/-function withoutNodeVersion<T>(fn: () => Promise<T>): Promise<T> {- const versions =- typeof process !== "undefined" && process.versions && typeof process.versions === "object"- ? process.versions- : null;- const hadNode = versions !== null && "node" in versions;- const savedNode = hadNode ? (versions as { node?: string }).node : undefined;- if (hadNode && versions) {- try {- Reflect.deleteProperty(versions, "node");- } catch {- (versions as { node?: string }).node = undefined;- }- }- return fn().finally(() => {- if (hadNode && versions && savedNode !== undefined) {- (versions as { node: string }).node = savedNode;- }- });-}--/** Whisper runs with internal 30s chunks; keep each forward pass bounded for WASM memory. */-const TRANSCRIBE_SLICE_SAMPLES = 12 * 60 * 16_000;--/** Very short slices are skipped in the multi-slice loop unless padded (see `padTailSliceForTranscribe`). */-const MIN_TRANSCRIBE_SLICE_SAMPLES = 800;--/**- * Pad a short tail slice so Whisper still runs; timestamps are clamped with `realDurationSec` so- * padding does not extend perceived audio on the timeline.- */-function padTailSliceForTranscribe(samples: Float32Array): {- slice: Float32Array;- realDurationSec: number;-} {- const realDurationSec = samples.length / 16_000;- if (samples.length >= MIN_TRANSCRIBE_SLICE_SAMPLES) {- return { slice: samples, realDurationSec };- }- const padded = new Float32Array(MIN_TRANSCRIBE_SLICE_SAMPLES);- padded.set(samples);- return { slice: padded, realDurationSec };-}--function segmentsFromTranscriberChunks(- chunks: Array<{ timestamp?: [number | null, number | null]; text?: unknown }>,- timeOffsetSec: number,- trims: TrimRegion[],- audioDurationSec: number,-): CaptionSegment[] {- const sorted = [...chunks].sort((x, y) => {- const ax = x.timestamp?.[0];- const ay = y.timestamp?.[0];- const na = typeof ax === "number" ? ax : -1;- const nb = typeof ay === "number" ? ay : -1;- return na - nb;- });-- const segments: CaptionSegment[] = [];-- for (let idx = 0; idx < sorted.length; idx++) {- const c = sorted[idx]!;- const ts = c.timestamp as [number | null, number | null] | undefined;- if (!ts) continue;- let a = ts[0];- let b = ts[1];- if (a == null) a = 0;- a = Math.max(0, a);- if (b == null) {- let nextStart: number | null = null;- for (let j = idx + 1; j < sorted.length; j++) {- const na = sorted[j]?.timestamp?.[0];- if (typeof na === "number") {- nextStart = na;- break;- }- }- b = nextStart ?? audioDurationSec;- }- if (b <= a) {- b = Math.min(a + 0.25, audioDurationSec);- }- b = Math.min(b, audioDurationSec);-- const text = String(c.text ?? "")- .replace(/\s+/g, " ")- .trim();- if (!text) continue;-- const startSec = a + timeOffsetSec;- const sliceEnd = timeOffsetSec + audioDurationSec;- const endSec = Math.min(Math.max(startSec + 0.08, b + timeOffsetSec), sliceEnd);- const startMs = Math.round(startSec * 1000);- const endMs = Math.round(endSec * 1000);- if (segmentOverlapsTrim(startMs, endMs, trims)) continue;-- segments.push({ startSec, endSec, text });- }-- segments.sort((u, v) => u.startSec - v.startSec || u.endSec - v.endSec);- const rawDeduped: CaptionSegment[] = [];- for (const seg of segments) {- const prev = rawDeduped[rawDeduped.length - 1];- if (prev && prev.text === seg.text && seg.startSec <= prev.endSec) {- prev.endSec = Math.max(prev.endSec, seg.endSec);- prev.startSec = Math.min(prev.startSec, seg.startSec);- continue;- }- rawDeduped.push(seg);- }- return rawDeduped;-}--async function runTranscriberOnSlice(- transcriber: (audio: Float32Array, opts: Record<string, unknown>) => Promise<unknown>,- samples: Float32Array,- opts: { forceFullSequences: boolean; timestampMode: "word" | "phrase" },-): Promise<unknown> {- const durationSec = samples.length / 16_000;- // Only chunk long clips; short-audio chunking regressed some Whisper.js runs (empty chunks).- const chunking = durationSec > 30 ? { chunk_length_s: 30, stride_length_s: 5 } : {};- return transcriber(samples, {- return_timestamps: opts.timestampMode === "word" ? "word" : true,- force_full_sequences: opts.forceFullSequences,- ...chunking,- });-}--function getChunksFromTranscriberResult(result: unknown): Array<{- timestamp?: [number | null, number | null];- text?: unknown;-}> {- if (result == null) return [];- if (Array.isArray(result)) {- const out: Array<{ timestamp?: [number | null, number | null]; text?: unknown }> = [];- for (const item of result) {- const chunks = (item as { chunks?: unknown })?.chunks;- if (Array.isArray(chunks)) out.push(...chunks);- }- return out;- }- const chunks = (result as { chunks?: unknown })?.chunks;- return Array.isArray(chunks) ? chunks : [];-}--/** Prefer `chunks`; if the model only returned top-level `text`, synthesize one span for timing. */-function extractChunksFromAsrResult(result: unknown): Array<{- timestamp?: [number | null, number | null];- text?: unknown;-}> {- const fromChunks = getChunksFromTranscriberResult(result);- if (fromChunks.length > 0) return fromChunks;- const single = Array.isArray(result) ? result[0] : result;- const text =- typeof (single as { text?: unknown })?.text === "string"- ? String((single as { text: string }).text).trim()- : "";- if (text) {- return [{ timestamp: [0, null], text }];- }- return [];-}--/**- * Runs Whisper in-browser via Transformers.js. First run downloads model weights.- * Long audio is split into slices so one forward pass does not exhaust WASM memory;- * timestamps are shifted to the full timeline.- */-export async function transcribeMono16kToSegments(+export function transcribeMono16kToSegments(samples: Float32Array,options?: {trimRegions?: TrimRegion[];@@ -224,112 +42,50 @@ export async function transcribeMono16kToSegments(signal?: AbortSignal;},): Promise<TranscribeMono16kResult> {- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");-- const { transcriber } = await withoutNodeVersion(async () => {- const { pipeline, env } = await import("@xenova/transformers");- env.allowLocalModels = false;-- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");-- options?.onStatus?.("model");- // Default tiny weights only: the `output_attentions` revision has regressed inference for- // some environments (empty chunks / thrown errors) while phrase mode works on this model.- const t = await pipeline("automatic-speech-recognition", "Xenova/whisper-tiny");- return { transcriber: t };- });-- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");-- await yieldForUiPaint();-- const trims = options?.trimRegions ?? [];- options?.onStatus?.("transcribe");- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");- await yieldForUiPaint();- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");-- const transcribeOne = async (- ignoreTrims: boolean,- forceFullSequences: boolean,- timestampMode: "word" | "phrase",- ): Promise<CaptionSegment[]> => {- try {- const activeTrims = ignoreTrims ? [] : trims;- if (samples.length <= TRANSCRIBE_SLICE_SAMPLES) {- const { slice, realDurationSec } = padTailSliceForTranscribe(samples);- const result = await runTranscriberOnSlice(transcriber, slice, {- forceFullSequences,- timestampMode,- });- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");- return segmentsFromTranscriberChunks(- extractChunksFromAsrResult(result),- 0,- activeTrims,- realDurationSec,- );- }-- const all: CaptionSegment[] = [];- for (let offset = 0; offset < samples.length; offset += TRANSCRIBE_SLICE_SAMPLES) {- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");- const end = Math.min(offset + TRANSCRIBE_SLICE_SAMPLES, samples.length);- const sliceRaw = samples.subarray(offset, end);- const isFinalSlice = end >= samples.length;- if (sliceRaw.length === 0) continue;- if (sliceRaw.length < MIN_TRANSCRIBE_SLICE_SAMPLES && !isFinalSlice) continue;+ if (options?.signal?.aborted) {+ return Promise.reject(new DOMException("Aborted", "AbortError"));+ }- const { slice, realDurationSec } =- sliceRaw.length < MIN_TRANSCRIBE_SLICE_SAMPLES && isFinalSlice- ? padTailSliceForTranscribe(sliceRaw)- : { slice: sliceRaw, realDurationSec: sliceRaw.length / 16_000 };+ return new Promise<TranscribeMono16kResult>((resolve, reject) => {+ const worker = new Worker(new URL("./transcribe.worker.ts", import.meta.url), {+ type: "module",+ });- const result = await runTranscriberOnSlice(transcriber, slice, {- forceFullSequences,- timestampMode,- });- if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");- const tOff = offset / 16_000;- all.push(- ...segmentsFromTranscriberChunks(- extractChunksFromAsrResult(result),- tOff,- activeTrims,- realDurationSec,- ),- );+ let settled = false;+ const finish = (fn: () => void) => {+ if (settled) return;+ settled = true;+ options?.signal?.removeEventListener("abort", onAbort);+ worker.terminate();+ fn();+ };++ const onAbort = () => finish(() => reject(new DOMException("Aborted", "AbortError")));+ options?.signal?.addEventListener("abort", onAbort, { once: true });++ worker.onmessage = (e: MessageEvent<TranscribeWorkerResponse>) => {+ const msg = e.data;+ if (msg.type === "status") {+ options?.onStatus?.(msg.phase);+ return;}- return all;- } catch (e) {- if (e instanceof DOMException && e.name === "AbortError") throw e;- console.warn("[captioning] Whisper pass failed:", e);- return [];- }- };-- const attemptModes: Array<"word" | "phrase"> = ["word", "phrase"];- for (const timestampMode of attemptModes) {- let segments = await transcribeOne(false, true, timestampMode);- if (segments.length === 0) {- segments = await transcribeOne(false, false, timestampMode);- }- if (segments.length === 0 && trims.length > 0) {- segments = dropSegmentsOverlappingTrimRegions(- await transcribeOne(true, true, timestampMode),- trims,- );- if (segments.length === 0) {- segments = dropSegmentsOverlappingTrimRegions(- await transcribeOne(true, false, timestampMode),- trims,- );+ if (msg.type === "result") {+ finish(() => resolve({ segments: msg.segments, granularity: msg.granularity }));+ return;}- }- if (segments.length > 0) {- return { segments, granularity: timestampMode };- }- }-- return { segments: [], granularity: "phrase" };+ finish(() => reject(new Error(msg.message)));+ };++ worker.onerror = (e) => {+ finish(() => reject(new Error(e.message || "Caption transcription worker failed")));+ };++ // Structured-clone copy (not a transfer): the caller may reuse `samples`+ // for the full-buffer retry pass, so the buffer must stay valid here.+ const request: TranscribeWorkerRequest = {+ samples,+ trimRegions: options?.trimRegions ?? [],+ };+ worker.postMessage(request);+ });}diff --git a/src/lib/captioning/transcribe.worker.ts b/src/lib/captioning/transcribe.worker.tsnew file mode 100644index 000000000..edd16e8ec--- /dev/null+++ b/src/lib/captioning/transcribe.worker.ts@@ -0,0 +1,81 @@+/**+ * Web Worker: runs in-browser Whisper transcription off the renderer's main+ * thread so the editor UI never blocks while the model loads or audio is+ * transcribed.+ *+ * Input message: { samples: Float32Array; trimRegions: TrimRegion[] }+ * Output messages (see `TranscribeWorkerResponse`):+ * { type: "status", phase: "model" | "transcribe" } progress updates+ * { type: "result", segments, granularity } final captions+ * { type: "error", message } failure detail+ *+ * The caller terminates this worker to abort (model load / inference cannot be+ * cooperatively cancelled), so there is no in-worker abort handling.+ */++import type { TranscribeWorkerRequest, TranscribeWorkerResponse } from "./transcribe";+import { runTranscription, type TranscriberFn } from "./transcribeCore";++function post(message: TranscribeWorkerResponse): void {+ (self as unknown as Worker).postMessage(message);+}++/**+ * ONNX Runtime's wasm bundle treats `process.versions.node` (which can leak into+ * an Electron worker) as Node and tries `require("fs")`, which Vite does not+ * support. Mask it only while Transformers / ORT run. No-op when `process` is+ * undefined (the usual case in a Web Worker).+ */+function withoutNodeVersion<T>(fn: () => Promise<T>): Promise<T> {+ const versions =+ typeof process !== "undefined" && process.versions && typeof process.versions === "object"+ ? process.versions+ : null;+ const hadNode = versions !== null && "node" in versions;+ const savedNode = hadNode ? (versions as { node?: string }).node : undefined;+ if (hadNode && versions) {+ try {+ Reflect.deleteProperty(versions, "node");+ } catch {+ (versions as { node?: string }).node = undefined;+ }+ }+ return fn().finally(() => {+ if (hadNode && versions && savedNode !== undefined) {+ (versions as { node: string }).node = savedNode;+ }+ });+}++async function loadTranscriber(): Promise<TranscriberFn> {+ return withoutNodeVersion(async () => {+ const { pipeline, env } = await import("@xenova/transformers");+ env.allowLocalModels = false;+ // Default tiny weights only: the `output_attentions` revision has regressed inference for+ // some environments (empty chunks / thrown errors) while phrase mode works on this model.+ const transcriber = (await pipeline(+ "automatic-speech-recognition",+ "Xenova/whisper-tiny",+ )) as unknown as TranscriberFn;+ return transcriber;+ });+}++self.onmessage = async (event: MessageEvent<TranscribeWorkerRequest>) => {+ const { samples, trimRegions } = event.data;+ try {+ post({ type: "status", phase: "model" });+ const transcriber = await loadTranscriber();++ post({ type: "status", phase: "transcribe" });+ const { segments, granularity } = await runTranscription(+ transcriber,+ samples,+ trimRegions ?? [],+ );++ post({ type: "result", segments, granularity });+ } catch (e) {+ post({ type: "error", message: e instanceof Error ? e.message : String(e) });+ }+};diff --git a/src/lib/captioning/transcribeCore.ts b/src/lib/captioning/transcribeCore.tsnew file mode 100644index 000000000..111995246--- /dev/null+++ b/src/lib/captioning/transcribeCore.ts@@ -0,0 +1,269 @@+import type { TrimRegion } from "@/components/video-editor/types";+import type { CaptionSegment, TranscribeMono16kResult } from "./transcribe";++/**+ * Pure transcription algorithm shared by the captioning Web Worker. It takes an+ * already-constructed Whisper `transcriber` and turns mono 16 kHz audio into+ * timed caption segments. Kept free of DOM / Transformers.js imports so it can+ * run inside a worker and be unit-tested in isolation.+ */++/** A Transformers.js automatic-speech-recognition pipeline call. */+export type TranscriberFn = (+ audio: Float32Array,+ opts: Record<string, unknown>,+) => Promise<unknown>;++function segmentOverlapsTrim(startMs: number, endMs: number, trims: TrimRegion[]): boolean {+ return trims.some((t) => startMs < t.endMs && endMs > t.startMs);+}++/** Same trim-out rule as {@link segmentsFromTranscriberChunks}; for retry passes that used empty trims. */+function dropSegmentsOverlappingTrimRegions(+ segments: CaptionSegment[],+ trimRegions: TrimRegion[],+): CaptionSegment[] {+ if (trimRegions.length === 0) return segments;+ return segments.filter((s) => {+ const startMs = Math.round(s.startSec * 1000);+ const endMs = Math.round(s.endSec * 1000);+ return !segmentOverlapsTrim(startMs, endMs, trimRegions);+ });+}++/** Whisper runs with internal 30s chunks; keep each forward pass bounded for WASM memory. */+const TRANSCRIBE_SLICE_SAMPLES = 12 * 60 * 16_000;++/** Very short slices are skipped in the multi-slice loop unless padded (see `padTailSliceForTranscribe`). */+const MIN_TRANSCRIBE_SLICE_SAMPLES = 800;++/**+ * Pad a short tail slice so Whisper still runs; timestamps are clamped with `realDurationSec` so+ * padding does not extend perceived audio on the timeline.+ */+function padTailSliceForTranscribe(samples: Float32Array): {+ slice: Float32Array;+ realDurationSec: number;+} {+ const realDurationSec = samples.length / 16_000;+ if (samples.length >= MIN_TRANSCRIBE_SLICE_SAMPLES) {+ return { slice: samples, realDurationSec };+ }+ const padded = new Float32Array(MIN_TRANSCRIBE_SLICE_SAMPLES);+ padded.set(samples);+ return { slice: padded, realDurationSec };+}++/** Converts raw Whisper chunk output into sorted, deduped, trim-filtered caption segments. */+function segmentsFromTranscriberChunks(+ chunks: Array<{ timestamp?: [number | null, number | null]; text?: unknown }>,+ timeOffsetSec: number,+ trims: TrimRegion[],+ audioDurationSec: number,+): CaptionSegment[] {+ const sorted = [...chunks].sort((x, y) => {+ const ax = x.timestamp?.[0];+ const ay = y.timestamp?.[0];+ const na = typeof ax === "number" ? ax : -1;+ const nb = typeof ay === "number" ? ay : -1;+ return na - nb;+ });++ const segments: CaptionSegment[] = [];++ for (let idx = 0; idx < sorted.length; idx++) {+ const c = sorted[idx]!;+ const ts = c.timestamp as [number | null, number | null] | undefined;+ if (!ts) continue;+ let a = ts[0];+ let b = ts[1];+ if (a == null) a = 0;+ a = Math.max(0, a);+ if (b == null) {+ let nextStart: number | null = null;+ for (let j = idx + 1; j < sorted.length; j++) {+ const na = sorted[j]?.timestamp?.[0];+ if (typeof na === "number") {+ nextStart = na;+ break;+ }+ }+ b = nextStart ?? audioDurationSec;+ }+ if (b <= a) {+ b = Math.min(a + 0.25, audioDurationSec);+ }+ b = Math.min(b, audioDurationSec);++ const text = String(c.text ?? "")+ .replace(/\s+/g, " ")+ .trim();+ if (!text) continue;++ const startSec = a + timeOffsetSec;+ const sliceEnd = timeOffsetSec + audioDurationSec;+ const endSec = Math.min(Math.max(startSec + 0.08, b + timeOffsetSec), sliceEnd);+ const startMs = Math.round(startSec * 1000);+ const endMs = Math.round(endSec * 1000);+ if (segmentOverlapsTrim(startMs, endMs, trims)) continue;++ segments.push({ startSec, endSec, text });+ }++ segments.sort((u, v) => u.startSec - v.startSec || u.endSec - v.endSec);+ const rawDeduped: CaptionSegment[] = [];+ for (const seg of segments) {+ const prev = rawDeduped[rawDeduped.length - 1];+ if (prev && prev.text === seg.text && seg.startSec <= prev.endSec) {+ prev.endSec = Math.max(prev.endSec, seg.endSec);+ prev.startSec = Math.min(prev.startSec, seg.startSec);+ continue;+ }+ rawDeduped.push(seg);+ }+ return rawDeduped;+}++/** Runs the transcriber on one audio slice, chunking only long clips. */+async function runTranscriberOnSlice(+ transcriber: TranscriberFn,+ samples: Float32Array,+ opts: { forceFullSequences: boolean; timestampMode: "word" | "phrase" },+): Promise<unknown> {+ const durationSec = samples.length / 16_000;+ // Only chunk long clips; short-audio chunking regressed some Whisper.js runs (empty chunks).+ const chunking = durationSec > 30 ? { chunk_length_s: 30, stride_length_s: 5 } : {};+ return transcriber(samples, {+ return_timestamps: opts.timestampMode === "word" ? "word" : true,+ force_full_sequences: opts.forceFullSequences,+ ...chunking,+ });+}++/** Flattens the various shapes a Transformers.js ASR result can take into a chunk list. */+function getChunksFromTranscriberResult(result: unknown): Array<{+ timestamp?: [number | null, number | null];+ text?: unknown;+}> {+ if (result == null) return [];+ if (Array.isArray(result)) {+ const out: Array<{ timestamp?: [number | null, number | null]; text?: unknown }> = [];+ for (const item of result) {+ const chunks = (item as { chunks?: unknown })?.chunks;+ if (Array.isArray(chunks)) out.push(...chunks);+ }+ return out;+ }+ const chunks = (result as { chunks?: unknown })?.chunks;+ return Array.isArray(chunks) ? chunks : [];+}++/** Prefer `chunks`; if the model only returned top-level `text`, synthesize one span for timing. */+function extractChunksFromAsrResult(result: unknown): Array<{+ timestamp?: [number | null, number | null];+ text?: unknown;+}> {+ const fromChunks = getChunksFromTranscriberResult(result);+ if (fromChunks.length > 0) return fromChunks;+ const single = Array.isArray(result) ? result[0] : result;+ const text =+ typeof (single as { text?: unknown })?.text === "string"+ ? String((single as { text: string }).text).trim()+ : "";+ if (text) {+ return [{ timestamp: [0, null], text }];+ }+ return [];+}++/**+ * Drives Whisper over (possibly sliced) mono 16 kHz audio and returns timed segments.+ * Long audio is split so one forward pass does not exhaust WASM memory; timestamps are+ * shifted back onto the full timeline. Tries word- then phrase-level timestamps, with a+ * trim-ignoring retry, before giving up.+ */+export async function runTranscription(+ transcriber: TranscriberFn,+ samples: Float32Array,+ trims: TrimRegion[],+): Promise<TranscribeMono16kResult> {+ const transcribeOne = async (+ ignoreTrims: boolean,+ forceFullSequences: boolean,+ timestampMode: "word" | "phrase",+ ): Promise<CaptionSegment[]> => {+ try {+ const activeTrims = ignoreTrims ? [] : trims;+ if (samples.length <= TRANSCRIBE_SLICE_SAMPLES) {+ const { slice, realDurationSec } = padTailSliceForTranscribe(samples);+ const result = await runTranscriberOnSlice(transcriber, slice, {+ forceFullSequences,+ timestampMode,+ });+ return segmentsFromTranscriberChunks(+ extractChunksFromAsrResult(result),+ 0,+ activeTrims,+ realDurationSec,+ );+ }++ const all: CaptionSegment[] = [];+ for (let offset = 0; offset < samples.length; offset += TRANSCRIBE_SLICE_SAMPLES) {+ const end = Math.min(offset + TRANSCRIBE_SLICE_SAMPLES, samples.length);+ const sliceRaw = samples.subarray(offset, end);+ const isFinalSlice = end >= samples.length;+ if (sliceRaw.length === 0) continue;+ if (sliceRaw.length < MIN_TRANSCRIBE_SLICE_SAMPLES && !isFinalSlice) continue;++ const { slice, realDurationSec } =+ sliceRaw.length < MIN_TRANSCRIBE_SLICE_SAMPLES && isFinalSlice+ ? padTailSliceForTranscribe(sliceRaw)+ : { slice: sliceRaw, realDurationSec: sliceRaw.length / 16_000 };++ const result = await runTranscriberOnSlice(transcriber, slice, {+ forceFullSequences,+ timestampMode,+ });+ const tOff = offset / 16_000;+ all.push(+ ...segmentsFromTranscriberChunks(+ extractChunksFromAsrResult(result),+ tOff,+ activeTrims,+ realDurationSec,+ ),+ );+ }+ return all;+ } catch (e) {+ console.warn("[captioning] Whisper pass failed:", e);+ return [];+ }+ };++ const attemptModes: Array<"word" | "phrase"> = ["word", "phrase"];+ for (const timestampMode of attemptModes) {+ let segments = await transcribeOne(false, true, timestampMode);+ if (segments.length === 0) {+ segments = await transcribeOne(false, false, timestampMode);+ }+ if (segments.length === 0 && trims.length > 0) {+ segments = dropSegmentsOverlappingTrimRegions(+ await transcribeOne(true, true, timestampMode),+ trims,+ );+ if (segments.length === 0) {+ segments = dropSegmentsOverlappingTrimRegions(+ await transcribeOne(true, false, timestampMode),+ trims,+ );+ }+ }+ if (segments.length > 0) {+ return { segments, granularity: timestampMode };+ }+ }++ return { segments: [], granularity: "phrase" };+}diff --git a/vite.config.ts b/vite.config.tsindex 914b307e5..213e44711 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -39,6 +39,11 @@ export default defineConfig({optimizeDeps: {exclude: ["@xenova/transformers"],},+ // The captioning worker dynamically imports @xenova/transformers, which makes the+ // worker bundle code-split — unsupported by the default "iife" worker format.+ worker: {+ format: "es",+ },build: {target: "esnext",minify: "terser",