🎥 Make videos programmatically with React
progress
Jonny Burgercf613bea48d2
diff --git a/packages/lambda/src/functions/streaming/streaming.ts b/packages/lambda/src/functions/streaming/streaming.tsindex 076a11dc1e..a3b0ba76b6 100644--- a/packages/lambda/src/functions/streaming/streaming.ts+++ b/packages/lambda/src/functions/streaming/streaming.ts@@ -15,7 +15,7 @@ const messageTypes = {} as const;type MessageTypeId = keyof typeof messageTypes;-type MessageType = (typeof messageTypes)[MessageTypeId]['type'];+export type MessageType = (typeof messageTypes)[MessageTypeId]['type'];export const formatMap: {[key in MessageType]: 'json' | 'binary'} = {[framesRendered]: 'json',@@ -83,7 +83,7 @@ export const messageTypeToMessageId = (return id;};-type StreamingMessage = {+export type StreamingMessage = {successType: 'error' | 'success';message: StreamingPayload;};@@ -92,144 +92,6 @@ export type OnMessage = (options: StreamingMessage) => void;const magicSeparator = Buffer.from('remotion_buffer:');-const parseJsonOrThrowSource = (data: Buffer, type: string) => {- const asString = data.toString('utf-8');- try {- return JSON.parse(asString);- } catch (err) {- throw new Error(`Invalid JSON (${type}): ${asString}`);- }-};--export const makeStreaming = (options: {onMessage: OnMessage}) => {- let outputBuffer = Buffer.from('');-- let unprocessedBuffers: Buffer[] = [];-- let missingData: null | {- dataMissing: number;- } = null;-- const processInput = () => {- let separatorIndex = outputBuffer.indexOf(magicSeparator);- if (separatorIndex === -1) {- return;- }-- separatorIndex += magicSeparator.length;-- let messageTypeString = '';- let lengthString = '';- let statusString = '';-- // Each message has the structure with `remotion_buffer:{[message_type_id]}:{[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) {- const nextDigit = outputBuffer[separatorIndex];- // 0x3a is the character ":"- if (nextDigit === 0x3a) {- separatorIndex++;- break;- }-- separatorIndex++;-- messageTypeString += String.fromCharCode(nextDigit);- }-- // eslint-disable-next-line no-constant-condition- while (true) {- const nextDigit = outputBuffer[separatorIndex];- if (nextDigit === 0x3a) {- separatorIndex++;- break;- }-- separatorIndex++;-- lengthString += String.fromCharCode(nextDigit);- }-- // eslint-disable-next-line no-constant-condition- while (true) {- const nextDigit = outputBuffer[separatorIndex];- if (nextDigit === 0x3a) {- break;- }-- separatorIndex++;-- statusString += String.fromCharCode(nextDigit);- }-- const length = Number(lengthString);- const status = Number(statusString);-- const dataLength = outputBuffer.length - separatorIndex - 1;- if (dataLength < length) {- missingData = {- dataMissing: length - dataLength,- };-- return;- }-- const data = outputBuffer.subarray(- separatorIndex + 1,- separatorIndex + 1 + Number(lengthString),- );- const messageType = messageTypeIdToMessage(- messageTypeString as MessageTypeId,- );-- const innerPayload =- formatMap[messageType] === 'json'- ? parseJsonOrThrowSource(data, messageType)- : data;-- const payload: StreamingPayload = {- type: messageType,- payload: innerPayload,- };-- options.onMessage({- successType: status === 1 ? 'error' : 'success',- message: payload,- });- missingData = null;-- outputBuffer = outputBuffer.subarray(- separatorIndex + Number(lengthString) + 1,- );- processInput();- };-- return {- addData: (data: Buffer) => {- unprocessedBuffers.push(data);- const separatorIndex = data.indexOf(magicSeparator);- if (separatorIndex === -1) {- if (missingData) {- missingData.dataMissing -= data.length;- }-- if (!missingData || missingData.dataMissing > 0) {- return;- }- }-- unprocessedBuffers.unshift(outputBuffer);-- outputBuffer = Buffer.concat(unprocessedBuffers);- unprocessedBuffers = [];- processInput();- },- };-};-export const makePayloadMessage = ({message,status,diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.tsindex 6dd19d59bc..ec5a239fd5 100644--- a/packages/lambda/src/shared/call-lambda.ts+++ b/packages/lambda/src/shared/call-lambda.ts@@ -1,8 +1,12 @@/* eslint-disable @typescript-eslint/no-use-before-define */import type {InvokeWithResponseStreamResponseEvent} from '@aws-sdk/client-lambda';import {InvokeWithResponseStreamCommand} from '@aws-sdk/client-lambda';-import type {OnMessage} from '../functions/streaming/streaming';-import {makeStreaming} from '../functions/streaming/streaming';+import {RenderInternals} from '@remotion/renderer';+import type {+ MessageType,+ StreamingMessage,+} from '../functions/streaming/streaming';+import {formatMap, type OnMessage} from '../functions/streaming/streaming';import type {AwsRegion} from '../pricing/aws-regions';import {getLambdaClient} from './aws-clients';import type {LambdaPayloads, LambdaRoutines} from './constants';@@ -35,6 +39,15 @@ const parseJsonWithErrorSurfacing = ({}};+const parseJsonOrThrowSource = (data: Uint8Array, type: string) => {+ const asString = new TextDecoder('utf-8').decode(data);+ try {+ return JSON.parse(asString);+ } catch (err) {+ throw new Error(`Invalid JSON (${type}): ${asString}`);+ }+};+const parseJson = <T extends LambdaRoutines>({input,type,@@ -132,15 +145,28 @@ const callLambdaWithoutRetry = async <T extends LambdaRoutines>({let responseJson: Record<string, unknown> | null = null;- const {addData} = makeStreaming({- onMessage: (message) => {+ const {onData, clear} = RenderInternals.makeStreamer(+ (status, messageType, data) => {+ const innerPayload =+ formatMap[messageType as MessageType] === 'json'+ ? parseJsonOrThrowSource(data, messageType)+ : data;++ const message: StreamingMessage = {+ successType: status,+ message: {+ type: messageType as MessageType,+ payload: innerPayload,+ },+ };+if (message.message.type === 'response-json') {responseJson = message.message.payload;} else {onMessage(message);}},- });+ );const events =res.EventStream as AsyncIterable<InvokeWithResponseStreamResponseEvent>;@@ -152,7 +178,7 @@ const callLambdaWithoutRetry = async <T extends LambdaRoutines>({// `PayloadChunk`: These contain the actual raw bytes of the chunk// It has a single property: `Payload`if (event.PayloadChunk && event.PayloadChunk.Payload) {- addData(Buffer.from(event.PayloadChunk.Payload));+ onData(event.PayloadChunk.Payload);// Decode the raw bytes into a string a human can readconst decoded = new TextDecoder('utf-8').decode(event.PayloadChunk.Payload,@@ -185,5 +211,6 @@ const callLambdaWithoutRetry = async <T extends LambdaRoutines>({const json = parseJson<T>({input: responsePayload.trim(), type});+ clear();return json;};diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex d30ac4b6e7..48bf737dfd 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -145,6 +145,7 @@ 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';@@ -239,6 +240,7 @@ export const RenderInternals = {codecSupportsMedia,toMegabytes,internalEnsureBrowser,+ makeStreamer,};// Warn of potential performance issues with Apple Silicon (M1 chip under Rosetta)