🎥 Make videos programmatically with React
browser downloading logic
Jonny Burger4a2e2fcc59e5
diff --git a/packages/renderer/src/browser/BrowserFetcher.ts b/packages/renderer/src/browser/BrowserFetcher.tsindex 5fe5cf65da..a6d86e6ad1 100644--- a/packages/renderer/src/browser/BrowserFetcher.ts+++ b/packages/renderer/src/browser/BrowserFetcher.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import * as childProcess from 'node:child_process';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -22,9 +21,9 @@ import * as path from 'node:path';import extractZip from 'extract-zip';import {promisify} from 'node:util';-import {assert} from './assert';import {downloadFile} from '../assets/download-file';+import {makeFileExecutableIfItIsNot} from '../compositor/make-file-executable';import type {LogLevel} from '../log-level';import {Log} from '../logger';import {getDownloadsCacheDir} from './get-download-destination';@@ -46,10 +45,8 @@ function getChromeDownloadUrl(platform: Platform): string {return downloadURLs[platform];}-const readdirAsync = fs.promises.readdir;const mkdirAsync = fs.promises.mkdir;const unlinkAsync = promisify(fs.unlink.bind(fs));-const chmodAsync = promisify(fs.chmod.bind(fs));function existsAsync(filePath: string): Promise<boolean> {return new Promise((resolve) => {@@ -76,7 +73,7 @@ const getPlatform = (): Platform => {case 'win32':return 'win64';default:- assert(false, 'Unsupported platform: ' + platform);+ throw new Error('Unsupported platform: ' + platform);}};@@ -93,10 +90,14 @@ export const downloadBrowser = async (options: {const platform = getPlatform();const downloadURL = getChromeDownloadUrl(platform);const fileName = downloadURL.split('/').pop();- assert(fileName, `A malformed download URL was found: ${downloadURL}.`);+ if (!fileName) {+ throw new Error(`A malformed download URL was found: ${downloadURL}.`);+ }+const downloadsFolder = getDownloadsFolder();const archivePath = path.join(downloadsFolder, fileName);const outputPath = getFolderPath(downloadsFolder, platform);+if (await existsAsync(outputPath)) {return getRevisionInfo();}@@ -110,10 +111,12 @@ export const downloadBrowser = async (options: {// Use system Chromium builds on Linux ARM devicesif (os.platform() !== 'darwin' && os.arch() === 'arm64') {throw new Error(- 'The chromium binary is not available for arm64.' +- '\nIf you are on Ubuntu, you can install with: ' +- '\n\n sudo apt install chromium\n' +- '\n\n sudo apt install chromium-browser\n',+ [+ 'Chrome Headless Shell is not available for Linux for arm64 architecture.',+ 'If you are on Ubuntu, you can install with:',+ 'sudo apt install chromium',+ 'sudo apt install chromium-browser',+ ].join('\n'),);}@@ -137,7 +140,8 @@ export const downloadBrowser = async (options: {indent: options.indent,logLevel: options.logLevel,});- await install({archivePath, folderPath: outputPath});+ Log.info({indent: options.indent, logLevel: options.logLevel});+ await extractZip(archivePath, {dir: outputPath});} finally {if (await existsAsync(archivePath)) {await unlinkAsync(archivePath);@@ -145,7 +149,7 @@ export const downloadBrowser = async (options: {}const revisionInfo = getRevisionInfo();- await chmodAsync(revisionInfo.executablePath, 0o755);+ makeFileExecutableIfItIsNot(revisionInfo.executablePath);return revisionInfo;};@@ -159,27 +163,13 @@ const getExecutablePath = () => {const platform = getPlatform();const folderPath = getFolderPath(downloadsFolder, platform);- if (- platform === 'mac-x64' ||- platform === 'mac-arm64' ||- platform === 'linux'- ) {- return path.join(- folderPath,- `chrome-headless-shell-${platform}`,- 'chrome-headless-shell',- );- }-- if (platform === 'win64') {- return path.join(- folderPath,- `chrome-headless-shell-${platform}`,- 'chrome-headless-shell.exe',- );- }-- throw new Error('Can not download browser for platform: ' + platform);+ return path.join(+ folderPath,+ `chrome-headless-shell-${platform}`,+ platform === 'win64'+ ? 'chrome-headless-shell.exe'+ : 'chrome-headless-shell',+ );};export const getRevisionInfo = (): BrowserFetcherRevisionInfo => {@@ -198,79 +188,6 @@ export const getRevisionInfo = (): BrowserFetcherRevisionInfo => {};};-async function install({- archivePath,- folderPath,-}: {- archivePath: string;- folderPath: string;-}): Promise<unknown> {- if (archivePath.endsWith('.zip')) {- return extractZip(archivePath, {dir: folderPath});- }-- if (archivePath.endsWith('.dmg')) {- await mkdirAsync(folderPath);- return _installDMG(archivePath, folderPath);- }-- throw new Error(`Unsupported archive format: ${archivePath}`);-}--function _installDMG(dmgPath: string, folderPath: string): Promise<void> {- let mountPath: string | undefined;-- return new Promise<void>((fulfill, reject): void => {- const mountCommand = `hdiutil attach -nobrowse -noautoopen "${dmgPath}"`;- childProcess.exec(mountCommand, (err, stdout) => {- if (err) {- return reject(err);- }-- const volumes = stdout.match(/\/Volumes\/(.*)/m);- if (!volumes) {- return reject(new Error(`Could not find volume path in ${stdout}`));- }-- mountPath = volumes[0] as string;- readdirAsync(mountPath)- .then((fileNames) => {- const appName = fileNames.find((item) => {- return typeof item === 'string' && item.endsWith('.app');- });- if (!appName) {- return reject(new Error(`Cannot find app in ${mountPath}`));- }-- const copyPath = path.join(mountPath as string, appName);- childProcess.exec(`cp -R "${copyPath}" "${folderPath}"`, (_err) => {- if (_err) {- reject(_err);- } else {- fulfill();- }- });- })- .catch(reject);- });- })- .catch((error) => {- console.error(error);- })- .finally((): void => {- if (!mountPath) {- return;- }-- const unmountCommand = `hdiutil detach "${mountPath}" -quiet`;- childProcess.exec(unmountCommand, (err) => {- if (err) {- console.error(`Error unmounting dmg: ${err}`);- }- });- });-}-function toMegabytes(bytes: number) {const mb = bytes / 1024 / 1024;return `${Math.round(mb * 10) / 10} Mb`;diff --git a/packages/renderer/src/ensure-browser.ts b/packages/renderer/src/ensure-browser.tsnew file mode 100644index 0000000000..71c5164717--- /dev/null+++ b/packages/renderer/src/ensure-browser.ts@@ -0,0 +1,74 @@+import fs from 'fs';+import type {BrowserExecutable} from './browser-executable';+import {downloadBrowser, getRevisionInfo} from './browser/BrowserFetcher';+import {getLocalBrowser} from './get-local-browser';+import type {LogLevel} from './log-level';+import {Log} from './logger';++export type BrowserStatus =+ | {+ type: 'user-defined-path';+ path: string;+ }+ | {+ type: 'local-browser';+ path: string;+ }+ | {+ type: 'local-puppeteer-browser';+ path: string;+ }+ | {+ type: 'no-browser';+ };++export const ensureLocalBrowser = async ({+ indent,+ logLevel,+ preferredBrowserExecutable,+}: {+ preferredBrowserExecutable: BrowserExecutable;+ logLevel: LogLevel;+ indent: boolean;+}) => {+ const status = getBrowserStatus(preferredBrowserExecutable, logLevel, indent);+ if (status.type === 'no-browser') {+ Log.info(+ {indent, logLevel},+ 'No local browser could be found. Downloading Chrome Headless Shell https://www.remotion.dev/docs/miscellaneous/chrome-headless-shell',+ );+ await downloadBrowser({indent, logLevel});+ }+};++const getBrowserStatus = (+ browserExecutablePath: BrowserExecutable,+ logLevel: LogLevel,+ indent: boolean,+): BrowserStatus => {+ if (browserExecutablePath) {+ if (!fs.existsSync(browserExecutablePath)) {+ Log.warn(+ {+ indent,+ logLevel,+ },+ `Browser executable was specified as '${browserExecutablePath}' but the path doesn't exist.`,+ );+ }++ return {path: browserExecutablePath, type: 'user-defined-path'};+ }++ const localBrowser = getLocalBrowser();+ if (localBrowser !== null) {+ return {path: localBrowser, type: 'local-browser'};+ }++ const revision = getRevisionInfo();+ if (revision.local && fs.existsSync(revision.executablePath)) {+ return {path: revision.executablePath, type: 'local-puppeteer-browser'};+ }++ return {type: 'no-browser'};+};diff --git a/packages/renderer/src/get-local-browser-executable.ts b/packages/renderer/src/get-local-browser-executable.tsindex dd36c92de2..5d6eff5250 100644--- a/packages/renderer/src/get-local-browser-executable.ts+++ b/packages/renderer/src/get-local-browser-executable.ts@@ -1,71 +1,8 @@import fs from 'node:fs';-import os from 'node:os';import type {BrowserExecutable} from './browser-executable';-import {downloadBrowser, getRevisionInfo} from './browser/BrowserFetcher';-import type {LogLevel} from './log-level';-import {Log} from './logger';--const getSearchPathsForProduct = () => {- return [- process.env.PUPPETEER_EXECUTABLE_PATH ?? null,- process.platform === 'darwin'- ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'- : null,- process.platform === 'linux' ? '/usr/bin/google-chrome' : null,- process.platform === 'linux' ? '/usr/bin/chromium-browser' : null,- process.platform === 'linux' ? '/usr/bin/chromium' : null, // Debian- process.platform === 'linux'- ? '/app/.apt/usr/bin/google-chrome-stable'- : null,- process.platform === 'win32'- ? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'- : null,- process.platform === 'win32'- ? 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'- : null,- process.platform === 'win32'- ? os.homedir() +- '\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'- : null,- process.platform === 'win32'- ? 'C:\\Program Files\\Google\\Chrome SxS\\Application\\chrome.exe'- : null,- process.platform === 'win32'- ? 'C:\\Program Files (x86)\\Google\\Chrome SxS\\Application\\chrome.exe'- : null,- process.platform === 'win32'- ? os.homedir() +- '\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe'- : null,- ].filter(Boolean) as string[];-};--const getLocalBrowser = () => {- for (const p of getSearchPathsForProduct()) {- if (fs.existsSync(p)) {- return p;- }- }-- return null;-};--type BrowserStatus =- | {- type: 'user-defined-path';- path: string;- }- | {- type: 'local-browser';- path: string;- }- | {- type: 'local-puppeteer-browser';- path: string;- }- | {- type: 'no-browser';- };+import {getRevisionInfo} from './browser/BrowserFetcher';+import type {BrowserStatus} from './ensure-browser';+import {getLocalBrowser} from './get-local-browser';const getBrowserStatus = (browserExecutablePath: BrowserExecutable,@@ -93,25 +30,6 @@ const getBrowserStatus = (return {type: 'no-browser'};};-export const ensureLocalBrowser = async ({- indent,- logLevel,- preferredBrowserExecutable,-}: {- preferredBrowserExecutable: BrowserExecutable;- logLevel: LogLevel;- indent: boolean;-}) => {- const status = getBrowserStatus(preferredBrowserExecutable);- if (status.type === 'no-browser') {- Log.info(- {indent, logLevel},- 'No local browser could be found. Downloading Thorium https://www.remotion.dev/docs/miscellaneous/thorium-browser',- );- await downloadBrowser({indent, logLevel});- }-};-export const getLocalBrowserExecutable = (preferredBrowserExecutable: BrowserExecutable,): string => {diff --git a/packages/renderer/src/get-local-browser.ts b/packages/renderer/src/get-local-browser.tsnew file mode 100644index 0000000000..ab1206166b--- /dev/null+++ b/packages/renderer/src/get-local-browser.ts@@ -0,0 +1,46 @@+import fs from 'fs';+import {homedir} from 'node:os';++const getSearchPathsForProduct = () => {+ return [+ process.env.PUPPETEER_EXECUTABLE_PATH ?? null,+ process.platform === 'darwin'+ ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'+ : null,+ process.platform === 'linux' ? '/usr/bin/google-chrome' : null,+ process.platform === 'linux' ? '/usr/bin/chromium-browser' : null,+ process.platform === 'linux' ? '/usr/bin/chromium' : null, // Debian+ process.platform === 'linux'+ ? '/app/.apt/usr/bin/google-chrome-stable'+ : null,+ process.platform === 'win32'+ ? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'+ : null,+ process.platform === 'win32'+ ? 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'+ : null,+ process.platform === 'win32'+ ? homedir() + '\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'+ : null,+ process.platform === 'win32'+ ? 'C:\\Program Files\\Google\\Chrome SxS\\Application\\chrome.exe'+ : null,+ process.platform === 'win32'+ ? 'C:\\Program Files (x86)\\Google\\Chrome SxS\\Application\\chrome.exe'+ : null,+ process.platform === 'win32'+ ? homedir() ++ '\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe'+ : null,+ ].filter(Boolean) as string[];+};++export const getLocalBrowser = () => {+ for (const p of getSearchPathsForProduct()) {+ if (fs.existsSync(p)) {+ return p;+ }+ }++ return null;+};diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex fa5a634264..15c3552202 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -31,7 +31,6 @@ import {} from './get-extension-from-codec';import {getExtensionOfFilename} from './get-extension-of-filename';import {getRealFrameRange} from './get-frame-to-render';-import {ensureLocalBrowser} from './get-local-browser-executable';import {getDesiredPort} from './get-port';import {DEFAULT_STILL_IMAGE_FORMAT,@@ -82,6 +81,7 @@ export type {FfmpegOverrideFn} from './ffmpeg-override';export {FileExtension} from './file-extensions';export {FrameRange} from './frame-range';export {getCompositions, GetCompositionsOptions} from './get-compositions';+export {ensureLocalBrowser} from './get-local-browser-executable';export {getSilentParts} from './get-silent-parts';export {getVideoMetadata, VideoMetadata} from './get-video-metadata';export {@@ -147,7 +147,6 @@ import {} from './wait-for-symbolication-error-to-be-done';export const RenderInternals = {- ensureLocalBrowser,getActualConcurrency,serveStatic,validateEvenDimensionsWithCodec,