@open-take/runtime 0.2.2 → 0.2.3

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