Skip to content

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

feat(stt): surface the transcription timing and backend the helper reports

EtienneLescot644bce1b78fa
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.ts
index a6829aaa3..8facfdeb3 100644
--- a/electron/stt/index.test.ts
+++ b/electron/stt/index.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
import { planChunks } from "./chunking";
import { _resetSttManagerForTests, getSttManager, SttManager, shutdownStt } from "./index";
@@ -50,6 +50,9 @@ vi.mock("./gpuDetector", () => ({
}));
describe("SttManager", () => {
+ let infoSpy: MockInstance<typeof console.info>;
+ let warnSpy: MockInstance<typeof console.warn>;
+
beforeEach(() => {
fakeWhisperServer.start.mockClear();
fakeWhisperServer.transcribe.mockClear();
@@ -63,10 +66,17 @@ describe("SttManager", () => {
backend: "whispercpp-cpu",
});
_resetSttManagerForTests();
+ // The manager narrates every chunk (backend + timing) through `console.*`,
+ // which is what puts those lines in the main-process ring buffer. Capture
+ // them instead of letting a dozen lines per test onto the suite's output.
+ infoSpy = vi.spyOn(console, "info").mockImplementation(() => undefined);
+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
});
afterEach(() => {
_resetSttManagerForTests();
+ infoSpy.mockRestore();
+ warnSpy.mockRestore();
});
it("init() forwards model + transcribe phases to the sink", async () => {
@@ -131,6 +141,114 @@ describe("SttManager", () => {
}
});
+ /** The default fake answers without timing; this one measures every chunk. */
+ function mockTimedChunks(): void {
+ fakeWhisperServer.transcribe.mockResolvedValue({
+ segments: [],
+ wordSegments: [],
+ detectedLanguage: "en",
+ backend: "whispercpp-cpu",
+ timing: { elapsedSec: 45, audioSec: 90, rtf: 0.5 },
+ });
+ }
+
+ it("sums per-chunk timing into one figure for the whole run", async () => {
+ mockTimedChunks();
+ 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" });
+
+ // Summed, not averaged: chunks differ in length, so the mean of the
+ // per-chunk RTFs would not be the RTF of the run.
+ const chunkCount = planChunks(samples, 16000).length;
+ expect(chunkCount).toBeGreaterThan(1);
+ expect(result.timing).toEqual({
+ elapsedSec: 45 * chunkCount,
+ audioSec: 90 * chunkCount,
+ rtf: 0.5,
+ });
+ });
+
+ it("logs the backend and the timing of every chunk", async () => {
+ mockTimedChunks();
+ const samples = new Float32Array(200 * 16000);
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ await mgr.transcribe({ samples, language: "en" });
+
+ const chunkLines = infoSpy.mock.calls
+ .map(([line]) => String(line))
+ .filter((line) => line.startsWith("[stt] chunk "));
+ expect(chunkLines).toHaveLength(planChunks(samples, 16000).length);
+ // Both conventions on the line, so it can be read against the POC report
+ // without arithmetic.
+ expect(chunkLines[0]).toContain("whispercpp-cpu");
+ expect(chunkLines[0]).toContain("90.0s audio in 45.0s (0.50 rtf, 2.0x real-time)");
+ });
+
+ it("says so when the helper reports no timing at all", async () => {
+ // The default fake stands in for a staged binary older than the field.
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ const result = await mgr.transcribe({ samples: new Float32Array(16000) });
+ expect(result.timing).toBeUndefined();
+ expect(infoSpy.mock.calls.some(([line]) => String(line).includes("no timing reported"))).toBe(
+ true,
+ );
+ });
+
+ it("puts the backend and a running rtf on every chunk's status event", async () => {
+ mockTimedChunks();
+ const samples = new Float32Array(200 * 16000);
+ const sink = vi.fn<(e: SttStatusEvent) => void>();
+ const mgr = new SttManager();
+ await mgr.init({ statusSink: sink, modelsBaseDir: "/tmp/fake-stt-models" });
+ sink.mockClear();
+ await mgr.transcribe({ samples, language: "en" });
+
+ // The response alone is too late to be a signal: it arrives once the whole
+ // recording is done, and the point is to explain the wait while it happens.
+ const reported = sink.mock.calls
+ .map(([event]) => event)
+ .filter((event) => event.backend !== undefined);
+ expect(reported).toHaveLength(planChunks(samples, 16000).length);
+ for (const event of reported) {
+ expect(event.backend).toBe("whispercpp-cpu");
+ expect(event.rtf).toBeCloseTo(0.5);
+ }
+ });
+
+ it("warns once per run — not once per chunk — that it landed on CPU", async () => {
+ mockTimedChunks();
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ await mgr.transcribe({ samples: new Float32Array(200 * 16000), language: "en" });
+
+ const cpuWarnings = warnSpy.mock.calls
+ .map(([line]) => String(line))
+ .filter((line) => line.includes("running on CPU"));
+ expect(cpuWarnings).toHaveLength(1);
+ });
+
+ it("stays quiet about the backend when a GPU one is bound", async () => {
+ fakeWhisperServer.transcribe.mockResolvedValue({
+ segments: [],
+ wordSegments: [],
+ detectedLanguage: "en",
+ backend: "whispercpp-vulkan",
+ timing: { elapsedSec: 20, audioSec: 90, rtf: 20 / 90 },
+ });
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ const result = await mgr.transcribe({ samples: new Float32Array(200 * 16000) });
+
+ expect(result.backend).toBe("whispercpp-vulkan");
+ expect(warnSpy.mock.calls.some(([line]) => String(line).includes("running on CPU"))).toBe(
+ false,
+ );
+ });
+
// Both spellings of "detect it for me". `"auto"` is the one the request
// contract documents, and it is truthy — which is exactly how it used to slip
// past the pin and let every chunk detect its own language.
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index 066186a40..b600c0cc1 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -5,6 +5,7 @@ import { ensureModels, modelPaths } from "./modelManager";
import type {
SttPhraseSegment,
SttStatusEvent,
+ SttTiming,
SttTranscribeRequest,
SttTranscribeResponse,
SttWordSegment,
@@ -61,6 +62,26 @@ function cancelledError(): Error {
return error;
}
+/**
+ * One transcription's cost, in both of the conventions this repo uses.
+ *
+ * whisper.cpp and the POC report measure RTF — wall-clock divided by audio, so
+ * LOWER is faster — while the figure that means something to a reader is its
+ * reciprocal ("2.1x real-time"). Printing both lets a log line be compared
+ * against tools/stt-eval/whispercpp-dtw-poc/REPORT.md 5 without arithmetic.
+ *
+ * ASCII "x" rather than the report's "×" glyph: these lines are read in a
+ * Windows console and in the diagnostics dump, neither of which is reliably
+ * UTF-8.
+ */
+function formatTiming(timing: SttTiming): string {
+ const speed = timing.rtf > 0 ? 1 / timing.rtf : 0;
+ return (
+ `${timing.audioSec.toFixed(1)}s audio in ${timing.elapsedSec.toFixed(1)}s ` +
+ `(${timing.rtf.toFixed(2)} rtf, ${speed.toFixed(1)}x real-time)`
+ );
+}
+
export interface SttManagerInitOptions {
statusSink?: (event: SttStatusEvent) => void;
/** Override the models cache directory; defaults to `app.getPath("userData") + "/stt-models"`. */
@@ -228,6 +249,13 @@ export class SttManager {
const wordSegments: SttWordSegment[] = [];
let detectedLanguage: string | null = null;
let backend = this.server.status.backend ?? "whispercpp-cpu";
+ // Summed, not averaged: chunks differ in length, so the mean of the
+ // per-chunk RTFs is not the RTF of the run.
+ let elapsedSec = 0;
+ let audioSec = 0;
+ let timedChunks = 0;
+ // The CPU verdict is worth saying once per run, not once per chunk.
+ let warnedCpu = false;
// Only the first chunk auto-detects; every later chunk is forced onto the
// language it resolved, so whisper cannot flip mid-recording on a chunk
// that opens with a proper noun or a silence and "transcribe" the rest as
@@ -298,18 +326,58 @@ export class SttManager {
if (!language) language = detectedLanguage;
}
backend = result.backend ?? backend;
+ if (result.timing) {
+ elapsedSec += result.timing.elapsedSec;
+ audioSec += result.timing.audioSec;
+ timedChunks++;
+ }
+ const runRtf = audioSec > 0 ? elapsedSec / audioSec : undefined;
+ // Through `console.*` on purpose: that is what the main-process ring
+ // buffer wraps (electron/diagnostics/main-log-buffer.ts), so these lines
+ // reach "Save Diagnostics". The helper's own stderr is forwarded with
+ // `process.stderr.write` in whisperServer.ts and never lands there.
+ console.info(
+ `[stt] chunk ${index + 1}/${chunks.length} on ${backend}: ` +
+ (result.timing
+ ? formatTiming(result.timing)
+ : "no timing reported (staged helper binary pre-dates the field)"),
+ );
+ // Falling back to CPU is silent on both sides — the helper retries
+ // without GPU when init returns null, and this process can relaunch the
+ // helper with `--cpu` — and it costs about half the throughput. A user
+ // staring at a transcription that takes twice as long has, without this,
+ // nothing anywhere telling them why.
+ if (!warnedCpu && backend === "whispercpp-cpu") {
+ warnedCpu = true;
+ console.warn(
+ "[stt] running on CPU - no GPU backend was bound. Expect roughly half " +
+ "the throughput of the Vulkan/Metal path (median 2.07x on the reference " +
+ "machine, tools/stt-eval/whispercpp-dtw-poc/REPORT.md 5.3).",
+ );
+ }
this.emit({
phase: "transcribe",
completedSec: chunk.endSample / SAMPLE_RATE,
totalSec,
+ backend,
+ rtf: runRtf,
});
}
+ const timing: SttTiming | undefined =
+ timedChunks > 0 && audioSec > 0
+ ? { elapsedSec, audioSec, rtf: elapsedSec / audioSec }
+ : undefined;
+ console.info(
+ `[stt] done on ${backend}: ${chunks.length} chunk(s), ` +
+ (timing ? formatTiming(timing) : "no timing reported"),
+ );
return {
segments,
wordSegments,
detectedLanguage: detectedLanguage ?? language ?? "auto",
backend,
+ timing,
};
}
diff --git a/electron/stt/transcriptionContract.ts b/electron/stt/transcriptionContract.ts
index 2fa8a88eb..68db62cc6 100644
--- a/electron/stt/transcriptionContract.ts
+++ b/electron/stt/transcriptionContract.ts
@@ -38,6 +38,28 @@ export type SttBackend =
| "whispercpp-cuda"
| "whispercpp-cpu";
+/**
+ * Wall-clock cost of a transcription, measured by the helper around
+ * `whisper_full` (`electron/native/whisper-stt/src/main.cpp`) and reported on
+ * every `/inference` response. Used both per chunk and summed over a whole run.
+ *
+ * `rtf` follows whisper.cpp's convention, which is also the POC report's:
+ * wall-clock DIVIDED BY audio duration, so lower is faster and < 1 means faster
+ * than real-time. The figure a reader can act on ("2.1x real-time") is its
+ * reciprocal — see `realtimeSpeed()` in
+ * `src/lib/ai-edition/transcription/status.ts`.
+ *
+ * Optional everywhere it appears because a staged helper binary can pre-date
+ * the `timing` field: `electron/native/bin/<tag>/` is gitignored, so a dev tree
+ * keeps whatever was last built there. Absent rather than zeroed on purpose —
+ * "not reported" and "took no time" must not render the same way.
+ */
+export interface SttTiming {
+ elapsedSec: number;
+ audioSec: number;
+ rtf: number;
+}
+
/** Status phase the renderer surfaces over `onStatus("model" | "transcribe")`. */
export type SttStatusPhase = "model" | "transcribe";
@@ -58,6 +80,24 @@ export interface SttStatusEvent {
*/
completedSec?: number;
totalSec?: number;
+ /**
+ * Backend the helper ACTUALLY bound, as reported by the chunk that just
+ * landed — not `gpuDetector`'s guess, which only picks a binary.
+ *
+ * This is the only signal a user has that they are on the slow path. Both
+ * routes onto it are silent (the helper retries without GPU when init
+ * returns null; the Node side can relaunch with `--cpu`), and the CPU path
+ * costs roughly half the throughput — median 2.07x on the reference machine,
+ * see tools/stt-eval/whispercpp-dtw-poc/REPORT.md 5.3.
+ */
+ backend?: SttBackend;
+ /**
+ * Real-time factor for the run SO FAR (total wall-clock / total audio), not
+ * for the chunk that just landed. Per-chunk values swing with how much speech
+ * a chunk happens to hold, and a figure that jumps every 90s reads as noise
+ * rather than as progress.
+ */
+ rtf?: number;
}
/** IPC request: renderer → main. */
@@ -76,6 +116,8 @@ export interface SttTranscribeResponse {
wordSegments: SttWordSegment[];
detectedLanguage: string;
backend: SttBackend;
+ /** Summed over every chunk of this request; absent if no chunk reported timing. */
+ timing?: SttTiming;
}
/** IPC success envelope; thrown errors cross as a rejection. */
diff --git a/electron/stt/whisperServer.test.ts b/electron/stt/whisperServer.test.ts
index 80e861636..b8851157e 100644
--- a/electron/stt/whisperServer.test.ts
+++ b/electron/stt/whisperServer.test.ts
@@ -168,6 +168,76 @@ describe("WhisperServerManager", () => {
}
});
+ /** Answer `/inference` with one canned body and run a single transcription. */
+ async function transcribeWith(json: unknown) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(JSON.stringify(json), { status: 200 })),
+ );
+ try {
+ const mgr = new WhisperServerManager();
+ (mgr as unknown as { process: unknown; port: number }).process = {};
+ (mgr as unknown as { process: unknown; port: number }).port = 9999;
+ return await mgr.transcribe({ samples: new Float32Array(1600) });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ }
+
+ it("reads the helper's timing block off an /inference response", async () => {
+ const result = await transcribeWith({
+ segments: [],
+ detected_language: "english",
+ backend: "whispercpp-vulkan",
+ timing: { elapsed_s: 5.5, audio_s: 11, rtf: 0.5 },
+ });
+ expect(result.timing).toEqual({ elapsedSec: 5.5, audioSec: 11, rtf: 0.5 });
+ });
+
+ // A staged binary older than the `timing` field just omits it — and
+ // `electron/native/bin/<tag>/` is gitignored, so a dev tree keeps whatever was
+ // last built there. Null, not zeroes: "not reported" and "took no time" must
+ // not reach the UI looking the same.
+ it("reports no timing at all when the helper omits the block", async () => {
+ const result = await transcribeWith({
+ segments: [],
+ detected_language: "english",
+ backend: "whispercpp-cpu",
+ });
+ expect(result.timing).toBeNull();
+ });
+
+ // `rtf` is derived from the other two, so a junk ratio is recoverable — and a
+ // NaN surviving this far would reach the renderer as "NaN× real-time".
+ it("recomputes rtf when the helper's own value is unusable", async () => {
+ const result = await transcribeWith({
+ segments: [],
+ backend: "whispercpp-cpu",
+ timing: { elapsed_s: 4, audio_s: 8, rtf: "not-a-number" },
+ });
+ expect(result.timing).toEqual({ elapsedSec: 4, audioSec: 8, rtf: 0.5 });
+ });
+
+ // Same defensive parse the segment bounds get: nothing on this wire is
+ // guaranteed by a schema.
+ it("accepts stringified durations", async () => {
+ const result = await transcribeWith({
+ segments: [],
+ backend: "whispercpp-cpu",
+ timing: { elapsed_s: "4", audio_s: "8", rtf: "0.5" },
+ });
+ expect(result.timing).toEqual({ elapsedSec: 4, audioSec: 8, rtf: 0.5 });
+ });
+
+ it("rejects a timing block with no usable durations", async () => {
+ const result = await transcribeWith({
+ segments: [],
+ backend: "whispercpp-cpu",
+ timing: { rtf: 0.5 },
+ });
+ expect(result.timing).toBeNull();
+ });
+
describe("WhisperServerManager language normalization", () => {
function captureFormField(language: string | undefined): Promise<string | null> {
return new Promise((resolve, reject) => {
diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.ts
index 1d8d667aa..5eb43fb19 100644
--- a/electron/stt/whisperServer.ts
+++ b/electron/stt/whisperServer.ts
@@ -8,7 +8,12 @@ import type { Readable } from "node:stream";
import { resolveBinaryPath } from "./gpuDetector";
import { snapWordBoundariesToAudio } from "./snapWordBoundaries";
-import type { SttBackend, SttPhraseSegment, SttWordSegment } from "./transcriptionContract";
+import type {
+ SttBackend,
+ SttPhraseSegment,
+ SttTiming,
+ SttWordSegment,
+} from "./transcriptionContract";
import { cleanupWav, writeSamplesAsWav } from "./wav";
/** whisper.cpp helper is stdio-shaped: stdin ignored, stdout/stderr captured. */
@@ -88,11 +93,23 @@ interface WhisperJsonSegment {
words?: WhisperJsonWord[];
}
+/**
+ * The helper's `timing` block, in its own snake_case wire spelling. Every field
+ * is optional and may arrive as a string for the same reason the segment bounds
+ * may (see `toSec`): nothing on the wire is guaranteed by a schema.
+ */
+interface WhisperJsonTiming {
+ elapsed_s?: number | string;
+ audio_s?: number | string;
+ rtf?: number | string;
+}
+
interface WhisperJsonResponse {
segments?: WhisperJsonSegment[];
language?: string;
detected_language?: string;
backend?: string;
+ timing?: WhisperJsonTiming;
}
export class WhisperServerManager {
@@ -445,12 +462,41 @@ export class WhisperServerManager {
return Number.isFinite(n) ? n : fallback;
}
+ /**
+ * Read the helper's `timing` block, or null when it is missing or unusable.
+ *
+ * Null rather than zeroes: a helper binary built before the field existed
+ * simply omits it, and callers have to be able to tell that apart from a
+ * transcription that genuinely took no time — one is "we don't know", the
+ * other would be a bug worth showing.
+ *
+ * `rtf` is recomputed from the two durations whenever the helper didn't send
+ * a usable one. It is derived data, and a NaN surviving this far would reach
+ * the UI as "NaN x real-time".
+ */
+ private toTiming(raw: WhisperJsonTiming | undefined): SttTiming | null {
+ if (!raw || typeof raw !== "object") return null;
+ const elapsedSec = this.toSec(raw.elapsed_s, Number.NaN);
+ const audioSec = this.toSec(raw.audio_s, Number.NaN);
+ if (!Number.isFinite(elapsedSec) || !Number.isFinite(audioSec)) return null;
+ const reported = this.toSec(raw.rtf, Number.NaN);
+ const rtf =
+ Number.isFinite(reported) && reported > 0
+ ? reported
+ : audioSec > 0
+ ? elapsedSec / audioSec
+ : 0;
+ return { elapsedSec, audioSec, rtf };
+ }
+
/** Run one transcription; serializes concurrent callers. */
async transcribe(opts: { samples: Float32Array; language?: string }): Promise<{
segments: SttPhraseSegment[];
wordSegments: SttWordSegment[];
detectedLanguage: string;
backend: SttBackend;
+ /** Null when the helper reported no usable `timing` block. */
+ timing: SttTiming | null;
}> {
const task = this.inFlight.then(() => this.transcribeImpl(opts));
this.inFlight = task.catch(() => undefined);
@@ -462,6 +508,7 @@ export class WhisperServerManager {
wordSegments: SttWordSegment[];
detectedLanguage: string;
backend: SttBackend;
+ timing: SttTiming | null;
}> {
const wavPath = await writeSamplesAsWav(opts.samples);
try {
@@ -494,7 +541,8 @@ export class WhisperServerManager {
);
const detectedLanguage = json.detected_language ?? json.language ?? "auto";
const backend = this.toBackend(json.backend);
- return { segments, wordSegments, detectedLanguage, backend };
+ const timing = this.toTiming(json.timing);
+ return { segments, wordSegments, detectedLanguage, backend, timing };
} finally {
await cleanupWav(wavPath);
}
diff --git a/src/components/ai-edition/TranscriptionStatus.tsx b/src/components/ai-edition/TranscriptionStatus.tsx
index 5d74dd55f..bae6a0976 100644
--- a/src/components/ai-edition/TranscriptionStatus.tsx
+++ b/src/components/ai-edition/TranscriptionStatus.tsx
@@ -11,7 +11,9 @@ import { Loader2 } from "lucide-react";
import { useScopedT } from "@/contexts/I18nContext";
import {
type AssetTranscriptionView,
+ isCpuBackend,
progressFraction,
+ realtimeSpeed,
} from "@/lib/ai-edition/transcription/status";
/** Human-readable state of one asset's transcript, in the user's language. */
@@ -34,9 +36,21 @@ export function useTranscriptionLabel(): (view: AssetTranscriptionView) => strin
// hang, so append the percentage as soon as the main process reports
// chunk progress — and only then (see `TranscriptionProgressBar`).
const fraction = progressFraction(view.progress);
- return fraction === null
- ? t("mediaStage.transcribing")
- : `${t("mediaStage.transcribing")} ${Math.round(fraction * 100)}%`;
+ const head =
+ fraction === null
+ ? t("mediaStage.transcribing")
+ : `${t("mediaStage.transcribing")} ${Math.round(fraction * 100)}%`;
+ // Two things only the run itself knows: which device is doing the work,
+ // and how fast. "CPU" appears on the slow path ONLY — naming the GPU
+ // backend on every healthy run would be noise, whereas landing on CPU
+ // costs about half the throughput and happens through fallbacks that are
+ // otherwise completely silent. The speed shows on any backend: "is this
+ // moving, and how fast" is the same question at 5× as at 0.9×.
+ const suffix: string[] = [];
+ if (isCpuBackend(view.backend)) suffix.push("CPU");
+ const speed = realtimeSpeed(view.rtf);
+ if (speed !== null) suffix.push(`${speed.toFixed(1)}×`);
+ return suffix.length === 0 ? head : `${head} · ${suffix.join(" · ")}`;
}
case "empty":
return t("mediaStage.noSpeechDetected");
@@ -68,7 +82,12 @@ export function TranscriptionStatusDot({
view: AssetTranscriptionView;
size?: number;
}) {
+ const t = useScopedT("editor");
const label = useTranscriptionLabel()(view);
+ // The label says "CPU"; this says what that costs. It has to be a <title>
+ // CHILD rather than the `title` attribute the dot below uses — lucide renders
+ // children inside its <svg>, and SVG has no tooltip-bearing `title` attribute.
+ const cpuHint = isCpuBackend(view.backend) ? t("mediaStage.cpuBackendHint") : null;
if (view.status === "running" || view.status === "queued") {
return (
<Loader2
@@ -76,7 +95,9 @@ export function TranscriptionStatusDot({
className="animate-spin"
style={{ color: "var(--accent)", flexShrink: 0 }}
aria-label={label}
- />
+ >
+ <title>{cpuHint ? `${label} — ${cpuHint}` : label}</title>
+ </Loader2>
);
}
const { fill, halo } = DOT_COLOR[view.status];
diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.json
index acac12eb2..c16264d02 100644
--- a/src/i18n/locales/ar/editor.json
+++ b/src/i18n/locales/ar/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "جارٍ النسخ…",
"pendingTranscription": "بانتظار النسخ",
"transcriptionFailed": "فشل النسخ",
+ "cpuBackendHint": "يعمل على المعالج — أبطأ بنحو 2× من معالج الرسوميات",
"noTranscript": "لا يوجد نص مكتوب",
"generating": "جارٍ الإنشاء",
"generationFailed": "فشل الإنشاء",
diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.json
index cc09660de..82c983b99 100644
--- a/src/i18n/locales/en/editor.json
+++ b/src/i18n/locales/en/editor.json
@@ -144,6 +144,7 @@
"transcribingEllipsis": "Transcribing…",
"pendingTranscription": "Pending transcription",
"transcriptionFailed": "Transcription failed",
+ "cpuBackendHint": "Running on CPU — about 2× slower than on the GPU",
"noTranscript": "No transcript",
"notGeneratedYet": "Not generated yet",
"regenerateAs": "Regenerate as",
diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.json
index 2124adde1..5a9dad91b 100644
--- a/src/i18n/locales/es/editor.json
+++ b/src/i18n/locales/es/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Transcribiendo…",
"pendingTranscription": "Transcripción pendiente",
"transcriptionFailed": "Error de transcripción",
+ "cpuBackendHint": "Ejecutándose en la CPU — unas 2× más lento que en la GPU",
"noTranscript": "Sin transcripción",
"generating": "Generando",
"generationFailed": "Error de generación",
diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.json
index 96e0e94c7..4a731a578 100644
--- a/src/i18n/locales/fr/editor.json
+++ b/src/i18n/locales/fr/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Transcription en cours…",
"pendingTranscription": "Transcription en attente",
"transcriptionFailed": "Échec de la transcription",
+ "cpuBackendHint": "Exécution sur le processeur — environ 2× plus lent que sur le GPU",
"noTranscript": "Aucune transcription",
"generating": "Génération en cours",
"generationFailed": "Échec de la génération",
diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.json
index e08a7f833..fdaf30c80 100644
--- a/src/i18n/locales/it/editor.json
+++ b/src/i18n/locales/it/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Trascrizione in corso…",
"pendingTranscription": "Trascrizione in attesa",
"transcriptionFailed": "Trascrizione non riuscita",
+ "cpuBackendHint": "In esecuzione su CPU — circa 2× più lento che su GPU",
"noTranscript": "Nessuna trascrizione",
"generating": "Generazione in corso",
"generationFailed": "Generazione non riuscita",
diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.json
index 524ed5156..355d807fe 100644
--- a/src/i18n/locales/ja-JP/editor.json
+++ b/src/i18n/locales/ja-JP/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "文字起こし中…",
"pendingTranscription": "文字起こし待機中",
"transcriptionFailed": "文字起こしに失敗しました",
+ "cpuBackendHint": "CPU で実行中 — GPU より約 2 倍低速です",
"noTranscript": "文字起こしなし",
"generating": "生成中",
"generationFailed": "生成に失敗しました",
diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.json
index ec6a431c9..29b4e60c1 100644
--- a/src/i18n/locales/ko-KR/editor.json
+++ b/src/i18n/locales/ko-KR/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "받아쓰는 중…",
"pendingTranscription": "받아쓰기 대기 중",
"transcriptionFailed": "받아쓰기 실패",
+ "cpuBackendHint": "CPU에서 실행 중 — GPU보다 약 2배 느립니다",
"noTranscript": "대본 없음",
"generating": "생성 중",
"generationFailed": "생성 실패",
diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.json
index 183e2c82f..5716ff9b6 100644
--- a/src/i18n/locales/pt-BR/editor.json
+++ b/src/i18n/locales/pt-BR/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Transcrevendo…",
"pendingTranscription": "Transcrição pendente",
"transcriptionFailed": "Falha na transcrição",
+ "cpuBackendHint": "Executando na CPU — cerca de 2× mais lento do que na GPU",
"noTranscript": "Sem transcrição",
"generating": "Gerando",
"generationFailed": "Falha na geração",
diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.json
index b6c3bf906..86b3f52d3 100644
--- a/src/i18n/locales/ru/editor.json
+++ b/src/i18n/locales/ru/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Расшифровка…",
"pendingTranscription": "Ожидает расшифровки",
"transcriptionFailed": "Ошибка расшифровки",
+ "cpuBackendHint": "Выполняется на процессоре — примерно в 2× медленнее, чем на GPU",
"noTranscript": "Нет расшифровки",
"generating": "Создание",
"generationFailed": "Ошибка создания",
diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.json
index 81abd078e..e05cad9a2 100644
--- a/src/i18n/locales/tr/editor.json
+++ b/src/i18n/locales/tr/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Metne dökülüyor…",
"pendingTranscription": "Metne dökme bekliyor",
"transcriptionFailed": "Metne dökme başarısız oldu",
+ "cpuBackendHint": "CPU üzerinde çalışıyor — GPU'ya göre yaklaşık 2× daha yavaş",
"noTranscript": "Transkript yok",
"generating": "Oluşturuluyor",
"generationFailed": "Oluşturma başarısız oldu",
diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.json
index 43f878897..6465e36f5 100644
--- a/src/i18n/locales/vi/editor.json
+++ b/src/i18n/locales/vi/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "Đang phiên âm…",
"pendingTranscription": "Đang chờ phiên âm",
"transcriptionFailed": "Phiên âm thất bại",
+ "cpuBackendHint": "Đang chạy trên CPU — chậm hơn khoảng 2× so với GPU",
"noTranscript": "Không có bản ghi lời thoại",
"generating": "Đang tạo",
"generationFailed": "Tạo thất bại",
diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.json
index 0d0689992..c657d4f6f 100644
--- a/src/i18n/locales/zh-CN/editor.json
+++ b/src/i18n/locales/zh-CN/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "正在转录…",
"pendingTranscription": "等待转录",
"transcriptionFailed": "转录失败",
+ "cpuBackendHint": "正在使用 CPU 运行 — 比 GPU 慢约 2 倍",
"noTranscript": "没有转录文本",
"generating": "正在生成",
"generationFailed": "生成失败",
diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.json
index f37bfe620..82665476b 100644
--- a/src/i18n/locales/zh-TW/editor.json
+++ b/src/i18n/locales/zh-TW/editor.json
@@ -150,6 +150,7 @@
"transcribingEllipsis": "轉錄中…",
"pendingTranscription": "等待轉錄",
"transcriptionFailed": "轉錄失敗",
+ "cpuBackendHint": "正在使用 CPU 執行 — 比 GPU 慢約 2 倍",
"noTranscript": "沒有逐字稿",
"generating": "產生中",
"generationFailed": "產生失敗",
diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.ts
index 0c0a23aa8..d0e587e6a 100644
--- a/src/lib/ai-edition/document/transcribe.ts
+++ b/src/lib/ai-edition/document/transcribe.ts
@@ -18,6 +18,10 @@ export interface TranscribeStatus {
phase: "extracting-audio" | "loading-model" | "transcribing";
completedSec?: number;
totalSec?: number;
+ /** Backend the helper bound for this run; `"whispercpp-cpu"` is the slow path. */
+ backend?: string;
+ /** Real-time factor for the run so far — wall-clock / audio, lower is faster. */
+ rtf?: number;
}
export interface TranscribeAssetOptions {
@@ -63,6 +67,11 @@ export async function transcribeAsset(
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,
}),
});
diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts
index 3c3c1139f..d851bd4a8 100644
--- a/src/lib/ai-edition/store/transcriptionStore.ts
+++ b/src/lib/ai-edition/store/transcriptionStore.ts
@@ -52,6 +52,13 @@ export interface TranscriptionJob {
phase?: TranscriptionPhase;
/** Chunk progress while transcribing; absent until the first chunk lands. */
progress?: TranscriptionProgress;
+ /**
+ * Which device the engine bound, and how fast it is going. Both arrive with
+ * the first landed chunk and are refreshed by every chunk after it; both stay
+ * absent against a helper binary too old to report timing at all.
+ */
+ backend?: string;
+ rtf?: number;
/** `"auto"` unless the user forced a language from the media card. */
language: string;
failure?: TranscriptionFailure;
@@ -369,6 +376,12 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {
status.completedSec !== undefined && status.totalSec !== undefined
? { completedSec: status.completedSec, totalSec: status.totalSec }
: undefined,
+ // Omitted rather than set to undefined when absent: `patchJob` spreads
+ // this object over the job, so a key that is present-but-undefined
+ // would blank out what the last chunk reported. The phases before the
+ // first chunk (audio extraction, the model download) carry neither.
+ ...(status.backend !== undefined ? { backend: status.backend } : {}),
+ ...(status.rtf !== undefined ? { rtf: status.rtf } : {}),
}),
});
if (controller.signal.aborted) {
diff --git a/src/lib/ai-edition/transcription/status.test.ts b/src/lib/ai-edition/transcription/status.test.ts
index 00d8864e1..00261712e 100644
--- a/src/lib/ai-edition/transcription/status.test.ts
+++ b/src/lib/ai-edition/transcription/status.test.ts
@@ -4,8 +4,10 @@ import {
type AssetTranscriptionView,
classifyTranscriptionError,
deriveAssetStatus,
+ isCpuBackend,
isPermanentFailure,
progressFraction,
+ realtimeSpeed,
resolveTranscriptGate,
transcriptHasSpeech,
transcriptRelevantAssetIds,
@@ -291,3 +293,60 @@ describe("transcriptRelevantAssetIds", () => {
expect(transcriptRelevantAssetIds(null)).toEqual([]);
});
});
+
+describe("realtimeSpeed", () => {
+ // The engine reports RTF (wall-clock / audio, lower is faster); the UI shows
+ // its reciprocal, which is the figure the POC report headlines.
+ it("inverts the engine's RTF into x-real-time", () => {
+ expect(realtimeSpeed(0.5)).toBe(2);
+ expect(realtimeSpeed(0.19)).toBeCloseTo(5.26, 2);
+ });
+
+ // Null rather than 0: a helper binary older than the `timing` field reports
+ // nothing at all, and "0.0x" would read as a measurement rather than a gap.
+ it.each([
+ ["undefined", undefined],
+ ["zero", 0],
+ ["negative", -1],
+ ["NaN", Number.NaN],
+ ["Infinity", Number.POSITIVE_INFINITY],
+ ])("has no answer for %s", (_label, rtf) => {
+ expect(realtimeSpeed(rtf)).toBeNull();
+ });
+});
+
+describe("isCpuBackend", () => {
+ it("singles out the CPU path and nothing else", () => {
+ expect(isCpuBackend("whispercpp-cpu")).toBe(true);
+ expect(isCpuBackend("whispercpp-vulkan")).toBe(false);
+ expect(isCpuBackend("whispercpp-metal")).toBe(false);
+ expect(isCpuBackend("whispercpp-cuda")).toBe(false);
+ expect(isCpuBackend(undefined)).toBe(false);
+ });
+});
+
+describe("deriveAssetStatus carries the engine's own report", () => {
+ // Both facts come from the main process on the chunk status events, and the
+ // view is the only thing the three status surfaces read.
+ it("passes the running job's backend and rtf onto the view", () => {
+ const derived = deriveAssetStatus({
+ assetId: "a",
+ job: { status: "running", backend: "whispercpp-cpu", rtf: 1.1 },
+ });
+ expect(derived.backend).toBe("whispercpp-cpu");
+ expect(derived.rtf).toBe(1.1);
+ });
+
+ // A finished run's transcript says nothing about the device that produced it,
+ // so the view must not carry a stale badge over a "ready" asset.
+ it("drops them once a transcript exists", () => {
+ const derived = deriveAssetStatus({
+ assetId: "a",
+ job: { status: "failed", backend: "whispercpp-cpu", rtf: 1.1 },
+ transcript: transcript("a", ["hello"]),
+ });
+ expect(derived.status).toBe("ready");
+ expect(derived.backend).toBeUndefined();
+ expect(derived.rtf).toBeUndefined();
+ });
+});
diff --git a/src/lib/ai-edition/transcription/status.ts b/src/lib/ai-edition/transcription/status.ts
index f05454b66..64fdb411c 100644
--- a/src/lib/ai-edition/transcription/status.ts
+++ b/src/lib/ai-edition/transcription/status.ts
@@ -40,6 +40,32 @@ export function progressFraction(progress: TranscriptionProgress | undefined): n
return Math.min(1, Math.max(0, progress.completedSec / progress.totalSec));
}
+/**
+ * Turn the engine's RTF (wall-clock / audio, whisper.cpp's convention, lower is
+ * faster) into the figure a reader can act on: "× real-time", where 2.1 means
+ * 2.1 seconds of audio transcribed per second of work.
+ *
+ * Null whenever nothing usable was reported — a helper binary older than the
+ * `timing` field sends none at all — so the UI shows no figure rather than a
+ * confident "0.0×".
+ */
+export function realtimeSpeed(rtf: number | undefined): number | null {
+ if (rtf === undefined || !Number.isFinite(rtf) || rtf <= 0) return null;
+ return 1 / rtf;
+}
+
+/**
+ * True when the run is on the CPU path rather than a GPU one.
+ *
+ * Worth its own predicate because it is the one backend value that changes what
+ * the user should expect: the same helper on the GPU is ~2x faster (median
+ * 2.07x, tools/stt-eval/whispercpp-dtw-poc/REPORT.md 5.3), and every route onto
+ * the CPU path is a silent fallback.
+ */
+export function isCpuBackend(backend: string | undefined): boolean {
+ return backend === "whispercpp-cpu";
+}
+
/**
* A media that has no audio track (or one Whisper cannot read) will fail the
* same way on every attempt, so that verdict is worth remembering: it is
@@ -94,6 +120,14 @@ export interface AssetTranscriptionView {
phase?: TranscriptionPhase;
progress?: TranscriptionProgress;
failure?: TranscriptionFailure;
+ /**
+ * Backend the running job is actually using, once a chunk has reported one.
+ * Only meaningful while `status === "running"` — it describes a run in
+ * flight, not the transcript a finished run left behind.
+ */
+ backend?: string;
+ /** Real-time factor for the run so far; pair with `realtimeSpeed()` to display. */
+ rtf?: number;
}
/** In-flight (or last-failed) state of one asset's job. Mirrors the store entry. */
@@ -102,6 +136,8 @@ export interface TranscriptionJobLike {
phase?: TranscriptionPhase;
progress?: TranscriptionProgress;
failure?: TranscriptionFailure;
+ backend?: string;
+ rtf?: number;
}
export function findAssetTranscript(
@@ -144,7 +180,14 @@ export function deriveAssetStatus(input: {
}): AssetTranscriptionView {
const { assetId, job, transcript, persistedFailure } = input;
if (job && job.status !== "failed") {
- return { assetId, status: job.status, phase: job.phase, progress: job.progress };
+ return {
+ assetId,
+ status: job.status,
+ phase: job.phase,
+ progress: job.progress,
+ backend: job.backend,
+ rtf: job.rtf,
+ };
}
if (transcript) {
return {
diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.ts
index 0ac43da2b..3ca985649 100644
--- a/src/lib/captioning/transcribe.ts
+++ b/src/lib/captioning/transcribe.ts
@@ -38,6 +38,13 @@ export interface SttRendererStatus {
phase: SttRendererStatusPhase;
completedSec?: number;
totalSec?: number;
+ /**
+ * Backend the helper actually bound (`"whispercpp-cpu"` when the GPU path was
+ * not taken). Reported per chunk during `"transcribe"`.
+ */
+ backend?: string;
+ /** Real-time factor for the run so far — wall-clock / audio, lower is faster. */
+ rtf?: number;
}
interface RendererSttApi {
diff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.md
index e95147ee4..205f58d0a 100644
--- a/technical-documentation/architecture/transcription-and-captions.md
+++ b/technical-documentation/architecture/transcription-and-captions.md
@@ -380,20 +380,40 @@ export interface SttTranscribeResponse {
detectedLanguage: string;
backend: SttBackend; // "whispercpp-metal" | "whispercpp-vulkan"
// | "whispercpp-cuda" | "whispercpp-cpu"
+ timing?: SttTiming; // { elapsedSec, audioSec, rtf }, summed over the chunks
}
```
`backend` is the device whisper.cpp actually bound at runtime — not the
-platform default `gpuDetector` would have guessed. Any consumer that wants
-to surface the backend in the UI reads it directly out of this field; the
-contract is the source of truth.
+platform default `gpuDetector` would have guessed — and `timing` is the
+helper's own measurement around `whisper_full`, summed over every chunk of
+the request. `rtf` keeps whisper.cpp's convention (wall-clock ÷ audio, so
+lower is faster); the "× real-time" figure the UI shows is its reciprocal,
+via `realtimeSpeed()` in `src/lib/ai-edition/transcription/status.ts`. It is
+optional because a staged helper binary can pre-date the field — absent, not
+zeroed, so "not reported" never renders as a measurement.
+
+For anything user-facing, though, read them off the STATUS events rather than
+this response: the response lands only once the whole recording is done,
+which is far too late to explain a wait that is already happening.
The request takes a raw `Float32Array` of mono 16 kHz PCM and an optional
ISO 639-1 `language` code; `"auto"` or absent leaves detection to Whisper.
Status events fan out on a separate channel
(`SttStatusEvent`, `phase: "model" | "transcribe"`) so the renderer can
drive a "downloading model" / "transcribing" indicator without holding open
-the inference request.
+the inference request. Every landed chunk also carries `backend` and a
+running `rtf` (cumulative for the run, not for that one chunk — a per-chunk
+figure swings with how much speech a chunk holds and reads as noise), which
+is what lets the media surfaces render "Transcribing 45% · CPU · 0.9×" while
+the work is still going.
+
+`SttManager` logs the same pair per chunk through `console.*` — the channel
+the main-process ring buffer wraps, so the lines reach "Save Diagnostics",
+which the helper's own stderr does not — and warns once per run when the
+backend is `whispercpp-cpu`. That warning exists because the CPU path costs
+roughly half the throughput (median 2.07×, see the POC report) and is only
+ever reached through fallbacks that are otherwise completely silent.
## Captions