Skip to content

🎥 Make videos programmatically with React

next iteration

Jonny Burgera5fde1448275
diff --git a/packages/cli/src/studio.ts b/packages/cli/src/studio.ts
index 3270c6dc0a..778ef61379 100644
--- a/packages/cli/src/studio.ts
+++ b/packages/cli/src/studio.ts
@@ -4,13 +4,11 @@ import {StudioServerInternals} from '@remotion/studio-server';
import {ConfigInternals} from './config';
import {getNumberOfSharedAudioTags} from './config/number-of-shared-audio-tags';
import {convertEntryPointToServeUrl} from './convert-entry-point-to-serve-url';
-import {detectRemotionServer} from './detect-remotion-server';
import {findEntryPoint} from './entry-point';
import {getEnvironmentVariables} from './get-env';
import {getGitSource} from './get-github-repository';
import {getInputProps} from './get-input-props';
import {getRenderDefaults} from './get-render-defaults';
-import {isPortOpen} from './is-port-open';
import {Log} from './log';
import {parsedCli} from './parsed-cli';
import {
@@ -78,32 +76,6 @@ export const studioCommand = async (
const desiredPort = getPort();
- const port = desiredPort ?? 3000;
- const isFree = await isPortOpen(port);
-
- if (!isFree && !parsedCli['force-new']) {
- const detection = await detectRemotionServer(port, remotionRoot);
-
- if (detection.type === 'match') {
- Log.info(
- {indent: false, logLevel},
- `Remotion Studio already running on port ${port}. Opening browser...`,
- );
- await StudioServerInternals.maybeOpenBrowser({
- url: `http://localhost:${port}`,
- browserFlag: parsedCli.browser,
- browserArgs: parsedCli['browser-args'],
- configValueShouldOpenBrowser:
- ConfigInternals.getShouldOpenBrowser(),
- // Minimist quirk: Adding `--no-open` flag will result in {['no-open']: false, open: true}
- // @ts-expect-error
- parsedCliOpen: parsedCli.open,
- logLevel,
- });
- return;
- }
- }
-
const fullEntryPath = convertEntryPointToServeUrl(file);
let inputProps = getInputProps((newProps) => {
@@ -167,7 +139,7 @@ export const studioCommand = async (
const gitSource = getGitSource({remotionRoot, disableGitSource, logLevel});
- await StudioServerInternals.startStudio({
+ const result = await StudioServerInternals.startStudio({
previewEntry: require.resolve('@remotion/studio/previewEntry'),
browserArgs: parsedCli['browser-args'],
browserFlag: parsedCli.browser,
@@ -204,8 +176,13 @@ export const studioCommand = async (
audioLatencyHint: parsedCli['audio-latency-hint'],
enableCrossSiteIsolation,
askAIEnabled,
+ forceNew: parsedCli['force-new'],
});
+ if (result.type === 'already-running') {
+ return;
+ }
+
// If the server is restarted through the UI, let's do the whole thing again.
await studioCommand(remotionRoot, args, logLevel);
};
diff --git a/packages/studio-server/src/detect-remotion-server.ts b/packages/studio-server/src/detect-remotion-server.ts
new file mode 100644
index 0000000000..40e1e6ebd2
--- /dev/null
+++ b/packages/studio-server/src/detect-remotion-server.ts
@@ -0,0 +1,63 @@
+import type {RemotionConfigResponse} from '@remotion/studio-shared';
+import http from 'http';
+
+type RemotionDetectionResult =
+ | {type: 'match'}
+ | {type: 'mismatch'}
+ | {type: 'not-remotion'};
+
+export const detectRemotionServer = ({
+ port,
+ cwd,
+ hostname,
+}: {
+ port: number;
+ cwd: string;
+ hostname: string;
+}): Promise<RemotionDetectionResult> => {
+ return new Promise((resolve) => {
+ const req = http.get(
+ {
+ hostname,
+ port,
+ path: '/__remotion_config',
+ timeout: 1000,
+ },
+ (res) => {
+ let data = '';
+
+ res.on('data', (chunk) => {
+ data += chunk;
+ });
+
+ res.on('end', () => {
+ try {
+ const json = JSON.parse(data) as RemotionConfigResponse;
+
+ if (json.isRemotion !== true) {
+ return resolve({type: 'not-remotion'});
+ }
+
+ // Normalize paths for comparison to avoid issues with different separators or casing on Windows
+ const normalize = (p: string) =>
+ p.replace(/\\/g, '/').toLowerCase();
+
+ if (normalize(json.cwd) === normalize(cwd)) {
+ return resolve({type: 'match'});
+ }
+
+ return resolve({type: 'mismatch'});
+ } catch {
+ resolve({type: 'not-remotion'});
+ }
+ });
+ },
+ );
+
+ req.on('error', () => resolve({type: 'not-remotion'}));
+ req.on('timeout', () => {
+ req.destroy();
+ resolve({type: 'not-remotion'});
+ });
+ });
+};
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 7007e4923a..cb98ddb2a8 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -24,9 +24,7 @@ export type {
} from '@remotion/studio-shared';
import {AnsiDiff} from './ansi-diff';
-import {openBrowser} from './better-opn';
import {parseAndApplyCodemod} from './codemods/duplicate-composition';
-import {maybeOpenBrowser} from './maybe-open-browser';
import {installFileWatcher} from './file-watcher';
import {getLatestRemotionVersion} from './get-latest-remotion-version';
import {getInstalledDependencies} from './helpers/get-installed-dependencies';
@@ -56,8 +54,6 @@ export const StudioServerInternals = {
AnsiDiff,
formatBytes,
parseAndApplyCodemod,
- openBrowser,
- maybeOpenBrowser,
getInstalledDependencies,
getInstallCommand,
};
diff --git a/packages/studio-server/src/is-port-open.ts b/packages/studio-server/src/is-port-open.ts
new file mode 100644
index 0000000000..e4298043ae
--- /dev/null
+++ b/packages/studio-server/src/is-port-open.ts
@@ -0,0 +1,23 @@
+import {createServer} from 'net';
+
+export const isPortOpen = (port: number): Promise<boolean> => {
+ return new Promise((resolve, reject) => {
+ const server = createServer();
+
+ server.once('error', (err: Error & {code: string}) => {
+ if (err.code === 'EADDRINUSE') {
+ resolve(false);
+ } else {
+ reject(err);
+ }
+ });
+
+ server.once('listening', () => {
+ server.close(() => {
+ resolve(true);
+ });
+ });
+
+ server.listen(port);
+ });
+};
diff --git a/packages/studio-server/src/start-studio.ts b/packages/studio-server/src/start-studio.ts
index b6fe980f7e..faf1206bd7 100644
--- a/packages/studio-server/src/start-studio.ts
+++ b/packages/studio-server/src/start-studio.ts
@@ -9,7 +9,9 @@ import type {
import crypto from 'node:crypto';
import {existsSync} from 'node:fs';
import path from 'node:path';
+import {detectRemotionServer} from './detect-remotion-server';
import {getNetworkAddress} from './get-network-address';
+import {isPortOpen} from './is-port-open';
import {maybeOpenBrowser} from './maybe-open-browser';
import type {QueueMethods} from './preview-server/api-types';
import {noOpUntilRestart} from './preview-server/close-and-restart';
@@ -23,6 +25,10 @@ import {startServer} from './preview-server/start-server';
import {printServerReadyComment, setServerReadyComment} from './server-ready';
import {watchRootFile} from './watch-root-file';
+export type StartStudioResult =
+ | {type: 'restarted'}
+ | {type: 'already-running'};
+
export const startStudio = async ({
browserArgs,
browserFlag,
@@ -52,6 +58,7 @@ export const startStudio = async ({
audioLatencyHint,
enableCrossSiteIsolation,
askAIEnabled,
+ forceNew,
}: {
browserArgs: string;
browserFlag: string;
@@ -81,7 +88,39 @@ export const startStudio = async ({
binariesDirectory: string | null;
forceIPv4: boolean;
askAIEnabled: boolean;
-}) => {
+ forceNew: boolean;
+}): Promise<StartStudioResult> => {
+ const portToCheck = desiredPort ?? 3000;
+ const portConfig = RenderInternals.getPortConfig(forceIPv4);
+
+ if (!forceNew) {
+ const isFree = await isPortOpen(portToCheck);
+
+ if (!isFree) {
+ const detection = await detectRemotionServer({
+ port: portToCheck,
+ cwd: remotionRoot,
+ hostname: portConfig.hostsToTry[0],
+ });
+
+ if (detection.type === 'match') {
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `Remotion Studio already running on port ${portToCheck}. Opening browser...`,
+ );
+ await maybeOpenBrowser({
+ browserArgs,
+ browserFlag,
+ configValueShouldOpenBrowser,
+ parsedCliOpen,
+ url: `http://localhost:${portToCheck}`,
+ logLevel,
+ });
+ return {type: 'already-running'};
+ }
+ }
+ }
+
try {
if (typeof Bun === 'undefined') {
process.title = 'node (npx remotion studio)';
@@ -196,4 +235,6 @@ export const startStudio = async ({
{indent: false, logLevel},
RenderInternals.chalk.blue('Restarting server...'),
);
+
+ return {type: 'restarted'};
};