@open-take/compositor 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,929 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, realpathSync, statSync } from "node:fs";
3
+ import {
4
+ mkdir,
5
+ mkdtemp,
6
+ readdir,
7
+ readFile,
8
+ rename,
9
+ rm,
10
+ symlink,
11
+ unlink,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import { createRequire } from "node:module";
15
+ import { tmpdir } from "node:os";
16
+ import { basename, dirname, extname, join, resolve, sep } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { renderVideo } from "@open-take/revideo-renderer";
19
+ import { repairBundledMediaPermissions, resolveFfmpeg, resolveFfprobe } from "./ffmpeg";
20
+ import { launchAudioAtS, launchDurationS } from "./launch-evaluate";
21
+ import type { LaunchAudioTrack, LaunchComposition, LaunchIssue } from "./launch-types";
22
+ import { formatLaunchIssues, validateLaunchComposition } from "./launch-validate";
23
+ import { walkMotionLayers } from "./motion-evaluate";
24
+ import type { MotionImageLayer, MotionLayer, MotionScene, MotionVideoLayer } from "./motion-types";
25
+ import { withRenderLock } from "./render-lock";
26
+
27
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
28
+
29
+ export type RenderLaunchOpts = {
30
+ composition: LaunchComposition;
31
+ compositionPath: string;
32
+ outPath: string;
33
+ chromePath: string;
34
+ draft?: boolean;
35
+ logProgress?: boolean;
36
+ onProgress?: (progress: number) => void;
37
+ };
38
+ export type RenderLaunchResult = { mp4Path: string; durationS: number; warnings: LaunchIssue[] };
39
+
40
+ /** Media subprocesses must not hang or retain unbounded corrupt-file diagnostics. */
41
+ async function run(
42
+ bin: string,
43
+ args: string[],
44
+ capture = false,
45
+ timeoutMs = 120_000,
46
+ ): Promise<string> {
47
+ return new Promise((ok, fail) => {
48
+ const child = spawn(bin, args, { stdio: ["ignore", capture ? "pipe" : "ignore", "pipe"] });
49
+ let out = "",
50
+ err = "",
51
+ settled = false;
52
+ const finish = (error?: Error) => {
53
+ if (settled) return;
54
+ settled = true;
55
+ clearTimeout(timer);
56
+ if (error) fail(error);
57
+ else ok(out);
58
+ };
59
+ const timer = setTimeout(() => {
60
+ child.kill("SIGKILL");
61
+ finish(new Error(`${basename(bin)} exceeded the ${timeoutMs / 1000}s media-operation limit`));
62
+ }, timeoutMs);
63
+ child.stdout?.on("data", (data: Buffer) => {
64
+ out += data.toString();
65
+ if (out.length > 1_000_000) {
66
+ child.kill("SIGKILL");
67
+ finish(new Error(`${basename(bin)} exceeded the media-output limit`));
68
+ }
69
+ });
70
+ child.stderr?.on("data", (data: Buffer) => {
71
+ err = (err + data.toString()).slice(-12000);
72
+ });
73
+ child.on("error", (error) => finish(error));
74
+ child.on("close", (code) =>
75
+ finish(code === 0 ? undefined : new Error(`${basename(bin)} exited ${code}: ${err.trim()}`)),
76
+ );
77
+ });
78
+ }
79
+
80
+ type MediaInfo = {
81
+ duration: number;
82
+ video: boolean;
83
+ audio: boolean;
84
+ videoDuration: number;
85
+ audioDuration: number;
86
+ width: number;
87
+ height: number;
88
+ };
89
+ async function probeMedia(path: string): Promise<MediaInfo> {
90
+ try {
91
+ const raw = await run(
92
+ await resolveFfprobe(),
93
+ [
94
+ "-v",
95
+ "error",
96
+ "-show_entries",
97
+ "format=duration:stream=codec_type,duration,width,height",
98
+ "-of",
99
+ "json",
100
+ path,
101
+ ],
102
+ true,
103
+ );
104
+ const data = JSON.parse(raw) as {
105
+ format?: { duration?: string };
106
+ streams?: { codec_type?: string; duration?: string; width?: number; height?: number }[];
107
+ };
108
+ const duration = Number(data.format?.duration);
109
+ if (!Number.isFinite(duration) || duration <= 0)
110
+ throw new Error("media has no finite positive duration");
111
+ const video = data.streams?.find((x) => x.codec_type === "video"),
112
+ audio = data.streams?.find((x) => x.codec_type === "audio");
113
+ const streamDuration = (stream: typeof video) => {
114
+ const n = Number(stream?.duration);
115
+ return Number.isFinite(n) && n > 0 ? n : duration;
116
+ };
117
+ return {
118
+ duration,
119
+ video: !!video,
120
+ audio: !!audio,
121
+ videoDuration: streamDuration(video),
122
+ audioDuration: streamDuration(audio),
123
+ width: video?.width ?? 0,
124
+ height: video?.height ?? 0,
125
+ };
126
+ } catch (error) {
127
+ throw new Error(
128
+ `could not probe ${path}: ${error instanceof Error ? error.message : String(error)}`,
129
+ );
130
+ }
131
+ }
132
+
133
+ type ImageInfo = { width: number; height: number };
134
+ const imageInputOptions = [
135
+ "-max_alloc",
136
+ "268435456",
137
+ "-protocol_whitelist",
138
+ "file,pipe",
139
+ "-format_whitelist",
140
+ "image2,png_pipe,jpeg_pipe,webp_pipe",
141
+ ];
142
+ async function probeMotionImage(path: string): Promise<ImageInfo> {
143
+ if (statSync(path).size > 64 * 1024 * 1024)
144
+ throw new Error("image exceeds the 64 MiB source-file limit");
145
+ const raw = await run(
146
+ await resolveFfprobe(),
147
+ [
148
+ "-v",
149
+ "error",
150
+ ...imageInputOptions,
151
+ "-show_entries",
152
+ "stream=codec_name,codec_type,width,height",
153
+ "-of",
154
+ "json",
155
+ path,
156
+ ],
157
+ true,
158
+ 30_000,
159
+ );
160
+ const data = JSON.parse(raw) as {
161
+ streams?: { codec_name?: string; codec_type?: string; width?: number; height?: number }[];
162
+ };
163
+ const stream = data.streams?.[0];
164
+ if (
165
+ data.streams?.length !== 1 ||
166
+ stream?.codec_type !== "video" ||
167
+ !["png", "mjpeg", "webp"].includes(stream.codec_name ?? "")
168
+ )
169
+ throw new Error("asset must decode as a single PNG, JPEG or WebP image");
170
+ const width = stream.width ?? 0,
171
+ height = stream.height ?? 0;
172
+ if (
173
+ !Number.isInteger(width) ||
174
+ !Number.isInteger(height) ||
175
+ width < 1 ||
176
+ height < 1 ||
177
+ width > 16384 ||
178
+ height > 16384 ||
179
+ width * height > 32_000_000
180
+ )
181
+ throw new Error(
182
+ "image dimensions must be positive, at most 16384px per side and at most 32 megapixels",
183
+ );
184
+ // Probing headers alone accepts truncated images. Decode a real frame before rendering.
185
+ await run(
186
+ await resolveFfmpeg(),
187
+ [
188
+ "-v",
189
+ "error",
190
+ "-xerror",
191
+ ...imageInputOptions,
192
+ "-i",
193
+ path,
194
+ "-frames:v",
195
+ "1",
196
+ "-f",
197
+ "null",
198
+ "-",
199
+ ],
200
+ false,
201
+ 30_000,
202
+ );
203
+ return { width, height };
204
+ }
205
+ function cropError(layer: MotionImageLayer, image: ImageInfo): string | undefined {
206
+ const crop = layer.crop;
207
+ if (crop && (crop.x + crop.width > image.width || crop.y + crop.height > image.height))
208
+ return `crop must stay inside the ${image.width}x${image.height} source image`;
209
+ return undefined;
210
+ }
211
+ function motionMedia(comp: LaunchComposition) {
212
+ const media: {
213
+ layer: MotionImageLayer | MotionVideoLayer;
214
+ path: string;
215
+ scene: MotionScene;
216
+ parents: MotionLayer[];
217
+ }[] = [];
218
+ const visit = (
219
+ layers: MotionLayer[],
220
+ prefix: string,
221
+ scene: MotionScene,
222
+ parents: MotionLayer[],
223
+ ) => {
224
+ layers.forEach((layer, i) => {
225
+ const path = `${prefix}[${i}]`;
226
+ if (layer.type === "image" || layer.type === "video")
227
+ media.push({ layer, path, scene, parents });
228
+ else if (layer.type === "group")
229
+ visit(layer.children, `${path}.children`, scene, [...parents, layer]);
230
+ });
231
+ };
232
+ comp.scenes.forEach((scene, i) => {
233
+ if (scene.type === "motion") visit(scene.layers, `scenes[${i}].layers`, scene, []);
234
+ });
235
+ return media;
236
+ }
237
+
238
+ function motionImages(comp: LaunchComposition) {
239
+ return motionMedia(comp).filter(
240
+ (item): item is typeof item & { layer: MotionImageLayer } => item.layer.type === "image",
241
+ );
242
+ }
243
+
244
+ /** Largest pixel stretch. Static matrix products are exact; animated extrema form
245
+ * a conservative bound because each supported easing stays between its keyframes. */
246
+ function mediaStretch(
247
+ item: ReturnType<typeof motionMedia>[number],
248
+ output: LaunchComposition["output"],
249
+ source: ImageInfo,
250
+ ) {
251
+ const { layer, parents, scene } = item;
252
+ const max = (node: MotionLayer, property: string, fallback: number) => {
253
+ const track =
254
+ scene.motion !== "off" ? node.animations?.find((t) => t.property === property) : undefined;
255
+ return track
256
+ ? Math.max(...track.keyframes.map((f) => Number(f.value)))
257
+ : Number((node as unknown as Record<string, unknown>)[property] ?? fallback);
258
+ };
259
+ const chain = [...parents, layer];
260
+ const animated =
261
+ scene.motion !== "off" &&
262
+ chain.some((node) =>
263
+ node.animations?.some((t) =>
264
+ ["scaleX", "scaleY", "rotation", "width", "height"].includes(t.property),
265
+ ),
266
+ );
267
+ let stretch = 1;
268
+ if (animated) {
269
+ for (const node of chain) stretch *= Math.max(max(node, "scaleX", 1), max(node, "scaleY", 1));
270
+ } else {
271
+ let a = 1,
272
+ b = 0,
273
+ c = 0,
274
+ d = 1;
275
+ for (const node of chain) {
276
+ const angle = ((node.rotation ?? 0) * Math.PI) / 180,
277
+ cos = Math.cos(angle),
278
+ sin = Math.sin(angle),
279
+ sx = node.scaleX ?? 1,
280
+ sy = node.scaleY ?? 1;
281
+ [a, b, c, d] = [
282
+ (a * cos + c * sin) * sx,
283
+ (b * cos + d * sin) * sx,
284
+ (-a * sin + c * cos) * sy,
285
+ (-b * sin + d * cos) * sy,
286
+ ];
287
+ }
288
+ const sum = a * a + b * b + c * c + d * d,
289
+ determinant = a * d - b * c;
290
+ stretch = Math.sqrt(
291
+ (sum + Math.sqrt(Math.max(0, sum * sum - 4 * determinant * determinant))) / 2,
292
+ );
293
+ }
294
+ const design = scene.designSize ?? { width: 1920, height: 1080 };
295
+ const fit = layer.fit === "cover" ? Math.max : Math.min;
296
+ const factor =
297
+ fit(
298
+ max(layer, "width", layer.width) / source.width,
299
+ max(layer, "height", layer.height) / source.height,
300
+ ) *
301
+ stretch *
302
+ Math.min(output.width / design.width, output.height / design.height);
303
+ return { factor, animated };
304
+ }
305
+
306
+ function warnEnlargement(
307
+ issues: LaunchIssue[],
308
+ path: string,
309
+ source: ImageInfo,
310
+ factor: number,
311
+ animated = false,
312
+ ) {
313
+ // Subpixel fitting/rounding below 1% is not a meaningful density loss.
314
+ if (factor <= 1.01 || !Number.isFinite(factor)) return;
315
+ issues.push({
316
+ severity: "warn",
317
+ path,
318
+ message: `Asset enlargement ${factor.toFixed(2)}x: ${source.width}x${source.height} source pixels ${animated ? "may be enlarged under conservative animation bounds" : "are enlarged at the authored size"}. Capture/export a higher-resolution source (at least ${Math.ceil(source.width * factor)}x${Math.ceil(source.height * factor)} for this footprint), reduce the displayed size, or choose a tighter source with enough pixels. Encoding bitrate cannot restore missing detail.`,
319
+ });
320
+ }
321
+
322
+ /** Internal preparation seam: call only on a validated clone, never authored composition data. */
323
+ export async function prepareMotionImages(
324
+ comp: LaunchComposition,
325
+ compositionPath: string,
326
+ assetsDir: string,
327
+ ): Promise<void> {
328
+ const base = dirname(resolve(compositionPath)),
329
+ cache = new Map<string, string>();
330
+ const ffmpeg = await resolveFfmpeg();
331
+ let count = 0;
332
+ for (const { layer } of motionImages(comp)) {
333
+ const source = resolve(base, layer.asset),
334
+ key = JSON.stringify([realpathSync(source), layer.crop]);
335
+ let asset = cache.get(key);
336
+ if (!asset) {
337
+ const info = await probeMotionImage(source),
338
+ invalidCrop = cropError(layer, info);
339
+ if (invalidCrop) throw new Error(invalidCrop);
340
+ const name = `motion-image-${count++}.png`,
341
+ crop = layer.crop;
342
+ const filters = [
343
+ crop ? `crop=w=${crop.width}:h=${crop.height}:x=${crop.x}:y=${crop.y}:exact=1` : "null",
344
+ "format=rgba",
345
+ ];
346
+ await run(
347
+ ffmpeg,
348
+ [
349
+ "-y",
350
+ "-v",
351
+ "error",
352
+ "-xerror",
353
+ ...imageInputOptions,
354
+ "-i",
355
+ source,
356
+ "-vf",
357
+ filters.join(","),
358
+ "-frames:v",
359
+ "1",
360
+ "-update",
361
+ "1",
362
+ join(assetsDir, name),
363
+ ],
364
+ false,
365
+ 30_000,
366
+ );
367
+ asset = `/assets/${name}`;
368
+ cache.set(key, asset);
369
+ }
370
+ layer.asset = asset;
371
+ delete layer.crop;
372
+ }
373
+ }
374
+
375
+ export async function validateLaunchAssets(
376
+ value: unknown,
377
+ compositionPath: string,
378
+ ): Promise<LaunchIssue[]> {
379
+ const base = dirname(resolve(compositionPath));
380
+ const issues = validateLaunchComposition(value, base);
381
+ if (issues.some((x) => x.severity === "error")) return issues;
382
+ const comp = value as LaunchComposition;
383
+ const probes = new Map<string, Promise<MediaInfo>>();
384
+ const inspect = async (
385
+ asset: string,
386
+ path: string,
387
+ kind: "video" | "audio",
388
+ trim: number,
389
+ duration: number,
390
+ loop = false,
391
+ ) => {
392
+ const full = resolve(base, asset);
393
+ let pending = probes.get(full);
394
+ if (!pending) {
395
+ pending = probeMedia(full);
396
+ probes.set(full, pending);
397
+ }
398
+ try {
399
+ const got = await pending;
400
+ if (!got[kind]) {
401
+ issues.push({ severity: "error", path, message: `asset has no ${kind} stream` });
402
+ return;
403
+ }
404
+ const available = kind === "video" ? got.videoDuration : got.audioDuration;
405
+ if (trim >= available || (!loop && trim + duration > available + 0.001))
406
+ issues.push({
407
+ severity: "error",
408
+ path,
409
+ message: `needs ${loop ? `a trim before ${trim.toFixed(3)}s` : `${(trim + duration).toFixed(3)}s`} but ${kind} media is ${available.toFixed(3)}s`,
410
+ });
411
+ return got;
412
+ } catch (error) {
413
+ issues.push({
414
+ severity: "error",
415
+ path,
416
+ message: error instanceof Error ? error.message : String(error),
417
+ });
418
+ }
419
+ };
420
+ for (const [i, scene] of comp.scenes.entries())
421
+ if (scene.type === "footage") {
422
+ const info = await inspect(
423
+ scene.asset,
424
+ `scenes[${i}].asset`,
425
+ "video",
426
+ scene.trimStartS ?? 0,
427
+ scene.durationS,
428
+ );
429
+ if (info?.width && info.height) {
430
+ const inset =
431
+ (scene.frame?.inset ?? 86) *
432
+ Math.min(comp.output.width / 1920, comp.output.height / 1080);
433
+ const fit = scene.fit === "cover" ? Math.max : Math.min;
434
+ warnEnlargement(
435
+ issues,
436
+ `scenes[${i}].asset`,
437
+ info,
438
+ fit(
439
+ (comp.output.width - 2 * inset) / info.width,
440
+ (comp.output.height - 2 * inset) / info.height,
441
+ ),
442
+ );
443
+ }
444
+ }
445
+ for (const [i, track] of (comp.audio ?? []).entries())
446
+ await inspect(
447
+ track.asset,
448
+ `audio[${i}].asset`,
449
+ "audio",
450
+ track.trimStartS ?? 0,
451
+ track.durationS ?? launchDurationS(comp) - launchAudioAtS(comp, track),
452
+ !!track.loop,
453
+ );
454
+ const imageProbes = new Map<string, Promise<ImageInfo>>();
455
+ for (const item of motionMedia(comp)) {
456
+ const { layer, path } = item;
457
+ if (layer.type === "video") {
458
+ const info = await inspect(
459
+ layer.asset,
460
+ `${path}.asset`,
461
+ "video",
462
+ layer.trimStartS ?? 0,
463
+ layer.durationS,
464
+ );
465
+ if (info?.width && info.height) {
466
+ const { factor, animated } = mediaStretch(item, comp.output, info);
467
+ warnEnlargement(issues, `${path}.asset`, info, factor, animated);
468
+ }
469
+ continue;
470
+ }
471
+ const source = resolve(base, layer.asset);
472
+ let pending = imageProbes.get(source);
473
+ if (!pending) {
474
+ pending = probeMotionImage(source);
475
+ imageProbes.set(source, pending);
476
+ }
477
+ try {
478
+ const image = await pending,
479
+ invalid = cropError(layer, image);
480
+ if (invalid) issues.push({ severity: "error", path: `${path}.crop`, message: invalid });
481
+ else {
482
+ const source = layer.crop ?? image;
483
+ const { factor, animated } = mediaStretch(item, comp.output, source);
484
+ warnEnlargement(issues, `${path}.asset`, source, factor, animated);
485
+ }
486
+ } catch (error) {
487
+ issues.push({
488
+ severity: "error",
489
+ path: `${path}.asset`,
490
+ message: `could not decode image: ${error instanceof Error ? error.message : String(error)}`,
491
+ });
492
+ }
493
+ }
494
+ return issues;
495
+ }
496
+
497
+ /** Internal preparation seam: lossless VP9 is decoded by the scene's explicit
498
+ * HTMLVideoElement (slow) decoder. Color conversion and fitting happen once;
499
+ * the codec adds no quantization before the final delivery encode. */
500
+ export async function prepareLaunchVideo(
501
+ source: string,
502
+ target: string,
503
+ opts: {
504
+ trimStartS: number;
505
+ durationS: number;
506
+ fps: number;
507
+ frame?: { width: number; height: number; fit: "contain" | "cover" };
508
+ },
509
+ ): Promise<void> {
510
+ const { frame } = opts;
511
+ const color = "flags=lanczos:out_range=tv:out_color_matrix=bt709";
512
+ const scale = frame
513
+ ? frame.fit === "cover"
514
+ ? `scale=${frame.width}:${frame.height}:force_original_aspect_ratio=increase:${color},crop=${frame.width}:${frame.height}`
515
+ : `scale=${frame.width}:${frame.height}:force_original_aspect_ratio=decrease:${color},pad=${frame.width}:${frame.height}:(ow-iw)/2:(oh-ih)/2:color=#0b1714`
516
+ : `scale=trunc(iw/2)*2:trunc(ih/2)*2:${color}`;
517
+ // Lossless high-density video preparation can exceed the shorter probe limit
518
+ // on a busy machine. Keep a separate, bounded ten-minute transcode deadline.
519
+ await run(
520
+ await resolveFfmpeg(),
521
+ [
522
+ "-y",
523
+ "-loglevel",
524
+ "error",
525
+ "-ss",
526
+ String(opts.trimStartS),
527
+ "-i",
528
+ source,
529
+ "-t",
530
+ String(opts.durationS + 1 / opts.fps),
531
+ "-map",
532
+ "0:v:0",
533
+ "-vf",
534
+ `${scale},setsar=1,format=yuv420p,setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709,tpad=stop_mode=clone:stop_duration=${1 / opts.fps}`,
535
+ "-c:v",
536
+ "libvpx-vp9",
537
+ "-lossless",
538
+ "1",
539
+ "-b:v",
540
+ "0",
541
+ "-cpu-used",
542
+ "4",
543
+ "-row-mt",
544
+ "1",
545
+ "-g",
546
+ String(Math.ceil(opts.fps)),
547
+ "-pix_fmt",
548
+ "yuv420p",
549
+ "-r",
550
+ String(opts.fps),
551
+ "-an",
552
+ target,
553
+ ],
554
+ false,
555
+ 600_000,
556
+ );
557
+ }
558
+
559
+ /** Trim each nested video independently; authored scene timing stays unchanged. */
560
+ export async function prepareMotionVideos(
561
+ comp: LaunchComposition,
562
+ compositionPath: string,
563
+ assetsDir: string,
564
+ ): Promise<void> {
565
+ let count = 0;
566
+ for (const { layer } of motionMedia(comp)) {
567
+ if (layer.type !== "video") continue;
568
+ const name = `motion-video-${count++}.webm`;
569
+ await prepareLaunchVideo(
570
+ resolve(dirname(resolve(compositionPath)), layer.asset),
571
+ join(assetsDir, name),
572
+ {
573
+ trimStartS: layer.trimStartS ?? 0,
574
+ durationS: layer.durationS,
575
+ fps: comp.output.fps,
576
+ },
577
+ );
578
+ layer.asset = `/assets/${name}`;
579
+ layer.trimStartS = 0;
580
+ }
581
+ }
582
+
583
+ function hostNodeModules(): string | null {
584
+ let dir = PKG_ROOT;
585
+ for (;;) {
586
+ const p = join(dir, "node_modules");
587
+ if (existsSync(p)) return p;
588
+ const up = dirname(dir);
589
+ if (up === dir) return null;
590
+ dir = up;
591
+ }
592
+ }
593
+ function depsRoot(): string | null {
594
+ try {
595
+ const parts = realpathSync(createRequire(import.meta.url).resolve("@revideo/core")).split(sep);
596
+ const i = parts.indexOf("node_modules");
597
+ return i < 0 ? null : parts.slice(0, i + 1).join(sep);
598
+ } catch {
599
+ return null;
600
+ }
601
+ }
602
+ async function copyWritable(from: string, to: string): Promise<void> {
603
+ await mkdir(to, { recursive: true });
604
+ for (const e of await readdir(from, { withFileTypes: true })) {
605
+ const a = join(from, e.name),
606
+ b = join(to, e.name);
607
+ if (e.isDirectory()) await copyWritable(a, b);
608
+ else if (e.isFile()) await writeFile(b, await readFile(a));
609
+ }
610
+ }
611
+ async function cleanup(dir: string): Promise<void> {
612
+ await unlink(join(dir, "node_modules")).catch(() => {});
613
+ if (process.env.OPEN_TAKE_KEEP_SCRATCH)
614
+ process.stderr.write(`launch render scratch kept: ${dir}\n`);
615
+ else await rm(dir, { recursive: true, force: true });
616
+ }
617
+
618
+ async function prepare(
619
+ comp: LaunchComposition,
620
+ compositionPath: string,
621
+ draft: boolean,
622
+ ): Promise<{ dir: string; rendered: LaunchComposition }> {
623
+ const dir = await mkdtemp(join(tmpdir(), "open-take-launch-"));
624
+ const base = dirname(resolve(compositionPath));
625
+ try {
626
+ await copyWritable(join(PKG_ROOT, "src"), join(dir, "src"));
627
+ await mkdir(join(dir, "public", "assets"), { recursive: true });
628
+ const nm = hostNodeModules();
629
+ if (!nm) throw new Error("launch render: could not locate node_modules");
630
+ await symlink(nm, join(dir, "node_modules"), "junction");
631
+ const draftScale = Math.min(1, 960 / Math.max(comp.output.width, comp.output.height));
632
+ const even = (value: number) => Math.max(2, Math.round(value / 2) * 2);
633
+ const output = draft
634
+ ? {
635
+ width: even(comp.output.width * draftScale),
636
+ height: even(comp.output.height * draftScale),
637
+ fps: Math.min(30, comp.output.fps),
638
+ }
639
+ : comp.output;
640
+ const rendered: LaunchComposition = structuredClone(comp);
641
+ rendered.output = output;
642
+ let n = 0;
643
+ for (const scene of rendered.scenes)
644
+ if (scene.type === "footage") {
645
+ // Keep each scene's media span and decoder resource independent.
646
+ // Decode only the authored span, never an hours-long source outside the film.
647
+ const name = `footage-${n++}.webm`;
648
+ const scale = Math.min(output.width / 1920, output.height / 1080);
649
+ const inset = (scene.frame?.inset ?? 86) * scale;
650
+ const width = even(output.width - inset * 2),
651
+ height = even(output.height - inset * 2);
652
+ const fit = scene.fit ?? "contain";
653
+ await prepareLaunchVideo(resolve(base, scene.asset), join(dir, "public", "assets", name), {
654
+ trimStartS: scene.trimStartS ?? 0,
655
+ durationS: scene.durationS,
656
+ fps: output.fps,
657
+ frame: { width, height, fit },
658
+ });
659
+ scene.asset = `/assets/${name}`;
660
+ scene.trimStartS = 0;
661
+ }
662
+ await prepareMotionImages(rendered, compositionPath, join(dir, "public", "assets"));
663
+ await prepareMotionVideos(rendered, compositionPath, join(dir, "public", "assets"));
664
+ await writeFile(
665
+ join(dir, "src", "scene", ".launch-composition.json"),
666
+ JSON.stringify(rendered, null, 2),
667
+ );
668
+ return { dir, rendered };
669
+ } catch (error) {
670
+ await cleanup(dir);
671
+ throw error;
672
+ }
673
+ }
674
+
675
+ function fadeFilter(
676
+ track: LaunchAudioTrack,
677
+ index: number,
678
+ at: number,
679
+ total: number,
680
+ duck: [number, number][],
681
+ loopSamples?: number,
682
+ ): string {
683
+ const trim = track.trimStartS ?? 0,
684
+ duration = track.durationS ?? Math.max(0, total - at);
685
+ const parts = [
686
+ `[${index + 1}:a]aresample=48000,atrim=start=${trim}:duration=${duration}`,
687
+ "asetpts=PTS-STARTPTS",
688
+ ];
689
+ if (loopSamples !== undefined)
690
+ parts.push(
691
+ `aloop=loop=-1:size=${loopSamples}`,
692
+ `atrim=duration=${duration}`,
693
+ "asetpts=PTS-STARTPTS",
694
+ );
695
+ let volume = String(track.gain ?? 1);
696
+ if (track.kind === "music" && duck.length) {
697
+ const expr = duck
698
+ .filter(([a, b]) => b > at && a < at + duration)
699
+ .map(([a, b]) => `between(t,${Math.max(0, a - at)},${Math.min(duration, b - at)})`)
700
+ .join("+");
701
+ if (expr) volume = `(${volume})*if(${expr},0.34,1)`;
702
+ }
703
+ parts.push(`volume='${volume}':eval=frame`);
704
+ if ((track.fadeInS ?? 0) > 0) parts.push(`afade=t=in:st=0:d=${track.fadeInS}`);
705
+ if ((track.fadeOutS ?? 0) > 0)
706
+ parts.push(
707
+ `afade=t=out:st=${Math.max(0, duration - (track.fadeOutS ?? 0))}:d=${track.fadeOutS}`,
708
+ );
709
+ parts.push(`adelay=${Math.round(at * 48000)}S:all=1`, `apad=whole_dur=${total}`);
710
+ return `${parts.join(",")}[a${index}]`;
711
+ }
712
+
713
+ export async function deliverLaunchMedia(
714
+ raw: string,
715
+ target: string,
716
+ comp: LaunchComposition,
717
+ compositionPath: string,
718
+ ): Promise<void> {
719
+ const ffmpeg = await resolveFfmpeg(),
720
+ base = dirname(resolve(compositionPath)),
721
+ total = launchDurationS(comp),
722
+ tracks = comp.audio ?? [];
723
+ const rawMedia = await probeMedia(raw);
724
+ if (!rawMedia.video) throw new Error("launch render: renderer output has no video stream");
725
+ const frameDuration = 1 / comp.output.fps;
726
+ // Revideo can round its final frame; a larger discrepancy means lost or extra content.
727
+ if (Math.abs(rawMedia.videoDuration - total) > frameDuration + 0.001) {
728
+ throw new Error(
729
+ `launch render: renderer produced ${rawMedia.videoDuration.toFixed(6)}s of video for an authored ${total.toFixed(6)}s film; only one output frame (${frameDuration.toFixed(6)}s) of rounding is allowed. Re-render the complete composition before delivery.`,
730
+ );
731
+ }
732
+ const videoFilter = `tpad=stop_mode=clone:stop_duration=${frameDuration},scale=in_color_matrix=bt601:out_color_matrix=bt709,format=yuv420p,setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709`;
733
+ const args = ["-y", "-loglevel", "error", "-i", raw];
734
+ const loopSamples: (number | undefined)[] = [];
735
+ for (const track of tracks) {
736
+ const source = resolve(base, track.asset);
737
+ const duration = track.durationS ?? total - launchAudioAtS(comp, track);
738
+ args.push("-t", String((track.trimStartS ?? 0) + duration), "-i", source);
739
+ if (track.loop) {
740
+ const media = await probeMedia(source);
741
+ loopSamples.push(
742
+ Math.max(
743
+ 1,
744
+ Math.round(Math.min(duration, media.audioDuration - (track.trimStartS ?? 0)) * 48000),
745
+ ),
746
+ );
747
+ } else loopSamples.push(undefined);
748
+ }
749
+ if (!tracks.length) {
750
+ args.push(
751
+ "-vf",
752
+ videoFilter,
753
+ "-c:v",
754
+ "libx264",
755
+ "-crf",
756
+ "18",
757
+ "-pix_fmt",
758
+ "yuv420p",
759
+ "-movflags",
760
+ "+faststart",
761
+ "-an",
762
+ "-t",
763
+ String(total),
764
+ target,
765
+ );
766
+ await run(ffmpeg, args);
767
+ return;
768
+ }
769
+ const duck = tracks
770
+ .filter((x) => x.kind === "narration" && x.duckMusic)
771
+ .map((x): [number, number] => {
772
+ const at = launchAudioAtS(comp, x);
773
+ return [at, at + (x.durationS ?? Math.max(0, total - at))];
774
+ });
775
+ const filters = tracks.map((x, i) =>
776
+ fadeFilter(x, i, launchAudioAtS(comp, x), total, duck, loopSamples[i]),
777
+ );
778
+ filters.push(
779
+ `${tracks.map((_, i) => `[a${i}]`).join("")}amix=inputs=${tracks.length}:duration=longest:normalize=0,atrim=duration=${total}[mix]`,
780
+ );
781
+ args.push(
782
+ "-filter_complex",
783
+ filters.join(";"),
784
+ "-map",
785
+ "0:v:0",
786
+ "-map",
787
+ "[mix]",
788
+ "-vf",
789
+ videoFilter,
790
+ "-c:v",
791
+ "libx264",
792
+ "-crf",
793
+ "18",
794
+ "-pix_fmt",
795
+ "yuv420p",
796
+ "-c:a",
797
+ "aac",
798
+ "-b:a",
799
+ "192k",
800
+ "-movflags",
801
+ "+faststart",
802
+ "-t",
803
+ String(total),
804
+ target,
805
+ );
806
+ await run(ffmpeg, args);
807
+ }
808
+
809
+ /** Stage beside the destination so failed encoding never replaces a good master. */
810
+ export async function publishLaunchMedia(
811
+ raw: string,
812
+ target: string,
813
+ comp: LaunchComposition,
814
+ compositionPath: string,
815
+ ): Promise<void> {
816
+ const stageDir = await mkdtemp(
817
+ join(dirname(target), `.open-take-launch-${basename(target, extname(target))}-`),
818
+ );
819
+ try {
820
+ const staged = join(stageDir, "delivery.mp4");
821
+ await deliverLaunchMedia(raw, staged, comp, compositionPath);
822
+ await rename(staged, target);
823
+ } finally {
824
+ await rm(stageDir, { recursive: true, force: true });
825
+ }
826
+ }
827
+
828
+ /** Internal filesystem preflight, shared by rendering and focused regression tests. */
829
+ export function assertLaunchOutputSafe(
830
+ comp: LaunchComposition,
831
+ compositionPath: string,
832
+ outPath: string,
833
+ ): void {
834
+ const out = resolve(outPath),
835
+ base = dirname(resolve(compositionPath));
836
+ const canonical = (path: string): string => {
837
+ if (existsSync(path)) return realpathSync(path);
838
+ const parent = dirname(path);
839
+ return parent === path ? path : join(canonical(parent), basename(path));
840
+ };
841
+ const forbidden = [
842
+ resolve(compositionPath),
843
+ ...comp.scenes.filter((x) => x.type === "footage").map((x) => resolve(base, x.asset)),
844
+ ...(comp.audio ?? []).map((x) => resolve(base, x.asset)),
845
+ ...comp.scenes.flatMap((scene) =>
846
+ scene.type === "motion"
847
+ ? walkMotionLayers(scene.layers)
848
+ .filter((layer) => layer.type === "image" || layer.type === "video")
849
+ .map((layer) => resolve(base, layer.asset))
850
+ : [],
851
+ ),
852
+ ];
853
+ const target = canonical(out),
854
+ outStat = existsSync(out) ? statSync(out) : undefined;
855
+ for (const source of forbidden) {
856
+ const sourceStat = existsSync(source) ? statSync(source) : undefined;
857
+ if (
858
+ canonical(source) === target ||
859
+ (outStat && sourceStat && outStat.dev === sourceStat.dev && outStat.ino === sourceStat.ino)
860
+ )
861
+ throw new Error("launch render: output must not overwrite the JSON or a required asset");
862
+ }
863
+ }
864
+
865
+ export async function renderLaunch(opts: RenderLaunchOpts): Promise<RenderLaunchResult> {
866
+ return withRenderLock(() => renderExclusive(opts));
867
+ }
868
+ async function renderExclusive(opts: RenderLaunchOpts): Promise<RenderLaunchResult> {
869
+ if (!opts.chromePath) throw new Error("renderLaunch: chromePath is required");
870
+ const issues = await validateLaunchAssets(opts.composition, opts.compositionPath);
871
+ const errors = issues.filter((x) => x.severity === "error");
872
+ if (errors.length)
873
+ throw new Error(
874
+ `launch composition has ${errors.length} error(s):\n${formatLaunchIssues(errors)}`,
875
+ );
876
+ const out = resolve(opts.outPath);
877
+ await mkdir(dirname(out), { recursive: true });
878
+ assertLaunchOutputSafe(opts.composition, opts.compositionPath, out);
879
+ await repairBundledMediaPermissions();
880
+ const { dir, rendered } = await prepare(opts.composition, opts.compositionPath, !!opts.draft);
881
+ const deps = depsRoot();
882
+ const prev = process.cwd();
883
+ try {
884
+ process.chdir(dir);
885
+ const produced = await renderVideo({
886
+ projectFile: "/src/scene/launch-project.ts",
887
+ settings: {
888
+ outFile: "launch.mov",
889
+ outDir: "out-render",
890
+ workers: 1,
891
+ projectSettings: {
892
+ // Revideo exports both range endpoints; cap the last frame explicitly
893
+ // instead of including its extra scene-completion frames.
894
+ range: [
895
+ 0,
896
+ Math.max(
897
+ 0,
898
+ (Math.ceil(launchDurationS(rendered) * rendered.output.fps - 1e-9) - 1) /
899
+ rendered.output.fps,
900
+ ),
901
+ ],
902
+ exporter: { name: "@revideo/core/ffmpeg", options: { format: "proRes" } },
903
+ },
904
+ logProgress: opts.logProgress ?? false,
905
+ progressCallback: (_w: number, p: number) => opts.onProgress?.(p),
906
+ viteConfig: { server: { fs: { allow: [dir, ...(deps ? [deps] : [])] } } },
907
+ puppeteer: {
908
+ args: [
909
+ "--no-sandbox",
910
+ "--disable-setuid-sandbox",
911
+ "--password-store=basic",
912
+ "--use-mock-keychain",
913
+ ],
914
+ executablePath: opts.chromePath,
915
+ },
916
+ },
917
+ });
918
+ process.chdir(prev);
919
+ await publishLaunchMedia(resolve(dir, produced), out, rendered, opts.compositionPath);
920
+ return {
921
+ mp4Path: out,
922
+ durationS: launchDurationS(rendered),
923
+ warnings: issues.filter((x) => x.severity === "warn"),
924
+ };
925
+ } finally {
926
+ process.chdir(prev);
927
+ await cleanup(dir);
928
+ }
929
+ }