🎥 Make videos programmatically with React
progress
Jonny Burger0373dd124ee1
diff --git a/packages/lambda/src/functions/helpers/merge-chunks.ts b/packages/lambda/src/functions/helpers/merge-chunks.tsindex 1e95df3878..4870ff15e2 100644--- a/packages/lambda/src/functions/helpers/merge-chunks.ts+++ b/packages/lambda/src/functions/helpers/merge-chunks.ts@@ -1,8 +1,5 @@import type {AudioCodec, LogLevel} from '@remotion/renderer';-import {RenderInternals} from '@remotion/renderer';import fs from 'fs';-import {existsSync, mkdirSync, rmSync} from 'node:fs';-import {join} from 'node:path';import type {CustomCredentials} from '../../shared/aws-clients';import {cleanupSerializedInputProps,@@ -15,16 +12,14 @@ import type {SerializedInputProps,} from '../../shared/constants';import {- CONCAT_FOLDER_TOKEN,ENCODING_PROGRESS_STEP_SIZE,encodingProgressKey,initalizedMetadataKey,rendersPrefix,} from '../../shared/constants';import type {DownloadBehavior} from '../../shared/content-disposition-header';-import {truthy} from '../../shared/truthy';import type {LambdaCodec} from '../../shared/validate-lambda-codec';-import {concatVideosS3, getAllFilesS3} from './concat-videos';+import {concatVideosS3} from './concat-videos';import {createPostRenderData} from './create-post-render-data';import {cleanupFiles} from './delete-chunks';import {getCurrentRegionInFunction} from './get-current-region';@@ -34,7 +29,6 @@ import {inspectErrors} from './inspect-errors';import {lambdaDeleteFile, lambdaLs, lambdaWriteFile} from './io';import {lambdaRenderHasAudioVideo} from './render-has-audio-video';import {timer} from './timer';-import type {EnhancedErrorInfo} from './write-lambda-error';import {writeLambdaError} from './write-lambda-error';import {writePostRenderData} from './write-post-render-data';@@ -62,6 +56,8 @@ export const mergeChunksAndFinishRender = async (options: {binariesDirectory: string | null;preferLossless: boolean;compositionStart: number;+ outdir: string;+ files: string[];}): Promise<PostRenderData> => {let lastProgressUploaded = 0;@@ -107,55 +103,12 @@ export const mergeChunksAndFinishRender = async (options: {});};- const onErrors = (errors: EnhancedErrorInfo[]) => {- RenderInternals.Log.error(- {indent: false, logLevel: options.logLevel},- 'Found Errors',- errors,- );-- const firstError = errors[0];- if (firstError.chunk !== null) {- throw new Error(- `Stopping Lambda function because error occurred while rendering chunk ${- firstError.chunk- }:\n${errors[0].stack- .split('\n')- .map((s) => ` ${s}`)- .join('\n')}`,- );- }-- throw new Error(- `Stopping Lambda function because error occurred: ${errors[0].stack}`,- );- };-- const outdir = join(RenderInternals.tmpDir(CONCAT_FOLDER_TOKEN), 'bucket');- if (existsSync(outdir)) {- rmSync(outdir, {- recursive: true,- });- }-- mkdirSync(outdir);-const {hasAudio, hasVideo} = lambdaRenderHasAudioVideo(options.renderMetadata,);- const chunkMultiplier = [hasAudio, hasVideo].filter(truthy).length;- const expectedFiles = chunkMultiplier * options.chunkCount;- const files = await getAllFilesS3({- bucket: options.bucketName,- expectedFiles,- outdir,- renderId: options.renderId,- region: getCurrentRegionInFunction(),- expectedBucketOwner: options.expectedBucketOwner,- onErrors,- logLevel: options.logLevel,- });+ // TODO: Add back get files+const encodingStart = Date.now();if (options.renderMetadata.type === 'still') {throw new Error('Cannot merge stills');@@ -167,8 +120,8 @@ export const mergeChunksAndFinishRender = async (options: {codec: options.codec,fps: options.fps,numberOfGifLoops: options.numberOfGifLoops,- files,- outdir,+ files: options.files,+ outdir: options.outdir,audioCodec: options.audioCodec,audioBitrate: options.audioBitrate,logLevel: options.logLevel,diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex 4910f27c7e..54b875d230 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -2,6 +2,8 @@import {InvokeCommand} from '@aws-sdk/client-lambda';import type {LogOptions} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';+import {existsSync, mkdirSync, rmSync, writeFileSync} from 'fs';+import path, {join} from 'path';import {VERSION} from 'remotion/version';import {getLambdaClient} from '../shared/aws-clients';import {callLambda} from '../shared/call-lambda';@@ -18,8 +20,10 @@ import type {RenderMetadata,} from '../shared/constants';import {+ CONCAT_FOLDER_TOKEN,LambdaRoutines,MAX_FUNCTIONS_PER_RENDER,+ chunkKeyForIndex,renderMetadataKey,} from '../shared/constants';import {DOCS_URL} from '../shared/docs-url';@@ -385,6 +389,17 @@ const innerLaunchHandler = async ({const framesRendered = new Array(lambdaPayloads.length).fill(0);+ const outdir = join(RenderInternals.tmpDir(CONCAT_FOLDER_TOKEN), 'bucket');+ if (existsSync(outdir)) {+ rmSync(outdir, {+ recursive: true,+ });+ }++ mkdirSync(outdir);++ const files: string[] = [];+// TODO: Now this will wait for the render to completeawait Promise.all(lambdaPayloads.map(async (payload, i) => {@@ -405,9 +420,41 @@ const innerLaunchHandler = async ({0,)} frames rendered (${message.payload.frames})`,);- } else if (message.type === 'chunk-rendered') {+ } else if (message.type === 'video-chunk-rendered') {+ const filename = join(+ outdir,+ // TODO: Can be simplified+ path.basename(+ chunkKeyForIndex({+ index: i,+ renderId: params.renderId,+ type: 'video',+ }),+ ),+ );+ writeFileSync(filename, message.payload);console.log(`[STREAMING]: ${message.payload.length} bytes chunk received`,+ filename,+ );+ files.push(filename);+ } else if (message.type === 'audio-chunk-rendered') {+ const filename = join(+ outdir,+ // TODO: Can be simplified+ path.basename(+ chunkKeyForIndex({+ index: i,+ renderId: params.renderId,+ type: 'audio',+ }),+ ),+ );+ writeFileSync(filename, message.payload);+ files.push(filename);+ console.log(+ `[STREAMING]: ${message.payload.length} bytes audio chunk received`,+ filename,);}},@@ -444,6 +491,8 @@ const innerLaunchHandler = async ({binariesDirectory: null,preferLossless: params.preferLossless,compositionStart: realFrameRange[0],+ outdir,+ files,});return postRenderData;diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex aa4b97162f..0d9b10f305 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -324,10 +324,19 @@ const renderHandler = async ({'Writing chunk to S3',);if (params.enableStreaming) {- await onStream({- type: 'chunk-rendered',- payload: fs.readFileSync(videoOutputLocation),- });+ if (audioOutputLocation) {+ await onStream({+ type: 'audio-chunk-rendered',+ payload: fs.readFileSync(audioOutputLocation),+ });+ }++ if (videoOutputLocation) {+ await onStream({+ type: 'video-chunk-rendered',+ payload: fs.readFileSync(videoOutputLocation),+ });+ }}const writeStart = Date.now();diff --git a/packages/lambda/src/functions/streaming/streaming.ts b/packages/lambda/src/functions/streaming/streaming.tsindex 41b9872249..076a11dc1e 100644--- a/packages/lambda/src/functions/streaming/streaming.ts+++ b/packages/lambda/src/functions/streaming/streaming.ts@@ -1,15 +1,17 @@const framesRendered = 'frames-rendered' as const;const errorOccurred = 'error-occurred' as const;const renderIdDetermined = 'render-id-determined' as const;-const chunkRendered = 'chunk-rendered' as const;+const videoChunkRendered = 'video-chunk-rendered' as const;+const audioChunkRendered = 'audio-chunk-rendered' as const;const responseJson = 'response-json' as const;const messageTypes = {'1': {type: framesRendered},'2': {type: errorOccurred},'3': {type: renderIdDetermined},- '4': {type: chunkRendered},- '5': {type: responseJson},+ '4': {type: videoChunkRendered},+ '5': {type: audioChunkRendered},+ '6': {type: responseJson},} as const;type MessageTypeId = keyof typeof messageTypes;@@ -20,7 +22,8 @@ export const formatMap: {[key in MessageType]: 'json' | 'binary'} = {[errorOccurred]: 'json',[renderIdDetermined]: 'json',[responseJson]: 'json',- [chunkRendered]: 'binary',+ [videoChunkRendered]: 'binary',+ [audioChunkRendered]: 'binary',};export type StreamingPayload =@@ -31,7 +34,11 @@ export type StreamingPayload =};}| {- type: typeof chunkRendered;+ type: typeof videoChunkRendered;+ payload: Buffer;+ }+ | {+ type: typeof audioChunkRendered;payload: Buffer;}| {