Skip to content

🎥 Make videos programmatically with React

Add `Webhook` and `renderId` support

njho5ba75fe42817
diff --git a/packages/cloudrun/src/api/render-media-on-cloudrun.ts b/packages/cloudrun/src/api/render-media-on-cloudrun.ts
index 60248800dd..72de622085 100644
--- a/packages/cloudrun/src/api/render-media-on-cloudrun.ts
+++ b/packages/cloudrun/src/api/render-media-on-cloudrun.ts
@@ -12,8 +12,10 @@ import type {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
+import {z} from 'zod';
import type {
CloudRunCrashResponse,
+ CloudRunPayload,
CloudRunPayloadType,
DownloadBehavior,
ErrorResponsePayload,
@@ -59,6 +61,8 @@ type InternalRenderMediaOnCloudrun = {
logLevel: LogLevel;
downloadBehavior: DownloadBehavior;
metadata?: Record<string, string> | null;
+ renderIdOverride: z.infer<typeof CloudRunPayload>['renderIdOverride'];
+ renderStatusWebhook: z.infer<typeof CloudRunPayload>['renderStatusWebhook'];
} & Partial<ToOptions<typeof BrowserSafeApis.optionsMap.renderMediaOnCloudRun>>;
export type RenderMediaOnCloudrunInput = {
@@ -72,6 +76,7 @@ export type RenderMediaOnCloudrunInput = {
forceBucketName?: string;
outName?: string;
updateRenderProgress?: (progress: number, error?: boolean) => void;
+ renderId: string | undefined;
codec: CloudrunCodec;
audioCodec?: AudioCodec;
encodingMaxRate?: string | null;
@@ -89,6 +94,8 @@ export type RenderMediaOnCloudrunInput = {
preferLossless?: boolean;
downloadBehavior?: DownloadBehavior;
metadata?: Record<string, string> | null;
+ renderIdOverride?: z.infer<typeof CloudRunPayload>['renderIdOverride'];
+ renderStatusWebhook?: z.infer<typeof CloudRunPayload>['renderStatusWebhook'];
} & Partial<ToOptions<typeof BrowserSafeApis.optionsMap.renderMediaOnCloudRun>>;
const internalRenderMediaOnCloudrunRaw = async ({
@@ -103,6 +110,8 @@ const internalRenderMediaOnCloudrunRaw = async ({
privacy,
outName,
updateRenderProgress,
+ renderIdOverride,
+ renderStatusWebhook,
jpegQuality,
audioCodec,
audioBitrate,
@@ -192,6 +201,8 @@ const internalRenderMediaOnCloudrunRaw = async ({
clientVersion: VERSION,
downloadBehavior,
metadata: metadata ?? null,
+ renderIdOverride,
+ renderStatusWebhook,
};
const client = await getAuthClientForUrl(cloudRunEndpoint);
@@ -325,6 +336,8 @@ export const renderMediaOnCloudrun = ({
colorSpace,
downloadBehavior,
metadata,
+ renderIdOverride,
+ renderStatusWebhook,
}: RenderMediaOnCloudrunInput): Promise<
RenderMediaOnCloudrunOutput | CloudRunCrashResponse
> => {
@@ -373,5 +386,7 @@ export const renderMediaOnCloudrun = ({
type: 'play-in-browser',
},
metadata: metadata ?? null,
+ renderIdOverride: renderIdOverride ?? undefined,
+ renderStatusWebhook: renderStatusWebhook ?? undefined,
});
};
diff --git a/packages/cloudrun/src/api/render-still-on-cloudrun.ts b/packages/cloudrun/src/api/render-still-on-cloudrun.ts
index 0799e6f572..2ff4cb2766 100644
--- a/packages/cloudrun/src/api/render-still-on-cloudrun.ts
+++ b/packages/cloudrun/src/api/render-still-on-cloudrun.ts
@@ -7,8 +7,10 @@ import {BrowserSafeApis} from '@remotion/renderer/client';
import {wrapWithErrorHandling} from '@remotion/renderer/error-handling';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
+import {z} from 'zod';
import type {
CloudRunCrashResponse,
+ CloudRunPayload,
CloudRunPayloadType,
DownloadBehavior,
ErrorResponsePayload,
@@ -42,6 +44,8 @@ type OptionalParameters = {
forceHeight: number | null;
indent: boolean;
downloadBehavior: DownloadBehavior;
+ renderIdOverride: z.infer<typeof CloudRunPayload>['renderIdOverride'];
+ renderStatusWebhook: z.infer<typeof CloudRunPayload>['renderStatusWebhook'];
} & ToOptions<typeof BrowserSafeApis.optionsMap.renderStillOnCloudRun>;
export type RenderStillOnCloudrunInput = Partial<OptionalParameters> &
@@ -95,6 +99,8 @@ const internalRenderStillOnCloudRun = async ({
delayRenderTimeoutInMilliseconds,
offthreadVideoCacheSizeInBytes,
downloadBehavior,
+ renderIdOverride,
+ renderStatusWebhook,
}: OptionalParameters & MandatoryParameters): Promise<
RenderStillOnCloudrunOutput | ErrorResponsePayload | CloudRunCrashResponse
> => {
@@ -136,6 +142,8 @@ const internalRenderStillOnCloudRun = async ({
offthreadVideoCacheSizeInBytes,
clientVersion: VERSION,
downloadBehavior,
+ renderIdOverride,
+ renderStatusWebhook,
};
const client = await getAuthClientForUrl(cloudRunEndpoint);
@@ -241,5 +249,7 @@ export const renderStillOnCloudrun = (options: RenderStillOnCloudrunInput) => {
serveUrl: options.serveUrl,
serviceName: options.serviceName ?? null,
downloadBehavior: options.downloadBehavior ?? {type: 'play-in-browser'},
+ renderIdOverride: options.renderIdOverride ?? undefined,
+ renderStatusWebhook: options.renderStatusWebhook ?? undefined,
});
};
diff --git a/packages/cloudrun/src/api/test/payloads.test.ts b/packages/cloudrun/src/api/test/payloads.test.ts
new file mode 100644
index 0000000000..1aebddb753
--- /dev/null
+++ b/packages/cloudrun/src/api/test/payloads.test.ts
@@ -0,0 +1,56 @@
+import {expect, test} from 'bun:test';
+import {z} from 'zod';
+import {CloudRunPayload} from '../../functions/helpers/payloads';
+
+test('CloudRunPayload should work with and without optional webhook fields', () => {
+ const basePayload = {
+ type: 'still' as const,
+ serveUrl: 'https://example.com',
+ composition: 'my-comp',
+ imageFormat: 'png' as const,
+ scale: 1,
+ privacy: 'public' as const,
+ envVariables: {},
+ outputBucket: 'my-bucket',
+ frame: 0,
+ delayRenderTimeoutInMilliseconds: 30000,
+ logLevel: 'info' as const,
+ clientVersion: '1.0.0',
+ downloadBehavior: {type: 'play-in-browser' as const},
+ outName: null,
+ offthreadVideoCacheSizeInBytes: null,
+ serializedInputPropsWithCustomSchema: JSON.stringify({}),
+ };
+
+ const withWebhook: z.infer<typeof CloudRunPayload> = {
+ ...basePayload,
+ renderIdOverride: 'custom-render-id',
+ renderStatusWebhook: {
+ url: 'https://webhook.example.com',
+ headers: {'x-custom-header': 'value'},
+ data: {key: 'value'},
+ },
+ };
+
+ const withoutWebhook = basePayload;
+
+ const parsedWithWebhook = CloudRunPayload.safeParse(withWebhook);
+ const parsedWithoutWebhook = CloudRunPayload.safeParse(withoutWebhook);
+
+ expect(parsedWithWebhook.success).toBe(true);
+ expect(parsedWithoutWebhook.success).toBe(true);
+
+ if (parsedWithWebhook.success) {
+ expect(parsedWithWebhook.data.renderIdOverride).toBe('custom-render-id');
+ expect(parsedWithWebhook.data.renderStatusWebhook).toEqual({
+ url: 'https://webhook.example.com',
+ headers: {'x-custom-header': 'value'},
+ data: {key: 'value'},
+ });
+ }
+
+ if (parsedWithoutWebhook.success) {
+ expect(parsedWithoutWebhook.data.renderIdOverride).toBeUndefined();
+ expect(parsedWithoutWebhook.data.renderStatusWebhook).toBeUndefined();
+ }
+});
diff --git a/packages/cloudrun/src/functions/helpers/payloads.ts b/packages/cloudrun/src/functions/helpers/payloads.ts
index 6d6608c934..9539ce47fb 100644
--- a/packages/cloudrun/src/functions/helpers/payloads.ts
+++ b/packages/cloudrun/src/functions/helpers/payloads.ts
@@ -69,6 +69,16 @@ export const CloudRunPayload = z.discriminatedUnion('type', [
clientVersion: z.string(),
downloadBehavior,
metadata: z.record(z.string()).optional().nullable(),
+ renderIdOverride: z.string().optional().nullable(),
+ renderStatusWebhook: z
+ .object({
+ url: z.string(),
+ headers: z.record(z.string()),
+ data: z.any(),
+ webhookProgressInterval: z.number().min(0).max(1).optional().nullable(),
+ })
+ .optional()
+ .nullable(),
}),
z.object({
type: z.literal('still'),
@@ -92,6 +102,16 @@ export const CloudRunPayload = z.discriminatedUnion('type', [
clientVersion: z.string(),
downloadBehavior,
metadata: z.record(z.string()).optional().nullable(),
+ renderIdOverride: z.string().optional().nullable(),
+ renderStatusWebhook: z
+ .object({
+ url: z.string(),
+ headers: z.record(z.string()),
+ data: z.any(),
+ webhookProgressInterval: z.number().min(0).max(1).optional().nullable(),
+ })
+ .optional()
+ .nullable(),
}),
]);
diff --git a/packages/cloudrun/src/functions/render-media-single-thread.ts b/packages/cloudrun/src/functions/render-media-single-thread.ts
index fbff2532c7..15dd5afbed 100644
--- a/packages/cloudrun/src/functions/render-media-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-media-single-thread.ts
@@ -37,7 +37,7 @@ export const renderMediaSingleThread = async (
);
}
- const renderId = randomHash({randomInTests: true});
+ const renderId = body.renderIdOverride ?? randomHash({randomInTests: true});
try {
const composition = await getCompositionFromBody(body);
@@ -47,7 +47,9 @@ export const renderMediaSingleThread = async (
body.audioCodec,
)}`;
const tempFilePath = `/tmp/${defaultOutName}`;
+
let previousProgress = 0.02;
+ let lastWebhookProgress = 0;
let writingProgress = Promise.resolve();
@@ -67,6 +69,7 @@ export const renderMediaSingleThread = async (
Math.round(progress * 100),
'%',
);
+
writingProgress = writingProgress.then(() => {
return new Promise((resolve) => {
res.write(JSON.stringify({onProgress: progress}) + '\n', () => {
@@ -74,6 +77,40 @@ export const renderMediaSingleThread = async (
});
});
});
+
+ if (body.renderStatusWebhook) {
+ const interval =
+ body.renderStatusWebhook.webhookProgressInterval ?? 0.1; // Default 10% intervals
+ const shouldCallWebhook =
+ progress === 1 || // Always call on completion
+ lastWebhookProgress === 0 || // Always call first time
+ progress - lastWebhookProgress >= interval; // Call if interval exceeded
+
+ if (shouldCallWebhook) {
+ fetch(body.renderStatusWebhook.url, {
+ method: 'POST',
+ headers: {
+ ...body.renderStatusWebhook.headers,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ ...body.renderStatusWebhook.data,
+ progress,
+ renderId,
+ renderedFrames,
+ encodedFrames,
+ }),
+ }).catch((err) => {
+ RenderInternals.Log.warn(
+ {indent: false, logLevel: body.logLevel},
+ 'Failed to call webhook:',
+ err,
+ );
+ });
+ lastWebhookProgress = progress;
+ }
+ }
+
previousProgress = progress;
}
};
diff --git a/packages/cloudrun/src/functions/render-still-single-thread.ts b/packages/cloudrun/src/functions/render-still-single-thread.ts
index 56ed83e187..aca09eb6ea 100644
--- a/packages/cloudrun/src/functions/render-still-single-thread.ts
+++ b/packages/cloudrun/src/functions/render-still-single-thread.ts
@@ -34,7 +34,7 @@ export const renderStillSingleThread = async (
);
}
- const renderId = randomHash({randomInTests: true});
+ const renderId = body.renderIdOverride ?? randomHash({randomInTests: true});
try {
Log.verbose(
diff --git a/packages/docs/docs/cloudrun/rendermediaoncloudrun.mdx b/packages/docs/docs/cloudrun/rendermediaoncloudrun.mdx
index 1db669d7da..645d9c6cc2 100644
--- a/packages/docs/docs/cloudrun/rendermediaoncloudrun.mdx
+++ b/packages/docs/docs/cloudrun/rendermediaoncloudrun.mdx
@@ -122,6 +122,55 @@ _optional_
A callback that is called with the progress of the render.
+### `renderStatusWebhook?`
+
+_optional_
+
+Your webhook URL that will be called with the progress of the render. This will be sent using a POST request.
+
+#### Arguments
+
+- `url`: The webhook URL endpoint.
+- `headers`: The headers to send. `Content-Type: application/json` is added automatically.
+- `data`: The data that you want to be sent alongside the progress data.
+- `webhookProgressInterval (optional)`: The interval at which the webhook is called. Defaults to 0.1 (10%). (min: 0.01, max: 1)
+
+
+```json title="Example Webhook URL Declaration"
+{
+ "url": "https://example.com/webhook",
+ "headers": {
+ "Authorization": "Bearer 1234567890"
+ },
+ "data": {
+ "projectId": "1234567890"
+ },
+ "webhookProgressInterval": 0.1
+}
+```
+
+#### Example Webhook Response
+
+```json title="Example Webhook Response"
+{
+ "progress": 0.1,
+ "renderedFrames": 100,
+ "encodedFrames": 100,
+ "renderId": "1234567890",
+ "projectId": "1234567890"
+}
+```
+
+### `renderIdOverride`
+
+_optional_
+
+Provide a specific render ID for the render. Otherwise a random one will be generated.
+
+:::note
+You will be responsible for ensuring that the render ID is unique, otherwise it will overwrite existing renders with the same configured Render ID.
+:::
+
### `audioCodec?`
_optional_