Skip to content

πŸŽ₯ Make videos programmatically with React

download video

Jonny Burger49a8efc53fc8
diff --git a/packages/lambda/src/api/deploy-function.ts b/packages/lambda/src/api/deploy-function.ts
index 901be6a203..7d2569251b 100644
--- a/packages/lambda/src/api/deploy-function.ts
+++ b/packages/lambda/src/api/deploy-function.ts
@@ -37,7 +37,7 @@ export const deployFunction = async (options: {
region: options.region,
zipFile: renderOut,
functionName: fnNameRender,
- accountId: accountId[1],
+ accountId,
memorySizeInMb: options.memorySizeInMb,
timeoutInSeconds: options.timeoutInSeconds,
layerArn: options.layerArn,
diff --git a/packages/lambda/src/api/download-video.ts b/packages/lambda/src/api/download-video.ts
new file mode 100644
index 0000000000..e031e6c389
--- /dev/null
+++ b/packages/lambda/src/api/download-video.ts
@@ -0,0 +1,60 @@
+import fs, {createWriteStream} from 'fs';
+import path from 'path';
+import {getExpectedOutName} from '../functions/helpers/expected-out-name';
+import {getRenderMetadata} from '../functions/helpers/get-render-metadata';
+import {lambdaReadFile} from '../functions/helpers/io';
+import {AwsRegion} from '../pricing/aws-regions';
+import {getAccountId} from '../shared/get-account-id';
+
+type DownloadVideoInput = {
+ region: AwsRegion;
+ bucketName: string;
+ renderId: string;
+ outPath: string;
+};
+
+type DownloadVideoOutput = {
+ outputPath: string;
+ size: number;
+};
+
+export const downloadVideo = async (
+ input: DownloadVideoInput
+): Promise<DownloadVideoOutput> => {
+ const expectedBucketOwner = await getAccountId({
+ region: input.region,
+ });
+ const renderMetadata = await getRenderMetadata({
+ // TODO: Weird method
+ exists: true,
+ bucketName: input.bucketName,
+ expectedBucketOwner,
+ region: input.region,
+ renderId: input.renderId,
+ });
+ if (!renderMetadata) {
+ throw new TypeError('Could not find render metadata in the S3 bucket.');
+ }
+
+ const readable = await lambdaReadFile({
+ bucketName: input.bucketName,
+ expectedBucketOwner,
+ key: getExpectedOutName(renderMetadata),
+ region: input.region,
+ });
+
+ const outputPath = path.resolve(process.cwd(), input.outPath);
+
+ await new Promise<void>((resolve, reject) => {
+ readable
+ .pipe(createWriteStream(outputPath))
+ .on('error', (err) => reject(err))
+ .on('close', () => resolve());
+ });
+
+ const {size} = await fs.promises.stat(outputPath);
+ return {
+ outputPath,
+ size,
+ };
+};
diff --git a/packages/lambda/src/cli/commands/render/progress.ts b/packages/lambda/src/cli/commands/render/progress.ts
index 994f2a88a2..a74b833ce5 100644
--- a/packages/lambda/src/cli/commands/render/progress.ts
+++ b/packages/lambda/src/cli/commands/render/progress.ts
@@ -20,11 +20,14 @@ export type MultiRenderProgress = {
cleanupInfo: CleanupInfo | null;
};
-export const makeInvokeProgress = (chunkProgress: LambdaInvokeProgress) => {
+export const makeInvokeProgress = (
+ chunkProgress: LambdaInvokeProgress,
+ totalSteps: number
+) => {
const {lambdasInvoked, totalLambdas, doneIn} = chunkProgress;
return [
'🌩 ',
- `(1/4)`,
+ `(1/${totalSteps})`,
CliInternals.makeProgressBar(
totalLambdas === null ? 0 : lambdasInvoked / totalLambdas
),
@@ -37,11 +40,14 @@ export const makeInvokeProgress = (chunkProgress: LambdaInvokeProgress) => {
].join(' ');
};
-export const makeChunkProgress = (chunkProgress: ChunkProgress) => {
+export const makeChunkProgress = (
+ chunkProgress: ChunkProgress,
+ totalSteps: number
+) => {
const {chunksInvoked, totalChunks, doneIn} = chunkProgress;
return [
'🧩',
- `(2/4)`,
+ `(2/${totalSteps})`,
CliInternals.makeProgressBar(
totalChunks === null ? 0 : chunksInvoked / totalChunks
),
@@ -54,15 +60,18 @@ export const makeChunkProgress = (chunkProgress: ChunkProgress) => {
].join(' ');
};
-export const makeEncodingProgress = (encodingProgress: EncodingProgress) => {
+export const makeEncodingProgress = (
+ encodingProgress: EncodingProgress,
+ totalSteps: number
+) => {
const {framesEncoded, totalFrames, doneIn} = encodingProgress;
return [
'πŸ“½ ',
- `(3/4)`,
+ `(3/${totalSteps})`,
CliInternals.makeProgressBar(
totalFrames === null ? 0 : framesEncoded / totalFrames
),
- `${doneIn === null ? 'Encoding' : 'Encoded'} frames`,
+ `${doneIn === null ? 'Combining' : 'Combined'} videos`,
doneIn === null
? `${Math.round(
totalFrames === null ? 0 : (framesEncoded / totalFrames) * 100
@@ -71,7 +80,10 @@ export const makeEncodingProgress = (encodingProgress: EncodingProgress) => {
].join(' ');
};
-export const makeCleanupProgress = (cleanupInfo: CleanupInfo | null) => {
+export const makeCleanupProgress = (
+ cleanupInfo: CleanupInfo | null,
+ totalSteps: number
+) => {
if (!cleanupInfo) {
return '';
}
@@ -79,15 +91,30 @@ export const makeCleanupProgress = (cleanupInfo: CleanupInfo | null) => {
const {done, filesDeleted, filesToDelete} = cleanupInfo;
return [
'πŸͺ£ ',
- `(4/4)`,
+ `(4/${totalSteps})`,
CliInternals.makeProgressBar(filesDeleted / filesToDelete),
- `${done ? 'Cleaned up' : 'Cleaning up'} `,
+ `${done ? 'Cleaned up' : 'Cleaning up'} artifacts`,
done
? CliInternals.chalk.gray('TODOms')
: `${Math.round((filesDeleted / filesToDelete) * 100)}%`,
].join(' ');
};
+export const makeDownloadProgess = (
+ totalSteps: number,
+ downloadedYet: boolean
+) => {
+ return [
+ 'πŸ’Ύ',
+ `(5/${totalSteps})`,
+ // TODO: More granularly
+ CliInternals.makeProgressBar(Number(downloadedYet)),
+ `${downloadedYet ? 'Downloaded' : 'Downloading'} video`,
+ // TODO
+ downloadedYet ? CliInternals.chalk.gray('TODOms') : '0%',
+ ].join(' ');
+};
+
export const makeMultiProgressFromStatus = (
status: RenderProgress
): MultiRenderProgress => {
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index 9d57cb393f..f34bb72174 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -1,4 +1,6 @@
import {CliInternals} from '@remotion/cli';
+import {Internals} from 'remotion';
+import {downloadVideo} from '../../../api/download-video';
import {getRenderProgress} from '../../../api/get-render-progress';
import {renderVideoOnLambda} from '../../../api/render-video-on-lambda';
import {
@@ -8,10 +10,12 @@ import {
import {sleep} from '../../../shared/sleep';
import {getAwsRegion} from '../../get-aws-region';
import {findFunctionName} from '../../helpers/find-function-name';
+import {formatBytes} from '../../helpers/format-bytes';
import {Log} from '../../log';
import {
makeChunkProgress,
makeCleanupProgress,
+ makeDownloadProgess,
makeEncodingProgress,
makeInvokeProgress,
makeMultiProgressFromStatus,
@@ -41,6 +45,8 @@ export const renderCommand = async (args: string[]) => {
process.exit(1);
}
+ const outName = args[2] ?? null;
+
// TODO: Further validate serveUrl
const cliOptions = await CliInternals.getCliOptions({
@@ -68,6 +74,8 @@ export const renderCommand = async (args: string[]) => {
framesPerLambda: cliOptions.framesPerLambda ?? DEFAULT_FRAMES_PER_LAMBDA,
});
+ const totalSteps = outName ? 5 : 4;
+
const progressBar = CliInternals.createOverwriteableCliOutput();
const status = await getRenderProgress({
@@ -79,10 +87,10 @@ export const renderCommand = async (args: string[]) => {
const multiProgress = makeMultiProgressFromStatus(status);
progressBar.update(
[
- makeInvokeProgress(multiProgress.lambdaInvokeProgress),
- makeChunkProgress(multiProgress.chunkProgress),
- makeEncodingProgress(multiProgress.encodingProgress),
- makeCleanupProgress(multiProgress.cleanupInfo),
+ makeInvokeProgress(multiProgress.lambdaInvokeProgress, totalSteps),
+ makeChunkProgress(multiProgress.chunkProgress, totalSteps),
+ makeEncodingProgress(multiProgress.encodingProgress, totalSteps),
+ makeCleanupProgress(multiProgress.cleanupInfo, totalSteps),
].join('\n')
);
@@ -98,17 +106,52 @@ export const renderCommand = async (args: string[]) => {
const newProgress = makeMultiProgressFromStatus(newStatus);
progressBar.update(
[
- makeInvokeProgress(newProgress.lambdaInvokeProgress),
- makeChunkProgress(newProgress.chunkProgress),
- makeEncodingProgress(newProgress.encodingProgress),
- makeCleanupProgress(newProgress.cleanupInfo),
- ].join('\n')
+ makeInvokeProgress(newProgress.lambdaInvokeProgress, totalSteps),
+ makeChunkProgress(newProgress.chunkProgress, totalSteps),
+ makeEncodingProgress(newProgress.encodingProgress, totalSteps),
+ makeCleanupProgress(newProgress.cleanupInfo, totalSteps),
+ ]
+ .filter(Internals.truthy)
+ .join('\n')
);
// Log.info(newStatus);
if (newStatus.done) {
- Log.info();
- Log.info('Done! ' + newStatus.outputFile);
+ progressBar.update(
+ [
+ makeInvokeProgress(newProgress.lambdaInvokeProgress, totalSteps),
+ makeChunkProgress(newProgress.chunkProgress, totalSteps),
+ makeEncodingProgress(newProgress.encodingProgress, totalSteps),
+ makeCleanupProgress(newProgress.cleanupInfo, totalSteps),
+ ]
+ .filter(Internals.truthy)
+ .join('\n')
+ );
+ if (outName) {
+ const {outputPath, size} = await downloadVideo({
+ bucketName: res.bucketName,
+ outPath: outName,
+ region: getAwsRegion(),
+ renderId: res.renderId,
+ });
+ progressBar.update(
+ [
+ makeInvokeProgress(newProgress.lambdaInvokeProgress, totalSteps),
+ makeChunkProgress(newProgress.chunkProgress, totalSteps),
+ makeEncodingProgress(newProgress.encodingProgress, totalSteps),
+ makeCleanupProgress(newProgress.cleanupInfo, totalSteps),
+ outName ? makeDownloadProgess(totalSteps, true) : null,
+ ]
+ .filter(Internals.truthy)
+ .join('\n')
+ );
+ Log.info();
+ Log.info('Done!', outputPath, formatBytes(size));
+ } else {
+ Log.info();
+ Log.info('Done! ' + newStatus.outputFile);
+ }
+
process.exit(0);
}
diff --git a/packages/lambda/src/functions/helpers/expected-out-name.ts b/packages/lambda/src/functions/helpers/expected-out-name.ts
new file mode 100644
index 0000000000..193dc50255
--- /dev/null
+++ b/packages/lambda/src/functions/helpers/expected-out-name.ts
@@ -0,0 +1,14 @@
+import {Codec} from 'remotion';
+import {outName, outStillName, RenderMetadata} from '../../defaults';
+
+export const getExpectedOutName = (renderMetadata: RenderMetadata) => {
+ if (renderMetadata.type === 'still') {
+ return outStillName(renderMetadata.renderId, renderMetadata.imageFormat);
+ }
+
+ if (renderMetadata.type === 'video') {
+ return outName(renderMetadata.renderId, renderMetadata.codec as Codec);
+ }
+
+ throw new TypeError('no type passed');
+};
diff --git a/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts b/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts
index 683dae4343..e11f4eee1d 100644
--- a/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts
+++ b/packages/lambda/src/functions/helpers/find-output-file-in-bucket.ts
@@ -1,6 +1,6 @@
import {_Object} from '@aws-sdk/client-s3';
-import {Codec} from 'remotion';
-import {outName, outStillName, RenderMetadata} from '../../shared/constants';
+import {RenderMetadata} from '../../shared/constants';
+import {getExpectedOutName} from './expected-out-name';
import {getCurrentRegionInFunction} from './get-current-region';
export const findOutputFileInBucket = ({
@@ -20,21 +20,8 @@ export const findOutputFileInBucket = ({
size: number;
lastModified: number;
} | null => {
- const expectedOutName = (() => {
- if (!renderMetadata) {
- return null;
- }
-
- if (type === 'still') {
- return outStillName(renderId, renderMetadata?.imageFormat);
- }
-
- if (type === 'video') {
- return outName(renderId, renderMetadata?.codec as Codec);
- }
-
- throw new TypeError('no type passed');
- })();
+ const expectedOutName =
+ renderMetadata === null ? null : getExpectedOutName(renderMetadata);
const output = expectedOutName
? renderMetadata
diff --git a/packages/lambda/src/functions/helpers/io.ts b/packages/lambda/src/functions/helpers/io.ts
index 2f0dfdc011..99d45b99fd 100644
--- a/packages/lambda/src/functions/helpers/io.ts
+++ b/packages/lambda/src/functions/helpers/io.ts
@@ -55,7 +55,7 @@ export const lambdaLs = async ({
}
// Prevent from accessing a foreign bucket, retry without ExpectedBucketOwner and see if it works. If it works then it's an owner mismatch.
- if (err.stack.includes('AccessDenied')) {
+ if ((err as Error).stack?.includes('AccessDenied')) {
await getS3Client(region).send(
new ListObjectsV2Command({
Bucket: bucketName,
@@ -107,7 +107,7 @@ export const lambdaReadFile = async ({
key: string;
region: AwsRegion;
expectedBucketOwner: string;
-}): Promise<Readable | Buffer> => {
+}): Promise<Readable> => {
const {Body} = await getS3Client(region).send(
new GetObjectCommand({
Bucket: bucketName,
diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.ts
index 605f90569b..947c6fc163 100644
--- a/packages/lambda/src/functions/launch.ts
+++ b/packages/lambda/src/functions/launch.ts
@@ -189,6 +189,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {
framesPerLambda: params.framesPerLambda,
memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),
region: getCurrentRegionInFunction(),
+ renderId: params.renderId,
};
await lambdaWriteFile({
diff --git a/packages/lambda/src/functions/still.ts b/packages/lambda/src/functions/still.ts
index 556424e8ac..5aedd60edd 100644
--- a/packages/lambda/src/functions/still.ts
+++ b/packages/lambda/src/functions/still.ts
@@ -99,6 +99,7 @@ export const innerStillHandler = async (
framesPerLambda: 1,
memorySizeInMb: Number(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE),
region: getCurrentRegionInFunction(),
+ renderId,
};
await lambdaWriteFile({
@@ -184,8 +185,10 @@ export const stillHandler = async (
// If this error is encountered, we can just retry as it
// is a very rare error to occur
const isBrowserError =
- err.message.includes('FATAL:zygote_communication_linux.cc') ||
- err.message.included('error while loading shared libraries: libnss3.so');
+ (err as Error).message.includes('FATAL:zygote_communication_linux.cc') ||
+ (err as Error).message.includes(
+ 'error while loading shared libraries: libnss3.so'
+ );
if (isBrowserError || params.maxRetries > 0) {
const retryPayload: LambdaPayloads[LambdaRoutines.still] = {
...params,
diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.ts
index 3e3587289d..a54becf053 100644
--- a/packages/lambda/src/shared/constants.ts
+++ b/packages/lambda/src/shared/constants.ts
@@ -219,6 +219,7 @@ export type RenderMetadata = {
memorySizeInMb: number;
lambdaVersion: LambdaVersions;
region: AwsRegion;
+ renderId: string;
};
export type LambdaVersions =
diff --git a/packages/lambda/src/shared/get-account-id.ts b/packages/lambda/src/shared/get-account-id.ts
index 9fce46ebc2..70ae68d335 100644
--- a/packages/lambda/src/shared/get-account-id.ts
+++ b/packages/lambda/src/shared/get-account-id.ts
@@ -13,5 +13,5 @@ export const getAccountId = async (options: {region: AwsRegion}) => {
throw new Error('Cannot get account ID');
}
- return accountId;
+ return accountId[1];
};