@open-take/runtime 0.1.1 → 0.2.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-CWFbnK9C.js";
2
- import { appendFile, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-BkVH_3Uv.js";
2
+ import { appendFile, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, dirname, extname, join, normalize, resolve } from "node:path";
5
5
  import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, finishName, formatIssues, formatIssues as formatIssues$1, lookName, motionName, planComposition, renderTake, resolveFfmpeg, validateComposition, validateComposition as validateComposition$1, zoomLevelName } from "@open-take/compositor";
@@ -8,6 +8,213 @@ import { createReadStream, statSync } from "node:fs";
8
8
  import { createServer } from "node:http";
9
9
  import { fileURLToPath } from "node:url";
10
10
 
11
+ //#region src/frame-diff.ts
12
+ const ANALYSIS_W = 960;
13
+ const CELL = 16;
14
+ /** min |gray delta| for a pixel to count as changed (h264 noise is ~2–6) */
15
+ const PIXEL_DELTA = 16;
16
+ /** a cell is "changed" when > this fraction of its pixels changed */
17
+ const CELL_FRAC = .08;
18
+ /** sample the "before" state this long before the action (ms). Kept TIGHT so
19
+ * everything that happens on the approach — the capture's own
20
+ * scrollIntoView, hover styles, the previous action's tail — is already
21
+ * painted and therefore NOT attributed to this action; a click's own effect
22
+ * can't land within one 60fps frame of the input, so this still precedes it.
23
+ * (Also < NEXT_CLEARANCE_MS, so adjacent events' windows can never overlap —
24
+ * no double attribution.) */
25
+ const BEFORE_MS = 30;
26
+ /** sample the "after" state this long after the action (+durationMs) settles —
27
+ * catches popover/reveal animations (ms; the capture itself sleeps ~1s
28
+ * between actions, so there is normally room). */
29
+ const SETTLE_MS = 500;
30
+ /** third sample this long after the "after" frame: cells STILL changing
31
+ * between the two are ambient motion (hero video, carousel, streaming text)
32
+ * — masked out of the action's diff so they can't poison effectBox (ms). */
33
+ const AMBIENT_MS = 250;
34
+ /** keep this much clearance before the NEXT action so its changes are never
35
+ * attributed to this one (ms). */
36
+ const NEXT_CLEARANCE_MS = 60;
37
+ /** a box-less event (bare press) only gets an effectBox when the change is at
38
+ * least this big — a blinking terminal cursor must not become a phantom
39
+ * punch target on an event that used to mean "full view". */
40
+ const MIN_NO_BOX_COVERAGE = .015;
41
+ /** per-cell changed-pixel counts of |before−after| > PIXEL_DELTA (symmetric —
42
+ * appearing light-on-dark content matters as much as dark-on-light). */
43
+ function cellCounts(a, b, w, h) {
44
+ const cw = Math.ceil(w / CELL);
45
+ const counts = new Uint16Array(cw * Math.ceil(h / CELL));
46
+ for (let y = 0; y < h; y++) {
47
+ const row = y * w;
48
+ const crow = Math.floor(y / CELL) * cw;
49
+ for (let x = 0; x < w; x++) {
50
+ const d = a[row + x] - b[row + x];
51
+ if (d > PIXEL_DELTA || d < -PIXEL_DELTA) counts[crow + Math.floor(x / CELL)]++;
52
+ }
53
+ }
54
+ return counts;
55
+ }
56
+ /**
57
+ * Pure diff of two grayscale frames (same w×h). Cell-based: a cell counts as
58
+ * changed when enough of its pixels moved. An isolated changed cell (no
59
+ * changed 8-neighbour) is kept only when it changed OVERWHELMINGLY (≥ half its
60
+ * pixels — a real single-cell payoff like a cart badge), else it's a speck
61
+ * (caret blink, cursor sliver) and is dropped.
62
+ *
63
+ * `ambient` (optional) is a THIRD frame sampled shortly after `after`: any
64
+ * cell still changing between `after` and `ambient` is ambient motion (hero
65
+ * video, carousel, streaming text) and is excluded — without this, one
66
+ * animating region would poison every event's effectBox with its union.
67
+ *
68
+ * `coverage` is the changed-CELL area fraction — the region the action
69
+ * affected — deliberately not the changed-PIXEL fraction: a nav swap between
70
+ * two white-ish pages repaints most of the frame while leaving most PIXELS
71
+ * white-on-white, and it's the affected region the director's pull-out
72
+ * threshold reasons about.
73
+ */
74
+ function diffFrames(before, after, w, h, ambient) {
75
+ const cw = Math.ceil(w / CELL);
76
+ const ch = Math.ceil(h / CELL);
77
+ const counts = cellCounts(before, after, w, h);
78
+ const minCount = Math.max(1, Math.floor(CELL * CELL * CELL_FRAC));
79
+ const strongCount = Math.floor(CELL * CELL * .5);
80
+ const ambientCounts = ambient ? cellCounts(after, ambient, w, h) : void 0;
81
+ const changed = (cx, cy) => cx >= 0 && cy >= 0 && cx < cw && cy < ch && counts[cy * cw + cx] >= minCount && (!ambientCounts || ambientCounts[cy * cw + cx] < minCount);
82
+ let kept = 0;
83
+ let x0 = cw;
84
+ let y0 = ch;
85
+ let x1 = -1;
86
+ let y1 = -1;
87
+ for (let cy = 0; cy < ch; cy++) for (let cx = 0; cx < cw; cx++) {
88
+ if (!changed(cx, cy)) continue;
89
+ let neighbour = counts[cy * cw + cx] >= strongCount;
90
+ for (let dy = -1; dy <= 1 && !neighbour; dy++) for (let dx = -1; dx <= 1; dx++) {
91
+ if (dx === 0 && dy === 0) continue;
92
+ if (changed(cx + dx, cy + dy)) {
93
+ neighbour = true;
94
+ break;
95
+ }
96
+ }
97
+ if (!neighbour) continue;
98
+ kept++;
99
+ if (cx < x0) x0 = cx;
100
+ if (cy < y0) y0 = cy;
101
+ if (cx > x1) x1 = cx;
102
+ if (cy > y1) y1 = cy;
103
+ }
104
+ if (kept === 0) return { coverage: 0 };
105
+ return {
106
+ coverage: kept / (cw * ch),
107
+ box: {
108
+ x: x0 * CELL,
109
+ y: y0 * CELL,
110
+ w: Math.min((x1 + 1) * CELL, w) - x0 * CELL,
111
+ h: Math.min((y1 + 1) * CELL, h) - y0 * CELL
112
+ }
113
+ };
114
+ }
115
+ /** Decode ONE grayscale frame at time `tSec` from `videoPath`, scaled to
116
+ * aw×ah. Resolves undefined on any failure (missing frame near EOF, etc.). */
117
+ function grabFrame(bin, videoPath, tSec, aw, ah) {
118
+ return new Promise((res) => {
119
+ const args = [
120
+ "-v",
121
+ "error",
122
+ "-ss",
123
+ tSec.toFixed(3),
124
+ "-i",
125
+ videoPath,
126
+ "-frames:v",
127
+ "1",
128
+ "-vf",
129
+ `scale=${aw}:${ah}`,
130
+ "-f",
131
+ "rawvideo",
132
+ "-pix_fmt",
133
+ "gray",
134
+ "-"
135
+ ];
136
+ const c = spawn(bin, args, { stdio: [
137
+ "ignore",
138
+ "pipe",
139
+ "ignore"
140
+ ] });
141
+ const chunks = [];
142
+ c.stdout.on("data", (b) => chunks.push(b));
143
+ c.on("error", () => res(void 0));
144
+ c.on("close", () => {
145
+ const buf = Buffer.concat(chunks);
146
+ res(buf.length === aw * ah ? new Uint8Array(buf) : void 0);
147
+ });
148
+ });
149
+ }
150
+ /**
151
+ * Annotate a capture log with per-event `effectBox` + `changeCoverage` by
152
+ * diffing the capture video around each action. Returns a NEW log (input
153
+ * untouched); events whose diff fails or whose sample window is degenerate are
154
+ * returned unchanged. Never throws.
155
+ */
156
+ async function annotateCaptureLog(log, videoPath, opts = {}) {
157
+ try {
158
+ const bin = opts.ffmpegBin ?? await resolveFfmpeg();
159
+ const vW = log.video.width;
160
+ const vH = log.video.height;
161
+ if (!(vW > 0) || !(vH > 0)) return log;
162
+ const aw = Math.min(ANALYSIS_W, vW);
163
+ const ah = Math.max(CELL, Math.round(vH * aw / vW));
164
+ const mx = log.viewport.w / aw;
165
+ const my = log.viewport.h / ah;
166
+ const durS = log.video.durationS ?? (log.tEndMs != null ? log.tEndMs / 1e3 : void 0);
167
+ const events = [...log.events];
168
+ for (let i = 0; i < events.length; i++) {
169
+ const e = events[i];
170
+ const durationMs = "durationMs" in e && e.durationMs != null ? e.durationMs : 0;
171
+ const before = Math.max(0, (e.tMs - BEFORE_MS) / 1e3);
172
+ let after = (e.tMs + durationMs + SETTLE_MS) / 1e3;
173
+ const next = events[i + 1];
174
+ const ceil = Math.min(
175
+ next ? (next.tMs - NEXT_CLEARANCE_MS) / 1e3 : Number.POSITIVE_INFINITY,
176
+ // never sample past the recording's end (the last frame would repeat —
177
+ // fine — but a seek past EOF returns nothing)
178
+ durS != null ? Math.max(0, durS - .05) : Number.POSITIVE_INFINITY
179
+ );
180
+ after = Math.min(after, ceil);
181
+ if (after <= before + .05) continue;
182
+ const ambientT = after + AMBIENT_MS / 1e3;
183
+ const wantAmbient = ambientT <= ceil;
184
+ const [fa, fb, fc] = await Promise.all([
185
+ grabFrame(bin, videoPath, before, aw, ah),
186
+ grabFrame(bin, videoPath, after, aw, ah),
187
+ wantAmbient ? grabFrame(bin, videoPath, ambientT, aw, ah) : Promise.resolve(void 0)
188
+ ]);
189
+ if (!fa || !fb) continue;
190
+ const d = diffFrames(fa, fb, aw, ah, fc);
191
+ const hasBox = "box" in e && e.box != null;
192
+ const attachBox = d.box && (hasBox || d.coverage >= MIN_NO_BOX_COVERAGE);
193
+ events[i] = {
194
+ ...e,
195
+ changeCoverage: Math.round(d.coverage * 1e3) / 1e3,
196
+ ...attachBox && d.box ? { effectBox: {
197
+ x: Math.round(d.box.x * mx),
198
+ y: Math.round(d.box.y * my),
199
+ w: Math.round(d.box.w * mx),
200
+ h: Math.round(d.box.h * my)
201
+ } } : {}
202
+ };
203
+ if (opts.logProgress) {
204
+ const eb = events[i].effectBox;
205
+ process.stderr.write(`frame-diff [${i}] ${e.kind ?? "click"}@${e.tMs}ms coverage=${events[i].changeCoverage}${eb ? ` effect=(${eb.x},${eb.y} ${eb.w}x${eb.h})` : ""}\n`);
206
+ }
207
+ }
208
+ return {
209
+ ...log,
210
+ events
211
+ };
212
+ } catch {
213
+ return log;
214
+ }
215
+ }
216
+
217
+ //#endregion
11
218
  //#region src/take.ts
12
219
  async function isFile(p) {
13
220
  return (await stat(p).catch(() => null))?.isFile() ?? false;
@@ -70,819 +277,958 @@ async function stagePrev(mp4Path, prevPath) {
70
277
  }
71
278
 
72
279
  //#endregion
73
- //#region src/edit-server.ts
74
- const CONTENT_TYPE = {
75
- ".html": "text/html; charset=utf-8",
76
- ".js": "text/javascript; charset=utf-8",
77
- ".mjs": "text/javascript; charset=utf-8",
78
- ".css": "text/css; charset=utf-8",
79
- ".json": "application/json; charset=utf-8",
80
- ".svg": "image/svg+xml",
81
- ".png": "image/png",
82
- ".jpg": "image/jpeg",
83
- ".ico": "image/x-icon",
84
- ".woff2": "font/woff2",
85
- ".woff": "font/woff",
86
- ".map": "application/json; charset=utf-8"
87
- };
88
- /** Locate the built editor SPA: a bundled copy (published package) first, then
89
- * the monorepo build. */
90
- function resolveEditorDist() {
91
- const here = fileURLToPath(import.meta.url);
92
- const pkgRoot = resolve(here, "..", "..");
93
- const candidates = [resolve(pkgRoot, "editor-dist"), resolve(pkgRoot, "..", "..", "apps", "editor", "dist")];
94
- return candidates.find((c) => existsHtml(c)) ?? null;
95
- }
96
- function existsHtml(dir) {
97
- return existsFile(join(dir, "index.html"));
98
- }
99
- function existsFile(path) {
280
+ //#region src/review.ts
281
+ /** Sibling capture log (`<capture>.json`), if present — enables the
282
+ * capture-lock check; silently absent otherwise (matches index.ts). */
283
+ async function loadLogSibling(capturePath) {
100
284
  try {
101
- return statSync(path).isFile();
285
+ return JSON.parse(await readFile(resolve(capturePath).replace(/\.mp4$/i, ".json"), "utf8"));
102
286
  } catch {
103
- return false;
287
+ return void 0;
104
288
  }
105
289
  }
106
- const sendJson = (res, status, obj) => {
107
- const body = JSON.stringify(obj);
108
- res.writeHead(status, {
109
- "Content-Type": "application/json; charset=utf-8",
110
- "Content-Length": Buffer.byteLength(body)
111
- });
112
- res.end(body);
290
+ const KIND_LABEL = {
291
+ click: "click",
292
+ type: "type",
293
+ drag: "drag",
294
+ scroll: "scroll",
295
+ hover: "hover",
296
+ press: "key"
113
297
  };
114
- async function readBody(req, capBytes = 32 * 1024 * 1024) {
115
- const chunks = [];
116
- let size = 0;
117
- for await (const c of req) {
118
- size += c.length;
119
- if (size > capBytes) throw new Error("request body too large");
120
- chunks.push(c);
121
- }
122
- return Buffer.concat(chunks).toString("utf8");
298
+ function beatTitle(e) {
299
+ if (e.label) return e.label;
300
+ if (e.kind === "type" && e.text) return `"${e.text}"`;
301
+ if (e.kind === "press" && e.keys) return e.keys;
302
+ return e.kind;
123
303
  }
124
- /** Stream a file with HTTP Range support (206) — required for <video> seeking. */
125
- async function serveFile(req, res, filePath) {
126
- const st = await stat(filePath).catch(() => null);
127
- if (!st?.isFile()) {
128
- sendJson(res, 404, { error: "not found" });
129
- return;
304
+ const trunc = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
305
+ function fmtTime(ms) {
306
+ const s = Math.max(0, Math.round(ms / 1e3));
307
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
308
+ }
309
+ /** "zoom medium (×1.5)" | "zoom ×1.85 (custom)" | "wide" */
310
+ function zoomText(e) {
311
+ if (!e.zoom.enabled) return "wide";
312
+ const name = zoomLevelName(e.zoom.scale);
313
+ const x = `×${Number(e.zoom.scale.toFixed(2))}`;
314
+ return name ? `zoom ${name} (${x})` : `zoom ${x} (custom)`;
315
+ }
316
+ function buildBeatSheet(comp, name) {
317
+ const n = comp.events.length;
318
+ const look = lookName(comp.framing) ?? "custom";
319
+ const pace = motionName(comp.cursor) ?? "custom";
320
+ const finish = finishName(comp.motionBlur) ?? "custom";
321
+ const lines = [`${name} · ${(comp.durationMs / 1e3).toFixed(1)}s · ${n} beat${n === 1 ? "" : "s"} · look ${look} · pace ${pace} · finish ${finish}`];
322
+ const first = comp.events[0];
323
+ if (!first || first.zoom.inAtMs > 400) lines.push(` in 0:00 full view, cursor glides in`);
324
+ comp.events.forEach((e, i) => {
325
+ const num = String(i + 1).padStart(2, " ");
326
+ const kind = KIND_LABEL[e.kind].padEnd(6, " ");
327
+ const title = trunc(beatTitle(e), 24).padEnd(25, " ");
328
+ lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);
329
+ });
330
+ const last = comp.events[n - 1];
331
+ if (last) {
332
+ const endMs = last.tMs + (last.durationMs ?? 0) + comp.cursor.holdMs;
333
+ lines.push(` out ${fmtTime(endMs)} zoom releases, holds to ${fmtTime(comp.durationMs)}`);
130
334
  }
131
- const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? "application/octet-stream";
132
- const range = req.headers.range;
133
- if (range) {
134
- const m = /bytes=(\d*)-(\d*)/.exec(range);
135
- const start = m?.[1] ? Number(m[1]) : 0;
136
- const end = m?.[2] ? Number(m[2]) : st.size - 1;
137
- if (start >= st.size || end >= st.size || start > end) {
138
- res.writeHead(416, { "Content-Range": `bytes */${st.size}` });
139
- res.end();
140
- return;
141
- }
142
- res.writeHead(206, {
143
- "Content-Range": `bytes ${start}-${end}/${st.size}`,
144
- "Accept-Ranges": "bytes",
145
- "Content-Length": end - start + 1,
146
- "Content-Type": type
335
+ lines.push(`say it like: "beat 2: no zoom" · "tighter on beat 3" · "look: slate" · "pace: brisk"`);
336
+ return lines.join("\n");
337
+ }
338
+ const SAY_IT_CARD = `SAY IT, I'LL CUT IT
339
+ instant (~10s) zoom off / tighter / looser on a beat · re-center a beat (name the
340
+ element) · hold longer · pace: calm / natural / brisk · look:
341
+ midnight / ink / slate / ocean / plum / ember / paper / plain ·
342
+ finish: smooth / crisp / heavy · quicker intro · shorter tail
343
+ re-shoot (~1m) change what's clicked or typed · add / cut / reorder beats ·
344
+ retime an action
345
+ compare taste questions come back as an A/B reel — answer with a letter
346
+ ("B"), or "between A and B", or "none, go darker"`;
347
+ /** Badge windows: each beat owns [its zoom.inAtMs, the next beat's) — the pill
348
+ * swaps as the camera starts moving toward the beat. INTRO/TAIL bracket them. */
349
+ function buildBadges(comp) {
350
+ const n = comp.events.length;
351
+ const badges = [];
352
+ let prevStart = 0;
353
+ const starts = comp.events.map((e) => {
354
+ const s = Math.max(e.zoom.inAtMs, prevStart + 1);
355
+ prevStart = s;
356
+ return s;
357
+ });
358
+ if (n === 0 || starts[0] > 400) badges.push({
359
+ fromMs: 0,
360
+ toMs: starts[0] ?? comp.durationMs,
361
+ text: "INTRO"
362
+ });
363
+ comp.events.forEach((e, i) => {
364
+ const last = i === n - 1;
365
+ const endOwn = e.tMs + (e.durationMs ?? 0) + comp.cursor.holdMs;
366
+ const to = last ? Math.min(endOwn, comp.durationMs) : starts[i + 1];
367
+ badges.push({
368
+ fromMs: starts[i],
369
+ toMs: to,
370
+ text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`
147
371
  });
148
- createReadStream(filePath, {
149
- start,
150
- end
151
- }).pipe(res);
152
- } else {
153
- res.writeHead(200, {
154
- "Content-Length": st.size,
155
- "Accept-Ranges": "bytes",
156
- "Content-Type": type
372
+ if (last && to < comp.durationMs + 1e3) badges.push({
373
+ fromMs: to,
374
+ toMs: comp.durationMs + 1500,
375
+ text: "TAIL"
157
376
  });
158
- createReadStream(filePath).pipe(res);
159
- }
377
+ });
378
+ return badges;
160
379
  }
161
- function openBrowser(url) {
162
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
163
- try {
164
- spawn(cmd, [url], {
165
- stdio: "ignore",
166
- detached: true,
167
- shell: process.platform === "win32"
168
- }).unref();
169
- } catch {}
380
+ /** Draft-quality transform: 30fps cap + motion blur OFF — up to ~12× faster
381
+ * than a blurred 60fps master, close enough for composition-level notes.
382
+ * (2 blur samples would render 2× the frames for a tmix window that rounds to
383
+ * 1 — all cost, zero blur.) FEEL questions (blur, pace, zoom silkiness) must
384
+ * be judged on full quality — use `ab`. */
385
+ function toDraft(comp) {
386
+ const { motionBlur: _mb,...rest } = comp;
387
+ return {
388
+ ...rest,
389
+ output: {
390
+ ...comp.output,
391
+ fps: Math.min(30, comp.output.fps)
392
+ }
393
+ };
170
394
  }
171
- async function startEditServer(opts) {
172
- const take = await resolveTakePaths(opts.takePath);
173
- for (const f of [take.compositionPath, take.capturePath]) if (!(await stat(f).catch(() => null))?.isFile()) throw new Error(`missing take file: ${f}`);
174
- const dist = resolveEditorDist();
175
- if (!dist) throw new Error("editor build not found — run `pnpm --filter @open-take/editor build` first");
176
- const loadCaptureLog = async () => {
177
- try {
178
- return JSON.parse(await readFile(take.captureLogPath, "utf8"));
179
- } catch {
180
- return null;
395
+ async function renderReview(take, opts = {}) {
396
+ await requireTakeFiles(take, { capture: true });
397
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
398
+ const captureLog = await loadLogSibling(take.capturePath);
399
+ const chromePath = await ensureChrome(opts.chromePath);
400
+ const decorated = {
401
+ ...toDraft(comp),
402
+ review: {
403
+ watermark: "REVIEW",
404
+ badges: buildBadges(comp)
181
405
  }
182
406
  };
183
- let job = null;
184
- let jobSeq = 0;
185
- /** Atomic write (tmp + rename) — agents read this file concurrently. */
186
- const persistComposition = async (comp) => {
187
- const tmp = `${take.compositionPath}.tmp`;
188
- await writeFile(tmp, JSON.stringify(comp, null, 2));
189
- await rename(tmp, take.compositionPath);
407
+ await renderTake({
408
+ composition: decorated,
409
+ videoPath: take.capturePath,
410
+ outPath: take.reviewPath,
411
+ captureLog,
412
+ logProgress: opts.logProgress ?? true,
413
+ chromePath,
414
+ writeCompositionSibling: false
415
+ });
416
+ return {
417
+ reviewPath: take.reviewPath,
418
+ sheet: buildBeatSheet(comp, take.name)
190
419
  };
191
- const server = createServer(async (req, res) => {
192
- try {
193
- const url$1 = new URL(req.url ?? "/", "http://localhost");
194
- const path = url$1.pathname;
195
- const method = req.method ?? "GET";
196
- if (method === "POST") {
197
- const host = req.headers.host ?? "";
198
- const origin = req.headers.origin;
199
- const sameOrigin = !origin || origin === `http://${host}`;
200
- const isJson = (req.headers["content-type"] ?? "").includes("application/json");
201
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || !sameOrigin || !isJson) {
202
- sendJson(res, 403, { error: "forbidden" });
203
- return;
204
- }
205
- }
206
- if (path === "/api/take" && method === "GET") {
207
- const composition = JSON.parse(await readFile(take.compositionPath, "utf8"));
208
- const captureLog = await loadCaptureLog();
209
- sendJson(res, 200, {
210
- composition,
211
- captureLog,
212
- source: { name: take.name },
213
- videoUrl: "/api/take/video",
214
- mp4Url: "/api/take/output"
215
- });
216
- return;
217
- }
218
- if (path === "/api/take/video" && method === "GET") {
219
- await serveFile(req, res, take.capturePath);
220
- return;
221
- }
222
- if (path === "/api/take/mtime" && method === "GET") {
223
- const st = await stat(take.compositionPath).catch(() => null);
224
- sendJson(res, 200, { mtime: st ? st.mtimeMs : 0 });
225
- return;
226
- }
227
- if (path === "/api/notes" && method === "POST") {
228
- const { text } = JSON.parse(await readBody(req));
229
- if (!text?.trim()) {
230
- sendJson(res, 400, { error: "empty note" });
231
- return;
232
- }
233
- const line = text.trim().replace(/\s+/g, " ").slice(0, 2e3);
234
- await appendFile(`${take.base}.notes.md`, `- ${line}\n`);
235
- process.stdout.write(`NOTE ${JSON.stringify({
236
- take: take.name,
237
- text: line
238
- })}\n`);
239
- sendJson(res, 200, { ok: true });
240
- return;
241
- }
242
- if (path === "/api/take/output" && method === "GET") {
243
- await serveFile(req, res, take.mp4Path);
244
- return;
245
- }
246
- if (path === "/api/composition" && method === "POST") {
247
- const comp = JSON.parse(await readBody(req));
248
- const captureLog = await loadCaptureLog();
249
- const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
250
- const errors = issues.filter((i) => i.severity === "error");
251
- if (errors.length) {
252
- sendJson(res, 400, { issues });
253
- return;
254
- }
255
- await persistComposition(comp);
256
- sendJson(res, 200, {
257
- ok: true,
258
- issues
259
- });
260
- return;
261
- }
262
- if (path === "/api/render" && method === "POST") {
263
- if (job?.status === "running") {
264
- sendJson(res, 409, { error: "a render is already in progress" });
265
- return;
266
- }
267
- const comp = JSON.parse(await readBody(req));
268
- const captureLog = await loadCaptureLog() ?? void 0;
269
- const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
270
- const errors = issues.filter((i) => i.severity === "error");
271
- if (errors.length) {
272
- sendJson(res, 400, { issues });
273
- return;
274
- }
275
- await persistComposition(comp);
276
- const id = `${Date.now().toString(36)}-${++jobSeq}`;
277
- job = {
278
- id,
279
- progress: 0,
280
- status: "running",
281
- clients: new Set()
282
- };
283
- sendJson(res, 200, { jobId: id });
284
- runRender(job, comp, captureLog);
285
- return;
420
+ }
421
+ function parseSetFlag(set, beat) {
422
+ const eq = set.indexOf("=");
423
+ if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got "${set}")`);
424
+ const key = set.slice(0, eq).trim();
425
+ const values = set.slice(eq + 1).split(",").map((v) => v.trim()).filter(Boolean);
426
+ if (values.length < 1) throw new Error(`ab: --set ${key}= needs at least one value`);
427
+ if (values.length > 3) throw new Error(`ab: at most 3 requested values (plus current) per reel`);
428
+ if (key === "zoom") {
429
+ if (!beat) throw new Error(`ab: --set zoom=… needs --beat <n> (which beat to reframe)`);
430
+ return {
431
+ knob: {
432
+ kind: "zoom",
433
+ beat
434
+ },
435
+ values
436
+ };
437
+ }
438
+ if (key === "look" || key === "pace" || key === "finish") return {
439
+ knob: { kind: key },
440
+ values
441
+ };
442
+ if (key.includes(".")) return {
443
+ knob: {
444
+ kind: "path",
445
+ path: key
446
+ },
447
+ values
448
+ };
449
+ throw new Error(`ab: unknown knob "${key}" — use zoom (with --beat), look, pace, finish, or a raw dot-path like cursor.holdMs`);
450
+ }
451
+ function setPath(comp, path, raw) {
452
+ const t = raw.trim();
453
+ const value = t === "true" ? true : t === "false" ? false : t === "null" ? null : Number.isFinite(Number(raw)) && t !== "" ? Number(raw) : raw;
454
+ const parts = path.split(".");
455
+ const next = structuredClone(comp);
456
+ let node = next;
457
+ for (const p of parts.slice(0, -1)) {
458
+ const child = node[p];
459
+ if (typeof child !== "object" || child == null) throw new Error(`ab: path "${path}" — "${p}" is not an object`);
460
+ node = child;
461
+ }
462
+ node[parts[parts.length - 1]] = value;
463
+ return next;
464
+ }
465
+ /** Current-state description for a knob (the implicit "keep it" variant). */
466
+ function currentDesc(comp, knob) {
467
+ if (knob.kind === "zoom") {
468
+ const e = comp.events[knob.beat - 1];
469
+ return e ? zoomText(e) : "?";
470
+ }
471
+ if (knob.kind === "look") return lookName(comp.framing) ?? "custom look";
472
+ if (knob.kind === "pace") return motionName(comp.cursor) ?? "custom pace";
473
+ if (knob.kind === "finish") return finishName(comp.motionBlur) ?? "custom finish";
474
+ const parts = knob.path.split(".");
475
+ let node = comp;
476
+ for (const p of parts) node = node?.[p];
477
+ return `${knob.path}=${JSON.stringify(node)}`;
478
+ }
479
+ function applyKnob(comp, knob, value) {
480
+ if (knob.kind === "zoom") {
481
+ const i = knob.beat - 1;
482
+ const e = comp.events[i];
483
+ if (!e) throw new Error(`ab: --beat ${knob.beat} out of range (1-${comp.events.length})`);
484
+ const events = comp.events.slice();
485
+ if (value === "off" || value === "wide") events[i] = {
486
+ ...e,
487
+ zoom: {
488
+ ...e.zoom,
489
+ enabled: false
286
490
  }
287
- const ev = /^\/api\/render\/([^/]+)\/events$/.exec(path);
288
- if (ev && method === "GET") {
289
- const id = ev[1];
290
- if (!job || job.id !== id) {
291
- sendJson(res, 404, { error: "unknown job" });
292
- return;
293
- }
294
- res.writeHead(200, {
295
- "Content-Type": "text/event-stream",
296
- "Cache-Control": "no-cache",
297
- Connection: "keep-alive"
298
- });
299
- emit(res, "progress", { progress: job.progress });
300
- if (job.status === "done") {
301
- emit(res, "done", { mp4Url: job.mp4Url });
302
- res.end();
303
- return;
304
- }
305
- if (job.status === "error") {
306
- emit(res, "failed", { message: job.error });
307
- res.end();
308
- return;
491
+ };
492
+ else {
493
+ const scale = value in ZOOM_LEVELS ? ZOOM_LEVELS[value] : Number(value);
494
+ if (!Number.isFinite(scale)) throw new Error(`ab: zoom value "${value}" — use off/light/medium/tight/close or a number`);
495
+ events[i] = {
496
+ ...e,
497
+ zoom: {
498
+ ...e.zoom,
499
+ enabled: true,
500
+ scale
309
501
  }
310
- job.clients.add(res);
311
- req.on("close", () => job?.clients.delete(res));
312
- return;
313
- }
314
- if (path.startsWith("/api/")) {
315
- sendJson(res, 404, { error: "no such endpoint" });
316
- return;
317
- }
318
- if (method !== "GET") {
319
- sendJson(res, 405, { error: "method not allowed" });
320
- return;
321
- }
322
- const rel = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
323
- let filePath = join(dist, rel === "/" ? "index.html" : rel);
324
- if (!filePath.startsWith(dist)) {
325
- sendJson(res, 403, { error: "forbidden" });
326
- return;
327
- }
328
- const fst = await stat(filePath).catch(() => null);
329
- if (!fst?.isFile()) filePath = join(dist, "index.html");
330
- await serveFile(req, res, filePath);
331
- } catch (err) {
332
- sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
502
+ };
333
503
  }
334
- });
335
- async function runRender(j, comp, captureLog) {
336
- try {
337
- await renderComposition({
338
- composition: comp,
339
- capturePath: take.capturePath,
340
- outPath: take.mp4Path,
341
- captureLog,
342
- chromePath: opts.chromePath,
343
- onProgress: (p) => {
344
- j.progress = p;
345
- for (const c of j.clients) emit(c, "progress", { progress: p });
346
- }
347
- });
348
- j.status = "done";
349
- j.progress = 1;
350
- j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;
351
- for (const c of j.clients) {
352
- emit(c, "done", { mp4Url: j.mp4Url });
353
- c.end();
504
+ return {
505
+ ...comp,
506
+ events
507
+ };
508
+ }
509
+ if (knob.kind === "look") {
510
+ const look = LOOKS[value];
511
+ if (!look) throw new Error(`ab: unknown look "${value}" — one of ${Object.keys(LOOKS).join("/")}`);
512
+ return {
513
+ ...comp,
514
+ framing: {
515
+ ...comp.framing,
516
+ ...structuredClone(look)
354
517
  }
355
- } catch (err) {
356
- j.status = "error";
357
- j.error = err instanceof Error ? err.message : String(err);
358
- for (const c of j.clients) {
359
- emit(c, "failed", { message: j.error });
360
- c.end();
518
+ };
519
+ }
520
+ if (knob.kind === "pace") {
521
+ const pace = MOTION[value];
522
+ if (!pace) throw new Error(`ab: unknown pace "${value}" — one of ${Object.keys(MOTION).join("/")}`);
523
+ const oldZoomInMs = comp.cursor.zoomInMs;
524
+ const events = comp.events.map((e) => e.zoom.inAtMs === Math.max(0, e.tMs - oldZoomInMs) ? {
525
+ ...e,
526
+ zoom: {
527
+ ...e.zoom,
528
+ inAtMs: Math.max(0, e.tMs - pace.zoomInMs)
361
529
  }
362
- } finally {
363
- j.clients.clear();
364
- }
530
+ } : e);
531
+ return {
532
+ ...comp,
533
+ events,
534
+ cursor: {
535
+ ...comp.cursor,
536
+ ...pace
537
+ }
538
+ };
365
539
  }
366
- const port = await listen(server, opts.port ?? 4178);
367
- const url = `http://127.0.0.1:${port}/`;
368
- process.stdout.write(`open-take editor → ${url}\n(serving take "${take.name}"; Ctrl-C to stop)\n`);
369
- if (opts.open !== false) openBrowser(url);
370
- return {
371
- url,
372
- close: () => new Promise((r) => server.close(() => r()))
373
- };
540
+ if (knob.kind === "finish") {
541
+ if (!(value in FINISH)) throw new Error(`ab: unknown finish "${value}" — one of ${Object.keys(FINISH).join("/")}`);
542
+ const mb = FINISH[value];
543
+ const { motionBlur: _mb,...rest } = comp;
544
+ return mb ? {
545
+ ...rest,
546
+ motionBlur: { ...mb }
547
+ } : rest;
548
+ }
549
+ return setPath(comp, knob.path, value);
374
550
  }
375
- function emit(res, event, data) {
376
- res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
551
+ function variantDesc(knob, value, comp) {
552
+ if (knob.kind === "zoom") {
553
+ const e = comp.events[knob.beat - 1];
554
+ return e ? zoomText(e) : value;
555
+ }
556
+ if (knob.kind === "path") return `${knob.path}=${value}`;
557
+ return value;
377
558
  }
378
- /** Bind to 127.0.0.1 only; if the port is taken, try the next few. */
379
- function listen(server, startPort) {
380
- return new Promise((res, rej) => {
381
- let port = startPort;
382
- const tryOne = () => {
383
- server.once("error", (e) => {
384
- if (e.code === "EADDRINUSE" && port < startPort + 20) {
385
- port++;
386
- tryOne();
387
- } else rej(e);
388
- });
389
- server.listen(port, "127.0.0.1", () => res(port));
390
- };
391
- tryOne();
392
- });
559
+ /** The reel's time window (ms): a beat's zoom arc with lead-in/out padding, so
560
+ * a taste question costs a ~4s render per variant, not the whole take. The
561
+ * window is the UNION across all variant compositions — a variant with a
562
+ * longer hold/zoom-out (or a rebased inAtMs) must not be cut mid-settle, since
563
+ * the settle is exactly what the reel exists to judge. */
564
+ function abWindow(comps, beat, full) {
565
+ if (full) return void 0;
566
+ const base = comps[0];
567
+ if (!base || base.events.length === 0) return void 0;
568
+ if (beat != null && (beat < 1 || beat > base.events.length)) throw new Error(`ab: --beat ${beat} out of range (1-${base.events.length})`);
569
+ let i = beat != null ? beat - 1 : base.events.findIndex((e) => e.zoom.enabled);
570
+ if (i < 0) i = 0;
571
+ let from = Number.POSITIVE_INFINITY;
572
+ let to = 0;
573
+ for (const c of comps) {
574
+ const e = c.events[i];
575
+ if (!e) continue;
576
+ const rampFrom = Math.min(e.zoom.inAtMs, e.tMs - c.cursor.zoomOutMs);
577
+ from = Math.min(from, Math.max(0, rampFrom - 1200));
578
+ const next = c.events[i + 1];
579
+ const ownEnd = e.tMs + (e.durationMs ?? 0) + c.cursor.holdMs + c.cursor.zoomOutMs;
580
+ to = Math.max(to, (next ? next.zoom.inAtMs : ownEnd) + 400);
581
+ }
582
+ if (!Number.isFinite(from)) return void 0;
583
+ return [from, Math.max(to, from + 1500)];
393
584
  }
394
-
395
- //#endregion
396
- //#region src/review.ts
397
- /** Sibling capture log (`<capture>.json`), if present — enables the
398
- * capture-lock check; silently absent otherwise (matches index.ts). */
399
- async function loadLogSibling(capturePath) {
585
+ const LETTERS = [
586
+ "A",
587
+ "B",
588
+ "C",
589
+ "D"
590
+ ];
591
+ async function renderAbReel(take, opts) {
592
+ await requireTakeFiles(take, { capture: true });
593
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
594
+ const captureLog = await loadLogSibling(take.capturePath);
595
+ const chromePath = await ensureChrome(opts.chromePath);
596
+ const { knob, values } = parseSetFlag(opts.set, opts.beat);
597
+ const cur = currentDesc(comp, knob);
598
+ const variants = [{
599
+ letter: "A",
600
+ desc: `current (${cur})`,
601
+ comp
602
+ }];
603
+ for (const v of values) {
604
+ const applied = applyKnob(comp, knob, v);
605
+ const desc = variantDesc(knob, v, applied);
606
+ if (desc === cur || variants.some((x) => x.desc === desc)) continue;
607
+ variants.push({
608
+ letter: LETTERS[variants.length],
609
+ desc,
610
+ comp: applied
611
+ });
612
+ }
613
+ if (variants.length < 2) throw new Error(`ab: every requested value matches the current state — nothing to compare`);
614
+ for (const v of variants) {
615
+ const issues = validateComposition$1(v.comp, captureLog ? { captureLog } : {});
616
+ const errors = issues.filter((i) => i.severity === "error");
617
+ if (errors.length) throw new Error(`ab: variant ${v.letter} (${v.desc}) is invalid:\n${formatIssues$1(errors)}`);
618
+ }
619
+ const windowMs = abWindow(variants.map((v) => v.comp), opts.beat, opts.full ?? false);
620
+ const rangeSec = windowMs ? [windowMs[0] / 1e3, windowMs[1] / 1e3] : void 0;
621
+ const clips = [];
400
622
  try {
401
- return JSON.parse(await readFile(resolve(capturePath).replace(/\.mp4$/i, ".json"), "utf8"));
402
- } catch {
403
- return void 0;
623
+ for (const v of variants) {
624
+ const base = opts.draft ? toDraft(v.comp) : v.comp;
625
+ const decorated = {
626
+ ...base,
627
+ review: { label: `${v.letter} · ${v.desc}` }
628
+ };
629
+ const clip = `${take.base}.ab.${v.letter}.mp4`;
630
+ if (opts.logProgress !== false) process.stderr.write(`variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : ""}\n`);
631
+ await renderTake({
632
+ composition: decorated,
633
+ videoPath: take.capturePath,
634
+ outPath: clip,
635
+ captureLog,
636
+ logProgress: opts.logProgress ?? true,
637
+ chromePath,
638
+ rangeSec,
639
+ writeCompositionSibling: false
640
+ });
641
+ clips.push(clip);
642
+ }
643
+ await concatWithGaps([...clips, ...clips], take.abPath, {
644
+ width: comp.output.width,
645
+ height: comp.output.height,
646
+ fps: opts.draft ? Math.min(30, comp.output.fps) : comp.output.fps
647
+ });
648
+ } finally {
649
+ await Promise.all(clips.map((c) => rm(c, { force: true })));
404
650
  }
405
- }
406
- const KIND_LABEL = {
407
- click: "click",
408
- type: "type",
409
- drag: "drag",
410
- scroll: "scroll",
411
- hover: "hover",
412
- press: "key"
413
- };
414
- function beatTitle(e) {
415
- if (e.label) return e.label;
416
- if (e.kind === "type" && e.text) return `"${e.text}"`;
417
- if (e.kind === "press" && e.keys) return e.keys;
418
- return e.kind;
419
- }
420
- const trunc = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
421
- function fmtTime(ms) {
422
- const s = Math.max(0, Math.round(ms / 1e3));
423
- return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
424
- }
425
- /** "zoom medium (×1.5)" | "zoom ×1.85 (custom)" | "wide" */
426
- function zoomText(e) {
427
- if (!e.zoom.enabled) return "wide";
428
- const name = zoomLevelName(e.zoom.scale);
429
- const x = `×${Number(e.zoom.scale.toFixed(2))}`;
430
- return name ? `zoom ${name} (${x})` : `zoom ${x} (custom)`;
431
- }
432
- function buildBeatSheet(comp, name) {
433
- const n = comp.events.length;
434
- const look = lookName(comp.framing) ?? "custom";
435
- const pace = motionName(comp.cursor) ?? "custom";
436
- const finish = finishName(comp.motionBlur) ?? "custom";
437
- const lines = [`${name} · ${(comp.durationMs / 1e3).toFixed(1)}s · ${n} beat${n === 1 ? "" : "s"} · look ${look} · pace ${pace} · finish ${finish}`];
438
- const first = comp.events[0];
439
- if (!first || first.zoom.inAtMs > 400) lines.push(` in 0:00 full view, cursor glides in`);
440
- comp.events.forEach((e, i) => {
441
- const num = String(i + 1).padStart(2, " ");
442
- const kind = KIND_LABEL[e.kind].padEnd(6, " ");
443
- const title = trunc(beatTitle(e), 24).padEnd(25, " ");
444
- lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);
651
+ const legend = [
652
+ `A/B reel: ${take.abPath} (${knobLabel(knob)})`,
653
+ ...variants.map((v) => ` ${v.letter} ${v.desc}`),
654
+ `answer with a letter — or "between A and B" / "none, try …"`
655
+ ].join("\n");
656
+ return {
657
+ abPath: take.abPath,
658
+ legend
659
+ };
660
+ }
661
+ function knobLabel(knob) {
662
+ if (knob.kind === "zoom") return `beat ${knob.beat} · zoom`;
663
+ if (knob.kind === "path") return knob.path;
664
+ return knob.kind;
665
+ }
666
+ /** before/after reel from the existing prev + current masters — no render at
667
+ * all, pure ffmpeg trims. Order convention: BEFORE then AFTER, twice. */
668
+ async function renderBeforeAfter(take, opts = {}) {
669
+ await requireTakeFiles(take);
670
+ if (!await stat(take.prevPath).catch(() => null)) throw new Error(`ab --before-after: no ${take.prevPath} yet (it appears after a re-render)`);
671
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
672
+ const win = abWindow([comp], opts.beat, opts.full ?? false);
673
+ const cut = async (src, out) => {
674
+ const args = [
675
+ "-y",
676
+ "-loglevel",
677
+ "error",
678
+ "-i",
679
+ src
680
+ ];
681
+ if (win) args.push("-ss", String(win[0] / 1e3), "-t", String((win[1] - win[0]) / 1e3));
682
+ args.push("-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
683
+ await ffmpeg(args);
684
+ };
685
+ const before = `${take.base}.ab.before.mp4`;
686
+ const after = `${take.base}.ab.after.mp4`;
687
+ await cut(take.prevPath, before);
688
+ await cut(take.mp4Path, after);
689
+ await concatWithGaps([
690
+ before,
691
+ after,
692
+ before,
693
+ after
694
+ ], take.abPath, {
695
+ width: comp.output.width,
696
+ height: comp.output.height,
697
+ fps: comp.output.fps
445
698
  });
446
- const last = comp.events[n - 1];
447
- if (last) {
448
- const endMs = last.tMs + (last.durationMs ?? 0) + comp.cursor.holdMs;
449
- lines.push(` out ${fmtTime(endMs)} zoom releases, holds to ${fmtTime(comp.durationMs)}`);
450
- }
451
- lines.push(`say it like: "beat 2: no zoom" · "tighter on beat 3" · "look: slate" · "pace: brisk"`);
452
- return lines.join("\n");
699
+ await Promise.all([rm(before, { force: true }), rm(after, { force: true })]);
700
+ const legend = [`before/after reel: ${take.abPath}`, ` plays BEFORE then AFTER, twice — say "keep the old one" to revert`].join("\n");
701
+ return {
702
+ abPath: take.abPath,
703
+ legend
704
+ };
453
705
  }
454
- const SAY_IT_CARD = `SAY IT, I'LL CUT IT
455
- instant (~10s) zoom off / tighter / looser on a beat · re-center a beat (name the
456
- element) · hold longer · pace: calm / natural / brisk · look:
457
- midnight / ink / slate / ocean / plum / ember / paper / plain ·
458
- finish: smooth / crisp / heavy · quicker intro · shorter tail
459
- re-shoot (~1m) change what's clicked or typed · add / cut / reorder beats ·
460
- retime an action
461
- compare taste questions come back as an A/B reel — answer with a letter
462
- ("B"), or "between A and B", or "none, go darker"`;
463
- /** Badge windows: each beat owns [its zoom.inAtMs, the next beat's) — the pill
464
- * swaps as the camera starts moving toward the beat. INTRO/TAIL bracket them. */
465
- function buildBadges(comp) {
466
- const n = comp.events.length;
467
- const badges = [];
468
- let prevStart = 0;
469
- const starts = comp.events.map((e) => {
470
- const s = Math.max(e.zoom.inAtMs, prevStart + 1);
471
- prevStart = s;
472
- return s;
706
+ async function ffmpeg(args) {
707
+ const bin = await resolveFfmpeg();
708
+ return new Promise((res, rej) => {
709
+ const c = spawn(bin, args, { stdio: [
710
+ "ignore",
711
+ "ignore",
712
+ "pipe"
713
+ ] });
714
+ let err = "";
715
+ c.stderr.on("data", (d) => {
716
+ err += d;
717
+ });
718
+ c.on("error", rej);
719
+ c.on("close", (code) => code === 0 ? res() : rej(new Error(`ffmpeg exited ${code}: ${err}`)));
473
720
  });
474
- if (n === 0 || starts[0] > 400) badges.push({
475
- fromMs: 0,
476
- toMs: starts[0] ?? comp.durationMs,
477
- text: "INTRO"
721
+ }
722
+ /** Concat clips with a 0.35s black gap between each, re-encoding via the concat
723
+ * FILTER (robust to per-clip encoder variance; everything shares WxH/fps). The
724
+ * gap comes from a lavfi color source — no font/text filters needed. */
725
+ async function concatWithGaps(clips, outPath, v) {
726
+ const args = [
727
+ "-y",
728
+ "-loglevel",
729
+ "error"
730
+ ];
731
+ for (const c of clips) args.push("-i", resolve(c));
732
+ args.push("-f", "lavfi", "-t", "0.35", "-i", `color=c=black:s=${v.width}x${v.height}:r=${v.fps}`);
733
+ const gapIdx = clips.length;
734
+ const seq = [];
735
+ const gapUses = clips.length - 1;
736
+ const split = gapUses > 1 ? `[${gapIdx}:v]split=${gapUses}${Array.from({ length: gapUses }, (_, i) => `[g${i}]`).join("")};` : "";
737
+ clips.forEach((_, i) => {
738
+ seq.push(`[${i}:v]`);
739
+ if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);
478
740
  });
479
- comp.events.forEach((e, i) => {
480
- const last = i === n - 1;
481
- const endOwn = e.tMs + (e.durationMs ?? 0) + comp.cursor.holdMs;
482
- const to = last ? Math.min(endOwn, comp.durationMs) : starts[i + 1];
483
- badges.push({
484
- fromMs: starts[i],
485
- toMs: to,
486
- text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`
487
- });
488
- if (last && to < comp.durationMs + 1e3) badges.push({
489
- fromMs: to,
490
- toMs: comp.durationMs + 1500,
491
- text: "TAIL"
741
+ const filter = `${split}${seq.join("")}concat=n=${seq.length}:v=1:a=0[v]`;
742
+ args.push("-filter_complex", filter, "-map", "[v]", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-r", String(v.fps), "-an", resolve(outPath));
743
+ await ffmpeg(args);
744
+ }
745
+ function spawnOpener(spec, fallbackLine) {
746
+ try {
747
+ const c = spawn(spec.command, spec.args, {
748
+ stdio: "ignore",
749
+ detached: true,
750
+ windowsVerbatimArguments: spec.windowsVerbatimArguments
492
751
  });
493
- });
494
- return badges;
752
+ c.on("error", () => process.stdout.write(fallbackLine));
753
+ c.unref();
754
+ } catch {
755
+ process.stdout.write(fallbackLine);
756
+ }
495
757
  }
496
- /** Draft-quality transform: 30fps cap + motion blur OFF — up to ~12× faster
497
- * than a blurred 60fps master, close enough for composition-level notes.
498
- * (2 blur samples would render 2× the frames for a tmix window that rounds to
499
- * 1 — all cost, zero blur.) FEEL questions (blur, pace, zoom silkiness) must
500
- * be judged on full quality — use `ab`. */
501
- function toDraft(comp) {
502
- const { motionBlur: _mb,...rest } = comp;
758
+ /** Wrap a path/URL for a verbatim Windows command line. Safe unquoted-inside:
759
+ * `"` is illegal in Windows filenames, and cmd stops treating `&` `^` `|` as
760
+ * metacharacters once quoted. */
761
+ const winQuote = (s) => `"${s}"`;
762
+ /** Pure command specs keep platform quoting independently testable on every
763
+ * CI runner, including the Windows-only `start` title argument rule. */
764
+ function getOpenCommand(target, platform = process.platform) {
765
+ if (platform === "darwin") return {
766
+ command: "open",
767
+ args: [target],
768
+ windowsVerbatimArguments: false
769
+ };
770
+ if (platform === "win32") return {
771
+ command: "cmd",
772
+ args: [
773
+ "/c",
774
+ "start",
775
+ "\"\"",
776
+ winQuote(target)
777
+ ],
778
+ windowsVerbatimArguments: true
779
+ };
503
780
  return {
504
- ...rest,
505
- output: {
506
- ...comp.output,
507
- fps: Math.min(30, comp.output.fps)
508
- }
781
+ command: "xdg-open",
782
+ args: [target],
783
+ windowsVerbatimArguments: false
509
784
  };
510
785
  }
511
- async function renderReview(take, opts = {}) {
512
- await requireTakeFiles(take, { capture: true });
513
- const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
514
- const captureLog = await loadLogSibling(take.capturePath);
515
- const chromePath = await ensureChrome(opts.chromePath);
516
- const decorated = {
517
- ...toDraft(comp),
518
- review: {
519
- watermark: "REVIEW",
520
- badges: buildBadges(comp)
521
- }
786
+ function getRevealCommand(absolutePath, platform = process.platform) {
787
+ if (platform === "darwin") return {
788
+ command: "open",
789
+ args: ["-R", absolutePath],
790
+ windowsVerbatimArguments: false
791
+ };
792
+ if (platform === "win32") return {
793
+ command: "explorer",
794
+ args: [`/select,${winQuote(absolutePath)}`],
795
+ windowsVerbatimArguments: true
522
796
  };
523
- await renderTake({
524
- composition: decorated,
525
- videoPath: take.capturePath,
526
- outPath: take.reviewPath,
527
- captureLog,
528
- logProgress: opts.logProgress ?? true,
529
- chromePath,
530
- writeCompositionSibling: false
531
- });
532
797
  return {
533
- reviewPath: take.reviewPath,
534
- sheet: buildBeatSheet(comp, take.name)
798
+ command: "xdg-open",
799
+ args: [dirname(absolutePath)],
800
+ windowsVerbatimArguments: false
535
801
  };
536
802
  }
537
- function parseSetFlag(set, beat) {
538
- const eq = set.indexOf("=");
539
- if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got "${set}")`);
540
- const key = set.slice(0, eq).trim();
541
- const values = set.slice(eq + 1).split(",").map((v) => v.trim()).filter(Boolean);
542
- if (values.length < 1) throw new Error(`ab: --set ${key}= needs at least one value`);
543
- if (values.length > 3) throw new Error(`ab: at most 3 requested values (plus current) per reel`);
544
- if (key === "zoom") {
545
- if (!beat) throw new Error(`ab: --set zoom=… needs --beat <n> (which beat to reframe)`);
546
- return {
547
- knob: {
548
- kind: "zoom",
549
- beat
550
- },
551
- values
552
- };
803
+ /** Open a file with the OS default player; degrade to printing the path. */
804
+ function openPath(p) {
805
+ const abs = resolve(p);
806
+ openWithOs(abs, `open: ${abs}\n`);
807
+ }
808
+ /** Hand a path or URL to the OS default handler. Windows needs `cmd /c start`
809
+ * with an EMPTY first argument: `start` reads a lone quoted argument as the
810
+ * window TITLE, so `start "<file>"` opens a blank console instead of the file. */
811
+ function openWithOs(target, fallbackLine) {
812
+ spawnOpener(getOpenCommand(target), fallbackLine);
813
+ }
814
+ /** Reveal a file in Finder/Explorer; degrade to printing the path. */
815
+ function revealPath(p) {
816
+ const abs = resolve(p);
817
+ spawnOpener(getRevealCommand(abs), `at: ${abs}\n`);
818
+ }
819
+
820
+ //#endregion
821
+ //#region src/edit-server.ts
822
+ const CONTENT_TYPE = {
823
+ ".html": "text/html; charset=utf-8",
824
+ ".js": "text/javascript; charset=utf-8",
825
+ ".mjs": "text/javascript; charset=utf-8",
826
+ ".css": "text/css; charset=utf-8",
827
+ ".json": "application/json; charset=utf-8",
828
+ ".svg": "image/svg+xml",
829
+ ".png": "image/png",
830
+ ".jpg": "image/jpeg",
831
+ ".ico": "image/x-icon",
832
+ ".woff2": "font/woff2",
833
+ ".woff": "font/woff",
834
+ ".map": "application/json; charset=utf-8"
835
+ };
836
+ /** Locate the built editor SPA: prefer the live monorepo build during
837
+ * development, then fall back to the bundled copy used by the published
838
+ * package. */
839
+ function resolveEditorDist() {
840
+ const here = fileURLToPath(import.meta.url);
841
+ const pkgRoot = resolve(here, "..", "..");
842
+ const candidates = [resolve(pkgRoot, "..", "..", "apps", "editor", "dist"), resolve(pkgRoot, "editor-dist")];
843
+ return candidates.find((c) => existsHtml(c)) ?? null;
844
+ }
845
+ function existsHtml(dir) {
846
+ return existsFile(join(dir, "index.html"));
847
+ }
848
+ function existsFile(path) {
849
+ try {
850
+ return statSync(path).isFile();
851
+ } catch {
852
+ return false;
553
853
  }
554
- if (key === "look" || key === "pace" || key === "finish") return {
555
- knob: { kind: key },
556
- values
557
- };
558
- if (key.includes(".")) return {
559
- knob: {
560
- kind: "path",
561
- path: key
562
- },
563
- values
564
- };
565
- throw new Error(`ab: unknown knob "${key}" — use zoom (with --beat), look, pace, finish, or a raw dot-path like cursor.holdMs`);
566
854
  }
567
- function setPath(comp, path, raw) {
568
- const t = raw.trim();
569
- const value = t === "true" ? true : t === "false" ? false : t === "null" ? null : Number.isFinite(Number(raw)) && t !== "" ? Number(raw) : raw;
570
- const parts = path.split(".");
571
- const next = structuredClone(comp);
572
- let node = next;
573
- for (const p of parts.slice(0, -1)) {
574
- const child = node[p];
575
- if (typeof child !== "object" || child == null) throw new Error(`ab: path "${path}" — "${p}" is not an object`);
576
- node = child;
855
+ const sendJson = (res, status, obj) => {
856
+ const body = JSON.stringify(obj);
857
+ res.writeHead(status, {
858
+ "Content-Type": "application/json; charset=utf-8",
859
+ "Content-Length": Buffer.byteLength(body)
860
+ });
861
+ res.end(body);
862
+ };
863
+ async function readBody(req, capBytes = 32 * 1024 * 1024) {
864
+ const chunks = [];
865
+ let size = 0;
866
+ for await (const c of req) {
867
+ size += c.length;
868
+ if (size > capBytes) throw new Error("request body too large");
869
+ chunks.push(c);
577
870
  }
578
- node[parts[parts.length - 1]] = value;
579
- return next;
871
+ return Buffer.concat(chunks).toString("utf8");
580
872
  }
581
- /** Current-state description for a knob (the implicit "keep it" variant). */
582
- function currentDesc(comp, knob) {
583
- if (knob.kind === "zoom") {
584
- const e = comp.events[knob.beat - 1];
585
- return e ? zoomText(e) : "?";
873
+ /** Stream a file with HTTP Range support (206) — required for <video> seeking. */
874
+ async function serveFile(req, res, filePath) {
875
+ const st = await stat(filePath).catch(() => null);
876
+ if (!st?.isFile()) {
877
+ sendJson(res, 404, { error: "not found" });
878
+ return;
879
+ }
880
+ const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? "application/octet-stream";
881
+ const range = req.headers.range;
882
+ if (range) {
883
+ const m = /bytes=(\d*)-(\d*)/.exec(range);
884
+ const start = m?.[1] ? Number(m[1]) : 0;
885
+ const end = m?.[2] ? Number(m[2]) : st.size - 1;
886
+ if (start >= st.size || end >= st.size || start > end) {
887
+ res.writeHead(416, { "Content-Range": `bytes */${st.size}` });
888
+ res.end();
889
+ return;
890
+ }
891
+ res.writeHead(206, {
892
+ "Content-Range": `bytes ${start}-${end}/${st.size}`,
893
+ "Accept-Ranges": "bytes",
894
+ "Content-Length": end - start + 1,
895
+ "Content-Type": type
896
+ });
897
+ createReadStream(filePath, {
898
+ start,
899
+ end
900
+ }).pipe(res);
901
+ } else {
902
+ res.writeHead(200, {
903
+ "Content-Length": st.size,
904
+ "Accept-Ranges": "bytes",
905
+ "Content-Type": type
906
+ });
907
+ createReadStream(filePath).pipe(res);
586
908
  }
587
- if (knob.kind === "look") return lookName(comp.framing) ?? "custom look";
588
- if (knob.kind === "pace") return motionName(comp.cursor) ?? "custom pace";
589
- if (knob.kind === "finish") return finishName(comp.motionBlur) ?? "custom finish";
590
- const parts = knob.path.split(".");
591
- let node = comp;
592
- for (const p of parts) node = node?.[p];
593
- return `${knob.path}=${JSON.stringify(node)}`;
594
909
  }
595
- function applyKnob(comp, knob, value) {
596
- if (knob.kind === "zoom") {
597
- const i = knob.beat - 1;
598
- const e = comp.events[i];
599
- if (!e) throw new Error(`ab: --beat ${knob.beat} out of range (1-${comp.events.length})`);
600
- const events = comp.events.slice();
601
- if (value === "off" || value === "wide") events[i] = {
602
- ...e,
603
- zoom: {
604
- ...e.zoom,
605
- enabled: false
606
- }
910
+ /** Open the editor in the default browser. Shares the OS-opener with review.ts
911
+ * — a private copy here is how the Windows `start`-eats-the-first-quoted-arg
912
+ * bug survived in one place after being noticed in the other. */
913
+ function openBrowser(url) {
914
+ openWithOs(url, `open: ${url}\n`);
915
+ }
916
+ async function startEditServer(opts, deps = {}) {
917
+ const take = await resolveTakePaths(opts.takePath);
918
+ for (const f of [take.compositionPath, take.capturePath]) if (!(await stat(f).catch(() => null))?.isFile()) throw new Error(`missing take file: ${f}`);
919
+ const dist = resolveEditorDist();
920
+ if (!dist) throw new Error("editor build not found — run `pnpm --filter @open-take/editor build` first");
921
+ const loadCaptureLog = async () => {
922
+ try {
923
+ return JSON.parse(await readFile(take.captureLogPath, "utf8"));
924
+ } catch {
925
+ return null;
926
+ }
927
+ };
928
+ let job = null;
929
+ let jobSeq = 0;
930
+ let renderStarting = false;
931
+ const compositionMtime = async () => (await stat(take.compositionPath).catch(() => null))?.mtimeMs ?? 0;
932
+ let writeLock = Promise.resolve();
933
+ const exclusive = (fn) => {
934
+ const run = writeLock.then(fn, fn);
935
+ writeLock = run.catch(() => {});
936
+ return run;
937
+ };
938
+ /** Persist unless someone else wrote first. `baseMtime` is the mtime the
939
+ * client last read. Every API write must provide it; 保留我的 re-bases to
940
+ * the 409's mtime and remains guarded against an even newer write.
941
+ *
942
+ * We check once before writing the temp file and again immediately before
943
+ * rename, so an agent write during serialization/I/O is refused too. No
944
+ * portable filesystem API provides compare-and-swap by mtime: a different
945
+ * process writing in the final stat→rename window can still be overwritten
946
+ * unless every writer honors the same lock. */
947
+ const persistGuarded = async (comp, baseMtime) => exclusive(async () => {
948
+ const onDisk = await compositionMtime();
949
+ if (baseMtime !== void 0 && onDisk !== baseMtime) return {
950
+ ok: false,
951
+ mtime: onDisk
607
952
  };
608
- else {
609
- const scale = value in ZOOM_LEVELS ? ZOOM_LEVELS[value] : Number(value);
610
- if (!Number.isFinite(scale)) throw new Error(`ab: zoom value "${value}" — use off/light/medium/tight/close or a number`);
611
- events[i] = {
612
- ...e,
613
- zoom: {
614
- ...e.zoom,
615
- enabled: true,
616
- scale
617
- }
953
+ const tmp = `${take.compositionPath}.tmp`;
954
+ let committed = false;
955
+ try {
956
+ await writeFile(tmp, JSON.stringify(comp, null, 2));
957
+ await deps.beforeCompositionCommit?.();
958
+ if (baseMtime !== void 0) {
959
+ const beforeRename = await compositionMtime();
960
+ if (beforeRename !== onDisk) return {
961
+ ok: false,
962
+ mtime: beforeRename
963
+ };
964
+ }
965
+ await rename(tmp, take.compositionPath);
966
+ committed = true;
967
+ return {
968
+ ok: true,
969
+ mtime: await compositionMtime()
618
970
  };
971
+ } finally {
972
+ if (!committed) await unlink(tmp).catch(() => {});
973
+ }
974
+ });
975
+ /** The write guard is mandatory. A missing base used to mean "force write",
976
+ * which made a bare JSON body an invisible escape hatch around conflict
977
+ * protection. Callers must first GET /api/take and echo its mtime. */
978
+ const readWrite = async (req, res) => {
979
+ let parsed;
980
+ try {
981
+ parsed = JSON.parse(await readBody(req));
982
+ } catch {
983
+ sendJson(res, 400, { error: "invalid JSON request body" });
984
+ return null;
985
+ }
986
+ const candidate = parsed && typeof parsed === "object" ? parsed : null;
987
+ if (!candidate?.composition || typeof candidate.baseMtime !== "number" || !Number.isFinite(candidate.baseMtime)) {
988
+ sendJson(res, 428, { error: "write precondition required: send { composition, baseMtime } using the mtime from GET /api/take" });
989
+ return null;
619
990
  }
620
991
  return {
621
- ...comp,
622
- events
623
- };
624
- }
625
- if (knob.kind === "look") {
626
- const look = LOOKS[value];
627
- if (!look) throw new Error(`ab: unknown look "${value}" — one of ${Object.keys(LOOKS).join("/")}`);
628
- return {
629
- ...comp,
630
- framing: {
631
- ...comp.framing,
632
- ...structuredClone(look)
633
- }
992
+ composition: candidate.composition,
993
+ baseMtime: candidate.baseMtime
634
994
  };
635
- }
636
- if (knob.kind === "pace") {
637
- const pace = MOTION[value];
638
- if (!pace) throw new Error(`ab: unknown pace "${value}" — one of ${Object.keys(MOTION).join("/")}`);
639
- const oldZoomInMs = comp.cursor.zoomInMs;
640
- const events = comp.events.map((e) => e.zoom.inAtMs === Math.max(0, e.tMs - oldZoomInMs) ? {
641
- ...e,
642
- zoom: {
643
- ...e.zoom,
644
- inAtMs: Math.max(0, e.tMs - pace.zoomInMs)
995
+ };
996
+ const server = createServer(async (req, res) => {
997
+ try {
998
+ const url$1 = new URL(req.url ?? "/", "http://localhost");
999
+ const path = url$1.pathname;
1000
+ const method = req.method ?? "GET";
1001
+ if (method === "POST") {
1002
+ const host = req.headers.host ?? "";
1003
+ const origin = req.headers.origin;
1004
+ const sameOrigin = !origin || origin === `http://${host}`;
1005
+ const isJson = (req.headers["content-type"] ?? "").includes("application/json");
1006
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || !sameOrigin || !isJson) {
1007
+ sendJson(res, 403, { error: "forbidden" });
1008
+ return;
1009
+ }
645
1010
  }
646
- } : e);
647
- return {
648
- ...comp,
649
- events,
650
- cursor: {
651
- ...comp.cursor,
652
- ...pace
1011
+ if (path === "/api/take" && method === "GET") {
1012
+ const mtime = await compositionMtime();
1013
+ const composition = JSON.parse(await readFile(take.compositionPath, "utf8"));
1014
+ const captureLog = await loadCaptureLog();
1015
+ sendJson(res, 200, {
1016
+ composition,
1017
+ captureLog,
1018
+ source: { name: take.name },
1019
+ videoUrl: "/api/take/video",
1020
+ mp4Url: "/api/take/output",
1021
+ mtime
1022
+ });
1023
+ return;
653
1024
  }
654
- };
655
- }
656
- if (knob.kind === "finish") {
657
- if (!(value in FINISH)) throw new Error(`ab: unknown finish "${value}" — one of ${Object.keys(FINISH).join("/")}`);
658
- const mb = FINISH[value];
659
- const { motionBlur: _mb,...rest } = comp;
660
- return mb ? {
661
- ...rest,
662
- motionBlur: { ...mb }
663
- } : rest;
664
- }
665
- return setPath(comp, knob.path, value);
666
- }
667
- function variantDesc(knob, value, comp) {
668
- if (knob.kind === "zoom") {
669
- const e = comp.events[knob.beat - 1];
670
- return e ? zoomText(e) : value;
671
- }
672
- if (knob.kind === "path") return `${knob.path}=${value}`;
673
- return value;
674
- }
675
- /** The reel's time window (ms): a beat's zoom arc with lead-in/out padding, so
676
- * a taste question costs a ~4s render per variant, not the whole take. The
677
- * window is the UNION across all variant compositions — a variant with a
678
- * longer hold/zoom-out (or a rebased inAtMs) must not be cut mid-settle, since
679
- * the settle is exactly what the reel exists to judge. */
680
- function abWindow(comps, beat, full) {
681
- if (full) return void 0;
682
- const base = comps[0];
683
- if (!base || base.events.length === 0) return void 0;
684
- if (beat != null && (beat < 1 || beat > base.events.length)) throw new Error(`ab: --beat ${beat} out of range (1-${base.events.length})`);
685
- let i = beat != null ? beat - 1 : base.events.findIndex((e) => e.zoom.enabled);
686
- if (i < 0) i = 0;
687
- let from = Number.POSITIVE_INFINITY;
688
- let to = 0;
689
- for (const c of comps) {
690
- const e = c.events[i];
691
- if (!e) continue;
692
- from = Math.min(from, Math.max(0, e.zoom.inAtMs - 1200));
693
- const next = c.events[i + 1];
694
- const ownEnd = e.tMs + (e.durationMs ?? 0) + c.cursor.holdMs + c.cursor.zoomOutMs;
695
- to = Math.max(to, (next ? next.zoom.inAtMs : ownEnd) + 400);
696
- }
697
- if (!Number.isFinite(from)) return void 0;
698
- return [from, Math.max(to, from + 1500)];
699
- }
700
- const LETTERS = [
701
- "A",
702
- "B",
703
- "C",
704
- "D"
705
- ];
706
- async function renderAbReel(take, opts) {
707
- await requireTakeFiles(take, { capture: true });
708
- const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
709
- const captureLog = await loadLogSibling(take.capturePath);
710
- const chromePath = await ensureChrome(opts.chromePath);
711
- const { knob, values } = parseSetFlag(opts.set, opts.beat);
712
- const cur = currentDesc(comp, knob);
713
- const variants = [{
714
- letter: "A",
715
- desc: `current (${cur})`,
716
- comp
717
- }];
718
- for (const v of values) {
719
- const applied = applyKnob(comp, knob, v);
720
- const desc = variantDesc(knob, v, applied);
721
- if (desc === cur || variants.some((x) => x.desc === desc)) continue;
722
- variants.push({
723
- letter: LETTERS[variants.length],
724
- desc,
725
- comp: applied
726
- });
727
- }
728
- if (variants.length < 2) throw new Error(`ab: every requested value matches the current state — nothing to compare`);
729
- for (const v of variants) {
730
- const issues = validateComposition$1(v.comp, captureLog ? { captureLog } : {});
731
- const errors = issues.filter((i) => i.severity === "error");
732
- if (errors.length) throw new Error(`ab: variant ${v.letter} (${v.desc}) is invalid:\n${formatIssues$1(errors)}`);
733
- }
734
- const windowMs = abWindow(variants.map((v) => v.comp), opts.beat, opts.full ?? false);
735
- const rangeSec = windowMs ? [windowMs[0] / 1e3, windowMs[1] / 1e3] : void 0;
736
- const clips = [];
737
- try {
738
- for (const v of variants) {
739
- const base = opts.draft ? toDraft(v.comp) : v.comp;
740
- const decorated = {
741
- ...base,
742
- review: { label: `${v.letter} · ${v.desc}` }
743
- };
744
- const clip = `${take.base}.ab.${v.letter}.mp4`;
745
- if (opts.logProgress !== false) process.stderr.write(`variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : ""}\n`);
746
- await renderTake({
747
- composition: decorated,
748
- videoPath: take.capturePath,
749
- outPath: clip,
1025
+ if (path === "/api/take/video" && method === "GET") {
1026
+ await serveFile(req, res, take.capturePath);
1027
+ return;
1028
+ }
1029
+ if (path === "/api/take/mtime" && method === "GET") {
1030
+ sendJson(res, 200, { mtime: await compositionMtime() });
1031
+ return;
1032
+ }
1033
+ if (path === "/api/notes" && method === "POST") {
1034
+ const { text } = JSON.parse(await readBody(req));
1035
+ if (!text?.trim()) {
1036
+ sendJson(res, 400, { error: "empty note" });
1037
+ return;
1038
+ }
1039
+ const line = text.trim().replace(/\s+/g, " ").slice(0, 2e3);
1040
+ await appendFile(`${take.base}.notes.md`, `- ${line}\n`);
1041
+ process.stdout.write(`NOTE ${JSON.stringify({
1042
+ take: take.name,
1043
+ text: line
1044
+ })}\n`);
1045
+ sendJson(res, 200, { ok: true });
1046
+ return;
1047
+ }
1048
+ if (path === "/api/take/output" && method === "GET") {
1049
+ await serveFile(req, res, take.mp4Path);
1050
+ return;
1051
+ }
1052
+ if (path === "/api/composition" && method === "POST") {
1053
+ const payload = await readWrite(req, res);
1054
+ if (!payload) return;
1055
+ const { composition: comp, baseMtime } = payload;
1056
+ const captureLog = await loadCaptureLog();
1057
+ const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
1058
+ const errors = issues.filter((i) => i.severity === "error");
1059
+ if (errors.length) {
1060
+ sendJson(res, 400, { issues });
1061
+ return;
1062
+ }
1063
+ const saved = await persistGuarded(comp, baseMtime);
1064
+ if (!saved.ok) {
1065
+ sendJson(res, 409, {
1066
+ conflict: true,
1067
+ mtime: saved.mtime
1068
+ });
1069
+ return;
1070
+ }
1071
+ sendJson(res, 200, {
1072
+ ok: true,
1073
+ issues,
1074
+ mtime: saved.mtime
1075
+ });
1076
+ return;
1077
+ }
1078
+ if (path === "/api/render" && method === "POST") {
1079
+ if (renderStarting || job?.status === "running") {
1080
+ sendJson(res, 409, { error: "a render is already in progress" });
1081
+ return;
1082
+ }
1083
+ renderStarting = true;
1084
+ try {
1085
+ const payload = await readWrite(req, res);
1086
+ if (!payload) return;
1087
+ const { composition: comp, baseMtime } = payload;
1088
+ const captureLog = await loadCaptureLog() ?? void 0;
1089
+ const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
1090
+ const errors = issues.filter((i) => i.severity === "error");
1091
+ if (errors.length) {
1092
+ sendJson(res, 400, { issues });
1093
+ return;
1094
+ }
1095
+ const saved = await persistGuarded(comp, baseMtime);
1096
+ if (!saved.ok) {
1097
+ sendJson(res, 409, {
1098
+ conflict: true,
1099
+ mtime: saved.mtime
1100
+ });
1101
+ return;
1102
+ }
1103
+ const id = `${Date.now().toString(36)}-${++jobSeq}`;
1104
+ job = {
1105
+ id,
1106
+ progress: 0,
1107
+ status: "running",
1108
+ clients: new Set()
1109
+ };
1110
+ sendJson(res, 200, {
1111
+ jobId: id,
1112
+ mtime: saved.mtime
1113
+ });
1114
+ runRender(job, comp, captureLog);
1115
+ } finally {
1116
+ renderStarting = false;
1117
+ }
1118
+ return;
1119
+ }
1120
+ const ev = /^\/api\/render\/([^/]+)\/events$/.exec(path);
1121
+ if (ev && method === "GET") {
1122
+ const id = ev[1];
1123
+ if (!job || job.id !== id) {
1124
+ sendJson(res, 404, { error: "unknown job" });
1125
+ return;
1126
+ }
1127
+ res.writeHead(200, {
1128
+ "Content-Type": "text/event-stream",
1129
+ "Cache-Control": "no-cache",
1130
+ Connection: "keep-alive"
1131
+ });
1132
+ emit(res, "progress", { progress: job.progress });
1133
+ if (job.status === "done") {
1134
+ emit(res, "done", { mp4Url: job.mp4Url });
1135
+ res.end();
1136
+ return;
1137
+ }
1138
+ if (job.status === "error") {
1139
+ emit(res, "failed", { message: job.error });
1140
+ res.end();
1141
+ return;
1142
+ }
1143
+ job.clients.add(res);
1144
+ req.on("close", () => job?.clients.delete(res));
1145
+ return;
1146
+ }
1147
+ if (path.startsWith("/api/")) {
1148
+ sendJson(res, 404, { error: "no such endpoint" });
1149
+ return;
1150
+ }
1151
+ if (method !== "GET") {
1152
+ sendJson(res, 405, { error: "method not allowed" });
1153
+ return;
1154
+ }
1155
+ const rel = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
1156
+ let filePath = join(dist, rel === "/" ? "index.html" : rel);
1157
+ if (!filePath.startsWith(dist)) {
1158
+ sendJson(res, 403, { error: "forbidden" });
1159
+ return;
1160
+ }
1161
+ const fst = await stat(filePath).catch(() => null);
1162
+ if (!fst?.isFile()) filePath = join(dist, "index.html");
1163
+ await serveFile(req, res, filePath);
1164
+ } catch (err) {
1165
+ sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
1166
+ }
1167
+ });
1168
+ async function runRender(j, comp, captureLog) {
1169
+ try {
1170
+ await (deps.renderComposition ?? renderComposition)({
1171
+ composition: comp,
1172
+ capturePath: take.capturePath,
1173
+ outPath: take.mp4Path,
750
1174
  captureLog,
751
- logProgress: opts.logProgress ?? true,
752
- chromePath,
753
- rangeSec,
754
- writeCompositionSibling: false
1175
+ chromePath: opts.chromePath,
1176
+ writeCompositionSibling: false,
1177
+ onProgress: (p) => {
1178
+ j.progress = p;
1179
+ for (const c of j.clients) emit(c, "progress", { progress: p });
1180
+ }
755
1181
  });
756
- clips.push(clip);
1182
+ j.status = "done";
1183
+ j.progress = 1;
1184
+ j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;
1185
+ for (const c of j.clients) {
1186
+ emit(c, "done", { mp4Url: j.mp4Url });
1187
+ c.end();
1188
+ }
1189
+ } catch (err) {
1190
+ j.status = "error";
1191
+ j.error = err instanceof Error ? err.message : String(err);
1192
+ for (const c of j.clients) {
1193
+ emit(c, "failed", { message: j.error });
1194
+ c.end();
1195
+ }
1196
+ } finally {
1197
+ j.clients.clear();
757
1198
  }
758
- await concatWithGaps([...clips, ...clips], take.abPath, {
759
- width: comp.output.width,
760
- height: comp.output.height,
761
- fps: opts.draft ? Math.min(30, comp.output.fps) : comp.output.fps
762
- });
763
- } finally {
764
- await Promise.all(clips.map((c) => rm(c, { force: true })));
765
1199
  }
766
- const legend = [
767
- `A/B reel: ${take.abPath} (${knobLabel(knob)})`,
768
- ...variants.map((v) => ` ${v.letter} ${v.desc}`),
769
- `answer with a letter — or "between A and B" / "none, try …"`
770
- ].join("\n");
1200
+ const port = await listen(server, opts.port ?? 4178);
1201
+ const url = `http://127.0.0.1:${port}/`;
1202
+ process.stdout.write(`open-take editor → ${url}\n(serving take "${take.name}"; Ctrl-C to stop)\n`);
1203
+ if (opts.open !== false) openBrowser(url);
771
1204
  return {
772
- abPath: take.abPath,
773
- legend
1205
+ url,
1206
+ close: () => new Promise((r) => server.close(() => r()))
774
1207
  };
775
1208
  }
776
- function knobLabel(knob) {
777
- if (knob.kind === "zoom") return `beat ${knob.beat} · zoom`;
778
- if (knob.kind === "path") return knob.path;
779
- return knob.kind;
780
- }
781
- /** before/after reel from the existing prev + current masters — no render at
782
- * all, pure ffmpeg trims. Order convention: BEFORE then AFTER, twice. */
783
- async function renderBeforeAfter(take, opts = {}) {
784
- await requireTakeFiles(take);
785
- if (!await stat(take.prevPath).catch(() => null)) throw new Error(`ab --before-after: no ${take.prevPath} yet (it appears after a re-render)`);
786
- const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
787
- const win = abWindow([comp], opts.beat, opts.full ?? false);
788
- const cut = async (src, out) => {
789
- const args = [
790
- "-y",
791
- "-loglevel",
792
- "error",
793
- "-i",
794
- src
795
- ];
796
- if (win) args.push("-ss", String(win[0] / 1e3), "-t", String((win[1] - win[0]) / 1e3));
797
- args.push("-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
798
- await ffmpeg(args);
799
- };
800
- const before = `${take.base}.ab.before.mp4`;
801
- const after = `${take.base}.ab.after.mp4`;
802
- await cut(take.prevPath, before);
803
- await cut(take.mp4Path, after);
804
- await concatWithGaps([
805
- before,
806
- after,
807
- before,
808
- after
809
- ], take.abPath, {
810
- width: comp.output.width,
811
- height: comp.output.height,
812
- fps: comp.output.fps
813
- });
814
- await Promise.all([rm(before, { force: true }), rm(after, { force: true })]);
815
- const legend = [`before/after reel: ${take.abPath}`, ` plays BEFORE then AFTER, twice — say "keep the old one" to revert`].join("\n");
816
- return {
817
- abPath: take.abPath,
818
- legend
819
- };
1209
+ function emit(res, event, data) {
1210
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
820
1211
  }
821
- async function ffmpeg(args) {
822
- const bin = await resolveFfmpeg();
1212
+ /** Bind to 127.0.0.1 only; if the port is taken, try the next few. Resolves the
1213
+ * port actually BOUND, which differs from the requested one when port 0 asks
1214
+ * the OS to choose (how the tests get an isolated server). */
1215
+ function listen(server, startPort) {
823
1216
  return new Promise((res, rej) => {
824
- const c = spawn(bin, args, { stdio: [
825
- "ignore",
826
- "ignore",
827
- "pipe"
828
- ] });
829
- let err = "";
830
- c.stderr.on("data", (d) => err += d);
831
- c.on("error", rej);
832
- c.on("close", (code) => code === 0 ? res() : rej(new Error(`ffmpeg exited ${code}: ${err}`)));
833
- });
834
- }
835
- /** Concat clips with a 0.35s black gap between each, re-encoding via the concat
836
- * FILTER (robust to per-clip encoder variance; everything shares WxH/fps). The
837
- * gap comes from a lavfi color source — no font/text filters needed. */
838
- async function concatWithGaps(clips, outPath, v) {
839
- const args = [
840
- "-y",
841
- "-loglevel",
842
- "error"
843
- ];
844
- for (const c of clips) args.push("-i", resolve(c));
845
- args.push("-f", "lavfi", "-t", "0.35", "-i", `color=c=black:s=${v.width}x${v.height}:r=${v.fps}`);
846
- const gapIdx = clips.length;
847
- const seq = [];
848
- const gapUses = clips.length - 1;
849
- const split = gapUses > 1 ? `[${gapIdx}:v]split=${gapUses}${Array.from({ length: gapUses }, (_, i) => `[g${i}]`).join("")};` : "";
850
- clips.forEach((_, i) => {
851
- seq.push(`[${i}:v]`);
852
- if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);
1217
+ let port = startPort;
1218
+ const tryOne = () => {
1219
+ server.once("error", (e) => {
1220
+ if (e.code === "EADDRINUSE" && port < startPort + 20) {
1221
+ port++;
1222
+ tryOne();
1223
+ } else rej(e);
1224
+ });
1225
+ server.listen(port, "127.0.0.1", () => {
1226
+ const addr = server.address();
1227
+ res(addr && typeof addr === "object" ? addr.port : port);
1228
+ });
1229
+ };
1230
+ tryOne();
853
1231
  });
854
- const filter = `${split}${seq.join("")}concat=n=${seq.length}:v=1:a=0[v]`;
855
- args.push("-filter_complex", filter, "-map", "[v]", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-r", String(v.fps), "-an", resolve(outPath));
856
- await ffmpeg(args);
857
- }
858
- /** Spawn a fire-and-forget opener. spawn ENOENT arrives ASYNCHRONOUSLY on the
859
- * child's "error" event (a try/catch around spawn never sees it and the
860
- * process would die with an unhandled error) — so degrade via the listener. */
861
- function spawnOpener(cmd, args, fallbackLine, useShell = false) {
862
- try {
863
- const c = spawn(cmd, args, {
864
- stdio: "ignore",
865
- detached: true,
866
- shell: useShell
867
- });
868
- c.on("error", () => process.stdout.write(fallbackLine));
869
- c.unref();
870
- } catch {
871
- process.stdout.write(fallbackLine);
872
- }
873
- }
874
- /** Open a file with the OS default player; degrade to printing the path. */
875
- function openPath(p) {
876
- const abs = resolve(p);
877
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
878
- spawnOpener(cmd, [abs], `open: ${abs}\n`, process.platform === "win32");
879
- }
880
- /** Reveal a file in Finder/Explorer; degrade to printing the path. */
881
- function revealPath(p) {
882
- const abs = resolve(p);
883
- if (process.platform === "darwin") spawnOpener("open", ["-R", abs], `at: ${abs}\n`);
884
- else if (process.platform === "win32") spawnOpener("explorer", [`/select,${abs}`], `at: ${abs}\n`, true);
885
- else spawnOpener("xdg-open", [dirname(abs)], `at: ${abs}\n`);
886
1232
  }
887
1233
 
888
1234
  //#endregion
@@ -909,11 +1255,12 @@ async function makeTake(plan, opts) {
909
1255
  const work = await mkdtemp(join(tmpdir(), "open-take-"));
910
1256
  const tmpVideo = join(work, "capture.mp4");
911
1257
  const chromePath = await ensureChrome(opts.capture?.chromePath);
912
- const log = await captureTake(plan, {
1258
+ const raw = await captureTake(plan, {
913
1259
  ...opts.capture,
914
1260
  chromePath,
915
1261
  videoPath: tmpVideo
916
1262
  });
1263
+ const log = opts.frameDiff === false ? raw : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.logProgress });
917
1264
  const capturePath = capturePathFor(opts.outPath);
918
1265
  const captureLogPath = captureLogPathFor(capturePath);
919
1266
  await mkdir(dirname(capturePath), { recursive: true });
@@ -958,7 +1305,8 @@ async function renderComposition(opts) {
958
1305
  logProgress: opts.logProgress ?? false,
959
1306
  chromePath,
960
1307
  captureLog: opts.captureLog,
961
- onProgress: opts.onProgress
1308
+ onProgress: opts.onProgress,
1309
+ writeCompositionSibling: opts.writeCompositionSibling
962
1310
  });
963
1311
  }
964
1312
  /** Convenience: load a `*.composition.json` and re-render over a saved capture.
@@ -982,5 +1330,5 @@ async function renderCompositionFile(opts) {
982
1330
  }
983
1331
 
984
1332
  //#endregion
985
- export { SAY_IT_CARD, buildBadges, buildBeatSheet, captureLogPathFor, captureTake, captureTakeCDP, ensureChrome, formatIssues, inspectPage, loadCaptureLogSibling, makeTake, openPath, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderReview, requireTakeFiles, resolveChrome, resolveTakePaths, revealPath, stagePrev, startEditServer, validateComposition };
1333
+ export { SAY_IT_CARD, annotateCaptureLog, buildBadges, buildBeatSheet, captureLogPathFor, captureTake, captureTakeCDP, diffFrames, ensureChrome, formatIssues, inspectPage, loadCaptureLogSibling, makeTake, openPath, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderReview, requireTakeFiles, resolveChrome, resolveTakePaths, revealPath, stagePrev, startEditServer, validateComposition };
986
1334
  //# sourceMappingURL=index.js.map