Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

perf(transcription): extract audio natively, off the UI thread

EtienneLescotc6b328c5bc07
diff --git a/electron/stt/extractAudio.test.ts b/electron/stt/extractAudio.test.ts
new file mode 100644
index 000000000..24e9694c8
--- /dev/null
+++ b/electron/stt/extractAudio.test.ts
@@ -0,0 +1,141 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const spawnMock = vi.fn();
+const resolveFfmpegMock = vi.fn<() => string | null>();
+
+vi.mock("node:child_process", () => ({ spawn: (...args: unknown[]) => spawnMock(...args) }));
+vi.mock("../media/audioPeaks", () => ({ resolveFfmpeg: () => resolveFfmpegMock() }));
+
+const { extractMono16kPcm, FfmpegUnavailableError, NoAudioTrackError } = await import(
+ "./extractAudio"
+);
+const { STT_NATIVE_EXTRACTION_UNAVAILABLE } = await import("./transcriptionContract");
+
+/** A stand-in for the ffmpeg child: two pipes and a close event, nothing more. */
+function fakeChild() {
+ const child = new EventEmitter() as EventEmitter & {
+ stdout: PassThrough;
+ stderr: PassThrough;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.kill = vi.fn();
+ return child;
+}
+
+/** The little-endian float32 bytes ffmpeg would emit for `values`. */
+function f32le(values: number[]): Buffer {
+ const buf = Buffer.alloc(values.length * 4);
+ values.forEach((v, i) => buf.writeFloatLE(v, i * 4));
+ return buf;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ resolveFfmpegMock.mockReturnValue("/usr/bin/ffmpeg");
+});
+
+describe("extractMono16kPcm", () => {
+ it("asks ffmpeg for exactly what whisper wants", async () => {
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const promise = extractMono16kPcm("/tmp/a.mp3");
+ child.stdout.end(f32le([0.5]));
+ child.emit("close", 0);
+ await promise;
+
+ const args = spawnMock.mock.calls[0][1] as string[];
+ // Mono, 16 kHz, float32 little-endian, no video. Anything else and whisper is
+ // reading the samples wrong rather than failing loudly.
+ expect(args).toContain("-vn");
+ expect(args.join(" ")).toContain("-ac 1");
+ expect(args.join(" ")).toContain("-ar 16000");
+ expect(args.join(" ")).toContain("-f f32le");
+ });
+
+ it("decodes the samples ffmpeg writes", async () => {
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const promise = extractMono16kPcm("/tmp/a.mp3");
+ child.stdout.end(f32le([0, 0.5, -0.25]));
+ child.emit("close", 0);
+
+ const out = await promise;
+ expect(Array.from(out)).toEqual([0, 0.5, -0.25]);
+ });
+
+ it("carries a float split across two chunks instead of dropping it", async () => {
+ // THE defect worth a test here: stdout chunk boundaries do not respect sample
+ // boundaries. Dropping the partial tail would shift every following sample and
+ // detune the whole track — audible, and invisible in a length check.
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const promise = extractMono16kPcm("/tmp/a.mp3");
+ const bytes = f32le([0.25, -0.75, 1]);
+ child.stdout.write(bytes.subarray(0, 6)); // one whole float + half of the next
+ child.stdout.write(bytes.subarray(6));
+ child.stdout.end();
+ child.emit("close", 0);
+
+ const out = await promise;
+ expect(Array.from(out)).toEqual([0.25, -0.75, 1]);
+ });
+
+ it("reports a file with no audio track", async () => {
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const promise = extractMono16kPcm("/tmp/silent.mp4");
+ child.stderr.end("Stream map '0:a' matches no streams");
+ child.stdout.end();
+ child.emit("close", 1);
+
+ await expect(promise).rejects.toBeInstanceOf(NoAudioTrackError);
+ });
+
+ it("keeps the samples when ffmpeg exits non-zero AFTER writing audio", async () => {
+ // A truncated file still yields usable audio; throwing it away would lose a
+ // transcript over a trailing byte.
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const promise = extractMono16kPcm("/tmp/truncated.mp3");
+ child.stdout.end(f32le([0.1, 0.2]));
+ child.emit("close", 1);
+
+ expect(Array.from(await promise)).toEqual([expect.closeTo(0.1, 6), expect.closeTo(0.2, 6)]);
+ });
+
+ it("refuses with the marker the renderer falls back on when ffmpeg is missing", async () => {
+ // The string is the contract across the IPC boundary, which drops the class.
+ resolveFfmpegMock.mockReturnValue(null);
+ await expect(extractMono16kPcm("/tmp/a.mp3")).rejects.toBeInstanceOf(FfmpegUnavailableError);
+ await expect(extractMono16kPcm("/tmp/a.mp3")).rejects.toThrow(
+ STT_NATIVE_EXTRACTION_UNAVAILABLE,
+ );
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it("kills the child when the caller aborts", async () => {
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const controller = new AbortController();
+ const promise = extractMono16kPcm("/tmp/a.mp3", { signal: controller.signal });
+ controller.abort();
+
+ await expect(promise).rejects.toMatchObject({ name: "AbortError" });
+ // Not merely stopping to await: ffmpeg would keep decoding a long file for
+ // minutes, which is the same leak the STT cancel path exists to prevent.
+ expect(child.kill).toHaveBeenCalled();
+ });
+
+ it("does not spawn at all when the signal is already aborted", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(
+ extractMono16kPcm("/tmp/a.mp3", { signal: controller.signal }),
+ ).rejects.toMatchObject({ name: "AbortError" });
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/electron/stt/extractAudio.ts b/electron/stt/extractAudio.ts
new file mode 100644
index 000000000..08168d21e
--- /dev/null
+++ b/electron/stt/extractAudio.ts
@@ -0,0 +1,152 @@
+// Native mono-16k extraction for transcription, in the main process.
+//
+// The renderer used to do this: `extractMono16kFromVideoUrl` read the whole media
+// into a `File`, took an `arrayBuffer()`, handed a `slice(0)` copy to
+// `decodeAudioData`, and resampled the result to mono 16k — all of it on the UI
+// thread, all of it before whisper ever saw a sample. On a four-minute bed that is
+// ~86 MB of decoded float32 plus two copies of the encoded bytes, and it froze the
+// editor at open. The inference itself was never the problem: it runs in
+// `whisper-stt-server`, in its own process, on the GPU.
+//
+// So this is the same remedy `useAudioPeaks` already got (see
+// `electron/media/audioPeaks.ts`, and the note there about WHICH ffmpeg is packaged
+// on Windows): let ffmpeg do it, in the main process, streaming. It costs
+// `durationSec * 16000 * 4` bytes — 15.7 MB for that same four-minute bed — and the
+// renderer never allocates any of it.
+//
+// It is deliberately NOT cached on disk, unlike peaks. Peaks are re-read on every
+// project open; extraction feeds one transcription, whose RESULT is what gets
+// persisted (`document.transcripts[]`). Caching the PCM would trade disk for work
+// that is already never repeated.
+
+import { spawn } from "node:child_process";
+import { resolveFfmpeg } from "../media/audioPeaks";
+import { STT_NATIVE_EXTRACTION_UNAVAILABLE } from "./transcriptionContract";
+
+/** What whisper.cpp wants, and what `decodePeaks` already asks ffmpeg for. */
+const SAMPLE_RATE = 16_000;
+
+/** Past this, it is not a recording — it is a wedged ffmpeg. Matches the peaks path. */
+const EXTRACT_TIMEOUT_MS = 60_000;
+
+/**
+ * Thrown when no ffmpeg can be resolved, so the caller can fall back to the
+ * renderer pipeline rather than failing the transcription outright. A distinct type
+ * because "there is no ffmpeg here" and "this file has no audio" want opposite
+ * responses: fall back, versus report a permanent failure for this asset.
+ */
+export class FfmpegUnavailableError extends Error {
+ constructor() {
+ super(`${STT_NATIVE_EXTRACTION_UNAVAILABLE}: no ffmpeg binary for native audio extraction`);
+ this.name = "FfmpegUnavailableError";
+ }
+}
+
+/** A media with no decodable audio track. Permanent for that file. */
+export class NoAudioTrackError extends Error {
+ constructor(filePath: string, detail: string) {
+ super(`No decodable audio in ${filePath}${detail ? `: ${detail}` : ""}`);
+ this.name = "NoAudioTrackError";
+ }
+}
+
+/**
+ * Decode `filePath` to mono 16 kHz float samples.
+ *
+ * Streams `f32le` straight off ffmpeg's stdout, so the only full-size allocation is
+ * the result itself. Chunk boundaries do not respect sample boundaries — a 4-byte
+ * float can straddle two `data` events — so a partial tail is carried into the next
+ * chunk rather than dropped, which would shift every following sample and detune the
+ * whole track.
+ */
+export async function extractMono16kPcm(
+ filePath: string,
+ options: { signal?: AbortSignal } = {},
+): Promise<Float32Array> {
+ const ffmpeg = resolveFfmpeg();
+ if (!ffmpeg) throw new FfmpegUnavailableError();
+ if (options.signal?.aborted) throw new DOMException("Aborted", "AbortError");
+
+ const child = spawn(
+ ffmpeg,
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-i",
+ filePath,
+ "-vn",
+ "-ac",
+ "1",
+ "-ar",
+ String(SAMPLE_RATE),
+ "-f",
+ "f32le",
+ "-",
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+
+ return new Promise<Float32Array>((resolve, reject) => {
+ const chunks: Float32Array[] = [];
+ let total = 0;
+ /** Bytes of a float that arrived split across two chunks. */
+ let carry: Buffer | null = null;
+ let stderr = "";
+ let settled = false;
+
+ const finish = (fn: () => void) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ options.signal?.removeEventListener("abort", onAbort);
+ fn();
+ };
+
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ finish(() =>
+ reject(new Error(`ffmpeg timed out after ${EXTRACT_TIMEOUT_MS}ms on ${filePath}`)),
+ );
+ }, EXTRACT_TIMEOUT_MS);
+
+ const onAbort = () => {
+ child.kill("SIGKILL");
+ finish(() => reject(new DOMException("Aborted", "AbortError")));
+ };
+ options.signal?.addEventListener("abort", onAbort, { once: true });
+
+ child.stdout.on("data", (c: Buffer) => {
+ const buf = carry ? Buffer.concat([carry, c]) : c;
+ const usable = buf.length - (buf.length % 4);
+ if (usable > 0) {
+ // Copy rather than view: a Buffer's memory is rarely 4-byte aligned, and
+ // `byteOffset` is almost never 0.
+ const view = new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + usable));
+ chunks.push(view);
+ total += view.length;
+ }
+ carry = usable < buf.length ? Buffer.from(buf.subarray(usable)) : null;
+ });
+ child.stderr.on("data", (c: Buffer) => {
+ stderr = (stderr + c.toString()).slice(-2048);
+ });
+ child.once("error", (err) => finish(() => reject(err)));
+ child.once("close", (code) => {
+ // A file with no audio track exits non-zero, and so does a corrupt one. The
+ // caller treats both the same way — this asset will not transcribe — so they
+ // share an error type; `stderr` carries which it was.
+ if (code !== 0 && total === 0) {
+ finish(() => reject(new NoAudioTrackError(filePath, stderr.trim())));
+ return;
+ }
+ const out = new Float32Array(total);
+ let at = 0;
+ for (const part of chunks) {
+ out.set(part, at);
+ at += part.length;
+ }
+ finish(() => resolve(out));
+ });
+ });
+}
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index c250ea4ac..1004726f5 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -1,6 +1,7 @@
import path from "node:path";
import { app, type IpcMain } from "electron";
import { planChunks } from "./chunking";
+import { extractMono16kPcm } from "./extractAudio";
import { ensureModels, modelPaths } from "./modelManager";
import type {
SttPhraseSegment,
@@ -237,12 +238,26 @@ export class SttManager {
}
/** Transcribe a whole recording, chunk by chunk, reporting progress as it goes. */
+ /** Decode `sourcePath` into the samples `transcribe` needs. */
+ private async extract(req: SttTranscribeRequest): Promise<Float32Array> {
+ if (!req.sourcePath) {
+ throw new Error("stt:transcribe needs either `samples` or `sourcePath`");
+ }
+ return extractMono16kPcm(req.sourcePath);
+ }
+
async transcribe(req: SttTranscribeRequest): Promise<SttTranscribeResponse> {
await this.init();
const epoch = this.cancelEpoch;
- const totalSec = req.samples.length / SAMPLE_RATE;
- const chunks = planChunks(req.samples, SAMPLE_RATE);
+ // Extraction is part of the run, and on a long file it is the part the user used
+ // to watch the editor freeze through. Doing it here means the renderer hands over
+ // a path and gets segments back, holding none of the audio. No new status phase:
+ // the caller already reports "extracting-audio" around this call, and the work
+ // simply moved to the other side of the IPC.
+ const samples = req.samples ?? (await this.extract(req));
+ const totalSec = samples.length / SAMPLE_RATE;
+ const chunks = planChunks(samples, SAMPLE_RATE);
this.emit({ phase: "transcribe", completedSec: 0, totalSec });
const segments: SttPhraseSegment[] = [];
@@ -285,7 +300,7 @@ export class SttManager {
if (this.cancelEpoch !== epoch) throw cancelledError();
const offsetSec = chunk.startSample / SAMPLE_RATE;
const result = await this.transcribeChunk(
- req.samples.subarray(chunk.startSample, chunk.endSample),
+ samples.subarray(chunk.startSample, chunk.endSample),
language,
).catch((error) => {
if (error instanceof Error && error.name === "AbortError") throw error;
diff --git a/electron/stt/transcriptionContract.ts b/electron/stt/transcriptionContract.ts
index cbce5a141..d2e67ae11 100644
--- a/electron/stt/transcriptionContract.ts
+++ b/electron/stt/transcriptionContract.ts
@@ -106,7 +106,24 @@ export interface SttStatusEvent {
/** IPC request: renderer → main. */
export interface SttTranscribeRequest {
- samples: Float32Array;
+ /**
+ * Mono-16k samples the CALLER decoded. Optional since native extraction landed:
+ * pass `sourcePath` instead and the main process decodes with ffmpeg, off the UI
+ * thread and without the renderer ever holding the audio. Kept for the caption
+ * path, which already has samples in hand and has no file to point at.
+ *
+ * Exactly one of `samples` / `sourcePath` is required.
+ */
+ samples?: Float32Array;
+ /**
+ * A media file for the main process to decode itself (ffmpeg -> mono 16k f32).
+ * Preferred: the renderer's own pipeline read the whole file, copied it twice and
+ * resampled it on the UI thread, which is what froze the editor at open.
+ *
+ * The caller falls back to its own decode when this cannot be honoured — see
+ * `FfmpegUnavailableError`.
+ */
+ sourcePath?: string;
/**
* ISO 639-1 language code (e.g. "en", "fr"). Omit / `"auto"` to let Whisper detect.
* The spec locks language detection on by default; we only honour an explicit value.
@@ -114,6 +131,17 @@ export interface SttTranscribeRequest {
language?: string;
}
+/**
+ * Marker carried in the error message when the main process cannot decode a
+ * `sourcePath` because no ffmpeg is resolvable on this install.
+ *
+ * A string rather than an error class because this crosses `ipcRenderer.invoke`,
+ * which reconstructs a plain `Error` from the message and drops the prototype and
+ * the `name`. Exported so neither side spells it out by hand — a fallback keyed on
+ * a literal typed twice is a fallback that silently stops working.
+ */
+export const STT_NATIVE_EXTRACTION_UNAVAILABLE = "stt:native-extraction-unavailable";
+
/** IPC response: main → renderer. */
export interface SttTranscribeResponse {
segments: SttPhraseSegment[];
diff --git a/src/lib/ai-edition/document/transcribe.test.ts b/src/lib/ai-edition/document/transcribe.test.ts
index e231d287a..0ca221a8c 100644
--- a/src/lib/ai-edition/document/transcribe.test.ts
+++ b/src/lib/ai-edition/document/transcribe.test.ts
@@ -1,4 +1,5 @@
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { STT_NATIVE_EXTRACTION_UNAVAILABLE } from "../../../../electron/stt/transcriptionContract";
import { type AxcutDocument, axcutSchemaVersion } from "../schema";
import { transcribeAsset } from "./transcribe";
@@ -12,10 +13,17 @@ vi.mock("@/lib/captioning", () => ({
sampleRate: 16_000,
})),
transcribeMono16kToSegments: vi.fn(),
+ transcribeSourceFileToSegments: vi.fn(),
}));
-const { transcribeMono16kToSegments } = await import("@/lib/captioning");
-const transcribeMock = vi.mocked(transcribeMono16kToSegments);
+const { extractMono16kFromVideoUrl, transcribeMono16kToSegments, transcribeSourceFileToSegments } =
+ await import("@/lib/captioning");
+// `transcribeAsset` sends the PATH now and lets the main process decode; the samples
+// entry point is only reached when no ffmpeg can be resolved. The assertions below
+// therefore target the native call, and the fallback has tests of its own at the end.
+const transcribeMock = vi.mocked(transcribeSourceFileToSegments);
+const rendererMock = vi.mocked(transcribeMono16kToSegments);
+const extractMock = vi.mocked(extractMono16kFromVideoUrl);
function makeDoc(): AxcutDocument {
return {
@@ -167,3 +175,52 @@ describe("transcribeAsset language handling", () => {
expect(t.language).toBe("auto");
});
});
+
+describe("transcribeAsset native extraction", () => {
+ // Call counts are the assertion here, so they start from zero every test —
+ // `mockResolvedValueOnce` queues a result, it does not clear the history.
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("hands the main process a path instead of decoding in the renderer", async () => {
+ // The point of the change: the renderer must not touch the audio at all on the
+ // happy path. `extractMono16kFromVideoUrl` reads the whole file, copies it twice
+ // and resamples on the UI thread — that is the freeze this avoids.
+ transcribeMock.mockResolvedValueOnce({
+ segments: [{ startSec: 0, endSec: 1, text: "hi" }],
+ granularity: "word",
+ detectedLanguage: "en",
+ });
+ await transcribeAsset(makeDoc(), "asset_1");
+ expect(transcribeMock).toHaveBeenCalledWith("/tmp/demo.mp4", expect.anything());
+ expect(extractMock).not.toHaveBeenCalled();
+ expect(rendererMock).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the renderer decode when the install has no ffmpeg", async () => {
+ // A dev checkout that never fetched ffmpeg, or a platform build missing it, must
+ // still transcribe rather than lose the feature.
+ transcribeMock.mockRejectedValueOnce(
+ new Error(`${STT_NATIVE_EXTRACTION_UNAVAILABLE}: no ffmpeg binary`),
+ );
+ rendererMock.mockResolvedValueOnce({
+ segments: [{ startSec: 0, endSec: 1, text: "hi" }],
+ granularity: "word",
+ detectedLanguage: "en",
+ });
+ const transcript = await transcribeAsset(makeDoc(), "asset_1");
+ expect(extractMock).toHaveBeenCalled();
+ expect(rendererMock).toHaveBeenCalled();
+ expect(transcript.segments.length).toBeGreaterThan(0);
+ });
+
+ it("does NOT fall back on any other failure", async () => {
+ // "This file has no audio" is a verdict. Re-deriving it in the renderer would buy
+ // the same answer for the price of the decode this change exists to avoid.
+ transcribeMock.mockRejectedValueOnce(new Error("No decodable audio in /tmp/demo.mp4"));
+ await expect(transcribeAsset(makeDoc(), "asset_1")).rejects.toThrow("No decodable audio");
+ expect(extractMock).not.toHaveBeenCalled();
+ expect(rendererMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.ts
index dcdfbc650..3a5d0fce4 100644
--- a/src/lib/ai-edition/document/transcribe.ts
+++ b/src/lib/ai-edition/document/transcribe.ts
@@ -6,7 +6,13 @@
// verbatim. No Python, no faster-whisper, no network calls. Privacy-safe.
import { toFileUrl } from "@/components/video-editor/projectPersistence";
-import { extractMono16kFromVideoUrl, transcribeMono16kToSegments } from "@/lib/captioning";
+import {
+ extractMono16kFromVideoUrl,
+ transcribeMono16kToSegments,
+ transcribeSourceFileToSegments,
+} from "@/lib/captioning";
+import type { SttRendererStatus } from "@/lib/captioning/transcribe";
+import { STT_NATIVE_EXTRACTION_UNAVAILABLE } from "../../../../electron/stt/transcriptionContract";
import type { AxcutDocument, AxcutTranscript, AxcutTranscriptSegment, AxcutWord } from "../schema";
/**
@@ -47,9 +53,6 @@ export async function transcribeAsset(
const videoUrl = toFileUrl(asset.originalPath);
options.onStatus?.({ phase: "extracting-audio" });
- const audioResult = await extractMono16kFromVideoUrl(videoUrl, {
- signal: options.signal,
- });
// Stay on loading-model until the main process reports inference chunks.
// Emitting "transcribing" here used to label the cold `server.start()` wait
@@ -62,28 +65,56 @@ export async function transcribeAsset(
// so the stored transcript reflects reality, not the input option.
const forcedLanguage =
options.language && options.language !== "auto" ? options.language : undefined;
- const result = await transcribeMono16kToSegments(audioResult.samples, {
+
+ // Forward the main process's per-chunk progress. Without this the status
+ // callback only ever fired the two coarse phases above, so a 30-minute
+ // recording showed one static "transcribing" for ten minutes.
+ const forwardStatus = (status: SttRendererStatus) =>
+ options.onStatus?.({
+ phase: status.phase === "model" ? "loading-model" : "transcribing",
+ completedSec: status.completedSec,
+ totalSec: status.totalSec,
+ // Which device is doing the work, and how fast. The main process is the
+ // only place that knows either, and a silent CPU fallback is exactly the
+ // case a user cannot otherwise diagnose.
+ backend: status.backend,
+ rtf: status.rtf,
+ ...(status.downloadedBytes !== undefined
+ ? { downloadedBytes: status.downloadedBytes }
+ : {}),
+ ...(status.totalBytes !== undefined ? { totalBytes: status.totalBytes } : {}),
+ });
+
+ // Native first. `extractMono16kFromVideoUrl` runs in the RENDERER: it reads the
+ // whole media into memory, copies it twice and resamples on the UI thread, which
+ // is what froze the editor at project open on a long import (measured on a
+ // four-minute bed: ~86 MB of decoded float32 there against 15.7 MB in the main
+ // process). Handing the path over keeps every byte on the other side of the IPC,
+ // and the whisper helper it feeds was already a separate process.
+ //
+ // The fallback is not decoration: an install with no resolvable ffmpeg — a dev
+ // checkout that never fetched it, a platform build missing the binary — must still
+ // transcribe rather than lose the feature. Only THAT case falls back. "This file
+ // has no audio" is a verdict, and re-deriving it in the renderer would buy the same
+ // answer for the price of the decode this exists to avoid.
+ const result = await transcribeSourceFileToSegments(asset.originalPath, {
trimRegions: [],
signal: options.signal,
language: forcedLanguage,
- // Forward the main process's per-chunk progress. Without this the status
- // callback only ever fired the two coarse phases above, so a 30-minute
- // recording showed one static "transcribing" for ten minutes.
- onStatus: (status) =>
- options.onStatus?.({
- phase: status.phase === "model" ? "loading-model" : "transcribing",
- completedSec: status.completedSec,
- totalSec: status.totalSec,
- // Which device is doing the work, and how fast. The main process is the
- // only place that knows either, and a silent CPU fallback is exactly the
- // case a user cannot otherwise diagnose.
- backend: status.backend,
- rtf: status.rtf,
- ...(status.downloadedBytes !== undefined
- ? { downloadedBytes: status.downloadedBytes }
- : {}),
- ...(status.totalBytes !== undefined ? { totalBytes: status.totalBytes } : {}),
- }),
+ onStatus: forwardStatus,
+ }).catch(async (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!message.includes(STT_NATIVE_EXTRACTION_UNAVAILABLE)) throw error;
+ const audioResult = await extractMono16kFromVideoUrl(videoUrl, {
+ signal: options.signal,
+ });
+ options.onStatus?.({ phase: "transcribing" });
+ return transcribeMono16kToSegments(audioResult.samples, {
+ trimRegions: [],
+ signal: options.signal,
+ language: forcedLanguage,
+ onStatus: forwardStatus,
+ });
});
const segments: AxcutTranscriptSegment[] = [];
diff --git a/src/lib/captioning/index.ts b/src/lib/captioning/index.ts
index 99da5a1f0..a5ad5dabd 100644
--- a/src/lib/captioning/index.ts
+++ b/src/lib/captioning/index.ts
@@ -12,4 +12,4 @@ export type {
CaptionTimestampGranularity,
TranscribeMono16kResult,
} from "./transcribe";
-export { transcribeMono16kToSegments } from "./transcribe";
+export { transcribeMono16kToSegments, transcribeSourceFileToSegments } from "./transcribe";
diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.ts
index a8c6ec3e9..7b8473608 100644
--- a/src/lib/captioning/transcribe.ts
+++ b/src/lib/captioning/transcribe.ts
@@ -74,12 +74,40 @@ interface RendererSttApi {
*/
export function transcribeMono16kToSegments(
samples: Float32Array,
- options?: {
- trimRegions?: TrimRegion[];
- onStatus?: (status: SttRendererStatus) => void;
- signal?: AbortSignal;
- language?: string;
- },
+ options?: TranscribeOptions,
+): Promise<TranscribeMono16kResult> {
+ return runTranscription({ samples }, options);
+}
+
+/**
+ * Same recognition, from a FILE the main process decodes itself.
+ *
+ * Preferred over `transcribeMono16kToSegments` wherever there is a path to point at.
+ * The samples entry point decodes in the renderer — whole file into memory, an
+ * `arrayBuffer()` copy, a `slice(0)` copy, then a resample loop on the UI thread —
+ * which is what froze the editor at open on a long import. Here the renderer sends a
+ * string and gets segments back.
+ *
+ * Rejects with a message carrying `STT_NATIVE_EXTRACTION_UNAVAILABLE` when the
+ * install has no ffmpeg, so the caller can fall back rather than lose the transcript.
+ */
+export function transcribeSourceFileToSegments(
+ sourcePath: string,
+ options?: TranscribeOptions,
+): Promise<TranscribeMono16kResult> {
+ return runTranscription({ sourcePath }, options);
+}
+
+export interface TranscribeOptions {
+ trimRegions?: TrimRegion[];
+ onStatus?: (status: SttRendererStatus) => void;
+ signal?: AbortSignal;
+ language?: string;
+}
+
+function runTranscription(
+ payload: { samples: Float32Array } | { sourcePath: string },
+ options?: TranscribeOptions,
): Promise<TranscribeMono16kResult> {
if (options?.signal?.aborted) {
return Promise.reject(new DOMException("Aborted", "AbortError"));
@@ -108,7 +136,7 @@ export function transcribeMono16kToSegments(
// iteration trimmed leading silence with a peak detector and got false
// positives on quiet music intros / room tone. VAD or nothing.
return api
- .transcribe({ samples, language: forcedLanguage })
+ .transcribe({ ...payload, language: forcedLanguage })
.then((result) => {
const words = result.wordSegments ?? [];
let segments: CaptionSegment[];