Skip to content

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

fix(compositor): resolve the PATH-dependent ffmpeg addon load and finish packaging

Etienne Lescot4bac8371924c
diff --git a/electron-builder.json5 b/electron-builder.json5
index 7bc02ba54..cbce12e3e 100644
--- a/electron-builder.json5
+++ b/electron-builder.json5
@@ -48,7 +48,7 @@
"from": "public/cursors",
"to": "cursors"
}
- ],
+ ],
"mac": {
"notarize": false,
@@ -95,19 +95,29 @@
"filter": ["linux-*/*"]
}
]
- },
- "win": {
- "target": [
- "nsis"
- ],
- "icon": "icons/icons/win/icon.ico",
- "artifactName": "${productName}.Setup.${version}.${ext}",
- "extraResources": [
- {
- "from": "electron/native/bin",
+ },
+ "win": {
+ "target": [
+ "nsis"
+ ],
+ "icon": "icons/icons/win/icon.ico",
+ "artifactName": "${productName}.Setup.${version}.${ext}",
+ "extraResources": [
+ {
+ "from": "electron/native/bin",
"to": "electron/native/bin",
"filter": ["win32-*/*"]
}
+ ],
+ // Native D3D11 compositor addon (Windows-only). Built by
+ // `npm run build:native:compositor` (scripts/build-windows-compositor-addon.mjs)
+ // before packaging. Packed into asar, then auto-unpacked by the top-level
+ // `asarUnpack: ["**/*.node"]` rule to app.asar.unpacked/... — matches the
+ // `.asar` -> `.asar.unpacked` rewrite compositorViewService.ts's
+ // buildCandidatePaths() already applies for packaged builds. Appends to
+ // (doesn't replace) the top-level `files` list.
+ "files": [
+ "electron/native/compositor-view/build"
]
},
"nsis": {
diff --git a/electron/native-bridge/services/compositorViewService.test.ts b/electron/native-bridge/services/compositorViewService.test.ts
new file mode 100644
index 000000000..fbdc76c54
--- /dev/null
+++ b/electron/native-bridge/services/compositorViewService.test.ts
@@ -0,0 +1,101 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { CompositorViewService, ffmpegSharedBinCandidates } from "./compositorViewService";
+
+describe("ffmpegSharedBinCandidates", () => {
+ it("lists the dev-vendored shared-ffmpeg dir before the arch-tagged native bin dir", () => {
+ const appRoot = "C:/fake/repo";
+ const candidates = ffmpegSharedBinCandidates(appRoot).map((p) => p.replace(/\\/g, "/"));
+ expect(candidates[0]).toBe(
+ `${appRoot}/poc-d3d/thirdparty/ffmpeg-master-latest-win64-lgpl-shared/bin`,
+ );
+ expect(candidates[1]).toMatch(/electron\/native\/bin\/(win32|darwin|linux)-(x64|arm64)$/);
+ });
+
+ it("also probes process.resourcesPath, since electron/native/bin ships only via extraResources in packaged builds", () => {
+ const original = process.resourcesPath;
+ Object.defineProperty(process, "resourcesPath", {
+ value: "C:/fake/resources",
+ configurable: true,
+ });
+ try {
+ const candidates = ffmpegSharedBinCandidates("C:/fake/repo").map((p) =>
+ p.replace(/\\/g, "/"),
+ );
+ expect(candidates).toContain(
+ `C:/fake/resources/electron/native/bin/${candidates[1]!.split("/").at(-1)}`,
+ );
+ } finally {
+ Object.defineProperty(process, "resourcesPath", { value: original, configurable: true });
+ }
+ });
+});
+
+describe("CompositorViewService ffmpeg PATH prepend", () => {
+ let tmpRoot: string;
+ let originalPath: string | undefined;
+ let originalPlatform: PropertyDescriptor | undefined;
+
+ beforeEach(() => {
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-compositor-test-"));
+ originalPath = process.env.PATH;
+ originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ process.env.PATH = originalPath;
+ if (originalPlatform) {
+ Object.defineProperty(process, "platform", originalPlatform);
+ }
+ });
+
+ it("prepends the ffmpeg shared-DLL dir to PATH when it exists, even though the addon itself is absent", () => {
+ const ffmpegDir = path.join(
+ tmpRoot,
+ "poc-d3d",
+ "thirdparty",
+ "ffmpeg-master-latest-win64-lgpl-shared",
+ "bin",
+ );
+ fs.mkdirSync(ffmpegDir, { recursive: true });
+ process.env.PATH = "C:\\Windows\\System32";
+
+ const service = new CompositorViewService({ appRoot: tmpRoot, isPackaged: false });
+ expect(service.hasAddon()).toBe(false); // no compositor_view.node under tmpRoot
+ expect(process.env.PATH?.split(path.delimiter)).toContain(ffmpegDir);
+ });
+
+ it("leaves PATH untouched when no ffmpeg shared-DLL dir exists", () => {
+ process.env.PATH = "C:\\Windows\\System32";
+ const before = process.env.PATH;
+
+ const service = new CompositorViewService({ appRoot: tmpRoot, isPackaged: false });
+ service.hasAddon();
+
+ expect(process.env.PATH).toBe(before);
+ });
+
+ it("does not duplicate the entry when PATH already contains it", () => {
+ const ffmpegDir = path.join(
+ tmpRoot,
+ "poc-d3d",
+ "thirdparty",
+ "ffmpeg-master-latest-win64-lgpl-shared",
+ "bin",
+ );
+ fs.mkdirSync(ffmpegDir, { recursive: true });
+ process.env.PATH = "C:\\Windows\\System32";
+
+ // simulates a second view/service instance loading after PATH was
+ // already primed by the first — same appRoot, fresh instance.
+ new CompositorViewService({ appRoot: tmpRoot, isPackaged: false }).hasAddon();
+ new CompositorViewService({ appRoot: tmpRoot, isPackaged: false }).hasAddon();
+
+ const occurrences = process.env.PATH?.split(path.delimiter).filter((p) => p === ffmpegDir);
+ expect(occurrences?.length).toBe(1);
+ });
+});
diff --git a/electron/native-bridge/services/compositorViewService.ts b/electron/native-bridge/services/compositorViewService.ts
index e3e53901e..94b4b9e32 100644
--- a/electron/native-bridge/services/compositorViewService.ts
+++ b/electron/native-bridge/services/compositorViewService.ts
@@ -149,6 +149,52 @@ function buildCandidatePaths(
return ordered.map((candidate) => candidate.replace(/\.asar([/\\])/, ".asar.unpacked$1"));
}
+/**
+ * Directories that may hold the ffmpeg shared DLLs (avcodec/avformat/avutil/…)
+ * the addon dynamically links against. Node's `require()` of a native addon
+ * does a Win32 `LoadLibrary` under the hood, which resolves dependent DLLs via
+ * the standard search order — including `PATH` — so whichever of these exists
+ * gets prepended to `process.env.PATH` before the `require()` in
+ * `tryLoadAddon`.
+ *
+ * Order: the dev-only vendored location first, then the arch-tagged bin dir
+ * under `appRoot` (dev / `electron-builder --dir` unpacked staging), then the
+ * *same* dir under `process.resourcesPath` — required for real packaged
+ * installers, since `electron/native/bin/**` ships exclusively via
+ * `extraResources` (see `electron-builder.json5`'s `files` list, which only
+ * packs `dist`/`dist-electron`) and is never inside `app.getAppPath()` there.
+ * Mirrors the appPath/resourcePath pattern `stt/gpuDetector.ts` already uses
+ * for the other native binaries in this same directory.
+ */
+export function ffmpegSharedBinCandidates(appRoot: string): string[] {
+ const tag = platformArchTag();
+ const resourcesPath =
+ typeof process.resourcesPath === "string" && process.resourcesPath.length > 0
+ ? process.resourcesPath
+ : null;
+ return [
+ path.join(appRoot, "poc-d3d", "thirdparty", "ffmpeg-master-latest-win64-lgpl-shared", "bin"),
+ path.join(appRoot, "electron", "native", "bin", tag),
+ ...(resourcesPath ? [path.join(resourcesPath, "electron", "native", "bin", tag)] : []),
+ ];
+}
+
+/** Prepends the first existing ffmpeg shared-DLL dir to `PATH` (no-op if already present or none found). */
+function ensureFfmpegSharedDllsOnPath(appRoot: string): void {
+ if (process.platform !== "win32") {
+ return;
+ }
+ const dir = ffmpegSharedBinCandidates(appRoot).find((candidate) => fs.existsSync(candidate));
+ if (!dir) {
+ return;
+ }
+ const current = process.env.PATH ?? "";
+ if (current.split(path.delimiter).includes(dir)) {
+ return;
+ }
+ process.env.PATH = `${dir}${path.delimiter}${current}`;
+}
+
function tryLoadAddon(candidates: string[]): CompositorViewAddon | null {
for (const candidate of candidates) {
try {
@@ -162,9 +208,12 @@ function tryLoadAddon(candidates: string[]): CompositorViewAddon | null {
if (loaded && typeof loaded === "object") {
return loaded as CompositorViewAddon;
}
- } catch {
- // try the next candidate — a single broken build
- // shouldn't kill the addon entirely.
+ } catch (err) {
+ // log and try the next candidate — a single broken build
+ // shouldn't kill the addon entirely, but silently swallowing this
+ // is exactly what made a missing-ffmpeg-DLL failure look like a
+ // generic "addon not present" no-op.
+ console.warn(`[compositor-view] failed to load addon candidate ${candidate}:`, err);
}
}
return null;
@@ -192,6 +241,7 @@ export class CompositorViewService {
const appRoot = this.options.appRoot ?? defaultAppRoot();
const isPackaged = this.options.isPackaged ?? defaultIsPackaged();
+ ensureFfmpegSharedDllsOnPath(appRoot);
const candidates = buildCandidatePaths(appRoot, isPackaged, envOverride);
const loaded = tryLoadAddon(candidates);
if (!loaded) {
diff --git a/package.json b/package.json
index 0f76c1067..e41d29685 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,8 @@
"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 && npm run fetch:ffmpeg && tsc && vite build && electron-builder --win --config.npmRebuild=false",
+ "build:native:compositor": "node scripts/build-windows-compositor-addon.mjs",
+ "build:win": "npm run build:native:win && npm run build:native:compositor && 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",
diff --git a/poc-d3d/.cargo/config.toml b/poc-d3d/.cargo/config.toml
index 996649fb1..79bdd9a87 100644
--- a/poc-d3d/.cargo/config.toml
+++ b/poc-d3d/.cargo/config.toml
@@ -1,6 +1,13 @@
# FFMPEG_DIR relatif au dossier poc-d3d/ (portable dans le repo). Y déposer le build
# ffmpeg LGPL-shared (voir README). LIBCLANG_PATH = install LLVM locale (bindgen).
# Ces valeurs cèdent à une vraie variable d'environnement (force=false par défaut).
+#
+# Pinné sur le MÊME build release-branch (n8.1.2-22-g94138f6973, tag BtbN
+# autobuild-2026-07-15-14-01) que scripts/fetch-ffmpeg.mjs vendorise dans
+# electron/native/bin/<tag>/ pour le packaging — pas un snapshot "master-latest"
+# flottant. L'addon (compositor-view-napi) doit être lié à la même version de
+# ffmpeg que celle shippée, sinon les DLLs vendorisées ne matchent pas les
+# noms de DLL importés (avcodec-NN.dll etc.) et le require() échoue au runtime.
[env]
-FFMPEG_DIR = { value = "thirdparty/ffmpeg-master-latest-win64-lgpl-shared", relative = true }
+FFMPEG_DIR = { value = "thirdparty/ffmpeg-n8.1.2-win64-lgpl-shared", relative = true }
LIBCLANG_PATH = "C:\\Program Files\\LLVM\\bin"
diff --git a/poc-d3d/x.bat b/poc-d3d/x.bat
index 0bbb9ed54..f4d7df131 100644
--- a/poc-d3d/x.bat
+++ b/poc-d3d/x.bat
@@ -3,6 +3,6 @@ REM Enveloppe de build, portable dans le repo (chemins via %~dp0) :
REM vcvars (INCLUDE/LIB pour libclang + linker MSVC), ffmpeg/bin sur PATH runtime, cargo.
REM Ajuste le chemin vcvars ci-dessous si ta version de Visual Studio diffère.
call "C:\Program Files\Microsoft Visual Studio\18\Insiders\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1
-set "PATH=%PATH%;%~dp0thirdparty\ffmpeg-master-latest-win64-lgpl-shared\bin"
+set "PATH=%PATH%;%~dp0thirdparty\ffmpeg-n8.1.2-win64-lgpl-shared\bin"
cd /d "%~dp0"
"%USERPROFILE%\.cargo\bin\cargo.exe" %*
diff --git a/scripts/build-windows-compositor-addon.mjs b/scripts/build-windows-compositor-addon.mjs
new file mode 100644
index 000000000..876e9cacf
--- /dev/null
+++ b/scripts/build-windows-compositor-addon.mjs
@@ -0,0 +1,186 @@
+// Builds the native D3D11 compositor addon (poc-d3d/compositor-view-napi) and
+// vendors it to electron/native/compositor-view/build/compositor_view.node,
+// the path compositorViewService.ts's candidate list resolves at runtime.
+//
+// Mirrors build-windows-wgc-helper.mjs's MSVC-environment discovery (vcvarsall
+// sweep), but drives `cargo build` instead of CMake/Ninja — poc-d3d is a Rust
+// workspace. FFMPEG_DIR and LIBCLANG_PATH come from poc-d3d/.cargo/config.toml
+// (portable, relative to poc-d3d/), not from this script: cargo picks those up
+// automatically because the build runs with cwd = poc-d3d/.
+//
+// The addon links against ffmpeg's shared DLLs (avcodec/avformat/avutil/…),
+// so it MUST be built against the same pinned ffmpeg release that
+// fetch-ffmpeg.mjs vendors into electron/native/bin/<tag>/ — otherwise the
+// DLL filenames the addon imports (avcodec-NN.dll etc.) won't match what's
+// shipped, and require() fails at runtime even with the right dir on PATH.
+// See poc-d3d/.cargo/config.toml for the pin.
+
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.join(__dirname, "..");
+const POC_D3D_DIR = path.join(ROOT, "poc-d3d");
+const BUILD_OUT_DIR = path.join(ROOT, "electron", "native", "compositor-view", "build");
+
+function findVcVarsAll() {
+ const explicit = process.env.VCVARSALL;
+ if (explicit && fs.existsSync(explicit)) {
+ return explicit;
+ }
+
+ const vswhere = "C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";
+ if (fs.existsSync(vswhere)) {
+ const result = spawnSync(
+ vswhere,
+ [
+ "-latest",
+ "-products",
+ "*",
+ "-requires",
+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
+ "-property",
+ "installationPath",
+ ],
+ { encoding: "utf8", windowsHide: true },
+ );
+ const installPath = result.stdout?.trim();
+ if (result.status === 0 && installPath) {
+ const candidate = path.join(installPath, "VC", "Auxiliary", "Build", "vcvarsall.bat");
+ if (fs.existsSync(candidate)) {
+ return candidate;
+ }
+ }
+ }
+
+ if (process.env.VSINSTALLDIR) {
+ const candidate = path.join(process.env.VSINSTALLDIR, "VC", "Auxiliary", "Build", "vcvarsall.bat");
+ if (fs.existsSync(candidate)) {
+ return candidate;
+ }
+ }
+
+ // vswhere doesn't always enumerate pre-release channels (e.g. "Insiders"
+ // builds) — walk the install roots generically so new VS releases and
+ // preview channels are found automatically (same policy as the wgc-capture
+ // helper build script).
+ const editions = ["Community", "Professional", "Enterprise", "BuildTools"];
+ const installRoots = [
+ "C:\\Program Files\\Microsoft Visual Studio",
+ "C:\\Program Files (x86)\\Microsoft Visual Studio",
+ ];
+
+ const listDirs = (dir) => {
+ try {
+ return fs
+ .readdirSync(dir, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => path.join(dir, entry.name));
+ } catch {
+ return [];
+ }
+ };
+
+ for (const installRoot of installRoots) {
+ for (const versionDir of listDirs(installRoot)) {
+ for (const channelDir of [versionDir, ...listDirs(versionDir)]) {
+ const direct = path.join(channelDir, "VC", "Auxiliary", "Build", "vcvarsall.bat");
+ if (fs.existsSync(direct)) {
+ return direct;
+ }
+ for (const edition of editions) {
+ const nested = path.join(channelDir, edition, "VC", "Auxiliary", "Build", "vcvarsall.bat");
+ if (fs.existsSync(nested)) {
+ return nested;
+ }
+ }
+ }
+ }
+ }
+
+ return null;
+}
+
+function run(command, args, options = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd: POC_D3D_DIR,
+ stdio: "inherit",
+ windowsHide: true,
+ ...options,
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`${command} ${args.join(" ")} failed with code ${code}`));
+ }
+ });
+ });
+}
+
+async function runInVsEnv(command) {
+ const vcvarsAll = findVcVarsAll();
+ if (!vcvarsAll) {
+ throw new Error(
+ "Could not find Visual Studio vcvarsall.bat. Install Visual Studio Build Tools with C++.",
+ );
+ }
+
+ const cargoExe = path.join(process.env.USERPROFILE ?? "", ".cargo", "bin", "cargo.exe");
+ if (!fs.existsSync(cargoExe)) {
+ throw new Error(`cargo not found at ${cargoExe}. Install Rust (rustup) first.`);
+ }
+
+ const cmdPath = path.join(
+ fs.mkdtempSync(path.join(process.env.TEMP ?? ROOT, "openscreen-build-compositor-")),
+ "build.cmd",
+ );
+ fs.writeFileSync(
+ cmdPath,
+ ["@echo off", `call "${vcvarsAll}" x64`, "if errorlevel 1 exit /b %errorlevel%", command, "exit /b %errorlevel%", ""].join(
+ "\r\n",
+ ),
+ );
+ try {
+ await run("cmd.exe", ["/d", "/c", cmdPath], { cwd: POC_D3D_DIR });
+ } finally {
+ fs.rmSync(path.dirname(cmdPath), { recursive: true, force: true });
+ }
+}
+
+if (process.platform !== "win32") {
+ console.log("Skipping native D3D11 compositor addon build: Windows-only.");
+ process.exit(0);
+}
+
+const ffmpegDir = fs.readFileSync(path.join(POC_D3D_DIR, ".cargo", "config.toml"), "utf8");
+const pinMatch = ffmpegDir.match(/value = "([^"]+)"/);
+if (pinMatch) {
+ const pinnedDir = path.join(POC_D3D_DIR, pinMatch[1]);
+ if (!fs.existsSync(pinnedDir)) {
+ throw new Error(
+ `FFMPEG_DIR pin (poc-d3d/.cargo/config.toml) points at ${pinnedDir}, which doesn't exist.\n` +
+ "Vendor the pinned ffmpeg shared SDK there before building the compositor addon " +
+ "(see poc-d3d/.cargo/config.toml for the pinned release).",
+ );
+ }
+}
+
+const cargoExeQuoted = `"%USERPROFILE%\\.cargo\\bin\\cargo.exe"`;
+await runInVsEnv(`${cargoExeQuoted} build -p compositor-view-napi --release`);
+
+const builtDll = path.join(POC_D3D_DIR, "target", "release", "compositor_view.dll");
+if (!fs.existsSync(builtDll)) {
+ throw new Error(`Compositor addon build completed but ${builtDll} was not found.`);
+}
+
+fs.mkdirSync(BUILD_OUT_DIR, { recursive: true });
+const dest = path.join(BUILD_OUT_DIR, "compositor_view.node");
+fs.copyFileSync(builtDll, dest);
+
+console.log(`Built ${builtDll}`);
+console.log(`Copied ${dest}`);
diff --git a/scripts/fetch-ffmpeg.mjs b/scripts/fetch-ffmpeg.mjs
index 1e91f0896..c9fc30cf0 100644
--- a/scripts/fetch-ffmpeg.mjs
+++ b/scripts/fetch-ffmpeg.mjs
@@ -7,6 +7,16 @@
// 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.
//
+// SECOND PURPOSE (Windows only): the native D3D11 compositor addon
+// (poc-d3d/compositor-view-napi) *dynamically links* against ffmpeg's shared
+// libraries (avcodec/avformat/avutil/…) at `require()` time — a completely
+// different artifact from the static `ffmpeg.exe` above (BtbN's "-shared"
+// build variant vs. its default static one). Without those DLLs reachable on
+// `PATH`, the addon's `require()` fails silently and the app falls back to a
+// no-op compositor (see electron/native-bridge/services/compositorViewService.ts).
+// This script vendors both from the *same* pinned release tag/commit so the
+// static exe and the shared DLLs are always the same audited ffmpeg build.
+//
// 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
@@ -75,6 +85,23 @@ const PINNED = {
},
};
+/**
+ * The "-shared" sibling of PINNED, from the *same* release tag and source
+ * commit (n8.1.2-22-g94138f6973) — same ffmpeg, just built with DLLs instead
+ * of static linking. Only the compositor addon needs this, and it's
+ * Windows-only (D3D11), so there's no linux/darwin entry here.
+ */
+const SHARED_PINNED = {
+ "win32-x64": {
+ asset: "ffmpeg-n8.1.2-22-g94138f6973-win64-lgpl-shared-8.1.zip",
+ sha256: "8bf72607f421282b64f02c6af8683c480e2d299c6b21349ab0f9b5e27c74e223",
+ },
+ "win32-arm64": {
+ asset: "ffmpeg-n8.1.2-22-g94138f6973-winarm64-lgpl-shared-8.1.zip",
+ sha256: "8ee2c32da356883297bac055ccf14e0b6eb1fbb2e5f92f24c569a171207da852",
+ },
+};
+
/** Enabling any of these makes the whole binary GPL. Source: ffmpeg.org/legal.html. */
const GPL_LIBS = [
"libx264",
@@ -203,6 +230,95 @@ function findExe(dir, name) {
return null;
}
+/** All `*.dll` files anywhere under `dir` (BtbN's shared builds nest a `bin/` under a versioned dir). */
+function findDlls(dir) {
+ const out = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ out.push(...findDlls(p));
+ } else if (entry.name.toLowerCase().endsWith(".dll")) {
+ out.push(p);
+ }
+ }
+ return out;
+}
+
+/** Downloads `spec.asset`, verifies its pinned SHA-256, and extracts it into a fresh temp dir. */
+async function downloadAndExtract(spec) {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-ffmpeg-"));
+ 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);
+ return tmp;
+}
+
+/**
+ * Vendors the ffmpeg *shared* DLLs the native D3D11 compositor addon links
+ * against, into the same `electron/native/bin/<tag>/` dir as the static exe
+ * — so both ship as one `extraResources` unit and
+ * `compositorViewService.ts`'s PATH-prepend finds them. Windows only.
+ */
+async function fetchSharedDlls(tag, binDir) {
+ const spec = SHARED_PINNED[tag];
+ if (!spec) {
+ console.log(`\nNo shared-ffmpeg pin for ${tag} (compositor addon is Windows-only) — skipping.`);
+ return;
+ }
+
+ // probe for any previously vendored DLL by name; re-download is driven by
+ // --force same as the static exe, checked once we know what we'd extract.
+ const alreadyVendored = fs
+ .readdirSync(binDir, { withFileTypes: true })
+ .some((e) => e.isFile() && e.name.toLowerCase().endsWith(".dll") && e.name.toLowerCase().startsWith("av"));
+ if (alreadyVendored && !process.argv.includes("--force")) {
+ console.log(`\nShared ffmpeg DLLs already present in ${binDir}. Use --force to re-vendor.`);
+ return;
+ }
+
+ console.log(`\nFetching shared ffmpeg DLLs for the compositor addon (${tag})...`);
+ const tmp = await downloadAndExtract(spec);
+ try {
+ const exe = findExe(tmp, "ffmpeg.exe");
+ if (!exe) throw new Error(`ffmpeg.exe not found inside ${spec.asset} (needed to verify licence)`);
+
+ // Same source commit as the static build, but configure flags are a
+ // separate BtbN job — verify this artifact's licence independently
+ // rather than assuming it matches.
+ console.log("Verifying licence (shared build)...");
+ const banner = assertLgpl(exe);
+ console.log(banner);
+
+ const dlls = findDlls(tmp);
+ if (dlls.length === 0) throw new Error(`No .dll files found inside ${spec.asset}`);
+
+ fs.mkdirSync(binDir, { recursive: true });
+ for (const dll of dlls) {
+ fs.copyFileSync(dll, path.join(binDir, path.basename(dll)));
+ }
+ console.log(`Vendored ${dlls.length} DLL(s) -> ${binDir}`);
+ console.log("LGPL verified: safe to ship with an MIT app.");
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+}
+
async function main() {
const tag = `${process.platform}-${process.arch}`;
@@ -229,49 +345,32 @@ async function main() {
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);
+ } else {
+ const tmp = await downloadAndExtract(spec);
+ try {
+ const found = findExe(tmp, spec.exe);
+ if (!found) throw new Error(`${spec.exe} not found inside ${spec.asset}`);
- 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);
- // 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);
- 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 });
+ }
+ }
- 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 });
+ if (process.platform === "win32") {
+ await fetchSharedDlls(tag, binDir);
}
}