🎥 Make videos programmatically with React
add an opt-in ability to package the browser
Igor Samokhovetse6107e9c4fa4
diff --git a/packages/docs/docs/electron.mdx b/packages/docs/docs/electron.mdxindex b0b7d8f155..138bdf3677 100644--- a/packages/docs/docs/electron.mdx+++ b/packages/docs/docs/electron.mdx@@ -53,9 +53,15 @@ Some Electron packaging setups copy optional binary dependencies automatically.The first render may download Chrome Headless Shell.-If your app expects users to render soon after launch, you can call [`ensureBrowser()`](/docs/renderer/ensure-browser) ahead of time, for example in the background after startup, to avoid doing the download during the first render.+If your app expects users to render soon after launch, you can call [`ensureBrowser()`](/docs/renderer/ensure-browser) ahead of time, for example in the background after startup.-This is optional. If rendering is behind a login wall, a purchase step, or another user action, you may prefer to wait until the user actually starts a render.+If rendering is behind a login wall, a purchase step, or another user action, you may prefer to wait until the user actually starts a render.++If you want to avoid a first-use download in packaged builds, you can also treat the browser as a packaged asset. Call [`ensureBrowser()`](/docs/renderer/ensure-browser) during packaging, copy the downloaded browser into `app.asar.unpacked`, and pass its path through the `browserExecutable` option in your packaged renders.++The official [Electron template](/templates/electron) leaves this disabled by default. Uncomment the browser staging block in `forge.config.ts` if you want packaged renders to work completely offline. This will increase the final app size significantly.++This is not supported for macOS universal builds. [`ensureBrowser()`](/docs/renderer/ensure-browser) only downloads a browser for the current architecture, so the other packaged architecture would not get an offline browser. For universal builds, prefer calling [`ensureBrowser()`](/docs/renderer/ensure-browser) at runtime instead.If you download the browser lazily during rendering, surface this progress in your UI.diff --git a/packages/it-tests/src/templates/electron.test.ts b/packages/it-tests/src/templates/electron.test.tsindex eaa04a4d3b..11cc59d19b 100644--- a/packages/it-tests/src/templates/electron.test.ts+++ b/packages/it-tests/src/templates/electron.test.ts@@ -84,6 +84,33 @@ async function copyTemplateForPublishCheck(workingDir: string): Promise<void> {packageJsonPath,contents.replaceAll('workspace:*', `^${remotionVersion}`),);++ const forgeConfigPath = path.join(workingDir, 'forge.config.ts');+ const forgeConfig = readFileSync(forgeConfigPath, 'utf8');+ writeFileSync(+ forgeConfigPath,+ forgeConfig+ .replace(+ '// unpackDir: "{node_modules/@remotion/compositor-*,remotion-browser}",',+ 'unpackDir: "{node_modules/@remotion/compositor-*,remotion-browser}",',+ )+ .replace(+ 'unpackDir: "node_modules/@remotion/compositor-*",',+ '// unpackDir: "node_modules/@remotion/compositor-*",',+ )+ .replace(+ `// await stageBrowser({+ // arch,+ // buildPath,+ // platform,+ // });`,+ `await stageBrowser({+ arch,+ buildPath,+ platform,+ });`,+ ),+ );}async function packagePublishedTemplate(workingDir: string): Promise<void> {@@ -98,15 +125,95 @@ async function packagePublishedTemplate(workingDir: string): Promise<void> {});}+function getPackagedProjectRoot(workingDir: string): string {+ return path.join(getPackagedResourcesPath(workingDir), 'app.asar');+}++function getPackagedBrowserExecutableRelativePath(): string | null {+ // There is no public API that exposes the downloaded browser layout.+ // This test intentionally asserts the current packaged folder structure so we+ // notice if `ensureBrowser()` changes where Headless Shell is placed. We keep+ // the expectation local to the test instead of importing renderer internals.+ switch (process.platform) {+ case 'darwin':+ if (process.arch === 'arm64') {+ return path.join(+ 'remotion-browser',+ 'mac-arm64',+ 'chrome-headless-shell-mac-arm64',+ 'chrome-headless-shell',+ );+ }++ if (process.arch === 'x64') {+ return path.join(+ 'remotion-browser',+ 'mac-x64',+ 'chrome-headless-shell-mac-x64',+ 'chrome-headless-shell',+ );+ }++ return null;+ case 'linux':+ if (process.arch === 'arm64') {+ return path.join(+ 'remotion-browser',+ 'linux-arm64',+ 'chrome-headless-shell-linux-arm64',+ 'headless_shell',+ );+ }++ if (process.arch === 'x64') {+ return path.join(+ 'remotion-browser',+ 'linux64',+ 'chrome-headless-shell-linux64',+ 'chrome-headless-shell',+ );+ }++ return null;+ case 'win32':+ if (process.arch === 'x64') {+ return path.join(+ 'remotion-browser',+ 'win64',+ 'chrome-headless-shell-win64',+ 'chrome-headless-shell.exe',+ );+ }++ return null;+ default:+ return null;+ }+}++function getPackagedBrowserExecutablePath(workingDir: string): string | null {+ const relativePath = getPackagedBrowserExecutableRelativePath();++ if (!relativePath) {+ return null;+ }++ return path.join(+ path.dirname(getPackagedProjectRoot(workingDir)),+ 'app.asar.unpacked',+ relativePath,+ );+}+async function runPackagedRender(workingDir: string,outputPath: string,-): Promise<void> {+): Promise<string> {const launchPath = getLaunchPath(workingDir);const commonOptions = {cwd: path.dirname(launchPath),- stdio: 'inherit' as const,timeout: 240000,+ all: true as const,};const linuxLaunchArgs =process.platform === 'linux'@@ -131,8 +238,12 @@ async function runPackagedRender(!process.env.WAYLAND_DISPLAY) {try {- await execa('xvfb-run', ['-a', launchPath, ...launchArgs], commonOptions);- return;+ const {all} = await execa(+ 'xvfb-run',+ ['-a', launchPath, ...launchArgs],+ commonOptions,+ );+ return all ?? '';} catch (error) {const execaError = error as {code?: string};if (execaError.code !== 'ENOENT') {@@ -143,7 +254,8 @@ async function runPackagedRender(}}- await execa(launchPath, launchArgs, commonOptions);+ const {all} = await execa(launchPath, launchArgs, commonOptions);+ return all ?? '';}test('Electron template should package and render after publish-style dependency rewriting', async () => {@@ -154,10 +266,26 @@ test('Electron template should package and render after publish-style dependencyawait packagePublishedTemplate(workingDir);const resourcesPath = getPackagedResourcesPath(workingDir);+expect(existsSync(path.join(resourcesPath, 'app.asar'))).toBe(true);- await runPackagedRender(workingDir, outputPath);+ const packagedBrowserExecutable =+ getPackagedBrowserExecutablePath(workingDir);++ expect(packagedBrowserExecutable).toBeTruthy();++ if (!packagedBrowserExecutable) {+ throw new Error(+ 'Expected packaged browser executable path to be resolvable',+ );+ }++ expect(existsSync(packagedBrowserExecutable)).toBe(true);++ const output = await runPackagedRender(workingDir, outputPath);+ expect(output).not.toContain('Downloading Chrome');+ expect(output).not.toContain('Downloading Chrome Headless Shell');expect(existsSync(outputPath)).toBe(true);expect(statSync(outputPath).size).toBeGreaterThan(0);} finally {diff --git a/packages/template-electron/forge.config.ts b/packages/template-electron/forge.config.tsindex 462d6a7bb1..2b2db01b0b 100644--- a/packages/template-electron/forge.config.ts+++ b/packages/template-electron/forge.config.ts@@ -1,7 +1,10 @@+import {existsSync} from "node:fs";import {cp, mkdir} from "node:fs/promises";import path from "node:path";+import {ensureBrowser} from "@remotion/renderer";import {VitePlugin} from "@electron-forge/plugin-vite";import {getCompositorPackage} from "./src/compositor-package";+import {getPackagedBrowserPaths} from "./src/packaged-browser";import {bundleRemotionProject, getPrebuiltRemotionBundlePath} from "./src/remotion-bundle";const DARWIN_COMPOSITOR_PACKAGES = [@@ -109,9 +112,53 @@ async function stageCompositorPackages({}}+export async function stageBrowser({+ arch,+ buildPath,+ platform,+}: {+ arch: string;+ buildPath: string;+ platform: string;+}): Promise<void> {+ const browserPaths = getPackagedBrowserPaths({+ arch,+ buildPath,+ platform,+ projectRoot: process.cwd(),+ });++ if (!browserPaths) {+ return;+ }++ await ensureBrowser();+ if (!existsSync(browserPaths.downloadedBrowserFolder)) {+ return;+ }++ if (!browserPaths.packagedBrowserCopyDestination) {+ return;+ }++ await mkdir(path.dirname(browserPaths.packagedBrowserCopyDestination), {+ recursive: true,+ });++ await cp(+ browserPaths.downloadedBrowserFolder,+ browserPaths.packagedBrowserCopyDestination,+ {recursive: true},+ );+}+const config = {packagerConfig: {asar: {+ // Uncomment the line below if you also uncomment the browser staging block.+ // This will increase the final app size significantly, but packaged renders+ // can run completely offline.+ // unpackDir: "{node_modules/@remotion/compositor-*,remotion-browser}",unpackDir: "node_modules/@remotion/compositor-*",},osxUniversal: {@@ -134,6 +181,19 @@ const config = {outDir: getPrebuiltRemotionBundlePath(buildPath),});+ // Uncomment to package Chrome Headless Shell into the app.+ // This will increase the final app size significantly, but packaged renders+ // can run completely offline.+ // IMPORTANT: This is not supported for macOS universal builds. `ensureBrowser()` only+ // downloads a browser for the current architecture, so the other packaged+ // architecture would not get an offline browser. For universal builds,+ // prefer calling `ensureBrowser()` at runtime instead.+ // await stageBrowser({+ // arch,+ // buildPath,+ // platform,+ // });+// Electron Forge's Vite packaging does not materialize this optional runtime binary// into the packaged app automatically, so stage the required compositor packages explicitly.await stageCompositorPackages({diff --git a/packages/template-electron/src/packaged-browser.ts b/packages/template-electron/src/packaged-browser.tsnew file mode 100644index 0000000000..9b8942e07f--- /dev/null+++ b/packages/template-electron/src/packaged-browser.ts@@ -0,0 +1,116 @@+import {existsSync} from "node:fs";+import path from "node:path";++export const PACKAGED_BROWSER_DIR = "remotion-browser";++type BrowserLayout = {+ platformDir: string;+ executableName: string;+};++type PackagedBrowserPaths = {+ downloadedBrowserFolder: string;+ packagedBrowserCopyDestination: string | null;+ packagedBrowserExecutablePath: string | null;+};++function getBrowserLayout({+ arch,+ platform,+}: {+ arch: string;+ platform: string;+}): BrowserLayout | null {+ switch (platform) {+ case "darwin":+ if (arch === "arm64") {+ return {+ platformDir: "mac-arm64",+ executableName: "chrome-headless-shell",+ };+ }++ if (arch === "x64") {+ return {+ platformDir: "mac-x64",+ executableName: "chrome-headless-shell",+ };+ }++ return null;+ case "linux":+ if (arch === "arm64") {+ return {+ platformDir: "linux-arm64",+ executableName: "headless_shell",+ };+ }++ if (arch === "x64") {+ return {+ platformDir: "linux64",+ executableName: "chrome-headless-shell",+ };+ }++ return null;+ case "win32":+ if (arch === "x64") {+ return {+ platformDir: "win64",+ executableName: "chrome-headless-shell.exe",+ };+ }++ return null;+ default:+ return null;+ }+}++export function getPackagedBrowserPaths({+ arch,+ buildPath,+ platform,+ projectRoot,+}: {+ arch: string;+ buildPath?: string;+ platform: string;+ projectRoot: string;+}): PackagedBrowserPaths | null {+ const browserLayout = getBrowserLayout({arch, platform});++ if (!browserLayout) {+ return null;+ }++ const downloadedBrowserFolder = path.join(+ projectRoot,+ "node_modules",+ ".remotion",+ "chrome-headless-shell",+ browserLayout.platformDir,+ );++ const packagedBrowserCopyDestination = buildPath+ ? path.join(buildPath, PACKAGED_BROWSER_DIR, browserLayout.platformDir)+ : null;++ const packagedBrowserExecutablePath = path.join(+ path.dirname(projectRoot),+ "app.asar.unpacked",+ PACKAGED_BROWSER_DIR,+ browserLayout.platformDir,+ `chrome-headless-shell-${browserLayout.platformDir}`,+ browserLayout.executableName,+ );++ return {+ downloadedBrowserFolder,+ packagedBrowserCopyDestination,+ packagedBrowserExecutablePath: existsSync(packagedBrowserExecutablePath)+ ? packagedBrowserExecutablePath+ : null,+ };+}diff --git a/packages/template-electron/src/render-video.ts b/packages/template-electron/src/render-video.tsindex 8686accade..f47dbc39c9 100644--- a/packages/template-electron/src/render-video.ts+++ b/packages/template-electron/src/render-video.ts@@ -17,6 +17,7 @@ import {getPrebuiltRemotionBundlePath,hasPrebuiltRemotionBundle,} from "./remotion-bundle";+import {getPackagedBrowserPaths} from "./packaged-browser";const compositionId = "HelloWorld";@@ -99,6 +100,13 @@ export const renderVideo = async ({cancelSignal?: CancelSignal;}): Promise<RenderResult> => {let wasCancelled = false;+ const browserExecutable = isPackaged+ ? getPackagedBrowserPaths({+ arch: process.arch,+ platform: process.platform,+ projectRoot,+ })?.packagedBrowserExecutablePath ?? null+ : null;async function finishCancelledRender(): Promise<RenderResult> {await rm(outputPath, {force: true});@@ -119,6 +127,7 @@ export const renderVideo = async ({});await ensureBrowser({+ browserExecutable,onBrowserDownload: ({chromeMode}) => {const browserName =chromeMode === "chrome-for-testing" ? "Chrome" : "Chrome Headless Shell";@@ -169,6 +178,7 @@ export const renderVideo = async ({id: compositionId,inputProps,binariesDirectory,+ browserExecutable,});if (wasCancelled) {@@ -187,6 +197,7 @@ export const renderVideo = async ({outputLocation: outputPath,inputProps,binariesDirectory,+ browserExecutable,cancelSignal,onProgress(progress) {onUpdate?.({