Skip to content

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

fix(stt): transcribe in chunks, with progress and per-chunk retry

Etienne Lescot63f072e5d39d
diff --git a/electron/stt/chunking.test.ts b/electron/stt/chunking.test.ts
new file mode 100644
index 000000000..eef6d2006
--- /dev/null
+++ b/electron/stt/chunking.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { planChunks } from "./chunking";
+
+const RATE = 16_000;
+
+/** Loud tone with silent gaps punched in at the given [startSec, endSec) ranges. */
+function toneWithSilences(durationSec: number, silences: [number, number][]): Float32Array {
+ const samples = new Float32Array(Math.round(durationSec * RATE));
+ for (let i = 0; i < samples.length; i++) {
+ samples[i] = Math.sin((i / RATE) * 2 * Math.PI * 440);
+ }
+ for (const [from, to] of silences) {
+ samples.fill(0, Math.round(from * RATE), Math.round(to * RATE));
+ }
+ return samples;
+}
+
+describe("planChunks", () => {
+ it("covers the whole buffer with contiguous chunks", () => {
+ const samples = toneWithSilences(25, []);
+ const chunks = planChunks(samples, RATE, { targetSec: 10, searchSec: 1 });
+ expect(chunks[0].startSample).toBe(0);
+ expect(chunks[chunks.length - 1].endSample).toBe(samples.length);
+ for (let i = 1; i < chunks.length; i++) {
+ expect(chunks[i].startSample).toBe(chunks[i - 1].endSample);
+ }
+ });
+
+ it("cuts inside a pause rather than on the fixed grid", () => {
+ // Pause at 9.5-9.9s: the ideal 10s boundary should be pulled back into it.
+ const samples = toneWithSilences(25, [
+ [9.5, 9.9],
+ [19.4, 19.8],
+ ]);
+ const chunks = planChunks(samples, RATE, { targetSec: 10, searchSec: 1 });
+ const cutSec = chunks[0].endSample / RATE;
+ expect(cutSec).toBeGreaterThanOrEqual(9.5);
+ expect(cutSec).toBeLessThan(9.9);
+ });
+
+ it("returns a single chunk when the recording is shorter than the target", () => {
+ const samples = toneWithSilences(5, []);
+ expect(planChunks(samples, RATE, { targetSec: 120 })).toEqual([
+ { startSample: 0, endSample: samples.length },
+ ]);
+ });
+
+ it("always makes progress, even on a fully silent buffer", () => {
+ // Every frame ties on energy, so the cut is whatever the scan settles on —
+ // what matters is that it never returns a zero-length chunk (infinite loop).
+ const samples = new Float32Array(60 * RATE);
+ const chunks = planChunks(samples, RATE, { targetSec: 10, searchSec: 5 });
+ for (const chunk of chunks) {
+ expect(chunk.endSample).toBeGreaterThan(chunk.startSample);
+ }
+ expect(chunks[chunks.length - 1].endSample).toBe(samples.length);
+ });
+
+ it("handles an empty buffer", () => {
+ expect(planChunks(new Float32Array(0), RATE)).toEqual([]);
+ });
+});
diff --git a/electron/stt/chunking.ts b/electron/stt/chunking.ts
new file mode 100644
index 000000000..8ef743eca
--- /dev/null
+++ b/electron/stt/chunking.ts
@@ -0,0 +1,114 @@
+/**
+ * Splits a long recording into inference-sized chunks for the STT pipeline.
+ *
+ * Why chunk at all: whisper-stt-server answers a `/inference` request only once
+ * it has transcribed the WHOLE upload, so a 30-minute recording was one ~10
+ * minute request with no progress and no recovery — one hiccup lost everything
+ * (and undici's 300s `headersTimeout` killed it outright before it ever
+ * finished). Per-chunk requests give the caller a progress signal, a retry unit,
+ * and requests short enough that no transport timeout is in play.
+ *
+ * Where the cut lands matters: slicing on a fixed grid cuts mid-word, and
+ * whisper then mis-transcribes both halves. So the boundary is nudged to the
+ * quietest 20ms frame within a search window around the ideal position — a
+ * pause between words in practice.
+ *
+ * ponytail: energy minimum, not a real VAD. whisper.cpp ships a Silero VAD, but
+ * it lives behind the server's own `--vad` flag and would run per REQUEST — it
+ * can't tell us where to cut BEFORE we upload. A plain RMS scan over a few
+ * seconds is enough to find a pause and costs nothing. If a recording is so
+ * dense that no pause exists in the window, the cut lands at the quietest point
+ * anyway and one word may be split; upgrade path is an overlap + de-duplication
+ * pass on the seam, which is a lot more code than it is worth today.
+ */
+
+/** One chunk of the source buffer: `[startSample, endSample)`. */
+export interface SttChunkPlan {
+ startSample: number;
+ /** Exclusive. */
+ endSample: number;
+}
+
+/** Energy is measured over frames this long; a cut lands on a frame boundary. */
+const FRAME_MS = 20;
+
+export interface PlanChunksOptions {
+ /** Ideal chunk length. Shorter = smoother progress, more per-request overhead. */
+ targetSec?: number;
+ /** How far on either side of the ideal boundary to hunt for a pause. */
+ searchSec?: number;
+}
+
+/**
+ * 90s is a compromise between three pressures: progress granularity (the bar
+ * only moves once a chunk lands), whisper's own quality (it decodes in 30s
+ * windows and loses cross-chunk context at every seam, so more seams is worse),
+ * and `whisperServer`'s 280s per-request ceiling — 90s of audio has to
+ * transcribe in under that on the SLOWEST machine we care about (~0.3x realtime;
+ * this Vulkan box does 3.1x, i.e. ~29s per chunk).
+ */
+const DEFAULT_TARGET_SEC = 90;
+
+/**
+ * Index of the quietest frame start in `[from, to)`. Both bounds are clamped by
+ * the caller; returns `from` when the range holds less than one full frame.
+ */
+function quietestFrameStart(
+ samples: Float32Array,
+ from: number,
+ to: number,
+ frameSamples: number,
+): number {
+ let bestStart = from;
+ let bestEnergy = Number.POSITIVE_INFINITY;
+ for (let start = from; start + frameSamples <= to; start += frameSamples) {
+ let energy = 0;
+ for (let i = start; i < start + frameSamples; i++) {
+ energy += samples[i] * samples[i];
+ }
+ if (energy < bestEnergy) {
+ bestEnergy = energy;
+ bestStart = start;
+ }
+ }
+ return bestStart;
+}
+
+/**
+ * Plan the chunk boundaries for `samples`. Chunks are contiguous and cover the
+ * whole buffer: `chunks[0].startSample === 0`, each `endSample` is the next
+ * `startSample`, and the last one ends at `samples.length`.
+ */
+export function planChunks(
+ samples: Float32Array,
+ sampleRate: number,
+ options: PlanChunksOptions = {},
+): SttChunkPlan[] {
+ if (samples.length === 0 || sampleRate <= 0) return [];
+ const targetSamples = Math.max(
+ 1,
+ Math.round((options.targetSec ?? DEFAULT_TARGET_SEC) * sampleRate),
+ );
+ const searchSamples = Math.max(0, Math.round((options.searchSec ?? 3) * sampleRate));
+ const frameSamples = Math.max(1, Math.round((FRAME_MS / 1000) * sampleRate));
+
+ const chunks: SttChunkPlan[] = [];
+ let start = 0;
+ while (start < samples.length) {
+ const ideal = start + targetSamples;
+ // Last chunk: what's left is at most one target long, so there's nothing to cut.
+ if (ideal >= samples.length) {
+ chunks.push({ startSample: start, endSample: samples.length });
+ break;
+ }
+ // The search window never reaches back to `start` (a zero-length chunk would
+ // loop forever) and never past the end of the buffer.
+ const from = Math.max(start + frameSamples, ideal - searchSamples);
+ const to = Math.min(samples.length, ideal + searchSamples);
+ const cut = to > from ? quietestFrameStart(samples, from, to, frameSamples) : ideal;
+ const endSample = Math.min(samples.length, Math.max(from, cut));
+ chunks.push({ startSample: start, endSample });
+ start = endSample;
+ }
+ return chunks;
+}
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.ts
index df94fc102..7e255c1ff 100644
--- a/electron/stt/index.test.ts
+++ b/electron/stt/index.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { planChunks } from "./chunking";
import { _resetSttManagerForTests, SttManager } from "./index";
import type { SttStatusEvent, SttTranscribeResponse } from "./transcriptionContract";
@@ -87,6 +88,79 @@ describe("SttManager", () => {
expect(fakeWhisperServer.transcribe).toHaveBeenCalledOnce();
});
+ it("splits a long recording and shifts each chunk's timestamps to absolute time", async () => {
+ // Every chunk reports the same relative segment at 1.0s; correct merging
+ // turns those into one absolute timestamp per chunk start.
+ fakeWhisperServer.transcribe.mockResolvedValue({
+ segments: [{ text: "hello", startSec: 1, endSec: 1.5 }],
+ wordSegments: [{ word: "hello", startSec: 1, endSec: 1.5 }],
+ detectedLanguage: "en",
+ backend: "whispercpp-cpu",
+ });
+ const samples = new Float32Array(200 * 16000);
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ const result = await mgr.transcribe({ samples, language: "en" });
+
+ const expectedOffsets = planChunks(samples, 16000).map((c) => c.startSample / 16000);
+ expect(expectedOffsets.length).toBeGreaterThan(1);
+ expect(fakeWhisperServer.transcribe).toHaveBeenCalledTimes(expectedOffsets.length);
+ expect(result.segments.map((s) => s.startSec)).toEqual(expectedOffsets.map((o) => o + 1));
+ expect(result.wordSegments.map((w) => w.startSec)).toEqual(expectedOffsets.map((o) => o + 1));
+ });
+
+ it("reports monotonic progress that ends on the full duration", async () => {
+ const sink = vi.fn<(e: SttStatusEvent) => void>();
+ const samples = new Float32Array(200 * 16000);
+ const mgr = new SttManager();
+ await mgr.init({ statusSink: sink, modelsBaseDir: "/tmp/fake-stt-models" });
+ sink.mockClear();
+ await mgr.transcribe({ samples, language: "en" });
+
+ const progress = sink.mock.calls
+ .map(([event]) => event)
+ .filter((event) => event.completedSec !== undefined);
+ expect(progress[0].completedSec).toBe(0);
+ expect(progress[progress.length - 1].completedSec).toBe(200);
+ for (const event of progress) expect(event.totalSec).toBe(200);
+ for (let i = 1; i < progress.length; i++) {
+ expect(progress[i].completedSec).toBeGreaterThan(progress[i - 1].completedSec ?? -1);
+ }
+ });
+
+ it("pins later chunks to the language detected on the first one", async () => {
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ await mgr.transcribe({ samples: new Float32Array(200 * 16000) });
+ const languages = fakeWhisperServer.transcribe.mock.calls.map(([req]) => req.language);
+ expect(languages[0]).toBeUndefined();
+ expect(languages.slice(1).every((l) => l === "en")).toBe(true);
+ });
+
+ it("retries a failed chunk instead of losing the whole transcription", async () => {
+ fakeWhisperServer.transcribe.mockRejectedValueOnce(new Error("helper died")).mockResolvedValue({
+ segments: [{ text: "hello", startSec: 0, endSec: 0.5 }],
+ wordSegments: [{ word: "hello", startSec: 0, endSec: 0.5 }],
+ detectedLanguage: "en",
+ backend: "whispercpp-cpu",
+ });
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ const result = await mgr.transcribe({ samples: new Float32Array(16000), language: "en" });
+ expect(result.segments).toHaveLength(1);
+ // start() again on the retry — the usual cause is a dead helper.
+ expect(fakeWhisperServer.start.mock.calls.length).toBeGreaterThan(1);
+ });
+
+ it("fails the request when a chunk never succeeds", async () => {
+ fakeWhisperServer.transcribe.mockRejectedValue(new Error("helper wedged"));
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ await expect(
+ mgr.transcribe({ samples: new Float32Array(16000), language: "en" }),
+ ).rejects.toThrow("helper wedged");
+ });
+
it("shutdown() stops whisper-stt-server", async () => {
const mgr = new SttManager();
await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index 641a3abe6..3cd847c16 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -1,10 +1,13 @@
import path from "node:path";
import { app, type IpcMain } from "electron";
+import { planChunks } from "./chunking";
import { ensureModels, modelPaths } from "./modelManager";
import type {
+ SttPhraseSegment,
SttStatusEvent,
SttTranscribeRequest,
SttTranscribeResponse,
+ SttWordSegment,
} from "./transcriptionContract";
import { WhisperServerManager } from "./whisperServer";
@@ -13,18 +16,40 @@ import { WhisperServerManager } from "./whisperServer";
*
* Workflow:
* 1. `init()` spawns `whisper-stt-server` (or queues the call if it's busy).
- * 2. `transcribe()` proxies the renderer's `Float32Array` through
- * whisper-stt-server's HTTP `/inference`, which returns both phrase- and
- * word-level segments in one pass (see whisperServer.ts). Word
- * timestamps come from whisper.cpp's native DTW token timestamps
- * (`t_dtw`, SMALL aheads preset, `flash_attn = false`), see
+ * 2. `transcribe()` splits the renderer's `Float32Array` into chunks
+ * (`chunking.ts`) and runs each through whisper-stt-server's HTTP
+ * `/inference`, which returns both phrase- and word-level segments in one
+ * pass (see whisperServer.ts). Word timestamps come from whisper.cpp's
+ * native DTW token timestamps (`t_dtw`, SMALL aheads preset,
+ * `flash_attn = false`), see
* technical-documentation/architecture/transcription-and-captions.md § Decision rationale.
* 3. `shutdown()` tears down on app quit.
*
* Status events fan out via `statusSink` so the renderer can drive its
* "loading model" / "transcribing" indicator.
+ *
+ * Why chunked rather than one request: a 30-minute recording took ~10 minutes
+ * in a single `/inference` call — no progress to show, no way to recover from a
+ * transient failure without redoing everything, and long enough that the HTTP
+ * client's own header timeout killed it before whisper ever answered. Chunks
+ * turn that into a progress signal and a retry unit.
+ *
+ * Chunks run SEQUENTIALLY, and that is a measured choice, not an omission:
+ * whisper-stt-server holds a single model context, so concurrent `/inference`
+ * calls don't just serialize — they get SLOWER. Two 120s chunks took 76.9s one
+ * after the other and 144.1s fired together (0.53x, i.e. ~1.9x slower) on this
+ * Vulkan backend. A client-side worker pool is therefore a pessimisation. Real
+ * parallelism would need several server processes, each with its own copy of
+ * the model resident on the GPU; that trade (VRAM + spawn cost per worker) is
+ * worth revisiting only if a much smaller model ever becomes the default.
*/
+/** The renderer always sends mono 16 kHz (see `extractMono16kFromVideoUrl`). */
+const SAMPLE_RATE = 16_000;
+
+/** Attempts per chunk before the whole transcription fails. */
+const CHUNK_ATTEMPTS = 3;
+
export interface SttManagerInitOptions {
statusSink?: (event: SttStatusEvent) => void;
/** Override the models cache directory; defaults to `app.getPath("userData") + "/stt-models"`. */
@@ -36,6 +61,8 @@ export class SttManager {
private modelsBaseDir: string | null = null;
private statusSink: ((event: SttStatusEvent) => void) | null = null;
private initPromise: Promise<void> | null = null;
+ /** Kept from `prepare()` so a chunk retry can respawn a helper that died mid-run. */
+ private modelPath: string | null = null;
/** Wire a sink for the renderer status channel. */
setStatusSink(sink: ((event: SttStatusEvent) => void) | null): void {
@@ -97,23 +124,97 @@ export class SttManager {
});
const paths = modelPaths(modelsDir);
+ this.modelPath = paths.whisper;
await this.server.start({ modelPath: paths.whisper });
this.emit({ phase: "transcribe" });
}
- /** Run one transcription request through whisper-stt-server. */
+ /**
+ * Run one chunk, retrying a few times before giving up on the whole request.
+ *
+ * A failure here is usually the helper process dying (OOM, driver reset)
+ * rather than a bad chunk, so each retry first re-runs `server.start()` —
+ * idempotent when the helper is alive, a respawn when it isn't. That is what
+ * makes a 30-minute transcription survive one bad minute instead of losing
+ * the twenty that already succeeded.
+ */
+ private async transcribeChunk(
+ samples: Float32Array,
+ language: string | undefined,
+ ): Promise<Awaited<ReturnType<WhisperServerManager["transcribe"]>>> {
+ let lastError: unknown;
+ for (let attempt = 1; attempt <= CHUNK_ATTEMPTS; attempt++) {
+ try {
+ return await this.server.transcribe({ samples, language });
+ } catch (error) {
+ lastError = error;
+ if (attempt === CHUNK_ATTEMPTS) break;
+ if (this.modelPath) {
+ await this.server.start({ modelPath: this.modelPath }).catch(() => undefined);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
+ }
+ }
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
+ }
+
+ /** Transcribe a whole recording, chunk by chunk, reporting progress as it goes. */
async transcribe(req: SttTranscribeRequest): Promise<SttTranscribeResponse> {
await this.init();
- this.emit({ phase: "transcribe" });
- const phrase = await this.server.transcribe({
- samples: req.samples,
- language: req.language,
- });
- const backend = phrase.backend ?? this.server.status.backend ?? "whispercpp-cpu";
+
+ const totalSec = req.samples.length / SAMPLE_RATE;
+ const chunks = planChunks(req.samples, SAMPLE_RATE);
+ this.emit({ phase: "transcribe", completedSec: 0, totalSec });
+
+ const segments: SttPhraseSegment[] = [];
+ const wordSegments: SttWordSegment[] = [];
+ let detectedLanguage: string | null = null;
+ let backend = this.server.status.backend ?? "whispercpp-cpu";
+ // Only the first chunk auto-detects. Every later chunk is forced onto that
+ // language: whisper can otherwise flip mid-recording on a chunk that opens
+ // with a proper noun or a silence, and "transcribe" the rest as another
+ // language entirely.
+ let language = req.language;
+
+ for (const chunk of chunks) {
+ const offsetSec = chunk.startSample / SAMPLE_RATE;
+ const result = await this.transcribeChunk(
+ req.samples.subarray(chunk.startSample, chunk.endSample),
+ language,
+ );
+ // Chunk-relative timestamps → absolute, the only thing every consumer
+ // (captions, transcript editor, trims) reads.
+ for (const segment of result.segments) {
+ segments.push({
+ text: segment.text,
+ startSec: segment.startSec + offsetSec,
+ endSec: segment.endSec + offsetSec,
+ });
+ }
+ for (const word of result.wordSegments) {
+ wordSegments.push({
+ word: word.word,
+ startSec: word.startSec + offsetSec,
+ endSec: word.endSec + offsetSec,
+ confidence: word.confidence,
+ });
+ }
+ if (!detectedLanguage && result.detectedLanguage && result.detectedLanguage !== "auto") {
+ detectedLanguage = result.detectedLanguage;
+ if (!language) language = detectedLanguage;
+ }
+ backend = result.backend ?? backend;
+ this.emit({
+ phase: "transcribe",
+ completedSec: chunk.endSample / SAMPLE_RATE,
+ totalSec,
+ });
+ }
+
return {
- segments: phrase.segments,
- wordSegments: phrase.wordSegments,
- detectedLanguage: phrase.detectedLanguage,
+ segments,
+ wordSegments,
+ detectedLanguage: detectedLanguage ?? req.language ?? "auto",
backend,
};
}
diff --git a/electron/stt/transcriptionContract.ts b/electron/stt/transcriptionContract.ts
index 85b6c7152..2fa8a88eb 100644
--- a/electron/stt/transcriptionContract.ts
+++ b/electron/stt/transcriptionContract.ts
@@ -50,6 +50,14 @@ export interface SttStatusEvent {
totalBytes?: number;
/** Which model is downloading. */
model?: "whisper";
+ /**
+ * Seconds of audio transcribed so far, and the total for this request. Only
+ * when `phase === "transcribe"`. Progress is reported per CHUNK (see
+ * `chunking.ts`), so it steps rather than sweeps — whisper gives no
+ * sub-request progress signal to interpolate from.
+ */
+ completedSec?: number;
+ totalSec?: number;
}
/** IPC request: renderer → main. */
diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.ts
index 4762ebf6d..217a583ac 100644
--- a/electron/stt/whisperServer.ts
+++ b/electron/stt/whisperServer.ts
@@ -14,6 +14,24 @@ import { cleanupWav, writeSamplesAsWav } from "./wav";
/** whisper.cpp helper is stdio-shaped: stdin ignored, stdout/stderr captured. */
type WhisperChild = ChildProcessByStdio<null, Readable, Readable>;
+/**
+ * Per-request ceiling. whisper answers `/inference` only once the WHOLE upload
+ * is transcribed, so this bounds one chunk, not one recording.
+ *
+ * ponytail: 280s because Node's global fetch (undici) applies its own
+ * undocumented 300s `headersTimeout` that we cannot configure without taking a
+ * direct dependency on `undici` — going over it produces an opaque
+ * "TypeError: fetch failed" instead of anything actionable (this is exactly how
+ * a single 30-minute request died: killed at 300s while whisper needed 574s).
+ * Aborting at 280s keeps the failure OURS: named, logged with the helper's
+ * stderr, and retried by SttManager. The real ceiling this leaves is a machine
+ * so slow that one 90s chunk needs more than 280s (~0.3x realtime); the upgrade
+ * path is a direct `undici` dependency and
+ * `new Agent({ headersTimeout: 0, bodyTimeout: 0 })` as the fetch dispatcher,
+ * which removes the cliff entirely.
+ */
+const REQUEST_TIMEOUT_MS = 280_000;
+
/**
* Owns the long-lived `whisper-stt-server` process used to recognize speech.
*
@@ -291,7 +309,26 @@ export class WhisperServerManager {
form.set("file", blob, path.basename(opts.wavPath));
form.set("response_format", "verbose_json");
form.set("language", opts.language && opts.language !== "auto" ? opts.language : "auto");
- const res = await fetch(url, { method: "POST", body: form });
+ let res: Response;
+ try {
+ res = await fetch(url, {
+ method: "POST",
+ body: form,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ } catch (error) {
+ // Name the failure. Node's global fetch reports BOTH a real transport
+ // error and its own header timeout as a bare "fetch failed", which is
+ // how a too-long request used to reach the user as an unactionable
+ // "Transcription failed" toast.
+ const reason =
+ error instanceof Error && error.name === "TimeoutError" ? "timed out" : "failed";
+ throw new Error(
+ `whisper-stt-server /inference ${reason} after ${Math.round(REQUEST_TIMEOUT_MS / 1000)}s ` +
+ `(audio chunk too long for this machine, or the helper is wedged); ` +
+ `stderr=${this.stderrTail.slice(-256)}`,
+ );
+ }
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`whisper-stt-server /inference HTTP ${res.status}: ${text.slice(0, 512)}`);
diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.ts
index 460828b60..0c0a23aa8 100644
--- a/src/lib/ai-edition/document/transcribe.ts
+++ b/src/lib/ai-edition/document/transcribe.ts
@@ -9,9 +9,20 @@ import { toFileUrl } from "@/components/video-editor/projectPersistence";
import { extractMono16kFromVideoUrl, transcribeMono16kToSegments } from "@/lib/captioning";
import type { AxcutDocument, AxcutTranscript, AxcutTranscriptSegment, AxcutWord } from "../schema";
+/**
+ * What the caller can show while a transcription runs. `completedSec` /
+ * `totalSec` arrive only during `"transcribing"`, once the main process starts
+ * landing chunks — until then the phase alone is all there is to show.
+ */
+export interface TranscribeStatus {
+ phase: "extracting-audio" | "loading-model" | "transcribing";
+ completedSec?: number;
+ totalSec?: number;
+}
+
export interface TranscribeAssetOptions {
language?: string;
- onStatus?: (status: string) => void;
+ onStatus?: (status: TranscribeStatus) => void;
signal?: AbortSignal;
}
@@ -27,12 +38,12 @@ export async function transcribeAsset(
const videoUrl = toFileUrl(asset.originalPath);
- options.onStatus?.("extracting-audio");
+ options.onStatus?.({ phase: "extracting-audio" });
const audioResult = await extractMono16kFromVideoUrl(videoUrl, {
signal: options.signal,
});
- options.onStatus?.("transcribing");
+ options.onStatus?.({ phase: "transcribing" });
// Only pass `language` to the worker when the caller forced a specific
// code. `"auto"` (or any falsy value) leaves Whisper to detect from
// the audio. The pipeline tags every chunk with the language it used
@@ -44,6 +55,15 @@ export async function transcribeAsset(
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,
+ }),
});
const segments: AxcutTranscriptSegment[] = [];
diff --git a/src/lib/captioning/transcribe.test.ts b/src/lib/captioning/transcribe.test.ts
index 18c6cfa79..d8f461d81 100644
--- a/src/lib/captioning/transcribe.test.ts
+++ b/src/lib/captioning/transcribe.test.ts
@@ -115,12 +115,12 @@ describe("transcribeMono16kToSegments", () => {
expect(result.segments).toEqual([{ text: "hello world", startSec: 0, endSec: 0.65 }]);
});
- it("forwards 'model' / 'transcribe' phases to onStatus and tears the listener down", async () => {
+ it("forwards the whole status event to onStatus and tears the listener down", async () => {
const onStatus = vi.fn();
mockApi.transcribe.mockImplementationOnce(async () => {
// Simulate the IPC handler emitting a status event mid-flight.
lastStatusCb?.({ phase: "model" });
- lastStatusCb?.({ phase: "transcribe" });
+ lastStatusCb?.({ phase: "transcribe", completedSec: 90, totalSec: 300 });
return {
segments: [],
wordSegments: [{ word: "ok", startSec: 0, endSec: 0.1 }],
@@ -130,8 +130,14 @@ describe("transcribeMono16kToSegments", () => {
});
await transcribeMono16kToSegments(new Float32Array(1600), { onStatus });
- expect(onStatus).toHaveBeenCalledWith("model");
- expect(onStatus).toHaveBeenCalledWith("transcribe");
+ expect(onStatus).toHaveBeenCalledWith({ phase: "model" });
+ // The chunk progress must survive the hop, not just the phase — it is what
+ // drives the progress bar.
+ expect(onStatus).toHaveBeenCalledWith({
+ phase: "transcribe",
+ completedSec: 90,
+ totalSec: 300,
+ });
// onStatus listener is detached once the promise settles.
expect(lastStatusCb).toBeNull();
});
diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.ts
index a1b39d439..129949c22 100644
--- a/src/lib/captioning/transcribe.ts
+++ b/src/lib/captioning/transcribe.ts
@@ -28,6 +28,18 @@ export interface TranscribeMono16kResult {
export type SttRendererStatusPhase = "model" | "transcribe";
+/**
+ * Progress the main process reports while a transcription runs. `completedSec` /
+ * `totalSec` are present only during `"transcribe"`, and only once chunking has
+ * started — they let the UI show a real bar instead of an indeterminate spinner
+ * for what can be several minutes of work.
+ */
+export interface SttRendererStatus {
+ phase: SttRendererStatusPhase;
+ completedSec?: number;
+ totalSec?: number;
+}
+
interface RendererSttApi {
transcribe: (request: { samples: Float32Array; language?: string }) => Promise<{
segments: CaptionSegment[];
@@ -35,7 +47,7 @@ interface RendererSttApi {
detectedLanguage: string;
backend: string;
}>;
- onStatus?: (callback: (event: { phase: SttRendererStatusPhase }) => void) => () => void;
+ onStatus?: (callback: (event: SttRendererStatus) => void) => () => void;
}
/**
@@ -52,7 +64,7 @@ export function transcribeMono16kToSegments(
samples: Float32Array,
options?: {
trimRegions?: TrimRegion[];
- onStatus?: (phase: SttRendererStatusPhase) => void;
+ onStatus?: (status: SttRendererStatus) => void;
signal?: AbortSignal;
language?: string;
},
@@ -67,8 +79,7 @@ export function transcribeMono16kToSegments(
return Promise.resolve({ segments: [], granularity: "word" });
}
- const unsubscribe =
- options?.onStatus && api.onStatus?.((event) => options.onStatus?.(event.phase));
+ const unsubscribe = options?.onStatus && api.onStatus?.((event) => options.onStatus?.(event));
const forcedLanguage =
options?.language && options.language !== "auto" ? options.language : undefined;
// ponytail: word timestamps come back already absolute from whisper.cpp