@open-take/compositor 0.4.0 → 0.4.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-take/compositor",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Polish compositor (D3) — event log + captured frames -> polished mp4 + editable revideo composition.",
5
5
  "license": "MIT",
6
6
  "funding": "https://ko-fi.com/pascal18663",
@@ -23,7 +23,7 @@
23
23
  "@revideo/core": "0.11.0",
24
24
  "@revideo/ui": "0.11.0",
25
25
  "@revideo/vite-plugin": "0.11.0",
26
- "@open-take/revideo-renderer": "0.4.0"
26
+ "@open-take/revideo-renderer": "0.4.2"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/node": "^22.10.1",
@@ -0,0 +1,35 @@
1
+ // The decode guard's shared vocabulary — imported by BOTH sides of the
2
+ // browser/Node boundary. The scene (src/scene/scene.tsx, vite-compiled inside
3
+ // the render browser) probes the capture with a throwaway <video> and rejects
4
+ // with a message built here; render.ts (Node) recognises that rejection and
5
+ // retries with a VP9 intermediate. Only the message STRING survives the
6
+ // crossing — revideo forwards e.message through onRenderFailed — so the
7
+ // contract is a sentinel substring, not an error class.
8
+ //
9
+ // Keep this module dependency-free: the scene tree is copied verbatim into
10
+ // the render scratch and compiled for the browser, so a node:* import here
11
+ // would break the scene build.
12
+
13
+ export const CAPTURE_UNDECODABLE_MARK = "capture video is not decodable in the render browser";
14
+
15
+ /** Build the guard's rejection message. Both variants START with the mark so
16
+ * isCaptureUndecodable can match the forwarded string. */
17
+ export function buildUndecodableMessage(
18
+ kind: "media-error" | "timeout",
19
+ detail: string,
20
+ src: string,
21
+ ): string {
22
+ const why =
23
+ kind === "media-error"
24
+ ? `decode failed (${detail}) — this Chromium likely lacks the capture's codec`
25
+ : `no decode within 30s (${detail}) — the render browser may lack the capture's codec`;
26
+ return `${CAPTURE_UNDECODABLE_MARK}: ${why}; src=${src}`;
27
+ }
28
+
29
+ /** Did this render rejection come from the scene's decode guard? Substring
30
+ * match on the message — the Error identity does not survive the
31
+ * browser→Node crossing. */
32
+ export function isCaptureUndecodable(err: unknown): boolean {
33
+ const message = err instanceof Error ? err.message : String(err);
34
+ return message.includes(CAPTURE_UNDECODABLE_MARK);
35
+ }
package/src/ffmpeg.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // @revideo/ffmpeg — so the fallback costs consumers no extra download). Throw
6
6
  // with an install hint only when neither exists.
7
7
 
8
- import { spawnSync } from "node:child_process";
8
+ import { spawn, spawnSync } from "node:child_process";
9
9
  import { chmod, stat } from "node:fs/promises";
10
10
 
11
11
  let cachedFfmpeg: string | undefined;
@@ -69,6 +69,46 @@ export async function resolveFfmpeg(): Promise<string> {
69
69
  );
70
70
  }
71
71
 
72
+ /** True when an `ffmpeg -encoders` table has a video-encoder ROW named
73
+ * `encoder` (" V....D libx264 ..."), not merely the name as a substring
74
+ * somewhere — descriptions repeat encoder names constantly. */
75
+ export function parseEncoders(encodersText: string, encoder: string): boolean {
76
+ const escaped = encoder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
77
+ return new RegExp(`^\\s*V\\S{5}\\s+${escaped}(?:\\s|$)`, "m").test(encodersText);
78
+ }
79
+
80
+ const encoderCache = new Map<string, Promise<boolean>>();
81
+
82
+ /** True when the RESOLVED ffmpeg (resolveFfmpeg — which may be a system
83
+ * binary lacking libvpx-vp9) offers the named video encoder. Cached per
84
+ * name; any failure is false, never a throw. */
85
+ export function ffmpegHasEncoder(name: string): Promise<boolean> {
86
+ let cached = encoderCache.get(name);
87
+ if (!cached) {
88
+ cached = hasEncoderOnce(name).catch(() => false);
89
+ encoderCache.set(name, cached);
90
+ }
91
+ return cached;
92
+ }
93
+
94
+ async function hasEncoderOnce(name: string): Promise<boolean> {
95
+ const ffmpeg = await resolveFfmpeg();
96
+ const text = await new Promise<string>((res, rej) => {
97
+ const child = spawn(ffmpeg, ["-hide_banner", "-encoders"], {
98
+ stdio: ["ignore", "pipe", "ignore"],
99
+ });
100
+ let out = "";
101
+ child.stdout.on("data", (d) => {
102
+ out += d;
103
+ });
104
+ child.on("error", rej);
105
+ child.on("close", (code) =>
106
+ code === 0 ? res(out) : rej(new Error(`ffmpeg -encoders exited ${code}`)),
107
+ );
108
+ });
109
+ return parseEncoders(text, name);
110
+ }
111
+
72
112
  export async function resolveFfprobe(): Promise<string> {
73
113
  if (cachedFfprobe) return cachedFfprobe;
74
114
  if (runsOk("ffprobe")) {
package/src/render.ts CHANGED
@@ -30,7 +30,8 @@ import { tmpdir } from "node:os";
30
30
  import { dirname, join, resolve, sep } from "node:path";
31
31
  import { fileURLToPath } from "node:url";
32
32
  import { renderVideo } from "@open-take/revideo-renderer";
33
- import { repairBundledMediaPermissions, resolveFfmpeg } from "./ffmpeg";
33
+ import { isCaptureUndecodable } from "./decode-guard";
34
+ import { ffmpegHasEncoder, repairBundledMediaPermissions, resolveFfmpeg } from "./ffmpeg";
34
35
  import { type PlanOpts, planComposition } from "./plan";
35
36
  import {
36
37
  type CaptureLog,
@@ -110,21 +111,37 @@ function run(cmd: string, args: string[]): Promise<void> {
110
111
 
111
112
  /** Normalise the capture to a constant-fps mp4 the web decoder can read.
112
113
  * fps follows the composition so a hi-fps capture can render at 60 (the
113
- * render grid must match — a 30-grid would throw away the extra frames). */
114
- async function toMp4(videoPath: string, outMp4: string, fps: number): Promise<void> {
114
+ * render grid must match — a 30-grid would throw away the extra frames).
115
+ *
116
+ * `codec` is normally h264; "vp9" is the retry arm for render browsers
117
+ * WITHOUT H.264 decoding (Playwright-style Chromium builds ship no
118
+ * proprietary codecs). The scene's decode guard rejects in seconds when the
119
+ * capture can't decode there (see src/decode-guard.ts); renderTakeExclusive
120
+ * catches that rejection and re-encodes the scratch capture with this arm
121
+ * before one retry. The VP9 fallback must keep the .mp4 container AND the
122
+ * capture.mp4 name: revideo routes video decoding by file extension, so a
123
+ * .webm would take a different (and broken) decode path — VP9-in-MP4 (vp09
124
+ * track) is the shape that works. */
125
+ async function toMp4(
126
+ videoPath: string,
127
+ outMp4: string,
128
+ fps: number,
129
+ codec: "h264" | "vp9",
130
+ ): Promise<void> {
115
131
  await mkdir(dirname(outMp4), { recursive: true });
132
+ const codecArgs =
133
+ codec === "vp9"
134
+ ? ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "24", "-row-mt", "1", "-cpu-used", "4"]
135
+ : ["-c:v", "libx264", "-crf", "18"];
116
136
  await run(await resolveFfmpeg(), [
117
137
  "-y",
118
138
  "-loglevel",
119
139
  "error",
120
140
  "-i",
121
141
  resolve(videoPath),
122
- "-c:v",
123
- "libx264",
142
+ ...codecArgs,
124
143
  "-pix_fmt",
125
144
  "yuv420p",
126
- "-crf",
127
- "18",
128
145
  "-r",
129
146
  String(fps),
130
147
  "-an",
@@ -260,8 +277,10 @@ async function prepareScratch(composition: TakeComposition, videoPath: string):
260
277
  // ignored on POSIX.
261
278
  await symlink(nm, join(dir, "node_modules"), "junction");
262
279
  // fps follows the composition: the render grid must match the source, or a
263
- // hi-fps capture is decimated before the scene ever sees it.
264
- await toMp4(videoPath, join(dir, "public", "capture.mp4"), composition.output.fps);
280
+ // hi-fps capture is decimated before the scene ever sees it. Always H.264
281
+ // here — the happy path — the decode-guard retry re-encodes as VP9 in
282
+ // place when the render browser can't take it.
283
+ await toMp4(videoPath, join(dir, "public", "capture.mp4"), composition.output.fps, "h264");
265
284
  return dir;
266
285
  } catch (error) {
267
286
  await cleanupScratch(dir);
@@ -338,65 +357,131 @@ async function renderTakeExclusive(opts: RenderTakeOpts): Promise<RenderTakeResu
338
357
  // monorepo root's postinstall script.
339
358
  await repairBundledMediaPermissions();
340
359
 
341
- // 1. lay out this render's own directory (scene + composition + capture)
360
+ // 1. lay out this render's own directory (scene + composition + capture).
361
+ // The intermediate starts as H.264; the decode-guard retry below swaps
362
+ // it for VP9 when the render browser turns out not to decode it.
342
363
  const scratch = await prepareScratch(composition, opts.videoPath);
343
364
  const deps = depsRoot();
365
+ // Resolved BEFORE the chdir below: the retry re-encode runs while cwd is
366
+ // the scratch dir, where a relative videoPath would resolve wrongly.
367
+ const videoAbs = resolve(opts.videoPath);
344
368
  try {
345
369
  // 2. render headless, with cwd pinned to the scratch dir.
346
370
  // revideo's @revideo/telemetry phones home to PostHog by default; this is an
347
371
  // all-local tool, so default it OFF (an explicit user-set value still wins).
348
372
  if (process.env.DISABLE_TELEMETRY === undefined) process.env.DISABLE_TELEMETRY = "true";
373
+
374
+ // One attempt = one renderVideo call with its own no-progress hint timer.
375
+ // A stuck render is SILENT: revideo's first progress tick fires only after
376
+ // the first frame fully renders, and legitimate pre-roll can take tens of
377
+ // seconds — so hint (never kill) when no tick has landed after 3 minutes.
378
+ const renderOnce = async (): Promise<string> => {
379
+ let noProgressTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
380
+ process.stderr.write(
381
+ "open-take: no render progress after 3 minutes — if this never advances, the render browser may be stuck decoding the capture (see OPEN_TAKE_CHROME)\n",
382
+ );
383
+ }, 180_000);
384
+ try {
385
+ return await renderVideo({
386
+ projectFile: "/src/scene/project.ts",
387
+ settings: {
388
+ outFile: "take.mov",
389
+ outDir: RENDER_OUT,
390
+ workers: 1,
391
+ // ProRes 4444 intermediate, NOT revideo's default wasm exporter: the
392
+ // wasm path encodes H.264 in-browser via WebCodecs at the browser's
393
+ // default bitrate (mp4-wasm passes `bitrate: undefined`, and revideo
394
+ // 0.11 exposes no knob) — at fps·samples that visibly softens fine
395
+ // detail, screen-space caption/title text worst of all, before the
396
+ // delivery encode ever runs. The ffmpeg exporter is fed lossless PNG
397
+ // frames and prores_ks 4444 keeps them visually intact (4:4:4, no
398
+ // DCT mush), leaving deliverMp4's CRF 18 as the single lossy
399
+ // generation. Costs scratch disk (GBs at fps·samples for a long
400
+ // take) and slower frame handoff — accepted for the master's text.
401
+ projectSettings: {
402
+ exporter: { name: "@revideo/core/ffmpeg", options: { format: "proRes" } },
403
+ ...(rangeSec ? { range: rangeSec } : {}),
404
+ },
405
+ logProgress: opts.logProgress ?? false,
406
+ // Wrapped even without opts.onProgress: the first tick proves the
407
+ // browser is decoding frames, which disarms the no-progress hint.
408
+ progressCallback: (_worker: number, progress: number) => {
409
+ if (noProgressTimer !== undefined) {
410
+ clearTimeout(noProgressTimer);
411
+ noProgressTimer = undefined;
412
+ }
413
+ opts.onProgress?.(progress);
414
+ },
415
+ // vite's dev server refuses to serve outside its root, and its root is
416
+ // now a tmp dir — so allow the dependency tree the scene imports
417
+ // through the node_modules link (vite resolves it to the realpath).
418
+ viteConfig: {
419
+ server: { fs: { allow: [scratch, ...(deps ? [deps] : [])] } },
420
+ },
421
+ // Reuse the capture-managed Chrome-for-Testing for both stages.
422
+ puppeteer: {
423
+ // --password-store/--use-mock-keychain: never touch the OS keychain, so
424
+ // macOS doesn't pop a "Chrome wants to use Chromium Safe Storage" prompt
425
+ // mid-render (matches the capture launch in runtime/cdp.ts).
426
+ args: [
427
+ "--no-sandbox",
428
+ "--disable-setuid-sandbox",
429
+ "--password-store=basic",
430
+ "--use-mock-keychain",
431
+ ],
432
+ executablePath: opts.chromePath,
433
+ },
434
+ },
435
+ });
436
+ } finally {
437
+ if (noProgressTimer !== undefined) clearTimeout(noProgressTimer);
438
+ }
439
+ };
440
+
349
441
  const prevCwd = process.cwd();
350
442
  process.chdir(scratch);
351
443
  let produced: string;
352
444
  try {
353
- produced = await renderVideo({
354
- projectFile: "/src/scene/project.ts",
355
- settings: {
356
- outFile: "take.mov",
357
- outDir: RENDER_OUT,
358
- workers: 1,
359
- // ProRes 4444 intermediate, NOT revideo's default wasm exporter: the
360
- // wasm path encodes H.264 in-browser via WebCodecs at the browser's
361
- // default bitrate (mp4-wasm passes `bitrate: undefined`, and revideo
362
- // 0.11 exposes no knob) — at fps·samples that visibly softens fine
363
- // detail, screen-space caption/title text worst of all, before the
364
- // delivery encode ever runs. The ffmpeg exporter is fed lossless PNG
365
- // frames and prores_ks 4444 keeps them visually intact (4:4:4, no
366
- // DCT mush), leaving deliverMp4's CRF 18 as the single lossy
367
- // generation. Costs scratch disk (GBs at fps·samples for a long
368
- // take) and slower frame handoff — accepted for the master's text.
369
- projectSettings: {
370
- exporter: { name: "@revideo/core/ffmpeg", options: { format: "proRes" } },
371
- ...(rangeSec ? { range: rangeSec } : {}),
372
- },
373
- logProgress: opts.logProgress ?? false,
374
- ...(opts.onProgress
375
- ? {
376
- progressCallback: (_worker: number, progress: number) => opts.onProgress!(progress),
377
- }
378
- : {}),
379
- // vite's dev server refuses to serve outside its root, and its root is
380
- // now a tmp dir — so allow the dependency tree the scene imports
381
- // through the node_modules link (vite resolves it to the realpath).
382
- viteConfig: {
383
- server: { fs: { allow: [scratch, ...(deps ? [deps] : [])] } },
384
- },
385
- // Reuse the capture-managed Chrome-for-Testing for both stages.
386
- puppeteer: {
387
- // --password-store/--use-mock-keychain: never touch the OS keychain, so
388
- // macOS doesn't pop a "Chrome wants to use Chromium Safe Storage" prompt
389
- // mid-render (matches the capture launch in runtime/cdp.ts).
390
- args: [
391
- "--no-sandbox",
392
- "--disable-setuid-sandbox",
393
- "--password-store=basic",
394
- "--use-mock-keychain",
395
- ],
396
- executablePath: opts.chromePath,
397
- },
398
- },
399
- });
445
+ try {
446
+ produced = await renderOnce();
447
+ } catch (error) {
448
+ // The scene's decode guard rejected: this browser cannot decode the
449
+ // H.264 intermediate (Playwright-style Chromium ships no proprietary
450
+ // codecs — before the guard, such a render hung forever; a real user
451
+ // lost ~20 minutes to that silence). Re-encode the scratch capture as
452
+ // VP9-in-MP4 and retry ONCE; without an ffmpeg that can, refuse with
453
+ // the fix. Any other rejection rethrows untouched.
454
+ if (!isCaptureUndecodable(error)) throw error;
455
+ const detail = error instanceof Error ? error.message : String(error);
456
+ if (!(await ffmpegHasEncoder("libvpx-vp9"))) {
457
+ throw new Error(
458
+ `render: the browser at ${opts.chromePath} cannot decode the capture (${detail}) — ` +
459
+ "point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build, or install an " +
460
+ "ffmpeg with libvpx-vp9 to enable the VP9 fallback",
461
+ { cause: error },
462
+ );
463
+ }
464
+ process.stderr.write(
465
+ "open-take: the render browser cannot decode the H.264 capture — retrying with a VP9 intermediate (output unchanged)\n",
466
+ );
467
+ await toMp4(
468
+ videoAbs,
469
+ join(scratch, "public", "capture.mp4"),
470
+ composition.output.fps,
471
+ "vp9",
472
+ );
473
+ try {
474
+ produced = await renderOnce();
475
+ } catch (retryError) {
476
+ if (!isCaptureUndecodable(retryError)) throw retryError;
477
+ const retryDetail = retryError instanceof Error ? retryError.message : String(retryError);
478
+ throw new Error(
479
+ `render: the browser at ${opts.chromePath} cannot decode the capture even as VP9 ` +
480
+ `(${retryDetail}) — point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build`,
481
+ { cause: retryError },
482
+ );
483
+ }
484
+ }
400
485
  } finally {
401
486
  process.chdir(prevCwd);
402
487
  }
@@ -13,6 +13,7 @@ import {
13
13
  carryWindow,
14
14
  ghostCardLines,
15
15
  } from "../math";
16
+ import { buildUndecodableMessage } from "../decode-guard";
16
17
  import comp from "./.composition.json";
17
18
 
18
19
  const vW = comp.source.videoWidth,
@@ -40,6 +41,45 @@ const CURSOR = [
40
41
  ].map(([x, y]) => [x * S, y * S]);
41
42
 
42
43
  export default makeScene2D("take", function* (view) {
44
+ // Fail fast if this browser cannot decode the capture: revideo's <Video>
45
+ // waitForCanPlay resolves only on 'canplay' (its 'error' handler just
46
+ // logs), so an undecodable capture — H.264 on a codec-less Chromium —
47
+ // otherwise hangs the render forever. A rejection here propagates out as a
48
+ // renderVideo failure; its message starts with the shared sentinel
49
+ // (decode-guard.ts), which render.ts recognises to retry with a VP9
50
+ // intermediate.
51
+ if (comp.source.videoUrl) {
52
+ yield new Promise((res, rej) => {
53
+ const el = document.createElement("video");
54
+ el.muted = true;
55
+ el.preload = "auto";
56
+ let timer = 0;
57
+ const done = (err) => {
58
+ clearTimeout(timer);
59
+ el.removeEventListener("canplay", onCanPlay);
60
+ el.removeEventListener("error", onError);
61
+ el.removeAttribute("src");
62
+ el.load();
63
+ if (err) rej(err);
64
+ else res(undefined);
65
+ };
66
+ const onCanPlay = () => done(undefined);
67
+ const onError = () => {
68
+ const e = el.error;
69
+ const detail = `MediaError code ${e ? e.code : "?"}: ${e?.message ? e.message : "no detail"}`;
70
+ done(new Error(buildUndecodableMessage("media-error", detail, comp.source.videoUrl)));
71
+ };
72
+ el.addEventListener("canplay", onCanPlay, { once: true });
73
+ el.addEventListener("error", onError, { once: true });
74
+ timer = setTimeout(() => {
75
+ const detail = `readyState=${el.readyState}`;
76
+ done(new Error(buildUndecodableMessage("timeout", detail, comp.source.videoUrl)));
77
+ }, 30000);
78
+ el.src = comp.source.videoUrl;
79
+ el.load();
80
+ });
81
+ }
82
+
43
83
  const t = createSignal(0);
44
84
 
45
85
  // The camera: ONE eased viewport rect (centre + size in lockstep, targets