Skip to content

🎥 Make videos programmatically with React

more abstractions

Jonny Burger3821e955647f
diff --git a/packages/cli/src/render-flows/still.ts b/packages/cli/src/render-flows/still.ts
index 3406481e2c..83f8672532 100644
--- a/packages/cli/src/render-flows/still.ts
+++ b/packages/cli/src/render-flows/still.ts
@@ -14,6 +14,7 @@ import type {
AggregateRenderProgress,
JobProgressCallback,
} from '@remotion/studio-server';
+import type {ArtifactProgress} from '@remotion/studio-shared';
import {existsSync, mkdirSync} from 'node:fs';
import path from 'node:path';
import {NoReactInternals} from 'remotion/no-react';
@@ -27,6 +28,7 @@ import {getCompositionWithDimensionOverride} from '../get-composition-with-dimen
import {makeHyperlink} from '../hyperlinks/make-link';
import {Log} from '../log';
import {makeOnDownload} from '../make-on-download';
+import {handleOnArtifact} from '../on-artifact';
import {parsedCli, quietFlagProvided} from '../parsed-cli';
import type {OverwriteableCliOutput} from '../progress-bar';
import {
@@ -124,15 +126,13 @@ export const renderStillFlow = async ({
const updateRenderProgress = ({
newline,
printToConsole,
- isUsingParallelEncoding,
}: {
newline: boolean;
printToConsole: boolean;
- isUsingParallelEncoding: boolean;
}) => {
const {output, progress, message} = makeRenderingAndStitchingProgress({
prog: aggregate,
- isUsingParallelEncoding,
+ isUsingParallelEncoding: false,
});
if (printToConsole) {
renderProgress.update(updatesDontOverwrite ? message : output, newline);
@@ -176,7 +176,6 @@ export const renderStillFlow = async ({
updateRenderProgress({
newline: false,
printToConsole: true,
- isUsingParallelEncoding: false,
});
},
indentOutput: indent,
@@ -299,6 +298,8 @@ export const renderStillFlow = async ({
const renderStart = Date.now();
+ let artifactState: ArtifactProgress = {received: []};
+
aggregate.rendering = {
frames: 0,
doneIn: null,
@@ -309,7 +310,6 @@ export const renderStillFlow = async ({
updateRenderProgress({
newline: false,
printToConsole: true,
- isUsingParallelEncoding: false,
});
const onDownload: RenderMediaOnDownload = makeOnDownload({
@@ -321,6 +321,14 @@ export const renderStillFlow = async ({
isUsingParallelEncoding: false,
});
+ const {onArtifact} = handleOnArtifact(artifactState, (progress) => {
+ artifactState = progress;
+ updateRenderProgress({
+ newline: false,
+ printToConsole: true,
+ });
+ });
+
await RenderInternals.internalRenderStill({
composition: config,
frame: stillFrame,
@@ -352,6 +360,7 @@ export const renderStillFlow = async ({
offthreadVideoCacheSizeInBytes,
binariesDirectory,
onBrowserDownload,
+ onArtifact,
});
aggregate.rendering = {
@@ -363,7 +372,6 @@ export const renderStillFlow = async ({
updateRenderProgress({
newline: true,
printToConsole: true,
- isUsingParallelEncoding: false,
});
Log.info(
{indent, logLevel},
diff --git a/packages/cloudrun/src/functions/render-media-single-thread.ts b/packages/cloudrun/src/functions/render-media-single-thread.ts
index 625d342106..2b977ee6f7 100644
--- a/packages/cloudrun/src/functions/render-media-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-media-single-thread.ts
@@ -64,9 +64,8 @@ export const renderMediaSingleThread = async (
enableMultiProcessOnLinux: true,
};
- const onArtifact: OnArtifact = (artifact) => {
- // TODO: Do something with the artifact
- console.log(artifact);
+ const onArtifact: OnArtifact = () => {
+ throw new Error('Emitting artifacts is not supported in Cloud Run');
};
await RenderInternals.internalRenderMedia({
diff --git a/packages/cloudrun/src/functions/render-still-single-thread.ts b/packages/cloudrun/src/functions/render-still-single-thread.ts
index d822f768cb..a650953d8e 100644
--- a/packages/cloudrun/src/functions/render-still-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-still-single-thread.ts
@@ -98,6 +98,9 @@ export const renderStillSingleThread = async (
onBrowserDownload: () => {
throw new Error('Should not download a browser in Cloud Run');
},
+ onArtifact: () => {
+ throw new Error('Emitting artifacts is not supported in Cloud Run');
+ },
});
Log.info({indent: false, logLevel: body.logLevel}, 'Still rendered');
diff --git a/packages/lambda/src/functions/still.ts b/packages/lambda/src/functions/still.ts
index 6df26d9a4a..c741ed64e4 100644
--- a/packages/lambda/src/functions/still.ts
+++ b/packages/lambda/src/functions/still.ts
@@ -1,4 +1,4 @@
-import type {StillImageFormat} from '@remotion/renderer';
+import type {EmittedArtifact, StillImageFormat} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import fs from 'node:fs';
import path from 'node:path';
@@ -18,6 +18,7 @@ import type {
import {
LambdaRoutines,
MAX_EPHEMERAL_STORAGE_IN_MB,
+ artifactName,
overallProgressKey,
} from '../shared/constants';
import {convertToServeUrl} from '../shared/convert-to-serve-url';
@@ -39,6 +40,7 @@ import {getCurrentRegionInFunction} from './helpers/get-current-region';
import {getOutputUrlFromMetadata} from './helpers/get-output-url-from-metadata';
import {lambdaWriteFile} from './helpers/io';
import {onDownloadsHelper} from './helpers/on-downloads-logger';
+import type {ReceivedAsset} from './helpers/overall-render-progress';
import {makeInitialOverallRenderProgress} from './helpers/overall-render-progress';
import {validateComposition} from './helpers/validate-composition';
import type {OnStream} from './streaming/streaming';
@@ -194,6 +196,58 @@ const innerStillHandler = async ({
throw new Error('Should not download a browser in Lambda');
};
+ const receivedAssets: ReceivedAsset[] = [];
+
+ const {key, renderBucketName, customCredentials} = getExpectedOutName(
+ renderMetadata,
+ bucketName,
+ getCredentialsFromOutName(lambdaParams.outName),
+ );
+
+ const onArtifact = (artifact: EmittedArtifact): {alreadyExisted: boolean} => {
+ if (receivedAssets.find((a) => a.filename === artifact.filename)) {
+ return {alreadyExisted: true};
+ }
+
+ const s3Key = artifactName(renderMetadata.renderId, artifact.filename);
+ receivedAssets.push({
+ filename: artifact.filename,
+ sizeInBytes: artifact.content.length,
+ s3Url: `https://s3.${region}.amazonaws.com/${renderBucketName}/${s3Key}`,
+ });
+
+ const startTime = Date.now();
+ RenderInternals.Log.info(
+ {indent: false, logLevel: lambdaParams.logLevel},
+ 'Writing artifact ' + artifact.filename + ' to S3',
+ );
+ lambdaWriteFile({
+ bucketName: renderBucketName,
+ key: s3Key,
+ body: artifact.content,
+ region,
+ privacy: lambdaParams.privacy,
+ expectedBucketOwner,
+ downloadBehavior: lambdaParams.downloadBehavior,
+ customCredentials,
+ })
+ .then(() => {
+ RenderInternals.Log.info(
+ {indent: false, logLevel: lambdaParams.logLevel},
+ `Wrote artifact to S3 in ${Date.now() - startTime}ms`,
+ );
+ })
+ .catch((err) => {
+ // TODO: Handle error
+ RenderInternals.Log.error(
+ {indent: false, logLevel: lambdaParams.logLevel},
+ 'Failed to write artifact to S3',
+ err,
+ );
+ });
+ return {alreadyExisted: false};
+ };
+
await RenderInternals.internalRenderStill({
composition,
output: outputPath,
@@ -229,14 +283,9 @@ const innerStillHandler = async ({
offthreadVideoCacheSizeInBytes: lambdaParams.offthreadVideoCacheSizeInBytes,
binariesDirectory: null,
onBrowserDownload,
+ onArtifact,
});
- const {key, renderBucketName, customCredentials} = getExpectedOutName(
- renderMetadata,
- bucketName,
- getCredentialsFromOutName(lambdaParams.outName),
- );
-
const {size} = await fs.promises.stat(outputPath);
await lambdaWriteFile({
@@ -284,6 +333,7 @@ const innerStillHandler = async ({
estimatedPrice: formatCostsInfo(estimatedPrice),
renderId,
outKey,
+ receivedAssets,
};
onStream({
@@ -301,6 +351,7 @@ export type RenderStillLambdaResponsePayload = {
sizeInBytes: number;
estimatedPrice: CostsInfo;
renderId: string;
+ receivedAssets: ReceivedAsset[];
};
export const stillHandler = async (
diff --git a/packages/renderer/src/collect-assets.ts b/packages/renderer/src/collect-assets.ts
new file mode 100644
index 0000000000..334d33df73
--- /dev/null
+++ b/packages/renderer/src/collect-assets.ts
@@ -0,0 +1,41 @@
+import type {TRenderAsset} from 'remotion/no-react';
+import type {Page} from './browser/BrowserPage';
+import {puppeteerEvaluateWithCatch} from './puppeteer-evaluate';
+
+export const collectAssets = async ({
+ frame,
+ freePage,
+ timeoutInMilliseconds,
+}: {
+ frame: number;
+ freePage: Page;
+ timeoutInMilliseconds: number;
+}) => {
+ const {value} = await puppeteerEvaluateWithCatch<TRenderAsset[]>({
+ pageFunction: () => {
+ return window.remotion_collectAssets();
+ },
+ args: [],
+ frame,
+ page: freePage,
+ timeoutInMilliseconds,
+ });
+
+ const fixedArtifacts = value.map((asset) => {
+ if (asset.type !== 'artifact') {
+ return asset;
+ }
+
+ const stringOrUintArray =
+ typeof asset.content === 'string'
+ ? asset.content
+ : new Uint8Array(Object.values(asset.content));
+
+ return {
+ ...asset,
+ content: stringOrUintArray,
+ };
+ });
+
+ return fixedArtifacts;
+};
diff --git a/packages/renderer/src/render-frames.ts b/packages/renderer/src/render-frames.ts
index 5bdc261ed5..b338772df0 100644
--- a/packages/renderer/src/render-frames.ts
+++ b/packages/renderer/src/render-frames.ts
@@ -526,15 +526,7 @@ const innerRenderFrames = async ({
}
}
- const stringOrUintArray =
- typeof artifact.content === 'string'
- ? artifact.content
- : new Uint8Array(Object.values(artifact.content));
-
- onArtifact?.({
- ...artifact,
- content: stringOrUintArray,
- });
+ onArtifact?.(artifact);
}
const compressedAssets = audioAndVideoAssets.map((asset) => {
diff --git a/packages/renderer/src/render-still.ts b/packages/renderer/src/render-still.ts
index 54b8453188..14796a1ce3 100644
--- a/packages/renderer/src/render-still.ts
+++ b/packages/renderer/src/render-still.ts
@@ -17,6 +17,7 @@ import type {Compositor} from './compositor/compositor';
import {convertToPositiveFrameIndex} from './convert-to-positive-frame-index';
import {ensureOutputDirectory} from './ensure-output-directory';
import {handleJavascriptException} from './error-handling/handle-javascript-exception';
+import {onlyArtifact} from './filter-asset-types';
import {findRemotionRoot} from './find-closest-package-json';
import type {StillImageFormat} from './image-format';
import {
@@ -34,6 +35,7 @@ import {DEFAULT_OVERWRITE} from './overwrite';
import type {RemotionServer} from './prepare-server';
import {makeOrReuseServer} from './prepare-server';
import {puppeteerEvaluateWithCatch} from './puppeteer-evaluate';
+import type {OnArtifact} from './render-frames';
import {seekToFrame} from './seek-to-frame';
import {setPropsAndEnv} from './set-props-and-env';
import {takeFrameAndCompose} from './take-frame-and-compose';
@@ -68,6 +70,7 @@ type InternalRenderStillOptions = {
serveUrl: string;
port: number | null;
offthreadVideoCacheSizeInBytes: number | null;
+ onArtifact: OnArtifact | null;
} & ToOptions<typeof optionsMap.renderStill>;
export type RenderStillOptions = {
@@ -99,6 +102,7 @@ export type RenderStillOptions = {
* @deprecated Renamed to `jpegQuality`
*/
quality?: never;
+ onArtifact?: OnArtifact;
} & Partial<ToOptions<typeof optionsMap.renderStill>>;
type CleanupFn = () => Promise<unknown>;
@@ -130,6 +134,7 @@ const innerRenderStill = async ({
indent,
serializedResolvedPropsWithCustomSchema,
onBrowserDownload,
+ onArtifact,
}: InternalRenderStillOptions & {
downloadMap: DownloadMap;
serveUrl: string;
@@ -316,7 +321,7 @@ const innerRenderStill = async ({
attempt: 0,
});
- const {buffer} = await takeFrameAndCompose({
+ const {buffer, collectedAssets} = await takeFrameAndCompose({
frame: stillFrame,
freePage: page,
height: composition.height,
@@ -331,6 +336,23 @@ const innerRenderStill = async ({
timeoutInMilliseconds,
});
+ const artifactAssets = onlyArtifact(collectedAssets);
+ const previousArtifactAssets = [];
+
+ for (const artifact of artifactAssets) {
+ for (const previousArtifact of previousArtifactAssets) {
+ if (artifact.filename === previousArtifact.filename) {
+ throw new Error(
+ `An artifact with output "${artifact.filename}" was already registered at frame ${previousArtifact.frame}, but now registered again at frame ${artifact.frame}. An artifact`,
+ );
+ }
+ }
+
+ previousArtifactAssets.push(artifact);
+
+ onArtifact?.(artifact);
+ }
+
await cleanup();
return {buffer: output ? null : buffer};
@@ -443,6 +465,7 @@ export const renderStill = (
logLevel: passedLogLevel,
binariesDirectory,
onBrowserDownload,
+ onArtifact,
} = options;
if (typeof jpegQuality !== 'undefined' && imageFormat !== 'jpeg') {
@@ -499,5 +522,6 @@ export const renderStill = (
onBrowserDownload:
onBrowserDownload ??
defaultBrowserDownloadProgress({indent, logLevel, api: 'renderStill()'}),
+ onArtifact: onArtifact ?? null,
});
};
diff --git a/packages/renderer/src/take-frame-and-compose.ts b/packages/renderer/src/take-frame-and-compose.ts
index 6324d63dfd..8f47880a9e 100644
--- a/packages/renderer/src/take-frame-and-compose.ts
+++ b/packages/renderer/src/take-frame-and-compose.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import type {ClipRegion, TRenderAsset} from 'remotion/no-react';
import type {DownloadMap} from './assets/download-map';
import type {Page} from './browser/BrowserPage';
+import {collectAssets} from './collect-assets';
import {compose} from './compositor/compose';
import type {Compositor} from './compositor/compositor';
import type {StillImageFormat, VideoImageFormat} from './image-format';
@@ -37,7 +38,7 @@ export const takeFrameAndCompose = async ({
compositor: Compositor;
timeoutInMilliseconds: number;
}): Promise<{buffer: Buffer | null; collectedAssets: TRenderAsset[]}> => {
- const [{value: clipRegion}, {value: collectedAssets}] = await Promise.all([
+ const [{value: clipRegion}, collectedAssets] = await Promise.all([
puppeteerEvaluateWithCatch<ClipRegion | null>({
pageFunction: () => {
if (typeof window.remotion_getClipRegion === 'undefined') {
@@ -51,15 +52,7 @@ export const takeFrameAndCompose = async ({
page: freePage,
timeoutInMilliseconds,
}),
- puppeteerEvaluateWithCatch<TRenderAsset[]>({
- pageFunction: () => {
- return window.remotion_collectAssets();
- },
- args: [],
- frame,
- page: freePage,
- timeoutInMilliseconds,
- }),
+ collectAssets({frame, freePage, timeoutInMilliseconds}),
]);
if (imageFormat === 'none') {