Files
patriothacks/e2e/openmotion/capture.mjs
T
OmO Orchestrator eb43d1c5c0 feat(demo): add OpenMotion-based promo video pipeline alongside the existing ffmpeg one
Migrates the promo video's compositing/motion-graphics layer (title cards,
margins, transitions, audio mix) to OpenMotion (Hyperframes 0.9.7), built
and verified across 3 independently-gated stages:

- e2e/openmotion-poc/: proof-of-concept proving real footage composites
  correctly with live-sourced margins and a flash-free title card
- e2e/openmotion/: the full video - intro, Act I/II/III, Epilogue, outro,
  and the real two-device Assembly sync scene, with continuous ambient
  audio, rendered to e2e/openmotion/renders/full.mp4 (1920x1080, 62.8s)

The existing e2e/demoVideoFull.e2e.mjs is untouched and remains the
production fallback (byte-for-byte unmodified, confirmed by every stage's
independent review). Real Playwright screen-recording of the actual app is
preserved as the footage source throughout - OpenMotion replaces only the
post-capture compositing, never the capture itself.

Every protection carried forward and independently re-verified at each
stage: no cursor overlay, 16:9 landscape with live-data margins, in-universe
copy (zero generic 'town' references), audible background audio (~-38dB,
no clipping), zero content clipping at any beat including the Assembly
two-device letterboxing, and the pacing fixes already proven in the ffmpeg
pipeline (no white-flash frames, graceful fade-to-black ending).
2026-11-19 16:35:31 -05:00

186 lines
7.4 KiB
JavaScript

// STAGE-2 OpenMotion full main-tour: footage capture.
//
// Records the FULL Acts I-III tour (driven by the shared `runTour()` in
// tour.mjs) as ONE continuous real-app Playwright recording - same
// viewport, same 2x device scale, same recordVideo mechanism, same single
// continuous event-log session as demoVideoFull.e2e.mjs's recordMainScene()
// - then slices that one webm into per-act mp4 clips at the act boundaries
// the tour marked. One continuous recording (not per-act contexts) keeps
// the real "one identity, one signed log, seeded once" continuity and
// means exactly ONE first-paint boot (at the very start, trimmed off the
// intro clip and covered by the intro title card) with NO reload between
// acts - the OpenMotion full-screen GSAP title cards replace the real
// tour's inter-act showActTitleCard() cards entirely.
//
// The act title cards are deliberately NOT captured here; they are rendered
// by the OpenMotion composition (see buildComposition.mjs). This script's
// only job is genuine per-act app footage + a manifest of clip durations
// and beat timings for the composition builder.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import ffmpegStatic from "ffmpeg-static";
import { mkdirSync, rmSync, readdirSync, existsSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { execFileSync } from "node:child_process";
import { runTour, forceLocalIdentityWinsFairDraw } from "./tour.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const OM_DIR = __dirname;
const ROOT = resolve(__dirname, "..", ".."); // worktree root
const VIDEO_TMP_DIR = resolve(OM_DIR, ".tmp-capture");
const ASSETS_DIR = resolve(OM_DIR, "assets");
const MANIFEST_OUT = resolve(OM_DIR, "capture-manifest.json");
// Same constants as recordMainScene(): a 414x896 phone pane recorded at 2x
// device-pixel density (sharp text) -> an 828x1792 raw webm.
const PANE = { width: 414, height: 896 };
const RECAST_SCALE = 2;
const MAIN_VIDEO_SIZE = { width: PANE.width * RECAST_SCALE, height: PANE.height * RECAST_SCALE };
const CLIP_FPS = 30; // CFR output so the Hyperframes <video> seek contract is clean
const VITE_PORT = 45000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const FFMPEG_BIN = ffmpegStatic;
// Per-act clip windows, keyed by the boundary marks runTour() records.
// Each entry: { name, from: <startMark>, to: <endMark>, leadGuard?: seconds }.
const CLIP_SPEC = [
{ name: "intro", from: "gridReady", to: "introEnd", leadGuard: 0.45 }, // trim first-paint boot
{ name: "act1", from: "introEnd", to: "act1End" },
{ name: "act2", from: "act1End", to: "act2End" },
{ name: "act3", from: "act2End", to: "act3End" },
{ name: "epilogue", from: "act3End", to: "epilogueEnd" }, // Stage-3 Epilogue footage
];
async function startVite() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
return vite;
}
function probeDurationSeconds(videoPath) {
try {
execFileSync(FFMPEG_BIN, ["-i", videoPath], { stdio: ["ignore", "pipe", "pipe"] });
return null;
} catch (e) {
const m = String(e.stderr ?? "").match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (!m) return null;
return Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]);
}
}
async function main() {
console.log("=== STAGE-2 capture: full Acts I-III tour (real app footage) ===");
const vite = await startVite();
const videoDir = resolve(VIDEO_TMP_DIR, "main");
rmSync(videoDir, { recursive: true, force: true });
mkdirSync(videoDir, { recursive: true });
const browser = await chromium.launch({
headless: true,
args: ["--no-sandbox", `--force-device-scale-factor=${RECAST_SCALE}`],
});
const context = await browser.newContext({
viewport: PANE,
deviceScaleFactor: RECAST_SCALE,
recordVideo: { dir: videoDir, size: MAIN_VIDEO_SIZE },
});
await forceLocalIdentityWinsFairDraw(context);
const marks = {};
const beats = [];
const page = await context.newPage();
const recordStart = Date.now(); // webm t~=0 anchor (page creation)
const api = {
async mark(name) {
marks[name] = (Date.now() - recordStart) / 1000;
console.log(`[mark] ${name} @ ${marks[name].toFixed(2)}s`);
},
async beat(label, note) {
beats.push({ label, note, offsetS: (Date.now() - recordStart) / 1000 });
console.log(`[beat +${((Date.now() - recordStart) / 1000).toFixed(1)}s] ${label}: ${note}`);
},
};
try {
await runTour(page, api, APP_URL);
} finally {
await context.close(); // flushes the .webm
await browser.close();
await vite.close();
}
const webm = readdirSync(videoDir).find((f) => f.endsWith(".webm"));
if (!webm) throw new Error(`no .webm produced in ${videoDir}`);
const webmPath = resolve(videoDir, webm);
const webmDuration = probeDurationSeconds(webmPath);
console.log(`\nRaw webm: ${webmPath} (duration ${webmDuration?.toFixed(2)}s)`);
// Linear wall-clock -> webm-time correction: recordVideo's t=0 and its
// playback rate differ from our wall-clock marks by a small startup
// latency + flush, so anchor the two timelines at 0 and at the final
// mark (recorded immediately before context.close) by scaling.
const lastMark = marks["epilogueEnd"];
const scale = webmDuration && lastMark ? webmDuration / lastMark : 1;
console.log(`[time] webm/wall scale = ${scale.toFixed(4)} (webm ${webmDuration?.toFixed(2)}s / wall ${lastMark?.toFixed(2)}s)`);
const toWebm = (wall) => wall * scale;
mkdirSync(ASSETS_DIR, { recursive: true });
const clips = [];
for (const spec of CLIP_SPEC) {
const fromWall = marks[spec.from];
const toWall = marks[spec.to];
if (fromWall == null || toWall == null) throw new Error(`missing mark for clip ${spec.name}: ${spec.from}/${spec.to}`);
const start = toWebm(fromWall) + (spec.leadGuard ?? 0);
const end = toWebm(toWall);
const dur = Math.max(0.1, end - start);
const outPath = resolve(ASSETS_DIR, `${spec.name}.mp4`);
if (existsSync(outPath)) rmSync(outPath);
// Frame-accurate re-encode to CFR 30fps h264 (muted, faststart). -ss
// before -i is fast-seek + decode-accurate under re-encode.
execFileSync(
FFMPEG_BIN,
[
"-y", "-ss", start.toFixed(3), "-i", webmPath, "-t", dur.toFixed(3),
"-vf", `fps=${CLIP_FPS}`, "-c:v", "libx264", "-pix_fmt", "yuv420p",
"-an", "-movflags", "+faststart", outPath,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
const outDur = probeDurationSeconds(outPath);
clips.push({ name: spec.name, path: `assets/${spec.name}.mp4`, durationS: outDur, srcStartS: start, srcEndS: end });
console.log(`[clip] ${spec.name}: ${start.toFixed(2)}-${end.toFixed(2)}s -> ${outPath} (${outDur?.toFixed(2)}s)`);
}
writeFileSync(
MANIFEST_OUT,
JSON.stringify(
{
recordedAt: new Date().toISOString(),
videoSize: MAIN_VIDEO_SIZE,
clipFps: CLIP_FPS,
webmDurationS: webmDuration,
marks,
clips,
beats,
},
null,
2,
),
);
console.log(`\nManifest: ${MANIFEST_OUT}`);
console.log(`Clips: ${clips.map((c) => `${c.name}=${c.durationS?.toFixed(1)}s`).join(", ")}`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});