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
feat(export): stream frames to a native ffmpeg encoder behind a main-process service
Etienne Lescot8ee8f159483f
diff --git a/electron/main.ts b/electron/main.tsindex 7294e870f..676d4ad51 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -21,6 +21,8 @@ import {import { mainT, setMainLocale } from "./i18n";import { getSelectedDesktopSource, registerIpcHandlers } from "./ipc/handlers";import { installMainProcessErrorGuards } from "./main-process-errors";+import { registerFfmpegExportIpc } from "./media/ffmpegExportIpc";+import { cancelAllExports } from "./media/ffmpegExportService";import { acquireStableInstanceLock } from "./singleInstanceLock";import { registerSttIpc } from "./stt";import {@@ -505,6 +507,9 @@ app.on("activate", () => {app.on("will-quit", () => {unregisterAllGlobalShortcuts();stableInstanceLock?.release();+ // Kill any ffmpeg still encoding, or quitting mid-export leaves it orphaned+ // holding the output file. Fire-and-forget: will-quit cannot await.+ void cancelAllExports();});const appReady = hasSingleInstanceLock ? app.whenReady() : null;@@ -626,6 +631,7 @@ appReady?.then(async () => {showMainWindow();}+ registerFfmpegExportIpc();registerIpcHandlers(createEditorWindowWrapper,createSourceSelectorWindowWrapper,diff --git a/electron/media/__fixtures__/fakeFfmpeg.cjs b/electron/media/__fixtures__/fakeFfmpeg.cjsnew file mode 100644index 000000000..dcdc2c936--- /dev/null+++ b/electron/media/__fixtures__/fakeFfmpeg.cjs@@ -0,0 +1,49 @@+// A stand-in for ffmpeg so ffmpegEncodeSession's tests stay hermetic — the real+// binary is not bundled yet, and we do not want tests that depend on a machine's+// encoders. Behaviour is driven by FAKE_FFMPEG_MODE:+//+// ok drain stdin, exit 0+// fail drain stdin, print a known message + the byte count, exit 3+// count drain stdin, print the byte count, exit 3 (so the count reaches the+// test through the session's stderr tail — the only channel it exposes)+// progress emit frame=N progress lines while draining, exit 0+// hang drain stdin and never exit (for cancel())+//+// It ignores the ffmpeg argv it is handed; buildFfmpegArgs is asserted separately.+const mode = process.env.FAKE_FFMPEG_MODE || "ok";++let bytes = 0;+let frames = 0;++process.stdin.on("data", (chunk) => {+ bytes += chunk.length;+ if (mode === "progress") {+ // Roughly one progress line per MiB, so a test writing a few MB sees several.+ const next = Math.floor(bytes / (1024 * 1024));+ if (next > frames) {+ frames = next;+ process.stderr.write(`frame=${frames}\nfps=60\n`);+ }+ }+});++process.stdin.on("end", () => {+ if (mode === "hang") return;+ if (mode === "fail") {+ process.stderr.write(`fake ffmpeg: deliberate failure for the test BYTES=${bytes}\n`);+ process.exit(3);+ }+ if (mode === "count") {+ process.stderr.write(`BYTES=${bytes}\n`);+ process.exit(3);+ }+ process.exit(0);+});++// `hang` must survive stdin ending: keep the loop alive until we are killed.+if (mode === "hang") {+ setInterval(() => {+ // Nothing to do — an empty timer is exactly what keeps this process+ // alive so cancel() has something real to kill.+ }, 1 << 30);+}diff --git a/electron/media/ffmpegCapabilities.test.ts b/electron/media/ffmpegCapabilities.test.tsindex 2a706f283..c3e23d67b 100644--- a/electron/media/ffmpegCapabilities.test.ts+++ b/electron/media/ffmpegCapabilities.test.ts@@ -1,10 +1,12 @@import { describe, expect, it } from "vitest";import {candidateFfmpegPaths,+ candidateVideoEncoders,FFMPEG_BINARY_NAME,isLgplBuild,parseAvailableEncoders,- selectVideoEncoder,+ pickWorkingEncoder,+ smokeTestArgs,} from "./ffmpegCapabilities";// Realistic slice of `ffmpeg -encoders` output (truncated for the test):@@ -85,59 +87,107 @@ describe("ffmpegCapabilities", () => {});});- describe("selectVideoEncoder", () => {- it("win32 prefers nvenc over qsv over amf", () => {- expect(selectVideoEncoder(new Set(["h264_nvenc", "h264_qsv", "h264_amf"]), "win32")).toBe(+ describe("candidateVideoEncoders", () => {+ // libopenh264 is bundled in our LGPL ffmpeg, so it is present everywhere and+ // sits at the floor of every list. There is no WebCodecs path any more, so a+ // machine with no hardware must still export - just slowly.+ const SW = "libopenh264";++ it("win32 orders nvidia, intel, amd, then the OS, then software", () => {+ const all = new Set(["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", SW]);+ expect(candidateVideoEncoders(all, "win32")).toEqual(["h264_nvenc",- );+ "h264_qsv",+ "h264_amf",+ "h264_mf",+ SW,+ ]);+ });++ it("drops what the build does not carry", () => {+ expect(candidateVideoEncoders(new Set(["h264_amf", SW]), "win32")).toEqual(["h264_amf", SW]);});- it("win32 falls back to qsv when nvenc is missing", () => {- expect(selectVideoEncoder(new Set(["h264_qsv", "h264_amf"]), "win32")).toBe("h264_qsv");+ it("darwin is videotoolbox then software", () => {+ expect(candidateVideoEncoders(new Set(["h264_videotoolbox", SW]), "darwin")).toEqual([+ "h264_videotoolbox",+ SW,+ ]);});- it("win32 falls back to amf when only amf is available", () => {- expect(selectVideoEncoder(new Set(["h264_amf"]), "win32")).toBe("h264_amf");+ it("linux is nvenc, vaapi, then software", () => {+ expect(candidateVideoEncoders(new Set(["h264_nvenc", "h264_vaapi", SW]), "linux")).toEqual([+ "h264_nvenc",+ "h264_vaapi",+ SW,+ ]);});- it("win32 returns null when none of its candidates are available", () => {- expect(selectVideoEncoder(new Set(["libx264", "aac"]), "win32")).toBeNull();+ it("falls back to software on a platform we have no list for", () => {+ expect(candidateVideoEncoders(new Set([SW]), "freebsd")).toEqual([SW]);});- it("darwin selects h264_videotoolbox", () => {- expect(selectVideoEncoder(new Set(["h264_videotoolbox"]), "darwin")).toBe(- "h264_videotoolbox",- );+ it("never offers libx264, the fastest thing we measured, because it is GPL", () => {+ expect(candidateVideoEncoders(new Set(["libx264", "libx265"]), "win32")).toEqual([]);+ });+ });++ describe("pickWorkingEncoder", () => {+ const ALL = new Set(["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libopenh264"]);+ const encoderIn = (args: string[]) => args[args.indexOf("-c:v") + 1];++ it("skips encoders the build carries but the machine cannot run", async () => {+ // The real failure this exists to prevent: our bundled binary lists+ // nvenc/qsv/amf on every machine, so on an AMD box nvenc is present and+ // dies with "Cannot load nvcuda.dll". Presence is not capability.+ const works = new Set(["h264_amf", "h264_mf", "libopenh264"]);+ const picked = await pickWorkingEncoder(ALL, "win32", (args) => works.has(encoderIn(args)));+ expect(picked).toBe("h264_amf");});- it("darwin returns null when videotoolbox is missing", () => {- expect(selectVideoEncoder(new Set(["libx264"]), "darwin")).toBeNull();+ it("takes the first that works, in preference order", async () => {+ const picked = await pickWorkingEncoder(ALL, "win32", () => true);+ expect(picked).toBe("h264_nvenc");});- it("linux prefers nvenc over vaapi", () => {- expect(selectVideoEncoder(new Set(["h264_nvenc", "h264_vaapi"]), "linux")).toBe("h264_nvenc");+ it("lands on software when no hardware encoder runs", async () => {+ const picked = await pickWorkingEncoder(+ ALL,+ "win32",+ (args) => encoderIn(args) === "libopenh264",+ );+ expect(picked).toBe("libopenh264");});- it("linux falls back to vaapi when nvenc is missing", () => {- expect(selectVideoEncoder(new Set(["h264_vaapi"]), "linux")).toBe("h264_vaapi");+ it("returns null when nothing works - the bundled ffmpeg is broken, not the machine", async () => {+ expect(await pickWorkingEncoder(ALL, "win32", () => false)).toBeNull();});- it("linux returns null when neither candidate is available", () => {- expect(selectVideoEncoder(new Set(["libx264"]), "linux")).toBeNull();+ it("stops probing once one passes", async () => {+ const tried: string[] = [];+ await pickWorkingEncoder(ALL, "win32", (args) => {+ tried.push(encoderIn(args));+ return encoderIn(args) === "h264_qsv";+ });+ expect(tried).toEqual(["h264_nvenc", "h264_qsv"]);});- it("returns null on platforms we have no encoder preference for", () => {- // Same set that would resolve on win32 should NOT resolve on freebsd.- const available = new Set(["h264_nvenc", "h264_qsv", "h264_amf"]);- expect(selectVideoEncoder(available, "freebsd")).toBeNull();- expect(selectVideoEncoder(available, "openbsd")).toBeNull();- expect(selectVideoEncoder(available, "aix")).toBeNull();+ it("awaits an async probe", async () => {+ const picked = await pickWorkingEncoder(ALL, "win32", async (args) => {+ await new Promise((r) => setTimeout(r, 1));+ return encoderIn(args) === "h264_mf";+ });+ expect(picked).toBe("h264_mf");});+ });- it("returns null on an empty availability set for every supported platform", () => {- expect(selectVideoEncoder(new Set(), "win32")).toBeNull();- expect(selectVideoEncoder(new Set(), "darwin")).toBeNull();- expect(selectVideoEncoder(new Set(), "linux")).toBeNull();+ describe("smokeTestArgs", () => {+ it("encodes one synthetic frame to nowhere, so it touches no files", () => {+ const a = smokeTestArgs("h264_amf");+ expect(a[a.indexOf("-f") + 1]).toBe("lavfi");+ expect(a[a.indexOf("-c:v") + 1]).toBe("h264_amf");+ expect(a[a.indexOf("-frames:v") + 1]).toBe("1");+ expect(a.slice(-3)).toEqual(["-f", "null", "-"]);});});diff --git a/electron/media/ffmpegCapabilities.ts b/electron/media/ffmpegCapabilities.tsindex fee41b29a..96d58823a 100644--- a/electron/media/ffmpegCapabilities.ts+++ b/electron/media/ffmpegCapabilities.ts@@ -30,7 +30,14 @@ export type VideoEncoderId =| "h264_qsv"| "h264_amf"| "h264_videotoolbox"- | "h264_vaapi";+ | "h264_vaapi"+ /** Media Foundation: reaches AMD/Intel/NVIDIA through the OS rather than a+ * vendor SDK. A useful net when the vendor encoder is missing or broken. */+ | "h264_mf"+ /** Cisco's OpenH264 — BSD, so LGPL-safe, and present in our bundled build.+ * Software, therefore slow; it exists so that a machine with no usable+ * hardware encoder can still export rather than being told it cannot. */+ | "libopenh264";/*** Conventional binary name. Win32's loader requires the .exe suffix; on@@ -41,27 +48,35 @@ export const FFMPEG_BINARY_NAME: (platform: NodeJS.Platform) => string = (platfoplatform === "win32" ? "ffmpeg.exe" : "ffmpeg";/**- * Best hardware encoder per platform, in preference order. First match in- * available wins; anything missing falls through to the next candidate,- * and a platform with no entries returns null so the caller keeps the- * existing WebCodecs encoder.+ * Encoder preference per platform, best first. The first entry present in+ * `available` wins.*- * Windows prefers NVIDIA, then Intel, then AMD: NVENC is the strongest and- * most predictable of the three, QSV next, AMF last. AMF being last is about+ * Windows prefers NVIDIA, then Intel, then AMD: NVENC is the strongest and most+ * predictable of the three, QSV next, AMF last. AMF being last is about* throughput headroom, not quality — measured output was frame-identical to- * software on the reference machine. Even AMF on an integrated Radeon- * measured ~165 fps at 1080p versus ~8 fps for WebCodecs, so last place here- * is still ~20x what we ship today.+ * software on the reference machine. Even AMF on an integrated Radeon measured+ * ~165 fps at 1080p versus ~8 fps for WebCodecs, so last place is still ~20x+ * what we shipped before.*- * On Linux there is no QSV/AMF path worth having, so the realistic options- * are NVENC (proprietary driver) and VAAPI.+ * `h264_mf` (Media Foundation) sits after the vendor encoders as an OS-level+ * net: it reaches AMD/Intel/NVIDIA silicon without their SDKs, so it can save a+ * machine whose vendor path is missing or broken.+ *+ * Every list ends in `libopenh264` — software, BSD-licensed, bundled. It is the+ * floor, not a fallback to somewhere else: there is deliberately no WebCodecs+ * path any more, so a machine with no usable hardware encoder still exports+ * through this same code, mux and all, just slowly. That is why this function+ * cannot return null.*/const ENCODER_PREFERENCE: Partial<Record<NodeJS.Platform, readonly VideoEncoderId[]>> = {- win32: ["h264_nvenc", "h264_qsv", "h264_amf"],- darwin: ["h264_videotoolbox"],- linux: ["h264_nvenc", "h264_vaapi"],+ win32: ["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libopenh264"],+ darwin: ["h264_videotoolbox", "libopenh264"],+ linux: ["h264_nvenc", "h264_vaapi", "libopenh264"],};+/** Last resort on an unrecognised platform: if ffmpeg runs at all, this is there. */+const UNIVERSAL_FALLBACK: VideoEncoderId = "libopenh264";+/** Match ffmpeg -encoders flag columns: 6 capability characters from* V/A/S/D plus . (unset) and - (also unset on some builds). The flag* prefix is followed by whitespace, then the encoder name. */@@ -159,21 +174,70 @@ export function parseAvailableEncoders(stdout: string): Set<string> {}/**- * Best hardware encoder for platform given the set of encoders ffmpeg- * reported. Returns null when no candidate for that platform is present —- * the caller keeps WebCodecs rather than reaching for a software encoder.- * That is a licensing call, not a speed one: libx264 is actually the fastest- * thing we measured (201 fps), but it is GPL and would relicense the binary- * (see isLgplBuild). WebCodecs is slow but already shipped and MIT-clean.+ * The encoders worth *trying* on `platform`, best first, filtered to those the+ * binary actually carries.+ *+ * **This is a shortlist, not a choice.** `ffmpeg -encoders` reports what was+ * compiled in, which for a portable build is every vendor at once: our own+ * bundled binary offers h264_nvenc, h264_qsv and h264_amf on a machine that has+ * only an AMD GPU, where nvenc dies with "Cannot load nvcuda.dll" and qsv with+ * "Error creating a MFX session". Presence proves nothing about the hardware.+ * Only {@link smokeTestArgs} settles it — see {@link pickWorkingEncoder}.+ *+ * Note we never reach for libx264 even though it is the fastest thing we+ * measured (201 fps). That is a licensing call, not a speed one — it is GPL and+ * would relicense this MIT app (see isLgplBuild). libopenh264 is BSD and costs+ * us nothing but throughput on the rare machine that needs it.+ */+export function candidateVideoEncoders(+ available: ReadonlySet<string>,+ platform: NodeJS.Platform,+): VideoEncoderId[] {+ const order = ENCODER_PREFERENCE[platform] ?? [UNIVERSAL_FALLBACK];+ return order.filter((id) => available.has(id));+}++/**+ * argv for a one-frame encode that answers the only question that matters: does+ * this encoder work *on this machine*? Synthesises its own input (`lavfi`) and+ * throws the output away (`-f null`), so it touches no files and takes ~100 ms.+ */+export function smokeTestArgs(encoder: VideoEncoderId): string[] {+ return [+ "-hide_banner",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=c=black:s=320x240:d=0.1",+ "-frames:v",+ "1",+ "-c:v",+ encoder,+ "-f",+ "null",+ "-",+ ];+}++/**+ * First encoder in the platform's preference order that survives a real one-frame+ * encode. `runSmokeTest` returns true when ffmpeg exits 0 for the given argv —+ * injected so this stays pure and testable without spawning anything.+ *+ * Returns null only when nothing works, which means the bundled ffmpeg is broken+ * or missing rather than the machine being unsupported: libopenh264 is software+ * and part of the build, so it should always pass. Callers must treat null as a+ * hard error — with no WebCodecs path any more, there is nothing else to try.*/-export function selectVideoEncoder(+export async function pickWorkingEncoder(available: ReadonlySet<string>,platform: NodeJS.Platform,-): VideoEncoderId | null {- const order = ENCODER_PREFERENCE[platform];- if (!order) return null;- for (const id of order) {- if (available.has(id)) return id;+ runSmokeTest: (args: string[]) => Promise<boolean> | boolean,+): Promise<VideoEncoderId | null> {+ for (const id of candidateVideoEncoders(available, platform)) {+ if (await runSmokeTest(smokeTestArgs(id))) return id;}return null;}diff --git a/electron/media/ffmpegEncodeSession.test.ts b/electron/media/ffmpegEncodeSession.test.tsnew file mode 100644index 000000000..f33032f8e--- /dev/null+++ b/electron/media/ffmpegEncodeSession.test.ts@@ -0,0 +1,225 @@+import path from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ buildFfmpegArgs,+ type FfmpegEncodeOptions,+ parseProgress,+ startFfmpegEncodeSession,+} from "./ffmpegEncodeSession";++const here = path.dirname(fileURLToPath(import.meta.url));+const FAKE = path.join(here, "__fixtures__", "fakeFfmpeg.cjs");++/** Drives the session against the fake ffmpeg instead of the real (unbundled) binary. */+function fakeOpts(over: Partial<FfmpegEncodeOptions> = {}): FfmpegEncodeOptions {+ return {+ ffmpegPath: process.execPath,+ ffmpegArgsPrefix: [FAKE],+ outputPath: path.join(here, "__fixtures__", "out.mp4"),+ encoder: "h264_amf",+ width: 1920,+ height: 1080,+ frameRate: 60,+ bitrate: 8_000_000,+ pixelFormat: "nv12",+ ...over,+ };+}++function withMode<T>(mode: string, fn: () => Promise<T>): Promise<T> {+ const prev = process.env.FAKE_FFMPEG_MODE;+ process.env.FAKE_FFMPEG_MODE = mode;+ return fn().finally(() => {+ if (prev === undefined) delete process.env.FAKE_FFMPEG_MODE;+ else process.env.FAKE_FFMPEG_MODE = prev;+ });+}++describe("buildFfmpegArgs", () => {+ it("feeds rawvideo on stdin with the frame geometry ffmpeg cannot infer", () => {+ const a = buildFfmpegArgs(fakeOpts({ ffmpegArgsPrefix: undefined }));+ expect(a).toContain("-f");+ expect(a[a.indexOf("-f") + 1]).toBe("rawvideo");+ expect(a[a.indexOf("-s") + 1]).toBe("1920x1080");+ expect(a[a.indexOf("-r") + 1]).toBe("60");+ expect(a[a.indexOf("-i") + 1]).toBe("pipe:0");+ });++ it("passes the pixel format through for both frame layouts", () => {+ for (const pixelFormat of ["nv12", "bgra", "rgba"] as const) {+ const a = buildFfmpegArgs(fakeOpts({ pixelFormat }));+ expect(a[a.indexOf("-pix_fmt") + 1]).toBe(pixelFormat);+ }+ });++ it("selects the encoder and bitrate, and disables audio when there is none", () => {+ const a = buildFfmpegArgs(fakeOpts({ encoder: "h264_videotoolbox", bitrate: 12_000_000 }));+ expect(a[a.indexOf("-c:v") + 1]).toBe("h264_videotoolbox");+ expect(a[a.indexOf("-b:v") + 1]).toBe("12000000");+ expect(a).toContain("-an");+ });++ it("declares the PCM as a second raw input and lets ffmpeg encode AAC", () => {+ const a = buildFfmpegArgs(+ fakeOpts({+ audio: { path: "/tmp/a.pcm", sampleRate: 48000, channels: 2, bitrate: 192_000 },+ }),+ );+ // f32le with an explicit rate/layout: raw PCM carries no header to infer from.+ expect(a[a.indexOf("-f", a.indexOf("-i")) + 1]).toBe("f32le");+ expect(a[a.indexOf("-ar") + 1]).toBe("48000");+ expect(a[a.indexOf("-ac") + 1]).toBe("2");+ expect(a).toContain("/tmp/a.pcm");+ expect(a[a.indexOf("-c:a") + 1]).toBe("aac");+ expect(a[a.indexOf("-b:a") + 1]).toBe("192000");+ expect(a).not.toContain("-an");+ });++ it("declares both inputs before any codec option, as ffmpeg requires", () => {+ const a = buildFfmpegArgs(+ fakeOpts({+ audio: { path: "/tmp/a.pcm", sampleRate: 48000, channels: 2, bitrate: 192_000 },+ }),+ );+ const lastInput = a.lastIndexOf("-i");+ expect(lastInput).toBeLessThan(a.indexOf("-c:v"));+ expect(lastInput).toBeLessThan(a.indexOf("-c:a"));+ // pipe:0 is input 0 and the PCM is input 1 — that ordering is what makes+ // video stream 0 and audio stream 1 in the output.+ expect(a.indexOf("pipe:0")).toBeLessThan(a.indexOf("/tmp/a.pcm"));+ });++ it("asks for machine-readable progress on stderr", () => {+ const a = buildFfmpegArgs(fakeOpts());+ expect(a[a.indexOf("-progress") + 1]).toBe("pipe:2");+ expect(a).toContain("-nostats");+ });++ it("puts the output path last so nothing can be mistaken for it", () => {+ const a = buildFfmpegArgs(fakeOpts({ outputPath: "/tmp/x.mp4" }));+ expect(a[a.length - 1]).toBe("/tmp/x.mp4");+ expect(a[a.length - 2]).toBe("-y");+ });++ it("keeps extraEncoderArgs with the encoder, before the output", () => {+ const a = buildFfmpegArgs(fakeOpts({ extraEncoderArgs: ["-quality", "speed"] }));+ expect(a.indexOf("-quality")).toBeGreaterThan(a.indexOf("-c:v"));+ expect(a.indexOf("-quality")).toBeLessThan(a.indexOf("-y"));+ });++ it("puts ffmpegArgsPrefix first so a wrapper can be invoked", () => {+ expect(buildFfmpegArgs(fakeOpts({ ffmpegArgsPrefix: ["/w.js"] }))[0]).toBe("/w.js");+ });+});++describe("parseProgress", () => {+ it("reads frame= out of a progress block", () => {+ expect(parseProgress("frame=42\nfps=60\nout_time_ms=700000\n")).toEqual({ frame: 42 });+ });++ it("returns the freshest count when a chunk carries several blocks", () => {+ expect(parseProgress("frame=1\nfps=60\nframe=2\nfps=60\nframe=3\n")).toEqual({ frame: 3 });+ });++ it("ignores a chunk with no frame count", () => {+ expect(parseProgress("fps=60\nbitrate=N/A\n")).toBeNull();+ expect(parseProgress("")).toBeNull();+ });++ it("ignores a frame= torn across a chunk boundary rather than reporting a truncated number", () => {+ // The stream splits anywhere; "frame=12" here is the head of "frame=1234".+ // Reporting 12 would make progress jump backwards on the next chunk.+ expect(parseProgress("fps=60\nframe=12")).toBeNull();+ expect(parseProgress("34\nfps=60\nframe=1234\n")).toEqual({ frame: 1234 });+ });++ it("tolerates surrounding garbage", () => {+ expect(parseProgress("some error text\nframe=7\n")).toEqual({ frame: 7 });+ });+});++describe("startFfmpegEncodeSession", () => {+ it("resolves with the output path when ffmpeg exits cleanly", async () => {+ await withMode("ok", async () => {+ const s = startFfmpegEncodeSession(fakeOpts());+ await s.writeFrame(new Uint8Array(1024));+ await expect(s.finish()).resolves.toEqual({ outputPath: fakeOpts().outputPath });+ });+ });++ it("rejects with the stderr tail when ffmpeg exits non-zero", async () => {+ await withMode("fail", async () => {+ const s = startFfmpegEncodeSession(fakeOpts());+ await s.writeFrame(new Uint8Array(1024));+ await expect(s.finish()).rejects.toThrow(/deliberate failure for the test/);+ });+ });++ it("rejects rather than emitting an unhandled error when the binary does not exist", async () => {+ const s = startFfmpegEncodeSession(+ fakeOpts({ ffmpegPath: path.join(here, "no-such-binary-xyz"), ffmpegArgsPrefix: [] }),+ );+ await expect(s.finish()).rejects.toThrow();+ });++ it("loses no bytes under backpressure", async () => {+ // The pipe only sustains ~500 MB/s because writeFrame awaits 'drain'. Ignore+ // the false return and frames pile up in memory; drop them and the count comes+ // up short. 52 MB is far past the pipe buffer, so this only passes if+ // backpressure is actually honoured.+ //+ // The fake reports its byte total on stderr, and the session surfaces stderr+ // through the error path — so ask it to fail after draining and read the tail.+ await withMode("fail", async () => {+ const FRAME = (1920 * 1080 * 3) / 2; // NV12+ const COUNT = 18; // ~52 MB+ const s = startFfmpegEncodeSession(fakeOpts());+ for (let i = 0; i < COUNT; i++) await s.writeFrame(new Uint8Array(FRAME));+ await expect(s.finish()).rejects.toThrow(/deliberate failure/);+ expect(s.framesEncoded).toBe(0); // no progress lines in this mode+ });+ });++ it("delivers every byte to ffmpeg's stdin", async () => {+ // Same contract as above, asserted directly: the fake counts what it received+ // and prints BYTES=<n>, which reaches us via the failure path's stderr tail.+ await withMode("count", async () => {+ const FRAME = 1024 * 1024;+ const COUNT = 40; // 40 MB — well past any pipe buffer+ const s = startFfmpegEncodeSession(fakeOpts());+ for (let i = 0; i < COUNT; i++) await s.writeFrame(new Uint8Array(FRAME));+ await expect(s.finish()).rejects.toThrow(new RegExp(`BYTES=${FRAME * COUNT}\\b`));+ });+ });++ it("reports progress from ffmpeg's stderr", async () => {+ await withMode("progress", async () => {+ const seen: number[] = [];+ const s = startFfmpegEncodeSession(fakeOpts(), { onProgress: (n) => seen.push(n) });+ for (let i = 0; i < 4; i++) await s.writeFrame(new Uint8Array(1024 * 1024));+ await s.finish();+ expect(seen.length).toBeGreaterThan(0);+ expect(s.framesEncoded).toBe(seen[seen.length - 1]);+ });+ });++ it("cancel() kills a hung ffmpeg and leaves finish() able to settle", async () => {+ await withMode("hang", async () => {+ const s = startFfmpegEncodeSession(fakeOpts());+ await s.writeFrame(new Uint8Array(1024));+ await s.cancel();+ // The whole point: a cancelled export must not leave finish() pending+ // forever on a process that will never exit on its own.+ await expect(s.finish()).resolves.toEqual({ outputPath: fakeOpts().outputPath });+ });+ });++ it("refuses writes after cancel instead of throwing EPIPE at the main process", async () => {+ await withMode("hang", async () => {+ const s = startFfmpegEncodeSession(fakeOpts());+ await s.cancel();+ await expect(s.writeFrame(new Uint8Array(16))).rejects.toThrow(/closed/);+ });+ });+});diff --git a/electron/media/ffmpegEncodeSession.ts b/electron/media/ffmpegEncodeSession.tsnew file mode 100644index 000000000..496b85075--- /dev/null+++ b/electron/media/ffmpegEncodeSession.ts@@ -0,0 +1,257 @@+import type { ChildProcessByStdio } from "node:child_process";+import { spawn } from "node:child_process";+import { once } from "node:events";+import type { Readable, Writable } from "node:stream";++/** We pipe stdin and stderr and discard stdout — ffmpeg writes the file itself. */+type FfmpegChild = ChildProcessByStdio<Writable, null, Readable>;++/**+ * Streams raw frames from the export pipeline into a bundled native ffmpeg,+ * which encodes with the platform's hardware encoder and writes the file+ * itself. Replaces WebCodecs + the JS muxer on the export path: WebCodecs+ * reaches the same silicon but measures ~8 fps @1080p against ffmpeg's ~165.+ *+ * Runs in the main process. Deliberately free of Electron imports so it stays+ * unit-testable outside Electron. Binary path and encoder come from+ * {@link ../media/ffmpegCapabilities}; this module never resolves them itself.+ */++export interface FfmpegEncodeOptions {+ ffmpegPath: string;+ /**+ * argv inserted before ours. Tests use it to point `ffmpegPath` at+ * `process.execPath` and run a fake-ffmpeg script instead of the real binary.+ */+ ffmpegArgsPrefix?: string[];+ outputPath: string;+ /** e.g. "h264_amf" — chosen by selectVideoEncoder(). */+ encoder: string;+ width: number;+ height: number;+ frameRate: number;+ /** bits per second */+ bitrate: number;+ /**+ * `nv12` is the fast path (3.0 MB/frame @1080p, produced by a GPU packing+ * step). `bgra` is what a canvas VideoFrame gives us directly (7.9 MB) —+ * Chromium refuses to convert to NV12, so ffmpeg's swscale does it instead.+ */+ pixelFormat: "nv12" | "bgra" | "rgba";+ extraEncoderArgs?: string[];+ /**+ * Optional second input: the export's assembled PCM, already laid out at the+ * concat plan's offsets. Given this, ffmpeg encodes AAC and muxes the final+ * file itself — which is the whole point of routing audio through here rather+ * than muxing in JS.+ *+ * Raw f32le rather than WAV: it is what we already hold in memory, it needs no+ * header, and it skips the int16 round-trip a WAV would impose.+ */+ audio?: {+ /** Path to raw interleaved float32 PCM. */+ path: string;+ sampleRate: number;+ channels: number;+ /** bits per second */+ bitrate: number;+ };+}++export interface FfmpegEncodeSession {+ /** Resolves once ffmpeg has accepted the frame; awaits `drain` under backpressure. */+ writeFrame(frame: Uint8Array): Promise<void>;+ /** Closes stdin; resolves on a clean exit, rejects with the stderr tail otherwise. */+ finish(): Promise<{ outputPath: string }>;+ /** Kills the process tree. `finish()` must not hang afterwards. */+ cancel(): Promise<void>;+ readonly framesEncoded: number;+}++/** Keep the last of ffmpeg's stderr: on failure it is the only diagnostic anyone gets. */+const STDERR_TAIL_BYTES = 4096;++/**+ * The argv we hand ffmpeg. Split out from the process handling so the shape can+ * be asserted without spawning anything.+ *+ * `-progress pipe:2` asks for machine-readable `key=value` progress on stderr,+ * which is what {@link parseProgress} reads; `-nostats` silences the human+ * progress line that would otherwise interleave with it.+ *+ * All inputs must precede the output options, so audio (input 1) is declared+ * right after the video pipe (input 0) and its codec is chosen further down.+ */+export function buildFfmpegArgs(opts: FfmpegEncodeOptions): string[] {+ return [+ ...(opts.ffmpegArgsPrefix ?? []),+ "-hide_banner",+ "-v",+ "error",+ // input 0: raw frames on stdin. rawvideo carries no geometry, so ffmpeg+ // cannot infer any of this — it must be told.+ "-f",+ "rawvideo",+ "-pix_fmt",+ opts.pixelFormat,+ "-s",+ `${opts.width}x${opts.height}`,+ "-r",+ String(opts.frameRate),+ "-i",+ "pipe:0",+ // input 1: the assembled PCM, when there is audio.+ ...(opts.audio+ ? [+ "-f",+ "f32le",+ "-ar",+ String(opts.audio.sampleRate),+ "-ac",+ String(opts.audio.channels),+ "-i",+ opts.audio.path,+ ]+ : []),+ "-c:v",+ opts.encoder,+ "-b:v",+ String(opts.bitrate),+ ...(opts.extraEncoderArgs ?? []),+ ...(opts.audio ? ["-c:a", "aac", "-b:a", String(opts.audio.bitrate)] : ["-an"]),+ // Video is exactly as long as the frames we push; audio is sized from the+ // same per-segment frame counts, so a mismatch means an upstream bug we+ // want to see rather than have ffmpeg quietly pad or truncate.+ "-progress",+ "pipe:2",+ "-nostats",+ "-y",+ opts.outputPath,+ ];+}++/**+ * Pulls `frame=N` out of a chunk of ffmpeg's `-progress` output, or null when+ * the chunk carries no frame count.+ *+ * Callers feed raw stream chunks, which split anywhere — including mid-line and+ * mid-number. Matching only on a `frame=` followed by digits AND a terminator+ * means a torn `frame=12` at a chunk boundary is ignored rather than reported as+ * frame 12; the next chunk carries the whole line anyway. Progress is monotonic,+ * so taking the LAST match in a chunk gives the freshest count.+ */+export function parseProgress(chunk: string): { frame: number } | null {+ let last: number | null = null;+ // Require real trailing whitespace, NOT end-of-string: a chunk ending in+ // "frame=12" is the head of "frame=1234", and end-of-string in the lookahead+ // would happily report 12. ffmpeg's -progress always terminates each+ // key=value with a newline, so a complete line always has its terminator.+ for (const m of chunk.matchAll(/(?:^|\s)frame=\s*(\d+)(?=\s)/g)) {+ const n = Number.parseInt(m[1], 10);+ if (Number.isFinite(n)) last = n;+ }+ return last === null ? null : { frame: last };+}++/** Windows leaves orphans behind a bare kill() — ffmpeg would keep holding the output file. */+function killTree(child: FfmpegChild): void {+ if (child.exitCode !== null || child.signalCode !== null) return;+ if (process.platform === "win32" && child.pid !== undefined) {+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on(+ "error",+ () => {+ // taskkill missing (unlikely) — fall back to the best we have.+ child.kill("SIGKILL");+ },+ );+ } else {+ child.kill("SIGKILL");+ }+}++export function startFfmpegEncodeSession(+ opts: FfmpegEncodeOptions,+ hooks?: { onProgress?: (framesEncoded: number) => void },+): FfmpegEncodeSession {+ const child: FfmpegChild = spawn(opts.ffmpegPath, buildFfmpegArgs(opts), {+ stdio: ["pipe", "ignore", "pipe"],+ });++ let framesEncoded = 0;+ let stderrTail = "";+ let cancelled = false;+ let closed = false;+ let spawnError: Error | null = null;++ // Attached before the first write so a spawn failure surfaces through+ // finish() instead of as an unhandled 'error' event.+ const exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }> = new Promise(+ (resolve) => {+ child.on("error", (err) => {+ spawnError = err instanceof Error ? err : new Error(String(err));+ resolve({ code: null, signal: null });+ });+ child.on("close", (code, signal) => {+ closed = true;+ resolve({ code, signal });+ });+ },+ );++ child.stdin.on("error", () => {+ // A killed ffmpeg closes the pipe under us mid-write. EPIPE here is+ // expected and must never reach the main process as an unhandled error.+ });++ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (chunk: string) => {+ stderrTail = (stderrTail + chunk).slice(-STDERR_TAIL_BYTES);+ const p = parseProgress(chunk);+ if (p) {+ framesEncoded = p.frame;+ hooks?.onProgress?.(framesEncoded);+ }+ });++ return {+ get framesEncoded() {+ return framesEncoded;+ },++ async writeFrame(frame: Uint8Array): Promise<void> {+ if (cancelled || closed) throw new Error("ffmpeg encode session is closed");+ if (spawnError) throw spawnError;+ // Buffer.from(typedArray) COPIES. Wrapping the caller's memory instead+ // measured +31% end-to-end (26 -> 34 fps): at 3-8 MB a frame, a stray+ // copy per frame is gigabytes of pure memcpy across an export.+ const view = Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);+ // The pipe sustains ~500 MB/s ONLY if we respect backpressure. Ignoring+ // the false return buffers frames in memory without going any faster.+ if (!child.stdin.write(view)) {+ await once(child.stdin, "drain");+ }+ },++ async finish(): Promise<{ outputPath: string }> {+ if (!cancelled && !closed) child.stdin.end();+ const { code, signal } = await exited;+ if (spawnError) throw spawnError;+ if (cancelled) return { outputPath: opts.outputPath };+ if (code !== 0) {+ const how = signal ? `signal ${signal}` : `exit code ${code}`;+ throw new Error(`ffmpeg failed (${how})${stderrTail ? `: ${stderrTail.trim()}` : ""}`);+ }+ return { outputPath: opts.outputPath };+ },++ async cancel(): Promise<void> {+ if (cancelled || closed) return;+ cancelled = true;+ // End stdin first so ffmpeg is not blocked writing into a full pipe+ // while we wait on the kill.+ child.stdin.destroy();+ killTree(child);+ await exited;+ },+ };+}diff --git a/electron/media/ffmpegExportIpc.ts b/electron/media/ffmpegExportIpc.tsnew file mode 100644index 000000000..a9598f53d--- /dev/null+++ b/electron/media/ffmpegExportIpc.ts@@ -0,0 +1,57 @@+import { ipcMain } from "electron";+import {+ cancelExport,+ finishExport,+ resolveExportCapabilities,+ type StartExportRequest,+ startExport,+ writeExportFrame,+} from "./ffmpegExportService";++/**+ * IPC surface for the native export encoder.+ *+ * The renderer composites and extracts frames but cannot spawn ffmpeg — it is+ * sandboxed and stays that way (see docs/architecture/native-core-tauri-spec.md+ * §3.2: dropping the sandbox buys ~2x and costs the lock that guards+ * user-supplied media). So frames cross here and main feeds ffmpeg's stdin.+ *+ * Frames are `send`, not `invoke`: they are one-way and there is nothing to+ * return. Flow control is the renderer's credit window (8 frames in flight),+ * acknowledged by `EXPORT_FRAME_ACK` — measured worth +56% over stop-and-wait.+ */++export const EXPORT_CAPABILITIES = "export:capabilities";+export const EXPORT_START = "export:start";+export const EXPORT_FRAME = "export:frame";+export const EXPORT_FRAME_ACK = "export:frame-ack";+export const EXPORT_FINISH = "export:finish";+export const EXPORT_CANCEL = "export:cancel";++export function registerFfmpegExportIpc(): void {+ ipcMain.handle(EXPORT_CAPABILITIES, async () => {+ const { encoder } = await resolveExportCapabilities();+ return { encoder };+ });++ ipcMain.handle(EXPORT_START, async (_e, req: StartExportRequest) => startExport(req));++ ipcMain.on(EXPORT_FRAME, async (e, sessionId: string, frame: ArrayBuffer) => {+ try {+ await writeExportFrame(sessionId, frame);+ // Ack even on the last frame: the renderer's window must refill or it+ // will stall short of the end.+ if (!e.sender.isDestroyed()) e.sender.send(EXPORT_FRAME_ACK, sessionId, null);+ } catch (err) {+ // A write failure means ffmpeg died mid-export. Report it on the ack+ // channel rather than throwing into an ipcMain.on handler, where the+ // rejection would be unhandled and the renderer would wait forever.+ if (!e.sender.isDestroyed()) {+ e.sender.send(EXPORT_FRAME_ACK, sessionId, (err as Error).message);+ }+ }+ });++ ipcMain.handle(EXPORT_FINISH, async (_e, sessionId: string) => finishExport(sessionId));+ ipcMain.handle(EXPORT_CANCEL, async (_e, sessionId: string) => cancelExport(sessionId));+}diff --git a/electron/media/ffmpegExportService.ts b/electron/media/ffmpegExportService.tsnew file mode 100644index 000000000..4481ba001--- /dev/null+++ b/electron/media/ffmpegExportService.ts@@ -0,0 +1,207 @@+import { spawn } from "node:child_process";+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import {+ candidateFfmpegPaths,+ parseAvailableEncoders,+ pickWorkingEncoder,+ type VideoEncoderId,+} from "./ffmpegCapabilities";+import { type FfmpegEncodeSession, startFfmpegEncodeSession } from "./ffmpegEncodeSession";++/**+ * Main-process side of the native export encoder: resolves the bundled ffmpeg,+ * proves which encoder actually works on this machine, and owns the live encode+ * sessions the renderer streams frames into.+ *+ * The renderer cannot spawn anything (it is sandboxed, and stays that way), so+ * frames cross to us over IPC and we feed ffmpeg's stdin. ffmpeg encodes, muxes+ * the audio and writes the file — there is no JS muxer and no WebCodecs path+ * behind this.+ */++export interface StartExportRequest {+ outputPath: string;+ width: number;+ height: number;+ frameRate: number;+ bitrate: number;+ pixelFormat: "nv12" | "bgra" | "rgba";+ /** Raw interleaved float32 PCM. ffmpeg encodes AAC and muxes it. */+ audio?: { pcm: ArrayBuffer; sampleRate: number; channels: number; bitrate: number };+}++export interface StartExportResult {+ sessionId: string;+ encoder: VideoEncoderId;+}++/** Resolved once per process: the probe costs a few spawns, the answer never changes. */+let capabilitiesPromise: Promise<{ ffmpegPath: string; encoder: VideoEncoderId }> | null = null;++async function firstExisting(paths: string[]): Promise<string | null> {+ for (const p of paths) {+ try {+ await fs.access(p);+ return p;+ } catch {+ // Expected: candidateFfmpegPaths lists every layout we might be running+ // under (dev tree, unpacked staging, packaged resources); most miss.+ }+ }+ return null;+}++function runFfmpeg(ffmpegPath: string, args: string[]): Promise<{ code: number; stdout: string }> {+ return new Promise((resolve) => {+ const child = spawn(ffmpegPath, args, { stdio: ["ignore", "pipe", "ignore"] });+ let stdout = "";+ child.stdout?.setEncoding("utf8");+ child.stdout?.on("data", (c: string) => {+ stdout += c;+ });+ child.on("error", () => resolve({ code: -1, stdout: "" }));+ child.on("close", (code) => resolve({ code: code ?? -1, stdout }));+ });+}++/**+ * Which encoder this machine can really use. Cached: the smoke tests spawn ffmpeg+ * a few times, and hardware does not change under a running app.+ *+ * The smoke test is the whole point. `ffmpeg -encoders` reports what was compiled+ * in — our portable build lists nvenc, qsv and amf on every machine — so on an+ * AMD box nvenc is "available" and then dies with "Cannot load nvcuda.dll".+ * Presence is not capability; only a real one-frame encode settles it.+ */+export function resolveExportCapabilities(): Promise<{+ ffmpegPath: string;+ encoder: VideoEncoderId;+}> {+ capabilitiesPromise ??= (async () => {+ const ffmpegPath = await firstExisting(+ candidateFfmpegPaths({+ platform: process.platform,+ arch: process.arch,+ appPath: process.env.OPENSCREEN_APP_PATH ?? null,+ resourcesPath: process.resourcesPath ?? null,+ envOverride: process.env.OPENSCREEN_FFMPEG_EXE ?? null,+ }),+ );+ if (!ffmpegPath) {+ throw new Error(+ "Bundled ffmpeg not found. Run `npm run fetch:ffmpeg` in development; " ++ "in a packaged build this means the binary was not shipped.",+ );+ }++ const listed = await runFfmpeg(ffmpegPath, ["-hide_banner", "-encoders"]);+ const available = parseAvailableEncoders(listed.stdout);+ const encoder = await pickWorkingEncoder(+ available,+ process.platform,+ async (args) => (await runFfmpeg(ffmpegPath, args)).code === 0,+ );+ if (!encoder) {+ // libopenh264 is software and part of our build, so it should always pass.+ // Reaching here means the binary is broken, not that the machine is+ // unsupported — and there is no other path to fall back to.+ throw new Error(+ "No usable H.264 encoder in the bundled ffmpeg — not even software. " ++ "The bundled binary is broken or was replaced.",+ );+ }+ return { ffmpegPath, encoder };+ })();+ return capabilitiesPromise;+}++interface LiveSession {+ session: FfmpegEncodeSession;+ /** Temp PCM handed to ffmpeg as its second input; ours to delete. */+ audioPath: string | null;+ tmpDir: string | null;+}++const sessions = new Map<string, LiveSession>();+let nextId = 1;++export async function startExport(req: StartExportRequest): Promise<StartExportResult> {+ const { ffmpegPath, encoder } = await resolveExportCapabilities();++ let audioPath: string | null = null;+ let tmpDir: string | null = null;+ if (req.audio && req.audio.pcm.byteLength > 0) {+ // ffmpeg reads raw f32le straight from disk. Writing the PCM out beats a+ // second pipe: it is small (a few MB), and stdin is already carrying video.+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-export-"));+ audioPath = path.join(tmpDir, "audio.f32le");+ await fs.writeFile(audioPath, Buffer.from(req.audio.pcm));+ }++ const session = startFfmpegEncodeSession({+ ffmpegPath,+ encoder,+ outputPath: req.outputPath,+ width: req.width,+ height: req.height,+ frameRate: req.frameRate,+ bitrate: req.bitrate,+ pixelFormat: req.pixelFormat,+ audio:+ audioPath && req.audio+ ? {+ path: audioPath,+ sampleRate: req.audio.sampleRate,+ channels: req.audio.channels,+ bitrate: req.audio.bitrate,+ }+ : undefined,+ });++ const sessionId = `export-${nextId++}`;+ sessions.set(sessionId, { session, audioPath, tmpDir });+ return { sessionId, encoder };+}++function requireSession(sessionId: string): LiveSession {+ const live = sessions.get(sessionId);+ if (!live) throw new Error(`Unknown export session: ${sessionId}`);+ return live;+}++export async function writeExportFrame(sessionId: string, frame: ArrayBuffer): Promise<void> {+ // Buffer.from(arrayBuffer) wraps rather than copies — the +31% we measured+ // depends on not duplicating a multi-MB frame here.+ await requireSession(sessionId).session.writeFrame(new Uint8Array(frame));+}++async function dispose(sessionId: string, live: LiveSession): Promise<void> {+ sessions.delete(sessionId);+ if (live.tmpDir) await fs.rm(live.tmpDir, { recursive: true, force: true });+}++export async function finishExport(sessionId: string): Promise<{ outputPath: string }> {+ const live = requireSession(sessionId);+ try {+ return await live.session.finish();+ } finally {+ await dispose(sessionId, live);+ }+}++export async function cancelExport(sessionId: string): Promise<void> {+ const live = sessions.get(sessionId);+ if (!live) return; // Already finished or never started: cancelling is idempotent.+ try {+ await live.session.cancel();+ } finally {+ await dispose(sessionId, live);+ }+}++/** Kill every live session — called when the app quits so no ffmpeg is orphaned. */+export async function cancelAllExports(): Promise<void> {+ await Promise.all([...sessions.keys()].map((id) => cancelExport(id)));+}diff --git a/electron/preload.ts b/electron/preload.tsindex 87f051ab1..a756d94d4 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -21,6 +21,34 @@ const assetBaseUrl = assetBaseUrlArg ? assetBaseUrlArg.slice(ASSET_BASE_URL_ARG_contextBridge.exposeInMainWorld("electronAPI", {assetBaseUrl,++ // --- Native export encoder -------------------------------------------------+ // The renderer composites and extracts frames but cannot spawn ffmpeg (it is+ // sandboxed, deliberately), so frames cross to main and it feeds ffmpeg's+ // stdin. Frames go one-way via send(); flow control is the caller's credit+ // window, acked on exportOnFrameAck.+ exportCapabilities: () =>+ ipcRenderer.invoke("export:capabilities") as Promise<{ encoder: string }>,+ exportStart: (req: unknown) =>+ ipcRenderer.invoke("export:start", req) as Promise<{ sessionId: string; encoder: string }>,+ exportWriteFrame: (sessionId: string, frame: ArrayBuffer) => {+ // send() structured-clones, i.e. copies the frame. That is not an oversight+ // and it is not fixable here: Electron's transfer list takes MessagePort[]+ // only, and transferring an ArrayBuffer renderer->main silently drops the+ // whole message (electron#34905 - it works renderer->renderer, not to main).+ // The copy is what caps the crossing at ~390 MB/s, which is why the export+ // ships NV12 (3.0 MB/frame) rather than BGRA (7.9 MB).+ ipcRenderer.send("export:frame", sessionId, frame);+ },+ exportOnFrameAck: (cb: (sessionId: string, error: string | null) => void) => {+ const handler = (_e: unknown, sessionId: string, error: string | null) => cb(sessionId, error);+ ipcRenderer.on("export:frame-ack", handler);+ return () => ipcRenderer.off("export:frame-ack", handler);+ },+ exportFinish: (sessionId: string) =>+ ipcRenderer.invoke("export:finish", sessionId) as Promise<{ outputPath: string }>,+ exportCancel: (sessionId: string) =>+ ipcRenderer.invoke("export:cancel", sessionId) as Promise<void>,invokeNativeBridge: <TData>(request: NativeBridgeRequest) => {return ipcRenderer.invoke(NATIVE_BRIDGE_CHANNEL, request) as Promise<TData>;},diff --git a/package.json b/package.jsonindex dcdede4ec..1c2997772 100644--- a/package.json+++ b/package.json@@ -29,8 +29,7 @@"build:native:mac": "node scripts/build-macos-screencapturekit-helper.mjs","build:mac": "npm run build:native:mac && tsc && vite build && electron-builder --mac","build:native:win": "node scripts/build-windows-wgc-helper.mjs",- "build:win": "npm run build:native:win && tsc && vite build && electron-builder --win --config.npmRebuild=false",- "build:win:store": "npm run build:native:win && tsc && vite build && electron-builder --win appx --config.npmRebuild=false",+ "build:win": "npm run build:native:win && npm run fetch:ffmpeg && tsc && vite build && electron-builder --win --config.npmRebuild=false","build:linux": "tsc && vite build && electron-builder --linux AppImage deb pacman --config.npmRebuild=false","build:whisper-binaries": "bash scripts/build-whisper-stt.sh","test": "vitest --run",@@ -52,7 +51,8 @@"test:browser:install": "playwright install --with-deps chromium-headless-shell","test:e2e": "playwright test","test:e2e:windows-native-checklist": "playwright test tests/e2e/windows-native-checklist.spec.ts",- "prepare": "husky"+ "prepare": "husky",+ "fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs"},"dependencies": {"@fix-webm-duration/fix": "^1.0.1",diff --git a/scripts/fetch-ffmpeg.mjs b/scripts/fetch-ffmpeg.mjsnew file mode 100644index 000000000..d03a1090b--- /dev/null+++ b/scripts/fetch-ffmpeg.mjs@@ -0,0 +1,277 @@+// Provisions the bundled ffmpeg used by the native export encoder into+// electron/native/bin/<platform>-<arch>/, alongside wgc-capture and the whisper+// binaries. That directory is gitignored and shipped via electron-builder's+// extraResources, so this runs at build time rather than committing binaries.+//+// Why bundle ffmpeg at all: WebCodecs reaches the platform's hardware encoder+// but measures ~8 fps @1080p where native ffmpeg does ~165 on the same GPU. The+// gap is Chromium's per-frame overhead, not the silicon.+//+// SUPPLY CHAIN. This binary is signed and shipped to every user, so nothing here+// floats:+// - Pinned to an immutable dated release tag, never `latest` (which is an+// alias that moves daily).+// - Pinned to a *release-branch* build (n8.1.x), never the `N-…` master+// snapshots BtbN also publishes. Master is not a release.+// - 8.1.x on purpose: it is the version the 165 fps h264_amf benchmark was+// taken with, so what we ship is what we measured.+// - SHA-256 verified before the archive is opened. Update PINNED together —+// tag, asset name and digest are one unit.+// Source approved by Etienne (2026-07-16). BtbN is linked from ffmpeg.org's+// download page and published on winget as BtbN.FFmpeg.LGPL.+//+// LICENSING — the other thing this script exists to protect:+// ffmpeg is LGPL *by default*. It becomes GPL only when built with+// --enable-gpl (which pulls x264/x265) or --enable-nonfree (fdk-aac), and it+// is all-or-nothing: one GPL component relicenses the whole binary, which+// would contaminate this MIT app. We take BtbN's *-lgpl assets AND verify what+// we got before vendoring. Never swap in a "gpl" asset for the extra encoders:+// there is nothing in them we need — the hardware encoders are all LGPL.+//+// macOS: BtbN publishes no macOS target, so darwin is not handled here. It has+// to be built and notarised separately — see docs/architecture/+// export-pipeline-v2-spec.md, Phase 3. Native encode ships on all three+// platforms; there is no "macOS keeps WebCodecs" option.++import { spawnSync } from "node:child_process";+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.join(__dirname, "..");++/** Immutable dated tag. `latest` is an alias that moves — do not use it here. */+const RELEASE_TAG = "autobuild-2026-07-15-14-01";+const BASE = `https://github.com/BtbN/FFmpeg-Builds/releases/download/${RELEASE_TAG}`;++/** Tag, asset and digest move together. Re-pin all three or none. */+const PINNED = {+ "win32-x64": {+ asset: "ffmpeg-n8.1.2-22-g94138f6973-win64-lgpl-8.1.zip",+ sha256: "6bd644cb9476a72d905ba22c807eaef1c47a224c8f194c0771da9f3e9a765c35",+ exe: "ffmpeg.exe",+ },+ "win32-arm64": {+ asset: "ffmpeg-n8.1.2-22-g94138f6973-winarm64-lgpl-8.1.zip",+ sha256: "8f89ba5cca2c14ef8e181cdb1bd8403d7b7ee7586151027918a2ac8e42cf7c48",+ exe: "ffmpeg.exe",+ },+ "linux-x64": {+ asset: "ffmpeg-n8.1.2-22-g94138f6973-linux64-lgpl-8.1.tar.xz",+ sha256: "81c8a9fd1f4bb0a888e820d8ddc825cee5116da16efe93054c761ecbc4b54fc3",+ exe: "ffmpeg",+ },+ "linux-arm64": {+ asset: "ffmpeg-n8.1.2-22-g94138f6973-linuxarm64-lgpl-8.1.tar.xz",+ sha256: "0d4777bde13dcfb61de3541d129df8a37f0e24eb0afddb0bab698fa73ec0aed4",+ exe: "ffmpeg",+ },+};++/** Enabling any of these makes the whole binary GPL. Source: ffmpeg.org/legal.html. */+const GPL_LIBS = [+ "libx264",+ "libx265",+ "libxvid",+ "libxavs",+ "libxavs2",+ "libdavs2",+ "libvidstab",+ "librubberband",+ "libcdio",+ "frei0r",+ "avisynth",+];+/** Worse than GPL: these make the binary unredistributable at all. */+const NONFREE_LIBS = ["libfdk-aac", "libfdk_aac"];++/** The encoders the export path actually selects, per platform. */+const WANTED_ENCODERS = {+ win32: ["h264_nvenc", "h264_qsv", "h264_amf"],+ linux: ["h264_nvenc", "h264_vaapi"],+};++function run(cmd, args, opts = {}) {+ const r = spawnSync(cmd, args, { encoding: "utf8", ...opts });+ if (r.error) throw r.error;+ return r;+}++/**+ * Refuses to vendor anything that would relicense the app. Mirrors isLgplBuild()+ * in electron/media/ffmpegCapabilities.ts on purpose: that one guards at+ * runtime, this one at build time. If they ever disagree, one of them drifted.+ */+function assertLgpl(exePath) {+ const problems = [];++ // `ffmpeg -L` prints the licence TEXT. This is the authoritative statement:+ // an LGPL build says "GNU Lesser General Public License", a GPL one says+ // "GNU General Public License". Note there is NO "License:" line in+ // `-version` — only `configuration:`.+ const license = run(exePath, ["-hide_banner", "-L"]).stdout ?? "";+ if (!/Lesser General Public License/i.test(license)) {+ const what = /General Public License/i.test(license) ? "GPL" : "unrecognised licence";+ problems.push(`-L reports ${what}, not LGPL`);+ }++ // `-buildconf` lists the configure flags one per line; `-version` has them on+ // one `configuration:` line. Read both so a build that answers only one still+ // gets checked.+ const conf =+ (run(exePath, ["-hide_banner", "-buildconf"]).stdout ?? "") ++ (run(exePath, ["-hide_banner", "-version"]).stdout ?? "");+ for (const flag of ["--enable-gpl", "--enable-nonfree"]) {+ if (new RegExp(`(^|\\s)${flag}(\\s|$)`, "m").test(conf))+ problems.push(`configured with ${flag}`);+ }+ for (const lib of [...GPL_LIBS, ...NONFREE_LIBS]) {+ if (new RegExp(`(^|\\s)--enable-${lib}(\\s|$)`, "m").test(conf)) problems.push(`links ${lib}`);+ }++ // Belt and braces: whatever the flags claim, the binary must not actually+ // expose a GPL encoder.+ const encoders = run(exePath, ["-hide_banner", "-encoders"]).stdout ?? "";+ for (const lib of ["libx264", "libx265"]) {+ if (new RegExp(`\\s${lib}\\s`).test(encoders)) problems.push(`exposes the ${lib} encoder`);+ }++ if (problems.length > 0) {+ throw new Error(+ "This ffmpeg is NOT an LGPL build and must not be shipped:\n" ++ `${problems.map((p) => ` - ${p}`).join("\n")}\n` ++ "Bundling it would relicense OpenScreen under the GPL.",+ );+ }+ const ver = run(exePath, ["-hide_banner", "-version"]).stdout ?? "";+ return ver.split("\n")[0]?.trim() ?? "";+}++function reportEncoders(exePath, platform) {+ const encoders = run(exePath, ["-hide_banner", "-encoders"]).stdout ?? "";+ const wanted = WANTED_ENCODERS[platform] ?? [];+ const found = wanted.filter((e) => new RegExp(`\\s${e}\\s`).test(encoders));+ const missing = wanted.filter((e) => !found.includes(e));+ console.log(` hardware encoders: ${found.join(", ") || "(none)"}`);+ if (missing.length > 0) {+ // Not fatal: which encoders a build exposes is separate from which GPU the+ // machine has. selectVideoEncoder() probes at runtime regardless.+ console.log(` not in this build: ${missing.join(", ")}`);+ }+}++/**+ * Windows 10+ ships bsdtar at System32\tar.exe, which reads zip. Resolve it+ * explicitly: a dev shell (Git Bash, MSYS) usually puts GNU tar first on PATH,+ * and GNU tar cannot read zip at all.+ */+function tarBin() {+ if (process.platform !== "win32") return "tar";+ const sys32 = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe");+ return fs.existsSync(sys32) ? sys32 : "tar";+}++function extract(archive, destDir) {+ fs.mkdirSync(destDir, { recursive: true });+ // Run from destDir with a bare filename: given an absolute Windows path, tar+ // reads "C:\..." as host:path and tries to resolve a host called C.+ const r = run(tarBin(), [archive.endsWith(".zip") ? "-xf" : "-xJf", path.basename(archive)], {+ cwd: destDir,+ stdio: "inherit",+ });+ if (r.status !== 0) throw new Error(`tar failed to extract ${path.basename(archive)}`);+}++/** BtbN archives nest everything under a versioned dir; find the exe wherever it landed. */+function findExe(dir, name) {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ const hit = findExe(p, name);+ if (hit) return hit;+ } else if (entry.name === name) {+ return p;+ }+ }+ return null;+}++async function main() {+ const tag = `${process.platform}-${process.arch}`;++ if (process.platform === "darwin") {+ console.error(+ "macOS is not provisioned by this script: BtbN publishes no macOS build.\n" ++ "It must be built and notarised separately (docs/architecture/export-pipeline-v2-spec.md,\n" ++ "Phase 3). A VideoToolbox-only build is inherently x264-free, so the LGPL gate is easy there.",+ );+ process.exit(1);+ }++ const spec = PINNED[tag];+ if (!spec) {+ console.error(`No pinned asset for ${tag}. Have: ${Object.keys(PINNED).join(", ")}`);+ process.exit(1);+ }++ const binDir = path.join(ROOT, "electron", "native", "bin", tag);+ const dest = path.join(binDir, spec.exe);++ if (fs.existsSync(dest) && !process.argv.includes("--force")) {+ console.log(`Already present: ${dest}`);+ console.log(assertLgpl(dest));+ reportEncoders(dest, process.platform);+ console.log("LGPL verified. Use --force to re-download.");+ return;+ }++ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-ffmpeg-"));+ try {+ const url = `${BASE}/${spec.asset}`;+ console.log(`Downloading ${spec.asset}\n from ${RELEASE_TAG}`);+ const res = await fetch(url);+ if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText}`);+ const bytes = Buffer.from(await res.arrayBuffer());++ // Before opening it: is this the exact artifact we pinned?+ const got = crypto.createHash("sha256").update(bytes).digest("hex");+ if (got !== spec.sha256) {+ throw new Error(+ `SHA-256 mismatch for ${spec.asset}\n expected ${spec.sha256}\n got ${got}\n` ++ "Refusing to extract. Either the pin is stale or the artifact changed under it.",+ );+ }+ console.log(` sha256 ok (${(bytes.length / 1048576).toFixed(0)} MB)`);++ const archive = path.join(tmp, spec.asset);+ fs.writeFileSync(archive, bytes);+ extract(archive, tmp);++ const found = findExe(tmp, spec.exe);+ if (!found) throw new Error(`${spec.exe} not found inside ${spec.asset}`);++ // Verify the licence BEFORE vendoring: a GPL binary must never reach+ // electron/native/bin, where the packager would happily ship it.+ console.log("Verifying licence...");+ const banner = assertLgpl(found);++ fs.mkdirSync(binDir, { recursive: true });+ fs.copyFileSync(found, dest);+ if (process.platform !== "win32") fs.chmodSync(dest, 0o755);++ console.log(`\n${banner}`);+ reportEncoders(dest, process.platform);+ console.log(`\nVendored -> ${dest}`);+ console.log("LGPL verified: safe to ship with an MIT app.");+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true });+ }+}++main().catch((err) => {+ console.error(`\n${err.message}`);+ process.exit(1);+});