🎥 Make videos programmatically with React
advance streaming
Jonny Burger35801aa34039
diff --git a/packages/lambda/src/functions/helpers/concat-videos.ts b/packages/lambda/src/functions/helpers/concat-videos.tsindex ef6f8bc71c..1573b94bcb 100644--- a/packages/lambda/src/functions/helpers/concat-videos.ts+++ b/packages/lambda/src/functions/helpers/concat-videos.ts@@ -1,196 +1,19 @@import type {AudioCodec, CancelSignal, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';-import fs, {createWriteStream, promises} from 'node:fs';-import path, {join} from 'node:path';-import type {AwsRegion} from '../../pricing/aws-regions';+import fs from 'node:fs';+import {join} from 'node:path';import {REMOTION_CONCATED_TOKEN,REMOTION_FILELIST_TOKEN,- chunkKey,- getErrorKeyPrefix,- rendersPrefix,} from '../../shared/constants';import type {LambdaCodec} from '../../shared/validate-lambda-codec';import {canConcatAudioSeamlessly,canConcatVideoSeamlessly,} from './can-concat-seamlessly';-import {inspectErrors} from './inspect-errors';-import {lambdaLs, lambdaReadFile} from './io';import {timer} from './timer';-import type {EnhancedErrorInfo} from './write-lambda-error';-const getChunkDownloadOutputLocation = ({- outdir,- file,-}: {- outdir: string;- file: string;-}) => {- return path.join(outdir, path.basename(file));-};--const downloadS3File = async ({- bucket,- key,- outdir,- region,- expectedBucketOwner,-}: {- bucket: string;- key: string;- outdir: string;- region: AwsRegion;- expectedBucketOwner: string;-}) => {- const Body = await lambdaReadFile({- bucketName: bucket,- key,- region,- expectedBucketOwner,- });- const outpath = getChunkDownloadOutputLocation({outdir, file: key});- if (Buffer.isBuffer(Body)) {- return promises.writeFile(outpath, Body);- }-- return new Promise<void>((resolve, reject) => {- Body.pipe(createWriteStream(outpath))- .on('error', (err) => reject(err))- .on('close', () => resolve());- });-};--export const getAllFilesS3 = ({- bucket,- expectedFiles,- outdir,- renderId,- region,- expectedBucketOwner,- onErrors,- logLevel,-}: {- bucket: string;- expectedFiles: number;- outdir: string;- renderId: string;- region: AwsRegion;- expectedBucketOwner: string;- onErrors: (errors: EnhancedErrorInfo[]) => void;- logLevel: LogLevel;-}): Promise<string[]> => {- const alreadyDownloading: {[key: string]: true} = {};- const downloaded: {[key: string]: true} = {};-- const getFiles = async () => {- const prefix = rendersPrefix(renderId);- const lsTimer = timer('Listing files', logLevel);- const contents = await lambdaLs({- bucketName: bucket,- prefix,- region,- expectedBucketOwner,- });- lsTimer.end();- return {- filesInBucket: contents- .filter((c) => c.Key?.startsWith(chunkKey(renderId)))- .map((_) => _.Key as string),- errorContents: contents.filter((c) =>- c.Key?.startsWith(getErrorKeyPrefix(renderId)),- ),- };- };-- return new Promise<string[]>((resolve, reject) => {- const loop = async () => {- const {filesInBucket, errorContents} = await getFiles();- const checkFinish = () => {- const areAllFilesDownloaded =- Object.keys(downloaded).length === expectedFiles;- RenderInternals.Log.info(- {indent: false, logLevel},- 'Checking for finish... ',- Object.keys(downloaded),- expectedFiles + ' files expected',- );- if (areAllFilesDownloaded) {- RenderInternals.Log.info(- {indent: false, logLevel},- 'All files are downloaded!',- );- resolve(- // Need to use downloaded variable, not filesInBucket- // as it may be out of date- Object.keys(downloaded)- .sort()- .map((file) => getChunkDownloadOutputLocation({outdir, file})),- );- }- };-- RenderInternals.Log.info(- {indent: false, logLevel},- `Found ${filesInBucket.length} out of ${expectedFiles}`,- );- const errors = (- await inspectErrors({- bucket,- contents: errorContents,- expectedBucketOwner,- region,- renderId,- })- ).filter((e) => e.isFatal);-- if (errors.length > 0) {- onErrors(errors);- // Will die here- }-- filesInBucket.forEach(async (key) => {- if (alreadyDownloading[key]) {- return;- }-- alreadyDownloading[key] = true;- try {- const downloadTimer = timer('Downloading ' + key, logLevel);- await downloadS3File({- bucket,- key,- outdir,- region,- expectedBucketOwner,- });- RenderInternals.Log.info(- {indent: false, logLevel},- 'Successfully downloaded',- key,- );- downloadTimer.end();- downloaded[key] = true;- checkFinish();- } catch (err) {- reject(err);- }- });-- const areAllFilesDownloading =- Object.keys(alreadyDownloading).length === expectedFiles;- if (!areAllFilesDownloading) {- setTimeout(() => {- loop().catch((err) => reject(err));- }, 100);- }- };-- loop().catch((err) => reject(err));- });-};--export const concatVideosS3 = async ({+export const concatVideos = async ({onProgress,numberOfFrames,codec,diff --git a/packages/lambda/src/functions/helpers/merge-chunks.ts b/packages/lambda/src/functions/helpers/merge-chunks.tsindex 7a68ca04a2..feb5988584 100644--- a/packages/lambda/src/functions/helpers/merge-chunks.ts+++ b/packages/lambda/src/functions/helpers/merge-chunks.ts@@ -18,7 +18,7 @@ import {} from '../../shared/constants';import type {DownloadBehavior} from '../../shared/content-disposition-header';import type {LambdaCodec} from '../../shared/validate-lambda-codec';-import {concatVideosS3} from './concat-videos';+import {concatVideos} from './concat-videos';import {createPostRenderData} from './create-post-render-data';import {cleanupFiles} from './delete-chunks';import {getCurrentRegionInFunction} from './get-current-region';@@ -121,7 +121,7 @@ export const mergeChunksAndFinishRender = async (options: {throw new Error('Cannot merge stills');}- const {outfile, cleanupChunksProm} = await concatVideosS3({+ const {outfile, cleanupChunksProm} = await concatVideos({onProgress,numberOfFrames: options.numberOfFrames,codec: options.codec,diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex a2cf350ee5..4da03ab2a9 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -319,20 +319,22 @@ const renderHandler = async ({'Writing chunk to S3',);if (audioOutputLocation) {- await onStream({+ onStream({type: 'audio-chunk-rendered',payload: fs.readFileSync(audioOutputLocation),});}if (videoOutputLocation) {- await onStream({+ onStream({type: 'video-chunk-rendered',payload: fs.readFileSync(videoOutputLocation),});}const writeStart = Date.now();++ // TODO: Should not have to do this anymoreawait Promise.all([lambdaWriteFile({bucketName: params.bucketName,diff --git a/packages/lambda/src/functions/streaming/streaming.ts b/packages/lambda/src/functions/streaming/streaming.tsindex b9e213b4e6..c215aceb64 100644--- a/packages/lambda/src/functions/streaming/streaming.ts+++ b/packages/lambda/src/functions/streaming/streaming.ts@@ -16,8 +16,8 @@ const messageTypes = {'6': {type: stillRendered},} as const;-type MessageTypeId = keyof typeof messageTypes;-export type MessageType = (typeof messageTypes)[MessageTypeId]['type'];+export type MessageTypeId = keyof typeof messageTypes;+type MessageType = (typeof messageTypes)[MessageTypeId]['type'];export const formatMap: {[key in MessageType]: 'json' | 'binary'} = {[framesRendered]: 'json',@@ -60,7 +60,7 @@ export type StreamingPayload =payload: RenderStillLambdaResponsePayload;};-export const messageTypeIdToMessage = (+export const messageTypeIdToMessageType = (messageTypeId: MessageTypeId,): MessageType => {const types = messageTypes[messageTypeId];@@ -108,12 +108,12 @@ export const makePayloadMessage = ({const concat = Buffer.concat([magicSeparator,- Buffer.from(String(status)),- Buffer.from(':'),Buffer.from(messageTypeToMessageId(message.type).toString()),Buffer.from(':'),Buffer.from(body.length.toString()),Buffer.from(':'),+ Buffer.from(String(status)),+ Buffer.from(':'),body,]);diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.tsindex d1201f0c84..193cef931f 100644--- a/packages/lambda/src/shared/call-lambda.ts+++ b/packages/lambda/src/shared/call-lambda.ts@@ -6,11 +6,14 @@ import {} from '@aws-sdk/client-lambda';import {RenderInternals} from '@remotion/renderer';import type {- MessageType,+ MessageTypeId,OnMessage,StreamingMessage,} from '../functions/streaming/streaming';-import {formatMap} from '../functions/streaming/streaming';+import {+ formatMap,+ messageTypeIdToMessageType,+} from '../functions/streaming/streaming';import type {AwsRegion} from '../pricing/aws-regions';import {getLambdaClient} from './aws-clients';import type {LambdaPayloads, LambdaRoutines} from './constants';@@ -121,16 +124,19 @@ const callLambdaWithStreamingWithoutRetry = async <T extends LambdaRoutines>({);const {onData, clear} = RenderInternals.makeStreamer(- (status, messageType, data) => {+ (status, messageTypeId, data) => {+ const messageType = messageTypeIdToMessageType(+ messageTypeId as MessageTypeId,+ );const innerPayload =- formatMap[messageType as MessageType] === 'json'+ formatMap[messageType] === 'json'? parseJsonOrThrowSource(data, messageType): data;const message: StreamingMessage = {successType: status,message: {- type: messageType as MessageType,+ type: messageType,payload: innerPayload,},};