Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(captions): upgrade whisper and recover GPU startup
Vitali Gusatinskyf61c6dda5e32
diff --git a/electron/native/whisper-stt/src/main.cpp b/electron/native/whisper-stt/src/main.cppindex 339f759b1..9f6abab6e 100644--- a/electron/native/whisper-stt/src/main.cpp+++ b/electron/native/whisper-stt/src/main.cpp@@ -224,6 +224,7 @@ int main(int argc, char** argv) {std::string model_path;std::string host = "127.0.0.1";bool host_from_flag = false;+ bool force_cpu = false;int port = 0;int threads = std::max(1u, std::thread::hardware_concurrency());@@ -233,6 +234,7 @@ int main(int argc, char** argv) {else if (a == "--host" && i + 1 < argc) { host = argv[++i]; host_from_flag = true; }else if (a == "--port" && i + 1 < argc) port = std::atoi(argv[++i]);else if (a == "--threads" && i + 1 < argc) threads = std::atoi(argv[++i]);+ else if (a == "--cpu") force_cpu = true;}// ponytail: prefer env var (matches the prior native STT model env var// shape; the Node wrapper passes both ways).@@ -268,20 +270,28 @@ int main(int argc, char** argv) {// ---- Init whisper context with DTW alignment (POC §4.1) ----whisper_context_params cparams = whisper_context_default_params();- cparams.use_gpu = true; // GPU offload via whatever backend was linked+ cparams.use_gpu = !force_cpu; // Parent retries with --cpu if a GPU backend aborts.cparams.flash_attn = false; // CRITICAL: DTW is silently disabled by v1.9.1// if flash_attn is true; the guardrail in the// /inference handler still runs, but skipping// the request is wasted work.cparams.dtw_token_timestamps = true;- cparams.dtw_aheads_preset = WHISPER_AHEADS_SMALL;+ cparams.dtw_aheads_preset = WHISPER_AHEADS_LARGE_V3_TURBO;whisper_context* ctx = whisper_init_from_file_with_params(model_path.c_str(), cparams);+ if (!ctx && cparams.use_gpu) {+ // Metal/Vulkan allocation can fail transiently when the editor or another+ // creative app is already using most GPU memory. Captions should degrade to+ // a slower CPU run instead of leaving the HTTP readiness probe to time out.+ log("GPU model initialization failed; retrying with CPU inference");+ cparams.use_gpu = false;+ ctx = whisper_init_from_file_with_params(model_path.c_str(), cparams);+ }if (!ctx) {log("whisper_init_from_file_with_params failed for " + model_path);return 3;}- const std::string active_backend = detect_active_backend();- log("model loaded: multilingual small; backend=" + active_backend);+ const std::string active_backend = cparams.use_gpu ? detect_active_backend() : "whispercpp-cpu";+ log("model loaded; backend=" + active_backend);// ---- HTTP server ----httplib::Server svr;diff --git a/electron/stt/index.ts b/electron/stt/index.tsindex aaa597184..398ed3097 100644--- a/electron/stt/index.ts+++ b/electron/stt/index.ts@@ -122,7 +122,7 @@ export class SttManager {if (options.statusSink) this.addStatusSink(options.statusSink);if (options.modelsBaseDir) this.modelsBaseDir = options.modelsBaseDir;if (!this.initPromise) {- // A REJECTED init must not be cached. `prepare()` downloads a 253 MB+ // A REJECTED init must not be cached. `prepare()` downloads a large// model on first run, and caching its rejection meant one dropped// connection poisoned the whole app session: every later transcription// — including the retry the UI offers, and every remaining asset in thediff --git a/electron/stt/modelManager.test.ts b/electron/stt/modelManager.test.tsindex e5f186fbd..e3f90ebf5 100644--- a/electron/stt/modelManager.test.ts+++ b/electron/stt/modelManager.test.ts@@ -19,7 +19,7 @@ describe("modelManager", () => {expect(STT_MODELS.whisper.cacheDir).toBe("whisper-ggml");expect(STT_MODELS.whisper.repoId).toBe("ggerganov/whisper.cpp");expect(STT_MODELS.whisper.files.length).toBe(1);- expect(STT_MODELS.whisper.files[0].name).toBe("ggml-small-q8_0.bin");+ expect(STT_MODELS.whisper.files[0].name).toBe("ggml-large-v3-turbo-q5_0.bin");expect(STT_MODELS.whisper.files[0].expectedSha256).not.toBeNull();for (const f of STT_MODELS.whisper.files) {expect(f.approximateBytes).toBeGreaterThan(0);@@ -32,7 +32,7 @@ describe("modelManager", () => {it("modelPaths places the GGML file under the cache directory", () => {const paths = modelPaths(dir);- expect(paths.whisper).toBe(path.join(dir, "whisper-ggml", "ggml-small-q8_0.bin"));+ expect(paths.whisper).toBe(path.join(dir, "whisper-ggml", "ggml-large-v3-turbo-q5_0.bin"));});it("areModelsPresent returns false when the model file is missing", async () => {@@ -92,7 +92,7 @@ describe("modelManager", () => {expect(fetches).toBe(1);expect(await readFile(paths.whisper)).toEqual(replacement);// The stale copy is displaced by the atomic rename, not quarantined- // beside it: a `.bad` sibling would strand 264 MB nothing ever reaps.+ // beside it: a `.bad` sibling would strand hundreds of MB nothing ever reaps.expect(existsSync(`${paths.whisper}.bad`)).toBe(false);expect(existsSync(`${paths.whisper}.partial`)).toBe(false);} finally {@@ -180,7 +180,7 @@ describe("modelManager", () => {const s = await stat(paths.whisper);expect(s.size).toBeGreaterThan(0);expect(progressCalls.length).toBeGreaterThanOrEqual(1);- expect(progressCalls[0].file).toBe("ggml-small-q8_0.bin");+ expect(progressCalls[0].file).toBe("ggml-large-v3-turbo-q5_0.bin");} finally {STT_MODELS.whisper.files[0].expectedSha256 = originalSha;}diff --git a/electron/stt/modelManager.ts b/electron/stt/modelManager.tsindex cb13fd31f..8a2d9e4c8 100644--- a/electron/stt/modelManager.ts+++ b/electron/stt/modelManager.ts@@ -13,9 +13,10 @@ import { pipeline } from "node:stream/promises";* from the `ggml-org` GitHub org the engine itself now lives under;* `ggml-org/whisper.cpp` on HuggingFace is a different, access-gated repo* and returns 401 on every file including README.md — confirmed by curl).- * whisper.cpp bakes precision into the file, so- * there is no runtime `--int8` flag; OpenScreen ships the q8_0 quantized- * `small` multilingual model by default.+ * whisper.cpp bakes precision into the file, so there is no runtime `--int8`+ * flag. OpenScreen uses the q5_0 quantized large-v3-turbo multilingual model:+ * substantially stronger recognition than `small`, while the turbo decoder+ * remains practical for interactive captions on Apple Silicon.** The file is verified by SHA-256 and written atomically (via .partial rename)* to prevent partial downloads from being treated as complete.@@ -27,7 +28,7 @@ import { pipeline } from "node:stream/promises";export type SttModelId = "whisper";export interface SttModelFile {- /** Relative path within the model directory (e.g. "ggml-small-q8_0.bin"). */+ /** Relative path within the model directory (e.g. "ggml-large-v3-turbo-q5_0.bin"). */name: string;/** HuggingFace resolve URL for this file. */url: string;@@ -54,13 +55,13 @@ const MODEL_BASE = "https://huggingface.co";// long-standing public model-file repo that never moved when the engine's// GitHub org was renamed.const MODEL_REPO = "ggerganov/whisper.cpp";-const MODEL_FILE = "ggml-small-q8_0.bin";+const MODEL_FILE = "ggml-large-v3-turbo-q5_0.bin";// Pinned to a commit rather than `main` so `expectedSha256` is an invariant and// not a bet: `main` is a mutable branch pointer, and a re-upload under it would// now invalidate every cache in the field at once instead of merely breaking new// installs. This revision was checked against HuggingFace's paths-info API — its// LFS oid for MODEL_FILE is exactly the digest below.-const MODEL_REVISION = "5359861c739e955e79d9a303bcbc70fb988958b1";+const MODEL_REVISION = "98aa99a0a9db05ae2342309f5096248665f7cba3";export const STT_MODELS: Record<SttModelId, SttModelDescriptor> = {whisper: {@@ -70,8 +71,8 @@ export const STT_MODELS: Record<SttModelId, SttModelDescriptor> = {{name: MODEL_FILE,url: `${MODEL_BASE}/${MODEL_REPO}/resolve/${MODEL_REVISION}/${MODEL_FILE}`,- expectedSha256: "49C8FB02B65E6049D5FA6C04F81F53B867B5EC9540406812C643F177317F779F",- approximateBytes: 264_000_000,+ expectedSha256: "394221709CD5AD1F40C46E6031CA61BCE88931E6E088C188294C6D5A55FFA7E2",+ approximateBytes: 574_041_195,},],},@@ -179,7 +180,7 @@ async function ensureFile(// would buy nothing — the rename at the end of this function is already// atomic, so there is no window to close — while costing the user their// only model if the replacement never lands (offline, HF 5xx, ENOSPC)- // and stranding 264 MB that nothing ever cleans up.+ // and stranding hundreds of MB that nothing ever cleans up.}}diff --git a/electron/stt/whisperServer.test.ts b/electron/stt/whisperServer.test.tsindex 2ee9bdfdc..9adc28c42 100644--- a/electron/stt/whisperServer.test.ts+++ b/electron/stt/whisperServer.test.ts@@ -1,3 +1,4 @@+import { EventEmitter } from "node:events";import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";@@ -274,6 +275,63 @@ describe("WhisperServerManager", () => {}});+ it("retries with CPU when the GPU helper exits during model startup", async () => {+ const fs = await import("node:fs/promises");+ const { spawn } = await import("node:child_process");+ const dir = await mkdtemp(path.join(tmpdir(), "whisper-cpu-fallback-"));+ try {+ const modelPath = path.join(dir, "ggml-large-v3-turbo-q5_0.bin");+ const fakeBinaryPath = path.join(dir, "whisper-stt-server");+ await fs.writeFile(modelPath, "dummy-ggml");+ await fs.writeFile(fakeBinaryPath, "x", { mode: 0o755 });++ const child = () => {+ const process = Object.assign(new EventEmitter(), {+ stdout: new EventEmitter(),+ stderr: new EventEmitter(),+ pid: 1234,+ kill: vi.fn(),+ });+ return process;+ };+ const gpuChild = child();+ const cpuChild = child();+ vi.mocked(spawn)+ .mockImplementationOnce(() => {+ queueMicrotask(() => {+ gpuChild.stderr.emit(+ "data",+ Buffer.from("ggml_metal_buffer_init: error: failed to allocate buffer"),+ );+ gpuChild.emit("exit", 1);+ });+ return gpuChild as never;+ })+ .mockReturnValueOnce(cpuChild as never);+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockImplementationOnce(() => new Promise<Response>(() => undefined))+ .mockResolvedValueOnce(new Response("ok", { status: 200 })),+ );++ const mgr = new WhisperServerManager();+ const result = await mgr.start({+ modelPath,+ binaryPath: fakeBinaryPath,+ backend: "whispercpp-metal",+ });+ expect(result.backend).toBe("whispercpp-cpu");+ expect(spawn).toHaveBeenCalledTimes(2);+ expect(vi.mocked(spawn).mock.calls[0]?.[1]).not.toContain("--cpu");+ expect(vi.mocked(spawn).mock.calls[1]?.[1]).toContain("--cpu");+ } finally {+ vi.unstubAllGlobals();+ await rm(dir, { recursive: true, force: true });+ }+ });+it("refuses to start when the model file is missing", async () => {const fs = await import("node:fs/promises");const dir = await mkdtemp(path.join(tmpdir(), "whisper-no-model-"));diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.tsindex 087073a2e..12313df94 100644--- a/electron/stt/whisperServer.ts+++ b/electron/stt/whisperServer.ts@@ -127,15 +127,21 @@ export class WhisperServerManager {}/** Check the server's HTTP root for a 200; resolves once responsive. */- private static async pollUntilReady(baseUrl: string, timeoutMs = 30_000): Promise<void> {+ private static async pollUntilReady(+ baseUrl: string,+ timeoutMs = 60_000,+ shouldContinue: () => boolean = () => true,+ ): Promise<void> {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {+ if (!shouldContinue()) throw new Error("whisper-stt-server exited before readiness");try {const res = await fetch(baseUrl, { method: "GET" });if (res.ok) return;} catch {// not up yet}+ if (!shouldContinue()) throw new Error("whisper-stt-server exited before readiness");await new Promise((resolve) => setTimeout(resolve, 250));}throw new Error(`whisper-stt-server at ${baseUrl} did not respond within ${timeoutMs}ms`);@@ -170,7 +176,8 @@ export class WhisperServerManager {const resolved = options.binaryPath? { path: options.binaryPath, backend: options.backend ?? "whispercpp-cpu" }: await resolveBinaryPath();- if (!resolved.path) {+ const binaryPath = resolved.path;+ if (!binaryPath) {const message ="whisper-stt-server binary not found; build it via scripts/build-whisper-stt.sh";this.recordError(message);@@ -178,12 +185,12 @@ export class WhisperServerManager {}try {if (process.platform !== "win32") {- await access(resolved.path, fsConstants.X_OK);- } else if (!existsSync(resolved.path)) {+ await access(binaryPath, fsConstants.X_OK);+ } else if (!existsSync(binaryPath)) {throw new Error("not found");}} catch {- const message = `whisper-stt-server binary at ${resolved.path} is not executable`;+ const message = `whisper-stt-server binary at ${binaryPath} is not executable`;this.recordError(message);throw new Error(message);}@@ -191,10 +198,9 @@ export class WhisperServerManager {throw new Error(`Whisper GGML model not found at ${options.modelPath}`);}- const port = await WhisperServerManager.pickFreePort();- const child = spawn(- resolved.path,- [+ const launch = async (forceCpu: boolean): Promise<{ port: number; backend: SttBackend }> => {+ const port = await WhisperServerManager.pickFreePort();+ const args = ["--model",options.modelPath,"--port",@@ -203,50 +209,85 @@ export class WhisperServerManager {"127.0.0.1","--threads",String(Math.max(1, os.cpus().length)),- ],- { stdio: ["ignore", "pipe", "pipe"] },- );+ ];+ if (forceCpu) args.push("--cpu");+ const child = spawn(binaryPath, args, { stdio: ["ignore", "pipe", "pipe"] });+ const activeBackend: SttBackend = forceCpu ? "whispercpp-cpu" : resolved.backend;- this.process = child;- this.port = port;- this.backend = resolved.backend;- this.startedAtMs = Date.now();- this.stderrTail = "";- this.lastError = null;+ this.process = child;+ this.port = port;+ this.backend = activeBackend;+ this.startedAtMs = Date.now();+ this.stderrTail = "";+ this.lastError = null;- child.stdout?.on("data", (chunk: Buffer) => {- process.stdout.write(`[whisper-stt-server] ${chunk.toString()}`);- });+ child.stdout?.on("data", (chunk: Buffer) => {+ process.stdout.write(`[whisper-stt-server] ${chunk.toString()}`);+ });- child.stderr.on("data", (chunk: Buffer) => {- const text = chunk.toString();- process.stderr.write(`[whisper-stt-server] ${text}`);- this.stderrTail = (this.stderrTail + text).slice(-this.stderrTailMax);- });- child.once("exit", (code) => {- if (this.process === child) {- const reason =- code === null- ? "exited without code"- : `exited with code ${code}; stderr=${this.stderrTail.slice(-512)}`;- this.recordError(reason);- this.process = null;- this.port = null;- this.startedAtMs = null;+ child.stderr.on("data", (chunk: Buffer) => {+ const text = chunk.toString();+ process.stderr.write(`[whisper-stt-server] ${text}`);+ this.stderrTail = (this.stderrTail + text).slice(-this.stderrTailMax);+ });+ child.once("exit", (code) => {+ if (this.process === child) {+ const reason =+ code === null+ ? "exited without code"+ : `exited with code ${code}; stderr=${this.stderrTail.slice(-512)}`;+ this.recordError(reason);+ this.process = null;+ this.port = null;+ this.startedAtMs = null;+ }+ });+ child.once("error", (err) => {+ this.recordError(`spawn error: ${err.message}`);+ });++ const exitedBeforeReady = new Promise<never>((_, reject) => {+ child.once("exit", (code) => {+ reject(+ new Error(+ `whisper-stt-server exited during startup (${code ?? "no code"}); ` ++ `stderr=${this.stderrTail.slice(-512)}`,+ ),+ );+ });+ child.once("error", reject);+ });+ try {+ await Promise.race([+ WhisperServerManager.pollUntilReady(+ `http://127.0.0.1:${port}`,+ 60_000,+ () => this.process === child,+ ),+ exitedBeforeReady,+ ]);+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ await this.stop();+ this.recordError(message);+ throw new Error(message);}- });- child.once("error", (err) => {- this.recordError(`spawn error: ${err.message}`);- });+ return { port, backend: activeBackend };+ };- const baseUrl = `http://127.0.0.1:${port}`;try {- await WhisperServerManager.pollUntilReady(baseUrl);+ return await launch(false);} catch (err) {- await this.stop();- throw err instanceof Error ? err : new Error(String(err));+ const startupLog = `${err instanceof Error ? err.message : String(err)} ${this.stderrTail}`;+ const gpuStartupFailed =+ resolved.backend !== "whispercpp-cpu" &&+ /(?:ggml_(?:metal|vulkan|cuda)|gpu).*(?:fail|error|allocat)/i.test(startupLog);+ if (!gpuStartupFailed) throw err;+ process.stderr.write(+ "[whisper-stt-server] GPU startup failed; retrying with CPU inference\n",+ );+ return launch(true);}- return { port, backend: resolved.backend };}/** Send SIGTERM and wait for the helper to exit. Resolves even if it was already down. */diff --git a/scripts/build-whisper-stt.sh b/scripts/build-whisper-stt.shindex 3dd1f304e..e62c6cc76 100644--- a/scripts/build-whisper-stt.sh+++ b/scripts/build-whisper-stt.sh@@ -237,7 +237,13 @@ libggml*.dylib|libwhisper*.dylib|libparakeet*.dylib|\libggml*.so|libggml*.so.*|libwhisper*.so|libwhisper*.so.*|\libparakeet*.so|libparakeet*.so.*|\*.metal)- cp -a "${f}" "${OUT_DIR}/"+ # The output directory may contain dereferenced regular files from a+ # downloaded release artifact. Remove the exact destination first so+ # cp can recreate this build's symlink farm without following an old+ # regular-file/symlink mix. -P preserves links without -a's macOS+ # chflags pass, which can itself report ELOOP while replacing a link.+ rm -f "${OUT_DIR}/${f##*/}"+ cp -P "${f}" "${OUT_DIR}/"found_libs=1;;esacdiff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.mdindex afd9ada74..a24d0f745 100644--- a/technical-documentation/architecture/transcription-and-captions.md+++ b/technical-documentation/architecture/transcription-and-captions.md@@ -98,7 +98,7 @@ subtitle is the reason rather than "With AI".### One phase, including the first-run model download-On a fresh install the GGML model (~253 MB) is not on disk. It is fetched by+On a fresh install the GGML model (~574 MB) is not on disk. It is fetched by`SttManager.prepare()` **inside** the `stt:transcribe` IPC call — i.e. inside arun this store has already marked `running` — so the user sees one single busyphase that simply takes longer the first time. That is deliberate: no separate@@ -224,15 +224,16 @@ so no second pass is needed.### Long-form recordings-`whisper_full()` handles recordings longer than 30 s internally; OpenScreen-implements no chunking of its own. The validation set exercises 130 s at WER-0.076 with full per-word coverage (see the validation report linked above).+OpenScreen splits long recordings at nearby low-energy boundaries, transcribes+the bounded chunks sequentially, then restores their absolute timestamps. This+keeps progress observable and makes a failed chunk retryable without running a+whole long recording again.### Model-The single shipped artifact is `ggml-small-q8_0.bin` from-`ggerganov/whisper.cpp` on HuggingFace: Whisper `small`, multilingual (~99-languages), q8_0 quantised, ~264 MB. Precision is baked into the GGML file —+The single shipped artifact is `ggml-large-v3-turbo-q5_0.bin` from+`ggerganov/whisper.cpp` on HuggingFace: Whisper `large-v3-turbo`, multilingual+(~99 languages), q5_0 quantised, ~574 MB. Precision is baked into the GGML file —there is no runtime `--int8` flag. `electron/stt/modelManager.ts` downloadsthe file once into the user-data cache and writes it through an atomic`.partial` rename, so a half-downloaded file can never be picked up as a@@ -284,7 +285,7 @@ bash scripts/build-whisper-stt.sh# issues inside whisper.cpp's vulkan-shaders-gen sub-project.# Run the helper directly for manual testing-set OPENSCREEN_WHISPER_MODEL=%APPDATA%\Electron\stt-models\whisper-ggml\ggml-small-q8_0.bin+set OPENSCREEN_WHISPER_MODEL=%APPDATA%\Electron\stt-models\whisper-ggml\ggml-large-v3-turbo-q5_0.binelectron\native\bin\win32-x64\whisper-stt-server.exe --port 20199 --threads 8# Test