Skip to content

🎥 Make videos programmatically with React

Make it use Web APIs

Jonny Burgerb56c6855f932
diff --git a/packages/renderer/src/compositor/compositor.ts b/packages/renderer/src/compositor/compositor.ts
index 1e67a7e7b9..a62310c845 100644
--- a/packages/renderer/src/compositor/compositor.ts
+++ b/packages/renderer/src/compositor/compositor.ts
@@ -20,13 +20,13 @@ export type Compositor = {
executeCommand: <T extends keyof CompositorCommand>(
type: T,
payload: CompositorCommand[T],
- ) => Promise<Buffer>;
+ ) => Promise<Uint8Array>;
waitForDone: () => Promise<void>;
pid: number | null;
};
type Waiter = {
- resolve: (data: Buffer) => void;
+ resolve: (data: Uint8Array) => void;
reject: (err: Error) => void;
};
@@ -115,21 +115,26 @@ export const startCompositor = <T extends keyof CompositorCommand>({
const onMessage = (
statusType: 'success' | 'error',
nonce: string,
- data: Buffer,
+ data: Uint8Array,
) => {
// Nonce '0' just means that the message should be logged
if (nonce === '0') {
- Log.verbose({indent, logLevel, tag: 'compositor'}, data.toString('utf8'));
+ Log.verbose(
+ {indent, logLevel, tag: 'compositor'},
+ new TextDecoder('utf8').decode(data),
+ );
} else if (waiters.has(nonce)) {
if (statusType === 'error') {
try {
- const parsed = JSON.parse(data.toString('utf8')) as ErrorPayload;
+ const parsed = JSON.parse(
+ new TextDecoder('utf8').decode(data),
+ ) as ErrorPayload;
(waiters.get(nonce) as Waiter).reject(
new Error(`Compositor error: ${parsed.error}\n${parsed.backtrace}`),
);
} catch (err) {
(waiters.get(nonce) as Waiter).reject(
- new Error(data.toString('utf8')),
+ new Error(new TextDecoder('utf8').decode(data)),
);
}
} else {
@@ -169,7 +174,7 @@ export const startCompositor = <T extends keyof CompositorCommand>({
} else {
const errorMessage =
Buffer.concat(stderrChunks).toString('utf-8') +
- getOutputBuffer().toString('utf-8');
+ new TextDecoder('utf-8').decode(getOutputBuffer());
runningStatus = {type: 'quit-with-error', error: errorMessage, signal};
const error =
@@ -260,7 +265,7 @@ export const startCompositor = <T extends keyof CompositorCommand>({
command: Type,
params: CompositorCommand[Type],
) => {
- return new Promise<Buffer>((_resolve, _reject) => {
+ return new Promise<Uint8Array>((_resolve, _reject) => {
if (runningStatus.type === 'quit-without-error') {
_reject(
new Error(
diff --git a/packages/renderer/src/get-silent-parts.ts b/packages/renderer/src/get-silent-parts.ts
index fd587a335a..fb70290de2 100644
--- a/packages/renderer/src/get-silent-parts.ts
+++ b/packages/renderer/src/get-silent-parts.ts
@@ -76,7 +76,7 @@ export const getSilentParts = async ({
});
const response = JSON.parse(
- res.toString('utf-8'),
+ new TextDecoder('utf-8').decode(res),
) as GetSilentPartsResponseRust;
await compositor.finishCommands();
diff --git a/packages/renderer/src/get-video-metadata.ts b/packages/renderer/src/get-video-metadata.ts
index f106e1a70a..5271cf916c 100644
--- a/packages/renderer/src/get-video-metadata.ts
+++ b/packages/renderer/src/get-video-metadata.ts
@@ -19,5 +19,7 @@ export const getVideoMetadata = async (
});
await compositor.finishCommands();
await compositor.waitForDone();
- return JSON.parse(metadataResponse.toString('utf-8')) as VideoMetadata;
+ return JSON.parse(
+ new TextDecoder('utf-8').decode(metadataResponse),
+ ) as VideoMetadata;
};
diff --git a/packages/renderer/src/offthread-video-server.ts b/packages/renderer/src/offthread-video-server.ts
index 4423fa67ec..32f5a96436 100644
--- a/packages/renderer/src/offthread-video-server.ts
+++ b/packages/renderer/src/offthread-video-server.ts
@@ -137,7 +137,7 @@ export const startOffthreadVideoServer = ({
let extractStart = Date.now();
downloadAsset({src, downloadMap, indent, logLevel})
.then((to) => {
- return new Promise<Buffer>((resolve, reject) => {
+ return new Promise<Uint8Array>((resolve, reject) => {
if (closed) {
reject(Error(REQUEST_CLOSED_TOKEN));
return;
diff --git a/packages/renderer/src/streaming.ts b/packages/renderer/src/streaming.ts
index 4feae2f9fc..9a035b7274 100644
--- a/packages/renderer/src/streaming.ts
+++ b/packages/renderer/src/streaming.ts
@@ -2,19 +2,29 @@ export const makeStreamer = (
onMessage: (
statusType: 'success' | 'error',
nonce: string,
- data: Buffer,
+ data: Uint8Array,
) => void,
) => {
- const separator = Buffer.from('remotion_buffer:');
- let unprocessedBuffers: Buffer[] = [];
- let outputBuffer = Buffer.from('');
+ const separatorStr = 'remotion_buffer:';
+ const separator = new Uint8Array(separatorStr.length);
+ for (let i = 0; i < separatorStr.length; i++) {
+ separator[i] = separatorStr.charCodeAt(i);
+ }
+
+ let unprocessedBuffers: Uint8Array[] = [];
+ let outputBuffer = new Uint8Array(0);
let missingData: null | {
dataMissing: number;
} = null;
const processInput = () => {
- let separatorIndex = outputBuffer.indexOf(separator);
- if (separatorIndex === -1) {
+ let separatorIndex = outputBuffer.indexOf(separator[0]); // Start checking for the first byte of the separator
+ if (
+ separatorIndex === -1 ||
+ outputBuffer
+ .subarray(separatorIndex, separatorIndex + separator.length)
+ .toString() !== separator.toString()
+ ) {
return;
}
@@ -24,10 +34,6 @@ export const makeStreamer = (
let lengthString = '';
let statusString = '';
- // Each message from Rust is prefixed with `remotion_buffer:{[nonce]}:{[length]}`
- // Let's read the buffer to extract the nonce, and if the full length is available,
- // we'll extract the data and pass it to the callback.
-
// eslint-disable-next-line no-constant-condition
while (true) {
if (separatorIndex > outputBuffer.length - 1) {
@@ -37,7 +43,6 @@ export const makeStreamer = (
const nextDigit = outputBuffer[separatorIndex];
separatorIndex++;
- // 0x3a is the character ":"
if (nextDigit === 0x3a) {
break;
}
@@ -103,9 +108,9 @@ export const makeStreamer = (
processInput();
};
- const onData = (data: Buffer) => {
+ const onData = (data: Uint8Array) => {
unprocessedBuffers.push(data);
- const separatorIndex = data.indexOf(separator);
+ const separatorIndex = data.indexOf(separator[0]);
if (separatorIndex === -1) {
if (missingData) {
missingData.dataMissing -= data.length;
@@ -117,7 +122,14 @@ export const makeStreamer = (
}
unprocessedBuffers.unshift(outputBuffer);
- outputBuffer = Buffer.concat(unprocessedBuffers);
+ outputBuffer = new Uint8Array(
+ unprocessedBuffers.reduce((acc, val) => acc + val.length, 0),
+ );
+ let offset = 0;
+ for (const buf of unprocessedBuffers) {
+ outputBuffer.set(buf, offset);
+ offset += buf.length;
+ }
unprocessedBuffers = [];
processInput();
@@ -128,7 +140,7 @@ export const makeStreamer = (
getOutputBuffer: () => outputBuffer,
clear: () => {
unprocessedBuffers = [];
- outputBuffer = Buffer.from('');
+ outputBuffer = new Uint8Array(0);
},
};
};
diff --git a/packages/renderer/src/test/compositor-rust.test.ts b/packages/renderer/src/test/compositor-rust.test.ts
index 577a45f288..4e32ddffe2 100644
--- a/packages/renderer/src/test/compositor-rust.test.ts
+++ b/packages/renderer/src/test/compositor-rust.test.ts
@@ -20,7 +20,8 @@ test(
const output = await compositor.executeCommand('Echo', {
message: expectedString,
});
- const isSame = output.toString('utf8') === 'Echo ' + expectedString;
+ const isSame =
+ new TextDecoder('utf-8').decode(output) === 'Echo ' + expectedString;
return isSame;
}),
);
diff --git a/packages/renderer/src/test/extract-frame-rust.test.ts b/packages/renderer/src/test/extract-frame-rust.test.ts
index 430e54126f..3e5b08f6df 100644
--- a/packages/renderer/src/test/extract-frame-rust.test.ts
+++ b/packages/renderer/src/test/extract-frame-rust.test.ts
@@ -243,9 +243,10 @@ test(
});
const header = data.subarray(0, BMP_HEADER_SIZE);
+ const view = new DataView(header.buffer);
- const width = header.readInt32LE(18);
- const height = header.readInt32LE(22);
+ const width = view.getInt32(18, true);
+ const height = view.getInt32(22, true);
expect(width).toBe(683);
expect(height).toBe(512);
@@ -288,8 +289,10 @@ test('Should be able to extract a frame with abnormal DAR', async () => {
const header = data.subarray(0, BMP_HEADER_SIZE);
- const width = header.readInt32LE(18);
- const height = header.readInt32LE(22);
+ const view = new DataView(header.buffer);
+
+ const width = view.getInt32(18, true);
+ const height = view.getInt32(22, true);
expect(width).toBe(1280);
expect(height).toBe(2276);
@@ -543,7 +546,7 @@ test('Should handle getting a frame from a WebM when it is not transparent', asy
});
// Should resort back to BMP because it is faster
- const header = data.slice(0, 8).toString('utf8');
+ const header = new TextDecoder('utf-8').decode(data.slice(0, 8));
expect(header).toContain('BM60');
expect(data.length).toBe(2764854);
@@ -569,7 +572,7 @@ test('Should handle a video with no frames at the beginning', async () => {
});
// Should resort back to BMP because it is faster
- const header = data.slice(0, 8).toString('utf8');
+ const header = new TextDecoder('utf-8').decode(data.slice(0, 8));
expect(header).toContain('BM6');
expect(data.length).toBe(6220854);
@@ -649,7 +652,7 @@ test('Two different starting times should not result in big seeking', async () =
expect(expected[9][2] / 100).toBeCloseTo(1.07, 1);
const stats = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson = JSON.parse(stats.toString('utf-8'));
+ const statsJson = JSON.parse(new TextDecoder('utf-8').decode(stats));
expect(statsJson.open_streams).toBe(2);
expect(statsJson.open_videos).toBe(1);
diff --git a/packages/renderer/src/test/rust-get-video-metadata.test.ts b/packages/renderer/src/test/rust-get-video-metadata.test.ts
index 270094b7a6..8613243eda 100644
--- a/packages/renderer/src/test/rust-get-video-metadata.test.ts
+++ b/packages/renderer/src/test/rust-get-video-metadata.test.ts
@@ -26,7 +26,9 @@ test('Should return video metadata', async () => {
const metadataResponse = await compositor.executeCommand('GetVideoMetadata', {
src: videoFile,
});
- const metadataJson = JSON.parse(metadataResponse.toString('utf-8'));
+ const metadataJson = JSON.parse(
+ new TextDecoder('utf-8').decode(metadataResponse),
+ );
const data: VideoMetadata = {
fps: 24,
diff --git a/packages/renderer/src/test/rust-memory-usage.test.ts b/packages/renderer/src/test/rust-memory-usage.test.ts
index b23deeacf6..2aa44b91a9 100644
--- a/packages/renderer/src/test/rust-memory-usage.test.ts
+++ b/packages/renderer/src/test/rust-memory-usage.test.ts
@@ -28,7 +28,7 @@ test('Memory usage should be determined ', async () => {
});
const stats = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson = JSON.parse(stats.toString('utf-8'));
+ const statsJson = JSON.parse(new TextDecoder('utf-8').decode(stats));
expect(statsJson.frames_in_cache).toBe(84);
expect(statsJson.open_streams).toBe(1);
expect(statsJson.open_videos).toBe(1);
@@ -42,7 +42,7 @@ test('Memory usage should be determined ', async () => {
});
const stats2 = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson2 = JSON.parse(stats2.toString('utf-8'));
+ const statsJson2 = JSON.parse(new TextDecoder('utf-8').decode(stats2));
expect(
statsJson2.frames_in_cache === 185 || statsJson2.frames_in_cache === 184,
@@ -55,7 +55,7 @@ test('Memory usage should be determined ', async () => {
});
const stats3 = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson3 = JSON.parse(stats3.toString('utf-8'));
+ const statsJson3 = JSON.parse(new TextDecoder('utf-8').decode(stats3));
expect(statsJson3.frames_in_cache).toBe(184);
await compositor.executeCommand('FreeUpMemory', {
@@ -63,7 +63,7 @@ test('Memory usage should be determined ', async () => {
});
const stats4 = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson4 = JSON.parse(stats4.toString('utf-8'));
+ const statsJson4 = JSON.parse(new TextDecoder('utf-8').decode(stats4));
expect(statsJson4).toEqual({
frames_in_cache: 184,
open_streams: 2,
@@ -75,7 +75,7 @@ test('Memory usage should be determined ', async () => {
});
const stats5 = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson5 = JSON.parse(stats5.toString('utf-8'));
+ const statsJson5 = JSON.parse(new TextDecoder('utf-8').decode(stats5));
expect(statsJson5).toEqual({
frames_in_cache: 0,
open_streams: 0,
@@ -115,7 +115,7 @@ test('Should respect the maximum frame cache limit', async () => {
});
const stats = await compositor.executeCommand('GetOpenVideoStats', {});
- const statsJson = JSON.parse(stats.toString('utf-8'));
+ const statsJson = JSON.parse(new TextDecoder('utf-8').decode(stats));
expect(statsJson).toEqual({
frames_in_cache: 84,
open_streams: 1,