🎥 Make videos programmatically with React
better tests
JonnyBurger60b625f604fe
diff --git a/packages/core/src/Artifact.tsx b/packages/core/src/Artifact.tsxindex e242987ec7..b786d1da4a 100644--- a/packages/core/src/Artifact.tsx+++ b/packages/core/src/Artifact.tsx@@ -1,5 +1,5 @@import type React from 'react';-import {useContext, useEffect, useState} from 'react';+import {useContext, useLayoutEffect, useState} from 'react';import {RenderAssetManager} from './RenderAssetManager';import type {DownloadBehavior} from './download-behavior';import {useCurrentFrame} from './use-current-frame';@@ -25,7 +25,7 @@ export const Artifact: React.FC<{return String(Math.random());});- useEffect(() => {+ useLayoutEffect(() => {if (!env.isRendering) {return;}diff --git a/packages/web-renderer/src/artifact.ts b/packages/web-renderer/src/artifact.tsindex aa7e75e263..86a4158eda 100644--- a/packages/web-renderer/src/artifact.ts+++ b/packages/web-renderer/src/artifact.ts@@ -67,3 +67,53 @@ export const onlyArtifact = async ({};export type OnArtifact = (asset: EmittedArtifact) => void;+export type ArtifactsRef = React.RefObject<{+ collectAssets: () => TRenderAsset[];+} | null>;++type PreviousArtifact = {+ frame: number;+ filename: string;+};++export const handleArtifacts = ({+ ref,+ onArtifact,+}: {+ ref: ArtifactsRef;+ onArtifact: OnArtifact | null;+}) => {+ const previousArtifacts: PreviousArtifact[] = [];++ const handle = async ({+ imageData,+ frame,+ }: {+ imageData: Blob | OffscreenCanvas | null;+ frame: number;+ }) => {+ const artifactAssets = ref.current!.collectAssets();++ if (onArtifact) {+ const artifacts = await onlyArtifact({+ assets: artifactAssets,+ frameBuffer: imageData,+ });+ for (const artifact of artifacts) {+ const previousArtifact = previousArtifacts.find(+ (a) => a.filename === artifact.filename,+ );+ if (previousArtifact) {+ throw new Error(+ `An artifact with output "${artifact.filename}" was already registered at frame ${previousArtifact.frame}, but now registered again at frame ${frame}. Artifacts must have unique names. https://remotion.dev/docs/artifacts`,+ );+ }++ onArtifact(artifact);+ previousArtifacts.push({frame, filename: artifact.filename});+ }+ }+ };++ return {handle};+};diff --git a/packages/web-renderer/src/render-media-on-web.tsx b/packages/web-renderer/src/render-media-on-web.tsxindex 1c8724fe59..5241778cb3 100644--- a/packages/web-renderer/src/render-media-on-web.tsx+++ b/packages/web-renderer/src/render-media-on-web.tsx@@ -2,7 +2,7 @@ import {BufferTarget, Output, VideoSample, VideoSampleSource} from 'mediabunny';import type {CalculateMetadataFunction} from 'remotion';import {Internals, type LogLevel} from 'remotion';import type {AnyZodObject, z} from 'zod';-import {onlyArtifact, type OnArtifact} from './artifact';+import {handleArtifacts, type OnArtifact} from './artifact';import {createScaffold} from './create-scaffold';import {getRealFrameRange, type FrameRange} from './frame-range';import type {@@ -181,6 +181,11 @@ const internalRenderMediaOnWeb = async <defaultOutName: resolved.defaultOutName,});+ const artifactsHandler = handleArtifacts({+ ref: collectAssets,+ onArtifact,+ });+cleanupFns.push(() => {cleanupScaffold();});@@ -263,16 +268,7 @@ const internalRenderMediaOnWeb = async <height: resolved.height,});- const artifactAssets = collectAssets.current!.collectAssets();- if (onArtifact) {- const artifacts = await onlyArtifact({- assets: artifactAssets,- frameBuffer: imageData,- });- for (const artifact of artifacts) {- onArtifact(artifact);- }- }+ await artifactsHandler.handle({imageData, frame: i});if (signal?.aborted) {throw new Error('renderMediaOnWeb() was cancelled');diff --git a/packages/web-renderer/src/render-still-on-web.tsx b/packages/web-renderer/src/render-still-on-web.tsxindex 73b7623c16..905fb7e9c7 100644--- a/packages/web-renderer/src/render-still-on-web.tsx+++ b/packages/web-renderer/src/render-still-on-web.tsx@@ -5,7 +5,7 @@ import {} from 'remotion';import type {AnyZodObject} from 'zod';import type {OnArtifact} from './artifact';-import {onlyArtifact} from './artifact';+import {handleArtifacts} from './artifact';import {createScaffold} from './create-scaffold';import type {CompositionCalculateMetadataOrExplicit,@@ -104,6 +104,11 @@ async function internalRenderStillOnWeb<defaultOutName: resolved.defaultOutName,});+ const artifactsHandler = handleArtifacts({+ ref: collectAssets,+ onArtifact,+ });+try {if (signal?.aborted) {throw new Error('renderStillOnWeb() was cancelled');@@ -127,16 +132,7 @@ async function internalRenderStillOnWeb<imageFormat,});- const artifactAssets = collectAssets.current!.collectAssets();- if (onArtifact) {- const artifacts = await onlyArtifact({- assets: artifactAssets,- frameBuffer: imageData,- });- for (const artifact of artifacts) {- onArtifact(artifact);- }- }+ await artifactsHandler.handle({imageData, frame});return imageData;} finally {diff --git a/packages/web-renderer/src/test/artifact.test.tsx b/packages/web-renderer/src/test/artifact.test.tsxindex 949fc82adb..b46be5839b 100644--- a/packages/web-renderer/src/test/artifact.test.tsx+++ b/packages/web-renderer/src/test/artifact.test.tsx@@ -45,7 +45,7 @@ test('should fail to render multiple artifacts with the same filename', async ()const artifacts: EmittedArtifact[] = [];- await renderMediaOnWeb({+ const prom = renderMediaOnWeb({composition: {component: Component,id: 'artifact-test',@@ -59,16 +59,9 @@ test('should fail to render multiple artifacts with the same filename', async ()artifacts.push(artifact);},});-- // TODO: This should fail because too many artifacts are emitted- expect(artifacts).toEqual([- {- filename: 'test.txt',- content: 'Hello World!',- frame: 0,- downloadBehavior: null,- },- ]);+ await expect(prom).rejects.toThrow(+ 'An artifact with output "test.txt" was already registered at frame 0, but now registered again at frame 1. Artifacts must have unique names. https://remotion.dev/docs/artifacts',+ );});test.todo('should be able to emit a thumbnail');diff --git a/packages/web-renderer/src/wait-for-ready.ts b/packages/web-renderer/src/wait-for-ready.tsindex e82e0f360b..c8faaa9354 100644--- a/packages/web-renderer/src/wait-for-ready.ts+++ b/packages/web-renderer/src/wait-for-ready.ts@@ -12,17 +12,28 @@ export const waitForReady = ({signal: AbortSignal | null;apiName: 'renderMediaOnWeb' | 'renderStillOnWeb';}) => {- if (scope.remotion_renderReady === true) {- return Promise.resolve();- }-const start = Date.now();const {promise, resolve, reject} = withResolvers<void>();- const interval = setInterval(() => {+ let cancelled = false;+ // We want to wait at least for 1 frame (1 cycle)+ let frameWaited = false;++ const check = () => {+ if (cancelled) {+ return;+ }+if (signal?.aborted) {+ cancelled = true;reject(new Error(`${apiName}() was cancelled`));- clearInterval(interval);+ return;+ }++ if (!frameWaited) {+ // Ensure at least one frame has passed+ frameWaited = true;+ requestAnimationFrame(check);return;}@@ -34,19 +45,17 @@ export const waitForReady = ({resolve();});});-- clearInterval(interval);return;}if (scope.remotion_cancelledError !== undefined) {+ cancelled = true;reject(scope.remotion_cancelledError);- clearInterval(interval);return;}if (Date.now() - start > timeoutInMilliseconds + 3000) {- // TODO: Error message should be just as good+ cancelled = true;reject(new Error(Object.values(scope.remotion_delayRenderTimeouts)@@ -54,9 +63,13 @@ export const waitForReady = ({.join(', '),),);- clearInterval(interval);+ return;}- }, 50);++ requestAnimationFrame(check);+ };++ requestAnimationFrame(check);return promise;};