🎥 Make videos programmatically with React
EFS flag
Jonny Burgerf3729e830da0
diff --git a/packages/lambda/src/concat-videos.ts b/packages/lambda/src/concat-videos.tsindex 619bc24c3e..85a32a0dc4 100644--- a/packages/lambda/src/concat-videos.ts+++ b/packages/lambda/src/concat-videos.ts@@ -1,9 +1,20 @@-import {GetObjectCommand, S3Client} from '@aws-sdk/client-s3';+import {+ GetObjectCommand,+ ListObjectsCommand,+ S3Client,+} from '@aws-sdk/client-s3';import {combineVideos} from '@remotion/renderer';-import {createWriteStream, readdirSync, rmdirSync} from 'fs';+import {+ createWriteStream,+ existsSync,+ mkdirSync,+ readdirSync,+ rmdirSync,+} from 'fs';import {join} from 'path';import {Readable} from 'stream';import xns from 'xns';+import {REGION} from './constants';import {timer} from './timer';import {tmpDir} from './tmpdir';@@ -65,33 +76,137 @@ const getAllFiles = async ({});};-export const concatVideos = xns(- async (- efsRemotionVideoPath,- efsRemotionVideoRenderDone,- expectedFiles = 20- ) => {- const getAllTimes = timer('get all files');- const files = await getAllFiles({- efsRemotionVideoPath,- expectedFiles,- efsRemotionVideoRenderDone,- });- getAllTimes.end();-- const outfile = join(tmpDir('remotion-concated'), 'concat.mp4');- const combine = timer('Combine videos');- const filelistDir = tmpDir('remotion-filelist');- await combineVideos({- files,- filelistDir,- output: outfile,- });- combine.end();+const getAllFilesS3 = async ({+ s3Client,+ bucket,+ expectedFiles,+ outdir,+}: {+ s3Client: S3Client;+ bucket: string;+ expectedFiles: number;+ outdir: string;+}): Promise<string[]> => {+ const alreadyDownloading: {[key: string]: true} = {};+ const downloaded: {[key: string]: true} = {};++ const getFiles = async () => {+ const lsTimer = timer('Listing files');+ const files = await s3Client.send(+ new ListObjectsCommand({+ Bucket: bucket,+ })+ );+ lsTimer.end();+ return (files.Contents || []).map((_) => _.Key as string);+ };++ return new Promise<string[]>((resolve, reject) => {+ const loop = async () => {+ const filesInBucket = await getFiles();+ const checkFinish = () => {+ const areAllFilesDownloaded =+ Object.keys(downloaded).length === expectedFiles;+ if (areAllFilesDownloaded) {+ resolve(filesInBucket.map((file) => join(outdir, file)));+ }+ };+ filesInBucket.forEach(async (content) => {+ if (alreadyDownloading[content]) {+ return;+ }+ alreadyDownloading[content] = true;+ try {+ const downloadTimer = timer('Downloading ' + content);+ await downloadS3File({+ bucket,+ content,+ outdir,+ s3Client,+ });+ downloadTimer.end();+ downloaded[content] = true;+ checkFinish();+ } catch (err) {+ reject(err);+ }+ });++ const areAllFilesDownloading =+ Object.keys(alreadyDownloading).length === expectedFiles;+ if (!areAllFilesDownloading) {+ setTimeout(() => {+ loop();+ }, 100);+ }+ };++ loop();+ });+};- rmdirSync(efsRemotionVideoPath, {+export const concatVideosS3 = async (+ s3Client: S3Client = new S3Client({region: REGION}),+ bucket = 'remotion-renders-0.7182592846197402',+ expectedFiles = 20+) => {+ const outdir = join(tmpDir('remotion-concat'), 'bucket');+ if (existsSync(outdir)) {+ rmdirSync(outdir, {recursive: true,});- return outfile;}-);+ mkdirSync(outdir);+ const files = await getAllFilesS3({+ s3Client,+ bucket,+ expectedFiles,+ outdir,+ });++ const outfile = join(tmpDir('remotion-concated'), 'concat.mp4');+ const combine = timer('Combine videos');+ const filelistDir = tmpDir('remotion-filelist');+ await combineVideos({+ files,+ filelistDir,+ output: outfile,+ });+ combine.end();++ rmdirSync(outdir, {+ recursive: true,+ });+ return outfile;+};++export const concatVideos = async (+ efsRemotionVideoPath: string,+ efsRemotionVideoRenderDone: string,+ expectedFiles = 20+) => {+ const getAllTimes = timer('get all files');+ const files = await getAllFiles({+ efsRemotionVideoPath,+ expectedFiles,+ efsRemotionVideoRenderDone,+ });+ getAllTimes.end();++ const outfile = join(tmpDir('remotion-concated'), 'concat.mp4');+ const combine = timer('Combine videos');+ const filelistDir = tmpDir('remotion-filelist');+ await combineVideos({+ files,+ filelistDir,+ output: outfile,+ });+ combine.end();++ rmdirSync(efsRemotionVideoPath, {+ recursive: true,+ });+ return outfile;+};++xns(concatVideosS3);diff --git a/packages/lambda/src/constants.ts b/packages/lambda/src/constants.tsindex 955671d99d..cd621ab8c0 100644--- a/packages/lambda/src/constants.ts+++ b/packages/lambda/src/constants.ts@@ -6,6 +6,7 @@ export const REMOTION_STITCHER_FN_ZIP = 'remotion-stitcher-function-';export const RENDER_FN_PREFIX = 'remotion-render-test-';export const RENDER_STITCHER_PREFIX = 'remotion-stitcher-test-';export const EFS_MOUNT_PATH = '/mnt/efs';+export const ENABLE_EFS = false;export type LambdaPayload =| {@@ -22,6 +23,7 @@ export type LambdaPayload =frameRange: [number, number];chunk: number;efsRemotionVideoPath: string;+ bucketName: string;composition: string;fps: number;height: number;diff --git a/packages/lambda/src/create-lambda.ts b/packages/lambda/src/create-lambda.tsindex 2dc0007e59..679e1deefd 100644--- a/packages/lambda/src/create-lambda.ts+++ b/packages/lambda/src/create-lambda.ts@@ -11,6 +11,7 @@ import {bundleLambda} from './bundle-lambda';import {bundleRemotion} from './bundle-remotion';import {EFS_MOUNT_PATH,+ ENABLE_EFS,LAMBDA_BUCKET_PREFIX,REGION,REMOTION_RENDER_FN_ZIP,@@ -25,7 +26,6 @@ const lambdaClient = new LambdaClient({const s3Client = new S3Client({region: REGION});-const ENABLE_EFS = true;type Developer = 'jonny' | 'shankhadeep';const developer: Developer = 'jonny' as Developer;@@ -108,7 +108,7 @@ xns(async () => {VpcConfig: ENABLE_EFS? {SubnetIds: [- developer === 'jonny'+ developer === 'shankhadeep'? 'subnet-be85fcd4': 'subnet-00e3aa99745996ff7',],diff --git a/packages/lambda/src/tmpdir.ts b/packages/lambda/src/tmpdir.tsindex ffac9b14d9..f2df36e244 100644--- a/packages/lambda/src/tmpdir.ts+++ b/packages/lambda/src/tmpdir.ts@@ -1,11 +1,13 @@import {mkdirSync, mkdtempSync} from 'fs';-import {EFS_MOUNT_PATH} from './constants';+import {EFS_MOUNT_PATH, ENABLE_EFS} from './constants';const isLambda = !!process.env.LAMBDA_TASK_ROOT;export const tmpDir = (str: string) => {if (isLambda) {- const dir = EFS_MOUNT_PATH + '/' + str + Math.random();+ const dir = ENABLE_EFS+ ? EFS_MOUNT_PATH + '/' + str + Math.random()+ : '/tmp/' + str + Math.random();mkdirSync(dir);return dir;}diff --git a/packages/lambda/template/render.ts b/packages/lambda/template/render.tsindex f6d8315ad1..0109445381 100644--- a/packages/lambda/template/render.ts+++ b/packages/lambda/template/render.ts@@ -12,9 +12,10 @@ import {} from '@remotion/renderer';import fs, {copyFileSync, writeFileSync} from 'fs';import path from 'path';-import {concatVideos} from '../src/concat-videos';+import {concatVideos, concatVideosS3} from '../src/concat-videos';import {EFS_MOUNT_PATH,+ ENABLE_EFS,LambdaPayload,REGION,RENDERS_BUCKET_PREFIX,@@ -82,14 +83,16 @@ export const handler = async (params: LambdaPayload) => {if (params.type === 'init') {const bucketName = RENDERS_BUCKET_PREFIX + Math.random();const efsRemotionVideoPath = EFS_MOUNT_PATH + '/remotion-video';- if (fs.existsSync(efsRemotionVideoPath)) {- fs.rmdirSync(efsRemotionVideoPath, {recursive: true});- }- fs.mkdirSync(efsRemotionVideoPath);- if (fs.existsSync(efsRemotionVideoRenderDone)) {- fs.rmdirSync(efsRemotionVideoRenderDone, {recursive: true});+ if (ENABLE_EFS) {+ if (fs.existsSync(efsRemotionVideoPath)) {+ fs.rmdirSync(efsRemotionVideoPath, {recursive: true});+ }+ fs.mkdirSync(efsRemotionVideoPath);+ if (fs.existsSync(efsRemotionVideoRenderDone)) {+ fs.rmdirSync(efsRemotionVideoRenderDone, {recursive: true});+ }+ fs.mkdirSync(efsRemotionVideoRenderDone);}- fs.mkdirSync(efsRemotionVideoRenderDone);// const bucketTimer = timer('Creating bucket');// TODO: Better validation@@ -138,6 +141,7 @@ export const handler = async (params: LambdaPayload) => {height: comp.height,width: comp.width,durationInFrames: params.durationInFrames,+ bucketName,};const callingLambdaTimer = timer('Calling lambda ' + chunks.indexOf(chunk)@@ -148,17 +152,20 @@ export const handler = async (params: LambdaPayload) => {// @ts-expect-errorPayload: JSON.stringify(payload),InvocationType: 'Event',- })+ }),+ {});callingLambdaTimer.end();}));reqSend.end();- const out = await concatVideos(- efsRemotionVideoPath,- efsRemotionVideoRenderDone,- chunkCount- );+ const out = ENABLE_EFS+ ? await concatVideos(+ efsRemotionVideoPath,+ efsRemotionVideoRenderDone,+ chunkCount+ )+ : await concatVideosS3(s3Client, bucketName);const outName = 'out.mp4';await s3Client.send(new PutObjectCommand({@@ -178,11 +185,13 @@ export const handler = async (params: LambdaPayload) => {if (!params.frameRange) {throw new Error('must pass framerange');}- if (!fs.existsSync(params.efsRemotionVideoPath)) {- fs.mkdirSync(params.efsRemotionVideoPath);- }- if (!fs.existsSync(efsRemotionVideoRenderDone)) {- fs.mkdirSync(efsRemotionVideoRenderDone);+ if (ENABLE_EFS) {+ if (!fs.existsSync(params.efsRemotionVideoPath)) {+ fs.mkdirSync(params.efsRemotionVideoPath);+ }+ if (!fs.existsSync(efsRemotionVideoRenderDone)) {+ fs.mkdirSync(efsRemotionVideoRenderDone);+ }}console.log(`Started rendering ${params.chunk}, frame ${params.frameRange}`@@ -212,19 +221,16 @@ export const handler = async (params: LambdaPayload) => {const outdir = `/tmp/${Math.random()}`;fs.mkdirSync(outdir);- const outputLocation = path.join(- params.efsRemotionVideoPath,- `chunk-${String(params.chunk).padStart(8, '0')}.mp4`- );- const intermediary = path.join(- outdir,- `chunk-${String(params.chunk).padStart(8, '0')}.mp4`- );+ const outputLocation = ENABLE_EFS+ ? path.join(+ params.efsRemotionVideoPath,+ `chunk-${String(params.chunk).padStart(8, '0')}.mp4`+ )+ : path.join(outdir, `chunk-${String(params.chunk).padStart(8, '0')}.mp4`);const outputFileLocation = path.join(efsRemotionVideoRenderDone,`chunk-${String(params.chunk).padStart(8, '0')}.txt`);- console.log(outputLocation);const stitchLabel = timer('stitcher');await stitchFramesToVideo({@@ -238,21 +244,34 @@ export const handler = async (params: LambdaPayload) => {fps: params.fps,height: params.height,width: params.width,- outputLocation: intermediary,+ outputLocation,// TODOcodec: 'h264',// TODOimageFormat: 'jpeg',});stitchLabel.end();- const copying = timer('copying');- copyFileSync(intermediary, outputLocation);- copying.end();+ if (ENABLE_EFS) {+ const copying = timer('copying');+ copyFileSync(outputLocation, outputLocation);+ copying.end();- const flag = timer('writing flag');- writeFileSync(outputFileLocation, 'true');- flag.end();- console.log('Done rendering!', outputDir, outputLocation);+ const flag = timer('writing flag');+ writeFileSync(outputFileLocation, 'true');+ flag.end();+ console.log('Done rendering!', outputDir, outputLocation);+ } else {+ const uploading = timer('uploading');+ await s3Client.send(+ new PutObjectCommand({+ Bucket: params.bucketName,+ Key: `chunk-${String(params.chunk).padStart(8, '0')}.mp4`,+ Body: fs.createReadStream(outputLocation),+ })+ );+ uploading.end();+ console.log('Done rendering!', outputDir, outputLocation);+ }} else {throw new Error('Command not found');}