/
render-media-on-cloudrun.ts
397 lines (373 loc) · 13.2 KB
/
render-media-on-cloudrun.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import type {
AudioCodec,
ChromiumOptions,
FrameRange,
LogLevel,
PixelFormat,
ProResProfile,
ToOptions,
VideoImageFormat,
} from '@remotion/renderer';
import type {BrowserSafeApis} from '@remotion/renderer/client';
import {NoReactAPIs} from '@remotion/renderer/pure';
import {NoReactInternals} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
import type {
CloudRunCrashResponse,
CloudRunPayloadType,
ErrorResponsePayload,
RenderMediaOnCloudrunOutput,
} from '../functions/helpers/payloads';
import type {GcpRegion} from '../pricing/gcp-regions';
import type {CloudrunCodec} from '../shared/validate-gcp-codec';
import {validateCloudrunCodec} from '../shared/validate-gcp-codec';
import {validatePrivacy} from '../shared/validate-privacy';
import {validateServeUrl} from '../shared/validate-serveurl';
import {getOrCreateBucket} from './get-or-create-bucket';
import {getAuthClientForUrl} from './helpers/get-auth-client-for-url';
import {getCloudrunEndpoint} from './helpers/get-cloudrun-endpoint';
type InternalRenderMediaOnCloudrun = {
cloudRunUrl: string | undefined;
serviceName: string | undefined;
region: GcpRegion;
serveUrl: string;
composition: string;
inputProps: Record<string, unknown>;
privacy: 'public' | 'private' | undefined;
forceBucketName: string | undefined;
outName: string | undefined;
updateRenderProgress:
| ((progress: number, error?: boolean) => void)
| undefined;
codec: CloudrunCodec;
audioCodec: AudioCodec | undefined;
jpegQuality: number | undefined;
proResProfile: ProResProfile | undefined;
pixelFormat: PixelFormat | undefined;
imageFormat: VideoImageFormat | undefined;
everyNthFrame: number | undefined;
frameRange: FrameRange | undefined;
envVariables: Record<string, string> | undefined;
chromiumOptions: ChromiumOptions | undefined;
forceWidth: number | null;
forceHeight?: number | null;
concurrency: number | string | null;
preferLossless: boolean | undefined;
indent: boolean;
logLevel: LogLevel;
} & Partial<ToOptions<typeof BrowserSafeApis.optionsMap.renderMediaOnCloudRun>>;
export type RenderMediaOnCloudrunInput = {
cloudRunUrl?: string;
serviceName?: string;
region: GcpRegion;
serveUrl: string;
composition: string;
inputProps?: Record<string, unknown>;
privacy?: 'public' | 'private';
forceBucketName?: string;
outName?: string;
updateRenderProgress?: (progress: number, error?: boolean) => void;
codec: CloudrunCodec;
audioCodec?: AudioCodec;
encodingMaxRate?: string | null;
encodingBufferSize?: string | null;
proResProfile?: ProResProfile;
pixelFormat?: PixelFormat;
imageFormat?: VideoImageFormat;
everyNthFrame?: number;
frameRange?: FrameRange;
envVariables?: Record<string, string>;
chromiumOptions?: ChromiumOptions;
forceWidth?: number | null;
forceHeight?: number | null;
concurrency?: number | string | null;
preferLossless?: boolean;
} & Partial<ToOptions<typeof BrowserSafeApis.optionsMap.renderMediaOnCloudRun>>;
const internalRenderMediaOnCloudrunRaw = async ({
cloudRunUrl,
serviceName,
region,
serveUrl,
composition,
inputProps,
codec,
forceBucketName,
privacy,
outName,
updateRenderProgress,
jpegQuality,
audioCodec,
audioBitrate,
videoBitrate,
encodingMaxRate,
encodingBufferSize,
proResProfile,
x264Preset,
crf,
pixelFormat,
imageFormat,
scale,
everyNthFrame,
numberOfGifLoops,
frameRange,
envVariables,
chromiumOptions,
muted,
forceWidth,
forceHeight,
logLevel,
delayRenderTimeoutInMilliseconds,
concurrency,
enforceAudioTrack,
preferLossless,
offthreadVideoCacheSizeInBytes,
colorSpace,
}: InternalRenderMediaOnCloudrun): Promise<
RenderMediaOnCloudrunOutput | CloudRunCrashResponse
> => {
const actualCodec = validateCloudrunCodec(codec);
validateServeUrl(serveUrl);
if (privacy) validatePrivacy(privacy);
const outputBucket =
forceBucketName ?? (await getOrCreateBucket({region})).bucketName;
const cloudRunEndpoint = await getCloudrunEndpoint({
cloudRunUrl,
serviceName,
region,
});
const data: CloudRunPayloadType = {
composition,
serveUrl,
codec: actualCodec,
serializedInputPropsWithCustomSchema:
NoReactInternals.serializeJSONWithDate({
indent: undefined,
staticBase: null,
data: inputProps ?? {},
}).serializedString,
jpegQuality: jpegQuality ?? null,
audioCodec: audioCodec ?? null,
audioBitrate: audioBitrate ?? null,
videoBitrate: videoBitrate ?? null,
encodingBufferSize: encodingBufferSize ?? null,
encodingMaxRate: encodingMaxRate ?? null,
crf: crf ?? null,
pixelFormat: pixelFormat ?? null,
imageFormat: imageFormat ?? null,
scale: scale ?? 1,
proResProfile: proResProfile ?? null,
x264Preset: x264Preset ?? null,
everyNthFrame: everyNthFrame ?? 1,
numberOfGifLoops: numberOfGifLoops ?? null,
frameRange: frameRange ?? null,
envVariables: envVariables ?? {},
chromiumOptions,
muted: muted ?? false,
outputBucket,
privacy,
outName,
forceWidth,
forceHeight,
type: 'media',
logLevel: logLevel ?? 'info',
delayRenderTimeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? null,
concurrency: concurrency ?? null,
enforceAudioTrack: enforceAudioTrack ?? false,
preferLossless: preferLossless ?? false,
offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? null,
colorSpace: colorSpace ?? null,
clientVersion: VERSION,
};
const client = await getAuthClientForUrl(cloudRunEndpoint);
const postResponse = await client.request({
url: cloudRunEndpoint,
method: 'POST',
data,
responseType: 'stream',
});
const renderResponse = await new Promise<
RenderMediaOnCloudrunOutput | CloudRunCrashResponse
>((resolve, reject) => {
// TODO: Add any sort of type safety
let response:
| RenderMediaOnCloudrunOutput
| ErrorResponsePayload
| CloudRunCrashResponse;
const startTime = Date.now();
const formattedStartTime = new Date().toISOString();
const stream: any = postResponse.data;
let accumulatedChunks = ''; // A buffer to accumulate chunks.
stream.on('data', (chunk: Buffer) => {
accumulatedChunks += chunk.toString(); // Add the new chunk to the buffer.
let parsedData;
try {
parsedData = JSON.parse(accumulatedChunks.trim());
accumulatedChunks = ''; // Clear the buffer after successful parsing.
} catch (e) {
// If parsing fails, it means we don't have a complete JSON string yet.
// We'll wait for more chunks.
return;
}
if (parsedData.response) {
response = parsedData.response;
} else if (parsedData.onProgress) {
updateRenderProgress?.(parsedData.onProgress);
}
if (parsedData.type === 'error') {
reject(parsedData);
}
});
stream.on('end', () => {
if (!response) {
const crashTime = Date.now();
const formattedCrashTime = new Date().toISOString();
updateRenderProgress?.(0, true);
resolve({
type: 'crash',
cloudRunEndpoint,
message:
'Service crashed without sending a response. Check the logs in GCP console.',
requestStartTime: formattedStartTime,
requestCrashTime: formattedCrashTime,
requestElapsedTimeInSeconds: (crashTime - startTime) / 1000,
});
} else if (response.type !== 'success' && response.type !== 'crash') {
throw response;
}
resolve(response);
});
stream.on('error', (error: Error) => {
reject(error);
});
});
return renderResponse;
};
export const internalRenderMediaOnCloudrun = NoReactAPIs.wrapWithErrorHandling(
internalRenderMediaOnCloudrunRaw,
) as typeof internalRenderMediaOnCloudrunRaw;
/**
* @description Triggers a render on a GCP Cloud Run service given a composition and a Cloud Run URL.
* @see [Documentation](https://remotion.dev/docs/cloudrun/renderMediaOnGcp)
* @param params.cloudRunUrl The URL of the Cloud Run service that should be used. Use either this or serviceName.
* @param params.serviceName The name of the Cloud Run service that should be used. Use either this or cloudRunUrl.
* @param params.region The region that the Cloud Run service is deployed in.
* @param params.serveUrl The URL of the deployed project
* @param params.composition The ID of the composition which should be rendered.
* @param params.inputProps The input props that should be passed to the composition.
* @param params.codec The media codec which should be used for encoding.
* @param params.forceBucketName The name of the bucket that the output file should be uploaded to.
* @param params.privacy Whether the output file should be public or private.
* @param params.outName The name of the output file.
* @param params.updateRenderProgress A callback that is called with the progress of the render.
* @param params.jpegQuality JPEG quality if JPEG was selected as the image format.
* @param params.audioCodec The encoding of the audio of the output video.
* @param params.audioBitrate The target bitrate for the audio of the generated video.
* @param params.videoBitrate The target bitrate of the generated video.
* @param params.encodingBufferSize The decoder buffer size, which determines the variability of the generated video bitrate.
* @param params.encodingMaxRate The maximum bitrate tolerance to be used, this is only used in conjunction with encodingBufferSize.
* @param params.proResProfile Sets a ProRes profile. Only applies to videos rendered with prores codec.
* @param params.x264Preset Sets a Preset profile. Only applies to videos rendered with h.264 codec.
* @param params.crf Constant Rate Factor, controlling the quality.
* @param params.pixelFormat Custom pixel format to use. Usually used for special use cases like transparent videos.
* @param params.imageFormat Which image format the frames should be rendered in.
* @param params.scale Scales the output dimensions by a factor.
* @param params.everyNthFrame Only used if rendering gigs - renders only every nth frame.
* @param params.numberOfGifLoops Only used if rendering gigs - how many times the gif should loop. Null means infinite.
* @param params.frameRange Specify a single frame (a number) or a range of frames (a tuple [number, number]) to be rendered.
* @param params.envVariables Object containing environment variables to be injected in your project.
* @param params.chromiumOptions Allows you to set certain Chromium / Google Chrome flags.
* @param params.muted If set to true, no audio is rendered.
* @param params.forceWidth Overrides default composition width.
* @param params.forceHeight Overrides default composition height.
* @param params.logLevel Level of logging that Cloud Run service should perform. Default "info".
* @param params.delayRenderTimeoutInMilliseconds A number describing how long the render may take to resolve all delayRender() calls before it times out.
* @param params.concurrency A number or a string describing how many browser tabs should be opened. Default "50%".
* @param params.enforceAudioTrack Render a silent audio track if there wouldn't be any otherwise.
* @param params.preferLossless Uses a lossless audio codec, if one is available for the codec. If you set audioCodec, it takes priority over preferLossless.
* @returns {Promise<RenderMediaOnCloudrunOutput>} See documentation for detailed structure
*/
export const renderMediaOnCloudrun = ({
cloudRunUrl,
serviceName,
region,
serveUrl,
composition,
inputProps,
codec,
forceBucketName,
privacy,
outName,
updateRenderProgress,
jpegQuality,
audioCodec,
audioBitrate,
videoBitrate,
encodingMaxRate,
encodingBufferSize,
proResProfile,
x264Preset,
crf,
pixelFormat,
imageFormat,
scale,
everyNthFrame,
numberOfGifLoops,
frameRange,
envVariables,
chromiumOptions,
muted,
forceWidth,
forceHeight,
logLevel,
delayRenderTimeoutInMilliseconds,
concurrency,
enforceAudioTrack,
preferLossless,
offthreadVideoCacheSizeInBytes,
colorSpace,
}: RenderMediaOnCloudrunInput): Promise<
RenderMediaOnCloudrunOutput | CloudRunCrashResponse
> => {
return internalRenderMediaOnCloudrun({
cloudRunUrl: cloudRunUrl ?? undefined,
serviceName: serviceName ?? undefined,
region,
serveUrl,
composition,
inputProps: inputProps ?? {},
codec,
forceBucketName: forceBucketName ?? undefined,
privacy: privacy ?? undefined,
outName: outName ?? undefined,
updateRenderProgress: updateRenderProgress ?? undefined,
jpegQuality: jpegQuality ?? undefined,
audioCodec: audioCodec ?? undefined,
audioBitrate: audioBitrate ?? null,
videoBitrate: videoBitrate ?? null,
encodingMaxRate: encodingMaxRate ?? null,
encodingBufferSize: encodingBufferSize ?? null,
proResProfile: proResProfile ?? undefined,
x264Preset: x264Preset ?? undefined,
crf: crf ?? undefined,
pixelFormat: pixelFormat ?? undefined,
imageFormat: imageFormat ?? undefined,
scale: scale ?? undefined,
everyNthFrame: everyNthFrame ?? undefined,
numberOfGifLoops: numberOfGifLoops ?? null,
frameRange: frameRange ?? undefined,
envVariables: envVariables ?? undefined,
chromiumOptions: chromiumOptions ?? undefined,
muted: muted ?? undefined,
forceWidth: forceWidth ?? null,
forceHeight: forceHeight ?? null,
logLevel: logLevel ?? 'info',
delayRenderTimeoutInMilliseconds:
delayRenderTimeoutInMilliseconds ?? undefined,
concurrency: concurrency ?? null,
enforceAudioTrack: enforceAudioTrack ?? undefined,
preferLossless: preferLossless ?? undefined,
offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? undefined,
colorSpace: colorSpace ?? undefined,
indent: false,
});
};