Skip to content

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

build(mac): ship the ffmpeg dylibs, and vendor them LGPL by construction

Etienne Lescot1589042e1caf
diff --git a/package.json b/package.json
index 7daf47777..4bb0f3d65 100644
--- a/package.json
+++ b/package.json
@@ -28,7 +28,7 @@
"docs:check": "node scripts/check-docs.mjs",
"preview": "vite preview",
"build:native:mac": "node scripts/build-macos-screencapturekit-helper.mjs",
- "build:mac": "npm run build:native:mac && npm run build:native:compositor:mac && tsc && vite build && electron-builder --mac",
+ "build:mac": "npm run build:native:mac && npm run fetch:ffmpeg:mac && npm run build:native:compositor:mac && tsc && vite build && electron-builder --mac",
"build:native:win": "node scripts/build-windows-wgc-helper.mjs",
"build:native:compositor": "node scripts/build-windows-compositor-addon.mjs",
"build:native:compositor:mac": "node scripts/build-macos-compositor-addon.mjs",
@@ -54,7 +54,8 @@
"test:e2e": "playwright test",
"test:e2e:windows-native-checklist": "playwright test tests/e2e/windows-native-checklist.spec.ts",
"prepare": "husky",
- "fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs"
+ "fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs",
+ "fetch:ffmpeg:mac": "node scripts/fetch-ffmpeg-macos.mjs"
},
"dependencies": {
"@fix-webm-duration/fix": "^1.0.1",
diff --git a/scripts/build-macos-compositor-addon.mjs b/scripts/build-macos-compositor-addon.mjs
index 1e1a7f0bb..a66bb2803 100644
--- a/scripts/build-macos-compositor-addon.mjs
+++ b/scripts/build-macos-compositor-addon.mjs
@@ -22,7 +22,7 @@
// A Homebrew ffmpeg will NOT do as a drop-in: brew's formula builds with
// --enable-gpl. It is fine to develop against, never fine to ship.
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -130,6 +130,100 @@ function installAtomically(from, to) {
fs.renameSync(tmp, to);
}
+/**
+ * Vendors the ffmpeg dylibs next to the addon and rewrites every install name to
+ * `@rpath`, so the packaged app loads its own copies instead of a build-machine path.
+ *
+ * Straight out of `cargo`, the `.node` references its dependencies by ABSOLUTE path
+ * (`otool -L` shows `/Users/…/crates/thirdparty/…/libavcodec.62.dylib`). That works on
+ * the machine that built it and nowhere else — the installed app would fail at
+ * `require()` with a dyld error naming a directory the user has never had. Windows does
+ * not hit this because `LoadLibrary` searches `PATH`, which is what
+ * `ensureFfmpegSharedDllsOnPath()` prepends; macOS has no such search, so the fix has to
+ * be baked into the binary.
+ *
+ * Three edits per artefact:
+ * - each dylib's own id becomes `@rpath/<name>`;
+ * - every inter-library reference (libavcodec -> libavutil, and so on) is rewritten;
+ * - the addon gains `@loader_path` as an rpath, so `@rpath/libavutil.60.dylib`
+ * resolves next to `compositor_view.node` — which is exactly where electron-builder
+ * puts them via the mac `extraResources` filter `darwin-*​/*`.
+ *
+ * Re-signing is required and not optional: `install_name_tool` invalidates the existing
+ * ad-hoc signature, and macOS kills a process that faults a page of a binary whose
+ * signature no longer matches (the same `SIGKILL (Code Signature Invalid)` documented on
+ * `installAtomically` above).
+ */
+function vendorFfmpegDylibs(nodePath, ffmpegDir) {
+ const outDir = path.dirname(nodePath);
+ const libDir = path.join(ffmpegDir, "lib");
+ const linked = execFileSync("otool", ["-L", nodePath], { encoding: "utf8" })
+ .split("\n")
+ .map((line) => line.trim().split(" ")[0])
+ .filter((p) => /\/lib(av|sw)\w+\.\d+\.dylib$/.test(p));
+ if (linked.length === 0) {
+ throw new Error(`${nodePath} links no ffmpeg dylib — nothing to vendor, which is wrong.`);
+ }
+
+ const names = linked.map((p) => path.basename(p));
+ for (const name of names) {
+ const from = path.join(libDir, name);
+ if (!fs.existsSync(from)) {
+ throw new Error(`Missing ${from}; the addon links it but the SDK does not ship it.`);
+ }
+ const to = path.join(outDir, name);
+ fs.copyFileSync(from, to);
+ fs.chmodSync(to, 0o755);
+ execFileSync("install_name_tool", ["-id", `@rpath/${name}`, to]);
+ }
+ // Inter-library references, and the addon's own.
+ for (const target of [...names.map((n) => path.join(outDir, n)), nodePath]) {
+ const deps = execFileSync("otool", ["-L", target], { encoding: "utf8" })
+ .split("\n")
+ .map((line) => line.trim().split(" ")[0])
+ .filter((p) => p.startsWith("/") && /lib(av|sw)\w+\.\d+\.dylib$/.test(p));
+ for (const dep of deps) {
+ execFileSync("install_name_tool", ["-change", dep, `@rpath/${path.basename(dep)}`, target]);
+ }
+ execFileSync("install_name_tool", ["-add_rpath", "@loader_path", target]);
+ // install_name_tool invalidates the signature; re-sign ad-hoc.
+ execFileSync("codesign", ["--force", "--sign", "-", target]);
+ }
+
+ const remaining = execFileSync("otool", ["-L", nodePath], { encoding: "utf8" })
+ .split("\n")
+ .map((l) => l.trim().split(" ")[0])
+ .filter((p) => p.startsWith("/") && /lib(av|sw)/.test(p));
+ if (remaining.length > 0) {
+ throw new Error(`Still absolute after rewriting: ${remaining.join(", ")}`);
+ }
+ console.log(`Vendored ${names.length} ffmpeg dylibs next to ${path.basename(nodePath)}`);
+}
+
+/**
+ * Refuses to package a GPL ffmpeg. `--enable-gpl` pulls x264/x265 in and relicenses this
+ * MIT app; a Homebrew ffmpeg is exactly that and is an easy thing to point MAC_FFMPEG_DIR
+ * at by accident. Same check `fetch-ffmpeg.mjs` runs on the Windows build.
+ */
+function assertLgpl(ffmpegDir) {
+ const bin = path.join(ffmpegDir, "bin", "ffmpeg");
+ if (!fs.existsSync(bin)) {
+ console.warn(`No ffmpeg binary at ${bin}; skipping the licence check.`);
+ return;
+ }
+ const banner = execFileSync(bin, ["-hide_banner", "-L"], { encoding: "utf8" });
+ if (/GNU General Public License/i.test(banner) || !/Lesser General Public/i.test(banner)) {
+ throw new Error(
+ `${ffmpegDir} is not an LGPL build — its own -L banner says so.\n` +
+ "Homebrew's ffmpeg is GPL (--enable-gpl). Build the LGPL tree instead:\n\n" +
+ `${FFMPEG_RECIPE}\n`,
+ );
+ }
+ console.log("ffmpeg licence: LGPL (checked via `ffmpeg -L`)");
+}
+
+assertLgpl(macFfmpegDir);
+
const dest = path.join(BUILD_OUT_DIR, "compositor_view.node");
installAtomically(builtDylib, dest);
@@ -140,12 +234,16 @@ const archBinDir = path.join(ROOT, "electron", "native", "bin", `darwin-${proces
const archDest = path.join(archBinDir, "compositor_view.node");
installAtomically(builtDylib, archDest);
+// Only the arch-tagged copy ships (mac `extraResources`, filter `darwin-*/*`), so that
+// is the one that gets its dylibs and its @rpath.
+vendorFfmpegDylibs(archDest, macFfmpegDir);
+
console.log(`Built ${builtDylib}`);
console.log(`Copied ${dest}`);
console.log(`Copied ${archDest}`);
console.log(
- "\nNOTE: this .node hardcodes absolute paths to the ffmpeg dylibs it was linked\n" +
- "against (see `otool -L`). That is fine for a dev build. Packaging still needs an\n" +
- "install_name_tool/@rpath pass plus the dylibs in extraResources — the macOS\n" +
- "equivalent of the PATH-prepend ensureFfmpegSharedDllsOnPath() does on Windows.",
+ `\nThe shipped copy (${archDest}) carries its own LGPL ffmpeg dylibs and resolves them\n` +
+ "through @rpath/@loader_path, so the packaged app does not depend on this machine's\n" +
+ "paths. The dev copy under electron/native/compositor-view/build/ keeps its absolute\n" +
+ "links, which is fine — it never leaves this checkout.",
);
diff --git a/scripts/fetch-ffmpeg-macos.mjs b/scripts/fetch-ffmpeg-macos.mjs
new file mode 100644
index 000000000..c3f946812
--- /dev/null
+++ b/scripts/fetch-ffmpeg-macos.mjs
@@ -0,0 +1,120 @@
+// Vendors an LGPL, shared ffmpeg for macOS into crates/thirdparty/, the tree
+// crates/compositor/build.rs probes.
+//
+// The macOS counterpart of scripts/fetch-ffmpeg.mjs, and it BUILDS rather than downloads
+// — not by preference. BtbN, whose pinned "-lgpl-shared" archives that script fetches for
+// Windows, publishes no macOS target. The macOS binaries that do circulate (evermeet,
+// osxexperts, Homebrew) are all GPL: they ship x264/x265, which `--enable-gpl` pulls in.
+// Linking any of them would relicense this MIT app under the GPL, so none of them is a
+// candidate however convenient.
+//
+// The build is therefore from source, from the pinned release tarball, checksummed, with
+// neither --enable-gpl nor --enable-nonfree — and the result is verified by asking the
+// binary itself (`ffmpeg -L`) rather than by trusting the configure line. That last step
+// is the one that matters: it is the same check fetch-ffmpeg.mjs performs on Windows, and
+// it is what catches a tree that was replaced by hand with a GPL one.
+//
+// Roughly five minutes on an M-series. Idempotent: an existing tree that passes the
+// licence check is left alone.
+
+import { execFileSync, 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, "..");
+const CRATES_DIR = path.join(ROOT, "crates");
+
+/** Pinned release. The directory name is what build.rs looks for. */
+const VERSION = "8.1.2";
+const TARBALL_SHA256 = "464beb5e7bf0c311e68b45ae2f04e9cc2af88851abb4082231742a74d97b524c";
+const DEST = path.join(CRATES_DIR, "thirdparty", `ffmpeg-n${VERSION}-macos64-lgpl-shared`);
+
+function run(cmd, args, opts = {}) {
+ const r = spawnSync(cmd, args, { stdio: "inherit", ...opts });
+ if (r.status !== 0) {
+ throw new Error(`${cmd} ${args.join(" ")} exited with ${r.status}`);
+ }
+}
+
+/** The binary's own licence banner — the only claim worth trusting. */
+function isLgpl(dir) {
+ const bin = path.join(dir, "bin", "ffmpeg");
+ if (!fs.existsSync(bin)) return false;
+ const banner = execFileSync(bin, ["-hide_banner", "-L"], { encoding: "utf8" });
+ return /Lesser General Public/i.test(banner) && !/GNU General Public License/i.test(banner);
+}
+
+if (process.platform !== "darwin") {
+ console.log("Skipping macOS ffmpeg vendoring: macOS-only (Windows uses fetch:ffmpeg).");
+ process.exit(0);
+}
+
+if (fs.existsSync(path.join(DEST, "include")) && isLgpl(DEST)) {
+ console.log(`ffmpeg already vendored at ${DEST} and its -L banner says LGPL. Nothing to do.`);
+ process.exit(0);
+}
+if (fs.existsSync(path.join(DEST, "include"))) {
+ throw new Error(
+ `${DEST} exists but is not an LGPL build (checked with \`ffmpeg -L\`).\n` +
+ "Refusing to reuse it — linking a GPL ffmpeg would relicense OpenScreen.\n" +
+ "Delete the directory and re-run to rebuild it from source.",
+ );
+}
+
+const work = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-ffmpeg-"));
+const tarball = path.join(work, `ffmpeg-${VERSION}.tar.xz`);
+
+console.log(`Downloading ffmpeg ${VERSION}…`);
+run("curl", ["-sSL", "-o", tarball, `https://ffmpeg.org/releases/ffmpeg-${VERSION}.tar.xz`]);
+
+const actual = crypto.createHash("sha256").update(fs.readFileSync(tarball)).digest("hex");
+if (actual !== TARBALL_SHA256) {
+ throw new Error(
+ `Checksum mismatch for the ffmpeg tarball.\n expected ${TARBALL_SHA256}\n got ${actual}`,
+ );
+}
+console.log("Checksum OK.");
+
+run("tar", ["-xJf", tarball, "-C", work]);
+const src = path.join(work, `ffmpeg-${VERSION}`);
+
+// No --enable-gpl, no --enable-nonfree. ffmpeg is LGPL by default and stops being so the
+// moment either appears; everything else here is about size and the macOS hardware paths.
+console.log("Configuring (LGPL, shared)…");
+run(
+ "./configure",
+ [
+ `--prefix=${DEST}`,
+ "--enable-shared",
+ "--disable-static",
+ "--disable-doc",
+ "--disable-debug",
+ "--enable-videotoolbox",
+ "--enable-audiotoolbox",
+ "--disable-x86asm",
+ `--arch=${process.arch === "arm64" ? "arm64" : "x86_64"}`,
+ "--cc=clang",
+ ],
+ { cwd: src },
+);
+
+console.log("Building…");
+const jobs = execFileSync("sysctl", ["-n", "hw.ncpu"], { encoding: "utf8" }).trim();
+run("make", ["-j", jobs], { cwd: src });
+run("make", ["install"], { cwd: src });
+
+if (!isLgpl(DEST)) {
+ fs.rmSync(DEST, { recursive: true, force: true });
+ throw new Error(
+ "The freshly built ffmpeg does not report an LGPL licence. The tree has been removed " +
+ "rather than left where build.rs would link it.",
+ );
+}
+
+fs.rmSync(work, { recursive: true, force: true });
+console.log(`\nVendored LGPL ffmpeg ${VERSION} at ${DEST}`);
+console.log("Verified with `ffmpeg -L`. `npm run build:native:compositor:mac` can now link it.");