Skip to content

πŸŽ₯ Make videos programmatically with React

wip

Matt McGillivray9ae113f964f1
diff --git a/packages/gcp/src/api/render-media-on-gcp.ts b/packages/gcp/src/api/render-media-on-gcp.ts
new file mode 100644
index 0000000000..7151cef7fd
--- /dev/null
+++ b/packages/gcp/src/api/render-media-on-gcp.ts
@@ -0,0 +1,96 @@
+import {Log} from '../cli/log';
+import type {GcpCodec} from '../shared/validate-gcp-codec';
+import {validateGcpCodec} from '../shared/validate-gcp-codec';
+import {validateServeUrl} from '../shared/validate-serveurl';
+
+export type RenderMediaOnGcpInput = {
+ cloudRunUrl: string;
+ // serviceName?: string;
+ serveUrl: string;
+ composition: string;
+ inputProps?: unknown;
+ codec: GcpCodec;
+ outputBucket: string;
+ outputFolderPath: string;
+ outName: string;
+};
+
+export type RenderMediaOnGcpOutput = {
+ renderId: string;
+ bucketName: string;
+ // cloudWatchLogs: string;
+ folderInGcpConsole: string;
+};
+
+/**
+ * @description Triggers a render on a GCP Cloud Run service given a composition and a Cloud Run URL.
+ * @see [Documentation](https://remotion.dev/docs/lambda/renderMediaOnGcp)
+ * @param params.cloudRunUrl The url of the Cloud Run service that should be used
+ * @param params.serviceName The name of the Cloud Run service that should be used
+ * @param params.serveUrl The URL of the deployed project
+ * @param params.composition The ID of the composition which should be rendered.
+ * @param params.inputProps The input props that should be passed to the composition.
+ * @param params.codec The media codec which should be used for encoding.
+ * @param params.outputBucket The name of the GCP Storage Bucket that will store the rendered media output.
+ * @param params.outputFolderPath The folder path of the GCP Storage Bucket that will store the rendered media output.
+ * @param params.outName The file name of the rendered media output.
+ * @returns {Promise<RenderMediaOnGcpOutput>} See documentation for detailed structure
+ */
+
+export const renderMediaOnGcp = async ({
+ cloudRunUrl,
+ // serviceName,
+ serveUrl,
+ composition,
+ inputProps,
+ codec,
+ outputBucket,
+ outputFolderPath,
+ outName,
+}: RenderMediaOnGcpInput): Promise<RenderMediaOnGcpOutput> => {
+ const actualCodec = validateGcpCodec(codec);
+ validateServeUrl(serveUrl);
+
+ // todo: allow serviceName to be passed in, and fetch the cloud run URL based on the name
+
+ try {
+ const postData = JSON.stringify({
+ type: 'media',
+ composition,
+ serveUrl,
+ codec: actualCodec,
+ inputProps,
+ outputBucket,
+ outputFile: `${outputFolderPath}${outName}`,
+ });
+ // Log.info(`Posting11: ${postData} to ${cloudRunUrl}`);
+
+ const response = await fetch(cloudRunUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(postData),
+ });
+
+ Log.info('response from Cloud Run πŸ‘‡');
+ Log.info(JSON.stringify(response.json()));
+
+ return {
+ renderId: 'res.renderId',
+ bucketName: 'res.bucketName',
+ // cloudWatchLogs: getCloudwatchStreamUrl({
+ // functionName,
+ // method: LambdaRoutines.renderer,
+ // region,
+ // renderId: res.renderId,
+ // rendererFunctionName: rendererFunctionName ?? null,
+ // }),
+ folderInGcpConsole: 'folderInGcpConsole',
+ };
+ } catch (e: any) {
+ // eslint-disable-next-line no-console
+ console.error('Error rendering media on GCP');
+ throw e;
+ }
+};
diff --git a/packages/gcp/src/cli/args.ts b/packages/gcp/src/cli/args.ts
index b473d223ad..39ad4e5f6e 100644
--- a/packages/gcp/src/cli/args.ts
+++ b/packages/gcp/src/cli/args.ts
@@ -13,6 +13,11 @@ type GCPCommandLineOptions = {
yes: boolean;
force: boolean;
f: boolean;
+
+ ['max-retries']: number;
+ ['out-name']: string | undefined;
+ ['output-bucket']: string;
+ ['output-folder-path']: string;
};
export const parsedGcpCli = CliInternals.minimist<GCPCommandLineOptions>(
diff --git a/packages/gcp/src/cli/commands/render/render.ts b/packages/gcp/src/cli/commands/render/render.ts
new file mode 100644
index 0000000000..f3d42d0e08
--- /dev/null
+++ b/packages/gcp/src/cli/commands/render/render.ts
@@ -0,0 +1,267 @@
+import {CliInternals} from '@remotion/cli';
+import {getCompositions} from '@remotion/renderer';
+// import {downloadMedia} from '../../../api/download-media';
+// import {getRenderProgress} from '../../../api/get-render-progress';
+import {renderMediaOnGcp} from '../../../api/render-media-on-gcp';
+// import type {EnhancedErrorInfo} from '../../../functions/helpers/write-lambda-error';
+// import type {RenderProgress} from '../../../shared/constants';
+import {BINARY_NAME, DEFAULT_MAX_RETRIES} from '../../../shared/constants';
+// import {sleep} from '../../../shared/sleep';
+import type {GcpCodec} from '../../../shared/validate-gcp-codec';
+import {validateMaxRetries} from '../../../shared/validate-retries';
+import {validateServeUrl} from '../../../shared/validate-serveurl';
+import {parsedGcpCli} from '../../args';
+import {quit} from '../../helpers/quit';
+import {Log} from '../../log';
+// import {makeMultiProgressFromStatus, makeProgressString} from './progress';
+
+export const RENDER_COMMAND = 'render';
+
+export const renderCommand = async (args: string[], remotionRoot: string) => {
+ const serveUrl = args[0];
+ if (!serveUrl) {
+ Log.error('No serve URL passed.');
+ Log.info(
+ 'Pass an additional argument specifying a URL where your Remotion project is hosted.'
+ );
+ Log.info();
+ Log.info(
+ `${BINARY_NAME} ${RENDER_COMMAND} <serve-url> <composition-id> [output-location]`
+ );
+ quit(1);
+ }
+
+ let composition: string = args[1];
+ if (!composition) {
+ Log.info('No compositions passed. Fetching compositions...');
+
+ validateServeUrl(serveUrl);
+ const comps = await getCompositions(serveUrl);
+ const {compositionId} = await CliInternals.selectComposition(comps);
+ composition = compositionId;
+ }
+
+ const outName = parsedGcpCli['out-name'] ?? 'out.mp4'; // Todo, workout file extension instead of assuming mp4
+ const downloadName = args[2] ?? null;
+
+ const {codec, reason} = CliInternals.getFinalCodec({
+ downloadName,
+ outName: outName ?? null,
+ });
+
+ const {inputProps} = await CliInternals.getCliOptions({
+ type: 'series',
+ isLambda: true, // TODO: what do I need to do with this?
+ remotionRoot,
+ });
+ const maxRetries = parsedGcpCli['max-retries'] ?? DEFAULT_MAX_RETRIES;
+ validateMaxRetries(maxRetries);
+
+ // const privacy = parsedLambdaCli.privacy ?? DEFAULT_OUTPUT_PRIVACY;
+ // validatePrivacy(privacy);
+
+ const outputBucket = parsedGcpCli['output-bucket']; // Todo: I think this should be optional with a fallback
+ const outputFolderPath = parsedGcpCli['output-folder-path']; // Todo: I think this should be optional with a fallback
+
+ const res = await renderMediaOnGcp({
+ cloudRunUrl: 'https://new-two-tv4h6muxbq-ts.a.run.app',
+ // serviceName,
+ serveUrl,
+ composition,
+ inputProps,
+ codec: codec as GcpCodec,
+ outputBucket,
+ outputFolderPath,
+ outName,
+ });
+
+ // const totalSteps = downloadName ? 6 : 5;
+
+ // const progressBar = CliInternals.createOverwriteableCliOutput(
+ // CliInternals.quietFlagProvided()
+ // );
+
+ Log.info(
+ CliInternals.chalk.gray(
+ `bucket = ${res.bucketName}, serveUrl = ${serveUrl}` // ToDo: use serviceName if available
+ )
+ );
+ Log.info(
+ CliInternals.chalk.gray(
+ `renderId = ${res.renderId}, codec = ${codec} (${reason})`
+ )
+ );
+ // const verbose = RenderInternals.isEqualOrBelowLogLevel(
+ // ConfigInternals.Logging.getLogLevel(),
+ // 'verbose'
+ // );
+
+ // Log.verbose(`CloudWatch logs (if enabled): ${res.cloudWatchLogs}`);
+ Log.verbose(`Render folder: ${res.folderInGcpConsole}`);
+ // const status = await getRenderProgress({
+ // functionName,
+ // bucketName: res.bucketName,
+ // renderId: res.renderId,
+ // region: getAwsRegion(),
+ // });
+ // const multiProgress = makeMultiProgressFromStatus(status);
+ // progressBar.update(
+ // makeProgressString({
+ // progress: multiProgress,
+ // steps: totalSteps,
+ // downloadInfo: null,
+ // retriesInfo: status.retriesInfo,
+ // verbose,
+ // totalFrames: getTotalFrames(status),
+ // timeToEncode: status.timeToEncode,
+ // })
+ // );
+
+ // eslint-disable-next-line no-constant-condition
+ // while (true) {
+ // await sleep(1000);
+ // const newStatus = await getRenderProgress({
+ // functionName,
+ // bucketName: res.bucketName,
+ // renderId: res.renderId,
+ // region: getAwsRegion(),
+ // });
+ // const newProgress = makeMultiProgressFromStatus(newStatus);
+ // progressBar.update(
+ // makeProgressString({
+ // progress: newProgress,
+ // steps: totalSteps,
+ // retriesInfo: newStatus.retriesInfo,
+ // downloadInfo: null,
+ // verbose,
+ // timeToEncode: newStatus.timeToEncode,
+ // totalFrames: getTotalFrames(newStatus),
+ // })
+ // );
+
+ // if (newStatus.done) {
+ // progressBar.update(
+ // makeProgressString({
+ // progress: newProgress,
+ // steps: totalSteps,
+ // downloadInfo: null,
+ // retriesInfo: newStatus.retriesInfo,
+ // verbose,
+ // timeToEncode: newStatus.timeToEncode,
+ // totalFrames: getTotalFrames(newStatus),
+ // })
+ // );
+ // if (downloadName) {
+ // const downloadStart = Date.now();
+ // const {outputPath, sizeInBytes} = await downloadMedia({
+ // bucketName: res.bucketName,
+ // outPath: downloadName,
+ // region: getAwsRegion(),
+ // renderId: res.renderId,
+ // onProgress: ({downloaded, totalSize}) => {
+ // progressBar.update(
+ // makeProgressString({
+ // progress: newProgress,
+ // steps: totalSteps,
+ // retriesInfo: newStatus.retriesInfo,
+ // downloadInfo: {
+ // doneIn: null,
+ // downloaded,
+ // totalSize,
+ // },
+ // verbose,
+ // timeToEncode: newStatus.timeToEncode,
+ // totalFrames: getTotalFrames(newStatus),
+ // })
+ // );
+ // },
+ // });
+ // progressBar.update(
+ // makeProgressString({
+ // progress: newProgress,
+ // steps: totalSteps,
+ // retriesInfo: newStatus.retriesInfo,
+ // downloadInfo: {
+ // doneIn: Date.now() - downloadStart,
+ // downloaded: sizeInBytes,
+ // totalSize: sizeInBytes,
+ // },
+ // verbose,
+ // timeToEncode: newStatus.timeToEncode,
+ // totalFrames: getTotalFrames(newStatus),
+ // })
+ // );
+ // Log.info();
+ // Log.info();
+ // Log.info('Done!', outputPath, CliInternals.formatBytes(sizeInBytes));
+ // } else {
+ // Log.info();
+ // Log.info();
+ // Log.info('Done! ' + newStatus.outputFile);
+ // }
+
+ // Log.info(
+ // [
+ // newStatus.renderMetadata
+ // ? `${newStatus.renderMetadata.estimatedTotalLambdaInvokations} Ξ»'s used`
+ // : null,
+ // newStatus.timeToFinish
+ // ? `${(newStatus.timeToFinish / 1000).toFixed(2)}sec`
+ // : null,
+ // `Estimated cost $${newStatus.costs.displayCost}`,
+ // ]
+ // .filter(Boolean)
+ // .join(', ')
+ // );
+ // if (newStatus.mostExpensiveFrameRanges) {
+ // Log.verbose('Most expensive frame ranges:');
+ // Log.verbose(
+ // newStatus.mostExpensiveFrameRanges
+ // .map((f) => {
+ // return `${f.frameRange[0]}-${f.frameRange[1]} (${f.timeInMilliseconds}ms)`;
+ // })
+ // .join(', ')
+ // );
+ // }
+
+ // quit(0);
+ // }
+
+ // if (newStatus.fatalErrorEncountered) {
+ // Log.error('\n');
+ // const uniqueErrors: EnhancedErrorInfo[] = [];
+ // for (const err of newStatus.errors) {
+ // if (uniqueErrors.find((e) => e.stack === err.stack)) {
+ // continue;
+ // }
+
+ // uniqueErrors.push(err);
+ // if (err.explanation) {
+ // Log.error(err.explanation);
+ // }
+
+ // const frames = RenderInternals.parseStack(err.stack.split('\n'));
+
+ // const errorWithStackFrame = new RenderInternals.SymbolicateableError({
+ // message: err.message,
+ // frame: err.frame,
+ // name: err.name,
+ // stack: err.stack,
+ // stackFrame: frames,
+ // });
+ // await CliInternals.handleCommonError(errorWithStackFrame);
+ // }
+
+ // quit(1);
+ // }
+ // }
+};
+
+// function getTotalFrames(status: RenderProgress): number | null {
+// return status.renderMetadata
+// ? RenderInternals.getFramesToRender(
+// status.renderMetadata.frameRange,
+// status.renderMetadata.everyNthFrame
+// ).length
+// : null;
+// }
diff --git a/packages/gcp/src/cli/index.ts b/packages/gcp/src/cli/index.ts
index 1bf547b138..279b368732 100644
--- a/packages/gcp/src/cli/index.ts
+++ b/packages/gcp/src/cli/index.ts
@@ -4,6 +4,7 @@ import {
compositionsCommand,
COMPOSITIONS_COMMAND,
} from './commands/compositions';
+import {renderCommand, RENDER_COMMAND} from './commands/render/render';
import {sitesCommand, SITES_COMMAND} from './commands/sites';
import {printHelp} from './help';
import {quit} from './helpers/quit';
@@ -15,6 +16,10 @@ const matchCommand = (args: string[], remotionRoot: string) => {
quit(0);
}
+ if (args[0] === RENDER_COMMAND) {
+ return renderCommand(args.slice(1), remotionRoot);
+ }
+
if (args[0] === CLOUD_RUN_COMMAND) {
return cloudRunCommand(args.slice(1));
}
diff --git a/packages/gcp/src/shared/constants.ts b/packages/gcp/src/shared/constants.ts
index bd52ff893a..79d8189c66 100644
--- a/packages/gcp/src/shared/constants.ts
+++ b/packages/gcp/src/shared/constants.ts
@@ -6,3 +6,9 @@ export const BINARY_NAME = 'remotion gcp';
export const REMOTION_BUCKET_PREFIX = 'remotioncloudrun-';
export const getSitesKey = (siteId: string) => `sites/${siteId}`;
+
+export const DEFAULT_MAX_RETRIES = 1;
+
+export const inputPropsKey = (hash: string) => {
+ return `input-props/${hash}.json`;
+};
diff --git a/packages/gcp/src/shared/validate-gcp-codec.ts b/packages/gcp/src/shared/validate-gcp-codec.ts
new file mode 100644
index 0000000000..e5b4e328ed
--- /dev/null
+++ b/packages/gcp/src/shared/validate-gcp-codec.ts
@@ -0,0 +1,37 @@
+const gcpCodecs = [
+ 'h264',
+ 'vp8',
+ 'vp9',
+ 'mp3',
+ 'aac',
+ 'wav',
+ 'gif',
+ 'prores',
+] as const;
+
+export type GcpCodec = typeof gcpCodecs[number];
+
+export const validateGcpCodec = (codec: unknown): GcpCodec => {
+ if (typeof codec !== 'string') {
+ throw new TypeError('"codec" must be a string ');
+ }
+
+ if (!(gcpCodecs as readonly string[]).includes(codec)) {
+ throw new TypeError(
+ "'" +
+ codec +
+ "' is not a valid codec for GCP Cloud Run. The following values are supported: " +
+ gcpCodecs.join(', ')
+ );
+ }
+
+ if ((codec as string) === 'h264-mkv') {
+ console.warn(
+ 'The "h264-mkv" codec for renderMediaOnGcp() is deprecated - it\'s now just "h264".'
+ );
+
+ return 'h264';
+ }
+
+ return codec as GcpCodec;
+};
diff --git a/packages/gcp/src/shared/validate-retries.ts b/packages/gcp/src/shared/validate-retries.ts
new file mode 100644
index 0000000000..10d1557b18
--- /dev/null
+++ b/packages/gcp/src/shared/validate-retries.ts
@@ -0,0 +1,27 @@
+export function validateMaxRetries(
+ maxRetries: unknown
+): asserts maxRetries is number {
+ if (typeof maxRetries !== 'number') {
+ throw new TypeError(
+ 'maxRetries must be a number, but is ' + JSON.stringify(maxRetries)
+ );
+ }
+
+ if (!Number.isFinite(maxRetries)) {
+ throw new TypeError('maxRetries must be finite, but is ' + maxRetries);
+ }
+
+ if (Number.isNaN(maxRetries)) {
+ throw new TypeError('maxRetries is NaN');
+ }
+
+ if (maxRetries < 0) {
+ throw new TypeError(`maxRetries cannot be negative but is ${maxRetries}`);
+ }
+
+ if (maxRetries % 1 !== 0) {
+ throw new TypeError(
+ `maxRetries should be an integer, but is ${maxRetries}.`
+ );
+ }
+}