Skip to content

🎥 Make videos programmatically with React

first working encoding

Jonny Burger85284f3ef826
diff --git a/packages/lambda/.gitignore b/packages/lambda/.gitignore
index b65d843069..81bf6abb5b 100644
--- a/packages/lambda/.gitignore
+++ b/packages/lambda/.gitignore
@@ -1,3 +1,7 @@
-build
+build-render
+build-stitcher
node_modules
function.zip
+function-render.zip
+function-stitcher.zip
+ffmpeg
diff --git a/packages/lambda/src/bundle-lambda.ts b/packages/lambda/src/bundle-lambda.ts
index 5396022534..283ba14bd3 100644
--- a/packages/lambda/src/bundle-lambda.ts
+++ b/packages/lambda/src/bundle-lambda.ts
@@ -23,8 +23,8 @@ const copyDir = function (src: string, dest: string): void {
}
};
-export const bundleLambda = async () => {
- const outdir = path.join(__dirname, '..', 'build');
+export const bundleLambda = async (type: 'render' | 'stitcher') => {
+ const outdir = path.join(__dirname, '..', `build-${type}`);
fs.mkdirSync(outdir, {
recursive: true,
});
@@ -32,12 +32,19 @@ export const bundleLambda = async () => {
fs.rmdirSync(outdir, {recursive: true});
fs.mkdirSync(outdir, {recursive: true});
- fs.mkdirSync(path.join(outdir, 'node_modules'), {recursive: true});
- copyDir(
- path.join(process.cwd(), 'node_modules/chrome-aws-lambda/'),
- path.join(__dirname, '..', 'build', 'node_modules/chrome-aws-lambda')
+ if (type === 'render') {
+ fs.mkdirSync(path.join(outdir, 'node_modules'), {recursive: true});
+ copyDir(
+ path.join(process.cwd(), 'node_modules/chrome-aws-lambda/'),
+ path.join(outdir, 'node_modules/chrome-aws-lambda')
+ );
+ }
+ const template = path.join(
+ __dirname,
+ '..',
+ 'template',
+ type === 'render' ? 'render.ts' : 'stitcher.ts'
);
- const template = path.join(__dirname, '..', 'template', 'render.ts');
await esbuild.build({
platform: 'node',
@@ -46,7 +53,7 @@ export const bundleLambda = async () => {
entryPoints: [template],
});
- const out = path.join(process.cwd(), 'function.zip');
+ const out = path.join(process.cwd(), `function-${type}.zip`);
await zl.archiveFolder(outdir, out);
return out;
};
diff --git a/packages/lambda/src/create-lambda.ts b/packages/lambda/src/create-lambda.ts
index 5a5258f1b7..ed17f4ba28 100644
--- a/packages/lambda/src/create-lambda.ts
+++ b/packages/lambda/src/create-lambda.ts
@@ -9,6 +9,7 @@ import {createReadStream} from 'fs';
import xns from 'xns';
import {bundleLambda} from './bundle-lambda';
import {bundleRemotion} from './bundle-remotion';
+import {createLayer} from './create-layer';
import {uploadDir} from './upload-dir';
const region = 'eu-central-1';
@@ -22,13 +23,20 @@ const s3Client = new S3Client({region});
const ENABLE_EFS = false;
xns(async () => {
+ // TODO: Only create layer if doesn't exist
+ const layer = await createLayer(lambdaClient);
const bucketName = 'remotion-bucket-' + Math.random();
const id = String(Math.random());
- const s3Key = `remotion-function-${id}.zip`;
- const fnName = 'remotion-test-' + String(Math.random()).replace('0.', '');
- const [remBundle, out] = await Promise.all([
+ const s3KeyRender = `remotion-render-function-${id}.zip`;
+ const s3KeyStitcher = `remotion-stitcher-function-${id}.zip`;
+ const fnNameRender =
+ 'remotion-render-test-' + String(Math.random()).replace('0.', '');
+ const fnNameStitcher =
+ 'remotion-stitcher-test-' + String(Math.random()).replace('0.', '');
+ const [remBundle, renderOut, stitcherOut] = await Promise.all([
bundleRemotion(),
- bundleLambda(),
+ bundleLambda('render'),
+ bundleLambda('stitcher'),
]);
await s3Client.send(
@@ -58,14 +66,24 @@ xns(async () => {
console.log('bundle uploaded');
// Upload lambda
- await s3Client.send(
- new PutObjectCommand({
- Bucket: bucketName,
- Body: createReadStream(out),
- Key: s3Key,
- ACL: 'public-read',
- })
- );
+ await Promise.all([
+ s3Client.send(
+ new PutObjectCommand({
+ Bucket: bucketName,
+ Body: createReadStream(renderOut),
+ Key: s3KeyRender,
+ ACL: 'public-read',
+ })
+ ),
+ s3Client.send(
+ new PutObjectCommand({
+ Bucket: bucketName,
+ Body: createReadStream(stitcherOut),
+ Key: s3KeyStitcher,
+ ACL: 'public-read',
+ })
+ ),
+ ]);
// TODO: Do it with HTTPS, but wait for certificate
const url = `http://${bucketName}.s3.${region}.amazonaws.com`;
@@ -74,9 +92,25 @@ xns(async () => {
new CreateFunctionCommand({
Code: {
S3Bucket: bucketName,
- S3Key: s3Key,
+ S3Key: s3KeyStitcher,
+ },
+ FunctionName: fnNameStitcher,
+ Handler: 'index.handler',
+ Role: 'arn:aws:iam::976210361945:role/lambda-admin', // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
+ Runtime: 'nodejs12.x',
+ Description: 'Encodes a Remotion video.',
+ MemorySize: 1769 * 2,
+ Timeout: 60,
+ Layers: [layer.LayerVersionArn as string],
+ })
+ );
+ await lambdaClient.send(
+ new CreateFunctionCommand({
+ Code: {
+ S3Bucket: bucketName,
+ S3Key: s3KeyRender,
},
- FunctionName: fnName,
+ FunctionName: fnNameRender,
Handler: 'index.handler',
Role: 'arn:aws:iam::976210361945:role/lambda-admin', // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
Runtime: 'nodejs12.x',
@@ -105,5 +139,5 @@ xns(async () => {
})
);
- return fnName;
+ return fnNameRender;
});
diff --git a/packages/lambda/src/create-layer.ts b/packages/lambda/src/create-layer.ts
new file mode 100644
index 0000000000..e981bfafad
--- /dev/null
+++ b/packages/lambda/src/create-layer.ts
@@ -0,0 +1,16 @@
+import {LambdaClient, PublishLayerVersionCommand} from '@aws-sdk/client-lambda';
+
+export const createLayer = (lambdaClient: LambdaClient) => {
+ return lambdaClient.send(
+ new PublishLayerVersionCommand({
+ Content: {
+ S3Bucket: 'remotion-binaries',
+ S3Key: 'ffmpeg.zip',
+ },
+ LayerName: 'remotion-ffmpeg-binaries',
+ LicenseInfo: 'https://ffmpeg.org/legal.html',
+ CompatibleRuntimes: ['nodejs14.x', 'nodejs12.x', 'nodejs10.x'],
+ Description: 'Adds ffmpeg and ffprobe binaries in PATH',
+ })
+ );
+};
diff --git a/packages/lambda/template/render.ts b/packages/lambda/template/render.ts
index ca8fc71afc..021c7fd0fb 100644
--- a/packages/lambda/template/render.ts
+++ b/packages/lambda/template/render.ts
@@ -56,6 +56,7 @@ export const handler = async (params: {serveUrl: string}) => {
inputProps: {},
onFrameUpdate: (i: number, output: string) => {
console.log('Rendered frames', i, output);
+ const start = Date.now();
s3Client
.send(
new PutObjectCommand({
@@ -67,6 +68,7 @@ export const handler = async (params: {serveUrl: string}) => {
)
.then(() => {
framesUploaded++;
+ console.log('Uploaded frame in ' + (Date.now() - start) + 'ms');
if (framesUploaded === totalFrames) {
resolve();
}
diff --git a/packages/lambda/template/stitcher.ts b/packages/lambda/template/stitcher.ts
new file mode 100644
index 0000000000..e0e159c555
--- /dev/null
+++ b/packages/lambda/template/stitcher.ts
@@ -0,0 +1,84 @@
+import {
+ GetObjectCommand,
+ ListObjectsCommand,
+ PutObjectCommand,
+ S3Client,
+} from '@aws-sdk/client-s3';
+import {stitchFramesToVideo} from '@remotion/renderer';
+import fs from 'fs';
+import path from 'path';
+import {Readable} from 'stream';
+
+// TODO: redundant
+const region = 'eu-central-1';
+
+const s3Client = new S3Client({region});
+
+const BIN_DIR = '/tmp/bin';
+
+fs.mkdirSync(BIN_DIR);
+
+export const handler = async (params: {bucket: string}) => {
+ console.log(fs.readdirSync('/tmp/bin'), process.env.PATH);
+ const id = String(Math.random());
+ const dir = `/tmp/${id}`;
+ const outdir = `/tmp/${Math.random()}`;
+ fs.mkdirSync(dir);
+ fs.mkdirSync(outdir);
+ const outputLocation = path.join(outdir, 'out.mp4');
+ console.log('ready!');
+ if (!params.bucket) {
+ throw new Error('Did not pass `bucket` param');
+ }
+ const listBucket = await s3Client.send(
+ new ListObjectsCommand({
+ Bucket: params.bucket,
+ })
+ );
+ // TODO: If 0 objects, not iterable.
+ for (const obj of listBucket.Contents) {
+ // TODO: parallel
+ const data = await s3Client.send(
+ new GetObjectCommand({
+ Bucket: params.bucket,
+ Key: obj.Key,
+ })
+ );
+ await new Promise<void>((resolve, reject) => {
+ (data.Body as Readable)
+ .pipe(fs.createWriteStream(path.join(dir, obj.Key)))
+ .on('error', (err) => reject(err))
+ .on('close', () => resolve());
+ });
+ }
+ console.log(fs.readdirSync(dir));
+ await stitchFramesToVideo({
+ assetsInfo: {
+ // TODO
+ assets: [],
+ bundleDir: '',
+ },
+ dir,
+ force: true,
+ // TODO
+ fps: 30,
+ // TODO
+ height: 1080,
+ //TODO,
+ width: 1080,
+ outputLocation,
+ // TODO
+ codec: 'h264',
+ // TODO
+ imageFormat: 'jpeg',
+ });
+ await s3Client.send(
+ new PutObjectCommand({
+ Bucket: params.bucket,
+ // TODO
+ Key: 'out.mp4',
+ Body: fs.createReadStream(outputLocation),
+ })
+ );
+ console.log('did stitch! awesome');
+};