@open-take/runtime 0.2.2 → 0.2.4

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,8 +1,8 @@
1
- import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-CSm-BO2n.js";
1
+ import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-DXTkPLLF.js";
2
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
- import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, finishName, formatIssues, formatIssues as formatIssues$1, lookName, math, motionName, planComposition, renderTake, resolveFfmpeg, validateComposition, validateComposition as validateComposition$1, zoomLevelName } from "@open-take/compositor";
5
+ import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, finishName, formatIssues, formatIssues as formatIssues$1, lookName, math, motionName, planComposition, renderTake, resolveFfmpeg, resolveFfprobe, validateComposition, validateComposition as validateComposition$1, zoomLevelName } from "@open-take/compositor";
6
6
  import { spawn } from "node:child_process";
7
7
  import { createReadStream, statSync } from "node:fs";
8
8
  import { createServer } from "node:http";
@@ -202,7 +202,8 @@ async function annotateCaptureLog(log, videoPath, opts = {}) {
202
202
  };
203
203
  if (opts.logProgress) {
204
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`);
205
+ const subThreshold = events[i].changeCoverage === 0 && !eb ? " (sub-threshold — a subtle effect can score 0; judge by frames)" : "";
206
+ 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})` : ""}${subThreshold}\n`);
206
207
  }
207
208
  }
208
209
  return {
@@ -237,7 +238,7 @@ async function resolveTakePaths(input) {
237
238
  }
238
239
  p = join(p, pick);
239
240
  }
240
- const base = p.replace(/\.prev\.composition\.json$/i, "").replace(/\.composition\.json$/i, "").replace(/\.capture\.json$/i, "").replace(/\.capture\.mp4$/i, "").replace(/\.review\.mp4$/i, "").replace(/\.ab\.mp4$/i, "").replace(/\.prev\.mp4$/i, "").replace(/\.mp4$/i, "");
241
+ const base = p.replace(/\.dossier\.md$/i, "").replace(/\.prev\.composition\.json$/i, "").replace(/\.composition\.json$/i, "").replace(/\.capture\.json$/i, "").replace(/\.capture\.mp4$/i, "").replace(/\.review\.mp4$/i, "").replace(/\.draft\.mp4$/i, "").replace(/\.ab\.mp4$/i, "").replace(/\.prev\.mp4$/i, "").replace(/\.mp4$/i, "");
241
242
  return {
242
243
  base,
243
244
  name: basename(base),
@@ -246,8 +247,10 @@ async function resolveTakePaths(input) {
246
247
  capturePath: `${base}.capture.mp4`,
247
248
  captureLogPath: `${base}.capture.json`,
248
249
  reviewPath: `${base}.review.mp4`,
250
+ draftPath: `${base}.draft.mp4`,
249
251
  abPath: `${base}.ab.mp4`,
250
- prevPath: `${base}.prev.mp4`
252
+ prevPath: `${base}.prev.mp4`,
253
+ dossierPath: `${base}.dossier.md`
251
254
  };
252
255
  }
253
256
  /** Friendly preflight: verbs die with a clear message instead of a raw ffmpeg
@@ -302,6 +305,10 @@ function beatTitle(e) {
302
305
  return e.kind;
303
306
  }
304
307
  const trunc = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
308
+ /** "click Open menu" — the shared beat vocabulary (beat sheet rows, frames rows). */
309
+ function beatLabel(e) {
310
+ return `${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)}`;
311
+ }
305
312
  function fmtTime(ms) {
306
313
  const s = Math.max(0, Math.round(ms / 1e3));
307
314
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
@@ -425,6 +432,26 @@ async function renderReview(take, opts = {}) {
425
432
  sheet: buildBeatSheet(comp, take.name)
426
433
  };
427
434
  }
435
+ /** Draft-quality re-render of the CURRENT composition to `<base>.draft.mp4` —
436
+ * no badges, no watermark, and never the master's path, so a mid-refine
437
+ * frame-check (edit → draft → `frames`) costs seconds without downgrading or
438
+ * clobbering the postable mp4. Disposable like the review copy. */
439
+ async function renderDraft(take, opts = {}) {
440
+ await requireTakeFiles(take, { capture: true });
441
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
442
+ const captureLog = await loadLogSibling(take.capturePath);
443
+ const chromePath = await ensureChrome(opts.chromePath);
444
+ await renderTake({
445
+ composition: toDraft(comp),
446
+ videoPath: take.capturePath,
447
+ outPath: take.draftPath,
448
+ captureLog,
449
+ logProgress: opts.logProgress ?? true,
450
+ chromePath,
451
+ writeCompositionSibling: false
452
+ });
453
+ return { draftPath: take.draftPath };
454
+ }
428
455
  function parseSetFlag(set, beat) {
429
456
  const eq = set.indexOf("=");
430
457
  if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got "${set}")`);
@@ -950,9 +977,9 @@ async function startEditServer(opts, deps = {}) {
950
977
  const compositionMtime = async () => (await stat(take.compositionPath).catch(() => null))?.mtimeMs ?? 0;
951
978
  let writeLock = Promise.resolve();
952
979
  const exclusive = (fn) => {
953
- const run = writeLock.then(fn, fn);
954
- writeLock = run.catch(() => {});
955
- return run;
980
+ const run$1 = writeLock.then(fn, fn);
981
+ writeLock = run$1.catch(() => {});
982
+ return run$1;
956
983
  };
957
984
  /** Persist unless someone else wrote first. `baseMtime` is the mtime the
958
985
  * client last read. Every API write must provide it; 保留我的 re-bases to
@@ -1250,6 +1277,217 @@ function listen(server, startPort) {
1250
1277
  });
1251
1278
  }
1252
1279
 
1280
+ //#endregion
1281
+ //#region src/frames.ts
1282
+ const COLS = 5;
1283
+ /** Per-beat camera windows on the composition timeline, buildBadges-style:
1284
+ * monotone starts (the ramp departure toward the beat), the actual landing,
1285
+ * and where the framing is released (the next beat's departure, or the own
1286
+ * hold's end). */
1287
+ function beatWindows(comp) {
1288
+ const ramps = math.cameraRampSchedule(comp);
1289
+ let prevStart = 0;
1290
+ const starts = comp.events.map((e, i) => {
1291
+ const s = Math.max(ramps[i]?.startMs ?? e.zoom.inAtMs, prevStart + 1);
1292
+ prevStart = s;
1293
+ return s;
1294
+ });
1295
+ return comp.events.map((e, i) => {
1296
+ const arrived = Math.max(e.tMs, ramps[i]?.landMs ?? e.tMs);
1297
+ const endOwn = arrived + (e.durationMs ?? 0) + comp.cursor.holdMs;
1298
+ const release = i < comp.events.length - 1 ? starts[i + 1] : Math.min(endOwn, comp.durationMs);
1299
+ return {
1300
+ startMs: starts[i],
1301
+ arrivedMs: arrived,
1302
+ releaseMs: release
1303
+ };
1304
+ });
1305
+ }
1306
+ const spread = (from, to, n) => Array.from({ length: n }, (_, k) => n === 1 ? from : from + (to - from) * k / (n - 1));
1307
+ function buildFramePlan(comp, opts = {}) {
1308
+ const wins = beatWindows(comp);
1309
+ const notes = [];
1310
+ const endCap = comp.durationMs - 60;
1311
+ if (opts.beat != null) {
1312
+ const i = opts.beat - 1;
1313
+ const e = comp.events[i];
1314
+ const w = wins[i];
1315
+ if (!e || !w) throw new Error(`frames: --beat ${opts.beat} out of range (1-${comp.events.length})`);
1316
+ const from = Math.max(comp.startMs ?? 0, w.startMs - 400);
1317
+ const to = Math.min(endCap, w.releaseMs + 400);
1318
+ const phase = (t) => t < w.arrivedMs ? "travel" : t <= w.releaseMs ? "hold" : "tail";
1319
+ const cells = spread(from, to, COLS * 2).map((t) => ({
1320
+ tMs: t,
1321
+ phase: phase(t)
1322
+ }));
1323
+ const label = `beat ${opts.beat} · ${beatLabel(e)}`;
1324
+ return {
1325
+ rows: [{
1326
+ label: `${label} 1/2`,
1327
+ cells: cells.slice(0, COLS)
1328
+ }, {
1329
+ label: `${label} 2/2`,
1330
+ cells: cells.slice(COLS)
1331
+ }],
1332
+ cols: COLS,
1333
+ notes
1334
+ };
1335
+ }
1336
+ const rows = [];
1337
+ const trim = comp.startMs ?? 0;
1338
+ const introEnd = wins.length ? wins[0].startMs - 100 : endCap;
1339
+ if (introEnd - trim > 800) rows.push({
1340
+ label: "in",
1341
+ cells: spread(trim, introEnd, COLS).map((tMs) => ({
1342
+ tMs,
1343
+ phase: "intro"
1344
+ }))
1345
+ });
1346
+ comp.events.forEach((e, i) => {
1347
+ const w = wins[i];
1348
+ if (w.releaseMs <= trim) {
1349
+ notes.push(`beat ${i + 1} ends before the startMs head trim — not sampled`);
1350
+ return;
1351
+ }
1352
+ const holdFrom = Math.max(trim, Math.min(w.arrivedMs + 80, endCap));
1353
+ const holdTo = Math.max(holdFrom, Math.min(w.releaseMs - 120, endCap));
1354
+ const cells = [];
1355
+ if (w.arrivedMs - w.startMs > 200 && w.startMs >= trim) cells.push({
1356
+ tMs: (w.startMs + w.arrivedMs) / 2,
1357
+ phase: "travel"
1358
+ });
1359
+ const holdN = COLS - cells.length;
1360
+ for (const tMs of spread(holdFrom, holdTo, holdN)) cells.push({
1361
+ tMs,
1362
+ phase: "hold"
1363
+ });
1364
+ rows.push({
1365
+ label: `beat ${i + 1} · ${beatLabel(e)}`,
1366
+ cells
1367
+ });
1368
+ });
1369
+ const lastRelease = wins.length ? wins[wins.length - 1].releaseMs : trim;
1370
+ if (comp.durationMs - lastRelease > 800) rows.push({
1371
+ label: "out",
1372
+ cells: spread(Math.max(trim, lastRelease), endCap, COLS).map((tMs) => ({
1373
+ tMs,
1374
+ phase: "tail"
1375
+ }))
1376
+ });
1377
+ return {
1378
+ rows,
1379
+ cols: COLS,
1380
+ notes
1381
+ };
1382
+ }
1383
+ function run(cmd, args) {
1384
+ return new Promise((res, rej) => {
1385
+ const c = spawn(cmd, args, { stdio: [
1386
+ "ignore",
1387
+ "pipe",
1388
+ "pipe"
1389
+ ] });
1390
+ let out = "";
1391
+ let err = "";
1392
+ c.stdout.on("data", (d) => {
1393
+ out += d;
1394
+ });
1395
+ c.stderr.on("data", (d) => {
1396
+ err += d;
1397
+ });
1398
+ c.on("error", rej);
1399
+ c.on("close", (code) => code === 0 ? res(out) : rej(new Error(`${cmd} exited ${code}: ${err}`)));
1400
+ });
1401
+ }
1402
+ async function mp4Duration(path) {
1403
+ const out = await run(await resolveFfprobe(), [
1404
+ "-v",
1405
+ "error",
1406
+ "-show_entries",
1407
+ "format=duration",
1408
+ "-of",
1409
+ "csv=p=0",
1410
+ resolve(path)
1411
+ ]);
1412
+ const s = Number.parseFloat(out.trim());
1413
+ if (!Number.isFinite(s) || s <= 0) throw new Error(`frames: could not read duration of ${path}`);
1414
+ return s * 1e3;
1415
+ }
1416
+ const fmtS = (ms) => `${(ms / 1e3).toFixed(1)}s`;
1417
+ function buildFrameSheet(plan, framesPath, trimMs, tileW) {
1418
+ const lines = [`frames: ${framesPath} · ${plan.cols} cols × ${plan.rows.length} rows${tileW ? ` · ${tileW}px tiles` : ""} · times on the composition timeline${trimMs ? ` (head −${(trimMs / 1e3).toFixed(1)}s already cut from the mp4)` : ""}`];
1419
+ plan.rows.forEach((r, i) => {
1420
+ const cells = r.cells.map((c) => c.phase === "hold" || c.phase === "intro" ? fmtS(c.tMs) : `${fmtS(c.tMs)}(${c.phase})`).join(" · ");
1421
+ lines.push(` row ${i + 1} ${r.label.padEnd(34, " ")} ${cells}`);
1422
+ });
1423
+ for (const n of plan.notes) lines.push(` ⚠ ${n}`);
1424
+ lines.push(`judge framing/payoff on HOLD cells only — travel cells are mid-motion by design (ramps + blur live there).`);
1425
+ return lines.join("\n");
1426
+ }
1427
+ /** Extract the plan's frames from a delivered take mp4 and tile them into
1428
+ * `<base>.frames[.beatN].png`. No Chrome, no render — a handful of ffmpeg
1429
+ * seeks; seconds, not minutes. */
1430
+ async function renderFrames(take, opts = {}) {
1431
+ await requireTakeFiles(take);
1432
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
1433
+ const src = resolve(opts.sourcePath ?? take.mp4Path);
1434
+ if (!(await stat(src).catch(() => null))?.isFile()) throw new Error(`frames: ${src} not found — render the take first`);
1435
+ const plan = buildFramePlan(comp, { beat: opts.beat });
1436
+ if (plan.rows.length === 0) throw new Error("frames: nothing to sample (no beats, no intro/tail)");
1437
+ const trim = comp.startMs ?? 0;
1438
+ const durMs = await mp4Duration(src);
1439
+ const ffmpeg$1 = await resolveFfmpeg();
1440
+ const framesPath = opts.beat != null ? `${take.base}.frames.beat${opts.beat}.png` : `${take.base}.frames.png`;
1441
+ const tileW = Math.round(opts.tileWidth ?? (opts.beat != null ? 720 : 480));
1442
+ if (!Number.isFinite(tileW) || tileW < 120 || tileW > 1920) throw new Error(`frames: tile width ${tileW} out of range (120-1920)`);
1443
+ const tileH = Math.round(tileW * comp.output.height / comp.output.width);
1444
+ const work = await mkdtemp(join(tmpdir(), "open-take-frames-"));
1445
+ try {
1446
+ const cells = plan.rows.flatMap((r) => r.cells);
1447
+ for (let i = 0; i < cells.length; i++) {
1448
+ const fileMs = Math.min(Math.max(cells[i].tMs - trim, 0), durMs - 50);
1449
+ await run(ffmpeg$1, [
1450
+ "-y",
1451
+ "-loglevel",
1452
+ "error",
1453
+ "-ss",
1454
+ String(fileMs / 1e3),
1455
+ "-i",
1456
+ src,
1457
+ "-frames:v",
1458
+ "1",
1459
+ "-vf",
1460
+ `scale=${tileW}:${tileH}`,
1461
+ join(work, `f${String(i).padStart(3, "0")}.png`)
1462
+ ]);
1463
+ }
1464
+ await run(ffmpeg$1, [
1465
+ "-y",
1466
+ "-loglevel",
1467
+ "error",
1468
+ "-framerate",
1469
+ "1",
1470
+ "-i",
1471
+ join(work, "f%03d.png"),
1472
+ "-frames:v",
1473
+ "1",
1474
+ "-vf",
1475
+ `tile=${plan.cols}x${plan.rows.length}`,
1476
+ framesPath
1477
+ ]);
1478
+ } finally {
1479
+ await rm(work, {
1480
+ recursive: true,
1481
+ force: true
1482
+ });
1483
+ }
1484
+ return {
1485
+ framesPath,
1486
+ sheet: buildFrameSheet(plan, framesPath, trim, tileW),
1487
+ plan
1488
+ };
1489
+ }
1490
+
1253
1491
  //#endregion
1254
1492
  //#region src/index.ts
1255
1493
  /** `<out>.mp4` → `<out>.capture.mp4` — the raw recording kept beside the
@@ -1279,11 +1517,14 @@ async function makeTake(plan, opts) {
1279
1517
  chromePath,
1280
1518
  videoPath: tmpVideo
1281
1519
  });
1282
- const log = opts.frameDiff === false ? raw : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });
1283
1520
  const capturePath = capturePathFor(opts.outPath);
1284
1521
  const captureLogPath = captureLogPathFor(capturePath);
1285
1522
  await mkdir(dirname(capturePath), { recursive: true });
1286
1523
  await copyFile(tmpVideo, capturePath);
1524
+ try {
1525
+ opts.onCaptureReady?.(capturePath);
1526
+ } catch {}
1527
+ const log = opts.frameDiff === false ? raw : await annotateCaptureLog(raw, tmpVideo, { logProgress: opts.verbose === true });
1287
1528
  await writeFile(captureLogPath, JSON.stringify(log, null, 2));
1288
1529
  const captureFps = opts.capture?.fps ?? 60;
1289
1530
  const planOpts = opts.planOpts?.output?.fps == null ? {
@@ -1295,13 +1536,15 @@ async function makeTake(plan, opts) {
1295
1536
  } : opts.planOpts;
1296
1537
  const composition = planComposition(log, planOpts);
1297
1538
  const { mp4Path, compositionPath } = await renderTake({
1298
- composition,
1539
+ composition: opts.draft ? toDraft(composition) : composition,
1299
1540
  videoPath: capturePath,
1300
1541
  outPath: resolve(opts.outPath),
1301
1542
  logProgress: opts.logProgress ?? false,
1302
1543
  chromePath,
1303
- captureLog: log
1544
+ captureLog: log,
1545
+ ...opts.draft ? { writeCompositionSibling: false } : {}
1304
1546
  });
1547
+ if (opts.draft) await writeFile(compositionPath, JSON.stringify(composition, null, 2));
1305
1548
  return {
1306
1549
  mp4Path,
1307
1550
  compositionPath,
@@ -1350,5 +1593,5 @@ async function renderCompositionFile(opts) {
1350
1593
  }
1351
1594
 
1352
1595
  //#endregion
1353
- 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 };
1596
+ export { SAY_IT_CARD, annotateCaptureLog, beatLabel, buildBadges, buildBeatSheet, buildFramePlan, buildFrameSheet, captureLogPathFor, captureTake, captureTakeCDP, diffFrames, ensureChrome, formatIssues, inspectPage, loadCaptureLogSibling, makeTake, openPath, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderDraft, renderFrames, renderReview, requireTakeFiles, resolveChrome, resolveTakePaths, revealPath, stagePrev, startEditServer, toDraft, validateComposition };
1354
1597
  //# sourceMappingURL=index.js.map