π₯ Make videos programmatically with React
progress updates working in CLI for rendering
Matt McGillivray39e0fe982958
diff --git a/packages/gcp/readme.md b/packages/gcp/readme.mdindex 82e6c8a35d..fc1c9c0140 100644--- a/packages/gcp/readme.md+++ b/packages/gcp/readme.md@@ -57,7 +57,7 @@ Navigate to the [Service Accounts](https://console.cloud.google.com/projectselecThis command will deploy a cloud-run service, and return the URL of the service. This cloud run service is what will be invoked to render media.<br><br>-## Command: `npx remotion gcp cloud-run deploy`+### Command: `npx remotion gcp cloud-run deploy`Options:@@ -86,7 +86,7 @@ To view the deployed service, navigate to the [Cloud Run](https://console.cloud.<br><br>-## Command: `npx remotion gcp sites create`+### Command: `npx remotion gcp sites create`Options:@@ -96,6 +96,10 @@ This command will bundle the site and upload it to a GCP bucket. To view storage# Render media on GCP+This command will render media on the deployed cloud-run service, and return metadata of the rendered file.++### Command: `pnpm exec remotion gcp render <serve-url> <cloud-run-url> <composition-name> --output-bucket=<GCS-bucket-name>`+## Manually, making a post requestWithin the Cloud Run service, you can see the URL of the service. Distributed rendering is not yet supported, but rendering a still or media in a single-threaded instance is available.@@ -148,7 +152,10 @@ To render media, send a POST request to the URL with the following body:## Using the CLI command, WIP-- π© Work out progress bar for CLI+- π© Render Media is largely finished+ - π© Address comments within+- π© Render Still command yet to be written+- π© Cloud Run render only ever puts the output in a bucket, not available for download.<br><br><br><br># To Dodiff --git a/packages/gcp/src/api/render-media-on-gcp.ts b/packages/gcp/src/api/render-media-on-gcp.tsindex 1c9c660f64..4577a2bef5 100644--- a/packages/gcp/src/api/render-media-on-gcp.ts+++ b/packages/gcp/src/api/render-media-on-gcp.ts@@ -13,6 +13,7 @@ export type RenderMediaOnGcpInput = {codec: GcpCodec;outputBucket: string;outputFile: string;+ updateRenderProgress?: (progress: number) => void;};export type RenderMediaOnGcpOutput = {@@ -56,9 +57,8 @@ export const renderMediaOnGcp = async ({codec,outputBucket,outputFile,-}: RenderMediaOnGcpInput): Promise<- RenderMediaOnGcpOutput | RenderMediaOnGcpErrOutput-> => {+ updateRenderProgress,+}: RenderMediaOnGcpInput): Promise<any> => {const actualCodec = validateGcpCodec(codec);validateServeUrl(serveUrl);validateCloudRunUrl(cloudRunUrl);@@ -75,10 +75,28 @@ export const renderMediaOnGcp = async ({outputFile,};- try {- const response: RenderMediaOnGcpOutput = await got+ const dataPromise = new Promise((resolve, reject) => {+ let response = {};+ got.stream.post(cloudRunUrl, {json: postData})- .json();+ .on('data', (chunk) => {+ const chunkResponse = JSON.parse(chunk.toString());+ if (chunkResponse.response) {+ response = chunkResponse.response;+ } else if (chunkResponse.onProgress) {+ updateRenderProgress?.(chunkResponse.onProgress);+ }+ })+ .on('end', () => {+ resolve(response);+ })+ .on('error', (error) => {+ reject(error);+ });+ });++ try {+ const response = await dataPromise;return response;} catch (e) {return {diff --git a/packages/gcp/src/cli/commands/cloud-run/deploy.ts b/packages/gcp/src/cli/commands/cloud-run/deploy.tsindex b036ee001a..9d2a3cbf45 100644--- a/packages/gcp/src/cli/commands/cloud-run/deploy.ts+++ b/packages/gcp/src/cli/commands/cloud-run/deploy.ts@@ -93,7 +93,7 @@ Validating Deployment of Cloud Run Service:`π Cloud Run Revision Deployed! π- Service Name = ${deployRevisionResult.name}+ Full Service Name = ${deployRevisionResult.name}Cloud Run URL = ${deployRevisionResult.uri}Project = ${projectID}GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${serviceName}/revisions@@ -132,14 +132,17 @@ Validating Deployment of Cloud Run Service:throw new Error(JSON.stringify(deployResult));}+ Log.info();+Log.info(CliInternals.chalk.blueBright(`-Cloud Run Deployed! π-Full Service Name = ${deployResult.name}-Cloud Run URL = ${deployResult.uri}-Project = ${projectID}-GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${serviceName}/revisions+π Cloud Run Deployed! π++ Full Service Name = ${deployResult.name}+ Cloud Run URL = ${deployResult.uri}+ Project = ${projectID}+ GCP Console URL = https://console.cloud.google.com/run/detail/${region}/${serviceName}/revisions`.trim()));diff --git a/packages/gcp/src/cli/commands/render/render.ts b/packages/gcp/src/cli/commands/render/render.tsindex 9675c7ec24..12f78c2d60 100644--- a/packages/gcp/src/cli/commands/render/render.ts+++ b/packages/gcp/src/cli/commands/render/render.ts@@ -1,25 +1,18 @@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 {RenderMediaOnGcpErrOutput,RenderMediaOnGcpOutput,} from '../../../api/render-media-on-gcp';+import {renderMediaOnGcp} from '../../../api/render-media-on-gcp';+import {BINARY_NAME} from '../../../shared/constants';import type {GcpCodec} from '../../../shared/validate-gcp-codec';-import {validateMaxRetries} from '../../../shared/validate-retries';+// 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) => {@@ -40,7 +33,7 @@ export const renderCommand = async (args: string[], remotionRoot: string) => {if (!cloudRunUrl) {Log.error('No Cloud Run Service URL passed.');Log.info(- 'Pass an additional argument specifying a the endpoint of your Cloud Run Service.'+ 'Pass an additional argument specifying the endpoint of your Cloud Run Service.');Log.info();Log.info(@@ -66,7 +59,7 @@ export const renderCommand = async (args: string[], remotionRoot: string) => {const outName = parsedGcpCli['out-name'] ?? 'out.mp4'; // Todo, workout file extension instead of assuming mp4const downloadName = args[2] ?? null;- const {codec, reason} = CliInternals.getFinalCodec({+ const {codec} = CliInternals.getFinalCodec({downloadName,outName: outName ?? null,});@@ -76,14 +69,24 @@ export const renderCommand = async (args: string[], remotionRoot: string) => {isLambda: true, // TODO: what do I need to do with this?remotionRoot,});- const maxRetries = parsedGcpCli['max-retries'] ?? DEFAULT_MAX_RETRIES;- validateMaxRetries(maxRetries);+ // const maxRetries = parsedGcpCli['max-retries'] ?? DEFAULT_MAX_RETRIES;+ // validateMaxRetries(maxRetries);// const privacy = parsedLambdaCli.privacy ?? DEFAULT_OUTPUT_PRIVACY;// validatePrivacy(privacy);- const outputBucket =- parsedGcpCli['output-bucket'] || 'remotioncloudrun-n8x4pc7dz3'; // Todo: I think this should be optional with a fallback+ const outputBucket = parsedGcpCli['output-bucket']; // Todo: I think this should be optional with a fallback+ if (!outputBucket) {+ Log.error('No Output Bucket passed.');+ Log.info(+ 'Pass an additional argument specifying the name of your GCS bucket.'+ );+ Log.info();+ Log.info(+ `${BINARY_NAME} ${RENDER_COMMAND} <serve-url> <cloud-run-url> <composition-id> [output-bucket]`+ );+ quit(1);+ }// Todo: Check cloudRunUrl is valid, as the error message is obtuseCliInternals.Log.info(@@ -101,6 +104,37 @@ Sending request to Cloud Run:));Log.info();++ const renderStart = Date.now();+ const progressBar = CliInternals.createOverwriteableCliOutput(+ CliInternals.quietFlagProvided()+ );++ const renderProgress: {+ progress: number;+ doneIn: number | null;+ } = {+ doneIn: null,+ progress: 0,+ };+ const updateProgress = () => {+ progressBar.update(+ [+ `Rendering on Cloud Run: `,+ CliInternals.makeProgressBar(renderProgress.progress),+ `${renderProgress.doneIn === null ? 'Rendering' : 'Rendered'}`,+ renderProgress.doneIn === null+ ? `${Math.round(renderProgress.progress * 100)}%`+ : CliInternals.chalk.gray(`${renderProgress.doneIn}ms`),+ ].join(' ')+ );+ };++ const updateRenderProgress = (progress: number) => {+ renderProgress.progress = progress;+ updateProgress();+ };+const res = await renderMediaOnGcp({cloudRunUrl,// serviceName,@@ -110,14 +144,21 @@ Sending request to Cloud Run:codec: codec as GcpCodec,outputBucket,outputFile: outName,+ updateRenderProgress,});+ renderProgress.doneIn = Date.now() - renderStart;+ updateProgress();+if (res.status === 'error') {const err = res as RenderMediaOnGcpErrOutput;Log.error(CliInternals.chalk.red(err.message));throw err.error;} else {const success = res as RenderMediaOnGcpOutput;+ Log.info(`++ `);Log.info(CliInternals.chalk.blueBright(`@@ -132,178 +173,4 @@ Sending request to Cloud Run:));}-- // const totalSteps = downloadName ? 6 : 5;-- // const progressBar = CliInternals.createOverwriteableCliOutput(- // CliInternals.quietFlagProvided()- // );-- // Log.verbose(`CloudWatch logs (if enabled): ${res.cloudWatchLogs}`);- // 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/functions/render-media-single-thread.ts b/packages/gcp/src/functions/render-media-single-thread.tsindex d472145846..8ac555e113 100644--- a/packages/gcp/src/functions/render-media-single-thread.ts+++ b/packages/gcp/src/functions/render-media-single-thread.ts@@ -1,23 +1,10 @@import type * as ff from '@google-cloud/functions-framework';import {Storage} from '@google-cloud/storage';+import type {RenderMediaOnProgress} from '@remotion/renderer';import {renderMedia} from '@remotion/renderer';import {randomHash} from '../shared/random-hash';import {getCompositionFromBody} from './helpers/get-composition-from-body';-/*- example JSON body: {- "composition": "HelloWorld",- "serveUrl": "https://remotionlambda-11kow3vq6f.s3.us-east-1.amazonaws.com/sites/xmycbufjs3/index.html",- "codec": "h264",- "inputProps": {- "titleText": "Welcome to Remotion",- "titleColor": "black"- },- "outputBucket": "remotionlambda-test",- "outputFile": "mediaOutput.mp4"- }-*/-export const renderMediaSingleThread = async (req: ff.Request,res: ff.Response@@ -29,6 +16,15 @@ export const renderMediaSingleThread = async (const tempFilePath = '/tmp/output.mp4';const renderId = randomHash({randomInTests: true});+ let previousProgress = 2;+ const onProgress: RenderMediaOnProgress = ({progress}) => {+ if (previousProgress !== progress) {+ res.write(JSON.stringify({onProgress: progress}));+ previousProgress = progress;+ }+ };++ res.writeHead(200, {'Content-Type': 'text/html'});await renderMedia({composition,@@ -36,6 +32,7 @@ export const renderMediaSingleThread = async (codec: req.body.codec,outputLocation: tempFilePath,inputProps: req.body.inputProps,+ onProgress,});const storage = new Storage();@@ -58,8 +55,5 @@ export const renderMediaSingleThread = async (};console.log('Render Completed:', responseData);-- const jsonContent = JSON.stringify(responseData);-- res.end(jsonContent);+ res.end(JSON.stringify({response: responseData}));};diff --git a/packages/gcp/src/functions/render-still-single-thread.ts b/packages/gcp/src/functions/render-still-single-thread.tsindex 6f1eaca925..2d138c16ea 100644--- a/packages/gcp/src/functions/render-still-single-thread.ts+++ b/packages/gcp/src/functions/render-still-single-thread.ts@@ -4,18 +4,6 @@ import {renderStill} from '@remotion/renderer';import {randomHash} from '../shared/random-hash';import {getCompositionFromBody} from './helpers/get-composition-from-body';-/*- example JSON body: {- "composition": "StillRender",- "serveUrl": "https://remotionlambda-11kow3vq6f.s3.us-east-1.amazonaws.com/sites/xmycbufjs3/index.html",- "inputProps": {- "text": "Created on Cloud Runβ’οΈ"- },- "outputBucket": "remotionlambda-test",- "outputFile": "stillOutput.png"- }-*/-export const renderStillSingleThread = async (req: ff.Request,res: ff.Response