Skip to content

🎥 Make videos programmatically with React

switch to uint8 array

Jonny Burger0cb0a2d691c8
diff --git a/packages/lambda/src/functions/helpers/create-post-render-data.ts b/packages/lambda/src/functions/helpers/create-post-render-data.ts
index 90b0cc2489..98bd7d0540 100644
--- a/packages/lambda/src/functions/helpers/create-post-render-data.ts
+++ b/packages/lambda/src/functions/helpers/create-post-render-data.ts
@@ -16,7 +16,6 @@ import type {OutputFileMetadata} from './find-output-file-in-bucket';
import {getFilesToDelete} from './get-files-to-delete';
import {getRetryStats} from './get-retry-stats';
import {getTimeToFinish} from './get-time-to-finish';
-import {lambdaRenderHasAudioVideo} from './render-has-audio-video';
import type {EnhancedErrorInfo} from './write-lambda-error';
export const createPostRenderData = ({
@@ -87,8 +86,6 @@ export const createPostRenderData = ({
renderId,
});
- const {hasAudio, hasVideo} = lambdaRenderHasAudioVideo(renderMetadata);
-
return {
cost: {
currency: 'USD',
@@ -111,8 +108,6 @@ export const createPostRenderData = ({
filesCleanedUp: getFilesToDelete({
chunkCount: renderMetadata.totalChunks,
renderId,
- hasAudio,
- hasVideo,
}).length,
timeToEncode,
timeToCleanUp: timeToDelete,
diff --git a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts b/packages/lambda/src/functions/helpers/get-cleanup-progress.ts
index e1efe3104c..d65c912ddf 100644
--- a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts
+++ b/packages/lambda/src/functions/helpers/get-cleanup-progress.ts
@@ -7,15 +7,11 @@ export const getCleanupProgress = ({
output,
chunkCount,
renderId,
- hasAudio,
- hasVideo,
}: {
contents: _Object[];
output: string | null;
chunkCount: number;
renderId: string;
- hasAudio: boolean;
- hasVideo: boolean;
}): null | CleanupInfo => {
if (output === null) {
return null;
@@ -24,8 +20,6 @@ export const getCleanupProgress = ({
const filesToDelete = getFilesToDelete({
chunkCount,
renderId,
- hasAudio,
- hasVideo,
});
const filesStillThere = contents.filter((c) => {
return filesToDelete.find((f) => {
diff --git a/packages/lambda/src/functions/helpers/get-files-to-delete.ts b/packages/lambda/src/functions/helpers/get-files-to-delete.ts
index c1f9046c14..c74ede8428 100644
--- a/packages/lambda/src/functions/helpers/get-files-to-delete.ts
+++ b/packages/lambda/src/functions/helpers/get-files-to-delete.ts
@@ -1,5 +1,4 @@
import {
- chunkKeyForIndex,
encodingProgressKey,
lambdaChunkInitializedPrefix,
lambdaTimingsPrefixForChunk,
@@ -13,33 +12,10 @@ export type CleanupJob = {
export const getFilesToDelete = ({
chunkCount,
renderId,
- hasVideo,
- hasAudio,
}: {
chunkCount: number;
renderId: string;
- hasVideo: boolean;
- hasAudio: boolean;
}): CleanupJob[] => {
- const videoChunks = hasVideo
- ? new Array(chunkCount).fill(true).map((_x, i) =>
- chunkKeyForIndex({
- index: i,
- renderId,
- type: 'video',
- }),
- )
- : [];
- const audioChunks = hasAudio
- ? new Array(chunkCount).fill(true).map((_x, i) =>
- chunkKeyForIndex({
- index: i,
- renderId,
- type: 'audio',
- }),
- )
- : [];
-
const lambdaTimings = new Array(chunkCount)
.fill(true)
.map((_x, i) => lambdaTimingsPrefixForChunk(renderId, i));
@@ -48,18 +24,6 @@ export const getFilesToDelete = ({
name: lambdaChunkInitializedPrefix(renderId),
type: 'prefix' as const,
},
- ...videoChunks.map((i) => {
- return {
- name: i,
- type: 'exact' as const,
- };
- }),
- ...audioChunks.map((i) => {
- return {
- name: i,
- type: 'exact' as const,
- };
- }),
...lambdaTimings.map((i) => {
return {
name: i,
diff --git a/packages/lambda/src/functions/helpers/get-progress.ts b/packages/lambda/src/functions/helpers/get-progress.ts
index 00fa427d77..00a98e624e 100644
--- a/packages/lambda/src/functions/helpers/get-progress.ts
+++ b/packages/lambda/src/functions/helpers/get-progress.ts
@@ -188,8 +188,6 @@ export const getProgress = async ({
contents,
output: outputFile?.url ?? null,
renderId,
- hasAudio,
- hasVideo,
});
const timeToFinish = getTimeToFinish({
@@ -199,6 +197,7 @@ export const getProgress = async ({
const chunkMultiplier = [hasAudio, hasVideo].filter(truthy).length;
+ // TODO: Those chunks are not in S3 anymore
const chunks = contents.filter((c) => c.Key?.startsWith(chunkKey(renderId)));
const framesRendered = renderMetadata
? getRenderedFramesProgress({
diff --git a/packages/lambda/src/functions/helpers/merge-chunks.ts b/packages/lambda/src/functions/helpers/merge-chunks.ts
index feb5988584..e036683f7b 100644
--- a/packages/lambda/src/functions/helpers/merge-chunks.ts
+++ b/packages/lambda/src/functions/helpers/merge-chunks.ts
@@ -27,7 +27,6 @@ import {getFilesToDelete} from './get-files-to-delete';
import {getOutputUrlFromMetadata} from './get-output-url-from-metadata';
import {inspectErrors} from './inspect-errors';
import {lambdaDeleteFile, lambdaLs, lambdaWriteFile} from './io';
-import {lambdaRenderHasAudioVideo} from './render-has-audio-video';
import {timer} from './timer';
import {writeLambdaError} from './write-lambda-error';
import {writePostRenderData} from './write-post-render-data';
@@ -110,10 +109,6 @@ export const mergeChunksAndFinishRender = async (options: {
});
};
- const {hasAudio, hasVideo} = lambdaRenderHasAudioVideo(
- options.renderMetadata,
- );
-
// TODO: Add back get files
const encodingStart = Date.now();
@@ -194,8 +189,6 @@ export const mergeChunksAndFinishRender = async (options: {
const jobs = getFilesToDelete({
chunkCount: options.chunkCount,
renderId: options.renderId,
- hasAudio,
- hasVideo,
});
const deletProm =
diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.ts
index a14774489d..581bac8c32 100644
--- a/packages/lambda/src/functions/index.ts
+++ b/packages/lambda/src/functions/index.ts
@@ -24,8 +24,7 @@ import {
streamWriter,
type ResponseStreamWriter,
} from './streaming/stream-writer';
-import type {OnStream} from './streaming/streaming';
-import {makePayloadMessage} from './streaming/streaming';
+import {makeStreamPayload, type OnStream} from './streaming/streaming';
const innerHandler = async ({
params,
@@ -172,9 +171,8 @@ const innerHandler = async ({
isWarm,
},
(payload) => {
- const message = makePayloadMessage({
+ const message = makeStreamPayload({
message: payload,
- status: 0,
});
responseWriter.write(message).catch((err) => {
reject(err);
diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.ts
index 85cae85b64..4224024826 100644
--- a/packages/lambda/src/functions/renderer.ts
+++ b/packages/lambda/src/functions/renderer.ts
@@ -10,7 +10,6 @@ import type {LambdaPayload, LambdaPayloads} from '../shared/constants';
import {
LambdaRoutines,
RENDERER_PATH_TOKEN,
- chunkKeyForIndex,
lambdaTimingsKey,
} from '../shared/constants';
import {isFlakyError} from '../shared/is-flaky-error';
@@ -336,40 +335,6 @@ const renderHandler = async ({
const writeStart = Date.now();
- // TODO: Should not have to do this anymore
- await Promise.all([
- lambdaWriteFile({
- bucketName: params.bucketName,
- key: chunkKeyForIndex({
- renderId: params.renderId,
- index: params.chunk,
- type: RenderInternals.isAudioCodec(params.codec) ? 'audio' : 'video',
- }),
- body: fs.createReadStream(videoOutputLocation),
- region: getCurrentRegionInFunction(),
- privacy: params.privacy,
- expectedBucketOwner: options.expectedBucketOwner,
- downloadBehavior: null,
- customCredentials: null,
- }),
- audioOutputLocation
- ? lambdaWriteFile({
- bucketName: params.bucketName,
- key: chunkKeyForIndex({
- renderId: params.renderId,
- index: params.chunk,
- type: 'audio',
- }),
- body: fs.createReadStream(audioOutputLocation),
- region: getCurrentRegionInFunction(),
- privacy: params.privacy,
- expectedBucketOwner: options.expectedBucketOwner,
- downloadBehavior: null,
- customCredentials: null,
- })
- : null,
- ]);
-
RenderInternals.Log.verbose(
{indent: false, logLevel: params.logLevel},
`Wrote chunk to S3 (${Date.now() - writeStart}ms)`,
diff --git a/packages/lambda/src/functions/streaming/stream-writer.ts b/packages/lambda/src/functions/streaming/stream-writer.ts
index 3231489f2b..4614145cf5 100644
--- a/packages/lambda/src/functions/streaming/stream-writer.ts
+++ b/packages/lambda/src/functions/streaming/stream-writer.ts
@@ -1,7 +1,7 @@
import type {ResponseStream} from '../helpers/streamify-response';
export type ResponseStreamWriter = {
- write: (message: Buffer) => Promise<void>;
+ write: (message: Uint8Array) => Promise<void>;
end: () => Promise<void>;
};
@@ -12,7 +12,7 @@ export const streamWriter = (
): ResponseStreamWriter => {
let promiseChain = Promise.resolve();
- const write = (message: Buffer): Promise<void> => {
+ const write = (message: Uint8Array): Promise<void> => {
promiseChain = promiseChain.then(() => {
return new Promise<void>((resolve, reject) => {
responseStream.write(message, (err) => {
diff --git a/packages/lambda/src/functions/streaming/streaming.ts b/packages/lambda/src/functions/streaming/streaming.ts
index c215aceb64..04a14943f8 100644
--- a/packages/lambda/src/functions/streaming/streaming.ts
+++ b/packages/lambda/src/functions/streaming/streaming.ts
@@ -1,3 +1,4 @@
+import {BrowserSafeApis} from '@remotion/renderer/client';
import type {RenderStillLambdaResponsePayload} from '../still';
const framesRendered = 'frames-rendered' as const;
@@ -92,32 +93,17 @@ export type StreamingMessage = {
export type OnMessage = (options: StreamingMessage) => void;
-const magicSeparator = Buffer.from('remotion_buffer:');
+export type OnStream = (payload: StreamingPayload) => void;
-export const makePayloadMessage = ({
- message,
- status,
-}: {
- message: StreamingPayload;
- status: 0 | 1;
-}): Buffer => {
+export const makeStreamPayload = ({message}: {message: StreamingPayload}) => {
const body =
formatMap[message.type] === 'json'
? Buffer.from(JSON.stringify(message.payload))
: (message.payload as Buffer);
- const concat = Buffer.concat([
- magicSeparator,
- Buffer.from(messageTypeToMessageId(message.type).toString()),
- Buffer.from(':'),
- Buffer.from(body.length.toString()),
- Buffer.from(':'),
- Buffer.from(String(status)),
- Buffer.from(':'),
+ return BrowserSafeApis.makeStreamPayloadMessage({
body,
- ]);
-
- return concat;
+ nonce: messageTypeToMessageId(message.type),
+ status: 0,
+ });
};
-
-export type OnStream = (payload: StreamingPayload) => void;
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index e653d2f163..1918aac68f 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -4,7 +4,7 @@ import {
InvokeCommand,
InvokeWithResponseStreamCommand,
} from '@aws-sdk/client-lambda';
-import {RenderInternals} from '@remotion/renderer';
+import {BrowserSafeApis} from '@remotion/renderer/client';
import type {
MessageTypeId,
OnMessage,
@@ -130,7 +130,7 @@ const callLambdaWithStreamingWithoutRetry = async <T extends LambdaRoutines>({
}),
);
- const {onData, clear} = RenderInternals.makeStreamer(
+ const {onData, clear} = BrowserSafeApis.makeStreamer(
(status, messageTypeId, data) => {
const messageType = messageTypeIdToMessageType(
messageTypeId as MessageTypeId,
diff --git a/packages/renderer/src/client.ts b/packages/renderer/src/client.ts
index 0a13c9b6fe..0eaf1746e0 100644
--- a/packages/renderer/src/client.ts
+++ b/packages/renderer/src/client.ts
@@ -32,6 +32,7 @@ import {
validPixelFormatsForCodec,
} from './pixel-format';
import {proResProfileOptions} from './prores-profile';
+import {makeStreamPayloadMessage, makeStreamer} from './streaming';
import {validateOutputFilename} from './validate-output-filename';
export {AvailableOptions, TypeOfOption} from './options';
@@ -66,4 +67,6 @@ export const BrowserSafeApis = {
logLevels,
getOutputCodecOrUndefined,
getExtensionFromAudioCodec,
+ makeStreamer,
+ makeStreamPayloadMessage,
};
diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts
index 48bf737dfd..d30ac4b6e7 100644
--- a/packages/renderer/src/index.ts
+++ b/packages/renderer/src/index.ts
@@ -145,7 +145,6 @@ import {
supportedAudioCodecs,
} from './options/audio-codec';
import {getShouldRenderAudio} from './render-has-audio';
-import {makeStreamer} from './streaming';
import {toMegabytes} from './to-megabytes';
import {validatePuppeteerTimeout} from './validate-puppeteer-timeout';
import {validateBitrate} from './validate-videobitrate';
@@ -240,7 +239,6 @@ export const RenderInternals = {
codecSupportsMedia,
toMegabytes,
internalEnsureBrowser,
- makeStreamer,
};
// Warn of potential performance issues with Apple Silicon (M1 chip under Rosetta)
diff --git a/packages/renderer/src/streaming.ts b/packages/renderer/src/streaming.ts
index 9a035b7274..7c36b72164 100644
--- a/packages/renderer/src/streaming.ts
+++ b/packages/renderer/src/streaming.ts
@@ -1,3 +1,7 @@
+export const streamingKey = 'remotion_buffer:';
+
+const magicWordStr = 'remotion_buffer:';
+
export const makeStreamer = (
onMessage: (
statusType: 'success' | 'error',
@@ -5,10 +9,9 @@ export const makeStreamer = (
data: Uint8Array,
) => void,
) => {
- const separatorStr = 'remotion_buffer:';
- const separator = new Uint8Array(separatorStr.length);
- for (let i = 0; i < separatorStr.length; i++) {
- separator[i] = separatorStr.charCodeAt(i);
+ const separator = new Uint8Array(magicWordStr.length);
+ for (let i = 0; i < magicWordStr.length; i++) {
+ separator[i] = magicWordStr.charCodeAt(i);
}
let unprocessedBuffers: Uint8Array[] = [];
@@ -144,3 +147,51 @@ export const makeStreamer = (
},
};
};
+
+export const makeStreamPayloadMessage = ({
+ status,
+ body,
+ nonce,
+}: {
+ nonce: string;
+ status: 0 | 1;
+ body: Uint8Array;
+}): Uint8Array => {
+ const nonceArr = new TextEncoder().encode(nonce);
+ const magicWordArr = new TextEncoder().encode(magicWordStr);
+ const separatorArr = new TextEncoder().encode(':');
+ const bodyLengthArr = new TextEncoder().encode(body.length.toString());
+ const statusArr = new TextEncoder().encode(String(status));
+
+ // Calculate total length of new Uint8Array
+ const totalLength =
+ nonceArr.length +
+ magicWordArr.length +
+ separatorArr.length * 3 +
+ bodyLengthArr.length +
+ statusArr.length +
+ body.length;
+
+ // Create a new Uint8Array to hold all combined parts
+ const concat = new Uint8Array(totalLength);
+
+ let offset = 0;
+
+ // Function to append data to concat
+ const appendToConcat = (data: Uint8Array) => {
+ concat.set(data, offset);
+ offset += data.length;
+ };
+
+ // Building the final Uint8Array
+ appendToConcat(magicWordArr);
+ appendToConcat(nonceArr);
+ appendToConcat(separatorArr);
+ appendToConcat(bodyLengthArr);
+ appendToConcat(separatorArr);
+ appendToConcat(statusArr);
+ appendToConcat(separatorArr);
+ appendToConcat(body);
+
+ return concat;
+};